_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 |
|---|---|---|---|---|---|---|---|---|
8f7fe45ceb2c43e78e300bb1302ff509e7839b5f9d15c6ce55b67bd36fea3a10 | gen-smtp/gen_smtp | smtp_socket.erl | Copyright 2009 < > . All rights reserved .
%%%
%%% 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.
%% @doc Facilitates transparent gen_tcp/ssl socket handling
-module(smtp_socket).
-define(TCP_LISTEN_OPTIONS, [
{active, false},
{backlog, 30},
{ip, {0, 0, 0, 0}},
{keepalive, true},
{packet, line},
{reuseaddr, true}
]).
-define(TCP_CONNECT_OPTIONS, [
{active, false},
{packet, line},
{ip, {0, 0, 0, 0}},
{port, 0}
]).
-define(SSL_LISTEN_OPTIONS, [
{active, false},
{backlog, 30},
{certfile, "server.crt"},
{depth, 0},
{keepalive, true},
{keyfile, "server.key"},
{packet, line},
{reuse_sessions, false},
{reuseaddr, true}
]).
-define(SSL_CONNECT_OPTIONS, [
{active, false},
{depth, 0},
{packet, line},
{ip, {0, 0, 0, 0}},
{port, 0}
]).
-ifdef(TEST).
-include_lib("eunit/include/eunit.hrl").
-endif.
%% API
-export([connect/3, connect/4, connect/5]).
-export([listen/2, listen/3, accept/1, accept/2]).
-export([send/2, recv/2, recv/3]).
-export([controlling_process/2]).
-export([peername/1]).
-export([close/1, shutdown/2]).
-export([active_once/1]).
-export([setopts/2]).
-export([get_proto/1]).
-export([begin_inet_async/1]).
-export([handle_inet_async/1, handle_inet_async/2, handle_inet_async/3]).
-export([extract_port_from_socket/1]).
-export([to_ssl_server/1, to_ssl_server/2, to_ssl_server/3]).
-export([to_ssl_client/1, to_ssl_client/2, to_ssl_client/3]).
-export([type/1]).
-type protocol() :: 'tcp' | 'ssl'.
-type address() :: inet:ip_address() | string() | binary().
-type socket() :: ssl:sslsocket() | gen_tcp:socket().
-export_type([socket/0]).
%%%-----------------------------------------------------------------
%%% API
%%%-----------------------------------------------------------------
-spec connect(Protocol :: protocol(), Address :: address(), Port :: pos_integer()) ->
{ok, socket()} | {error, any()}.
connect(Protocol, Address, Port) ->
connect(Protocol, Address, Port, [], infinity).
-spec connect(
Protocol :: protocol(), Address :: address(), Port :: pos_integer(), Options :: list()
) -> {ok, socket()} | {error, any()}.
connect(Protocol, Address, Port, Opts) ->
connect(Protocol, Address, Port, Opts, infinity).
-spec connect(
Protocol :: protocol(),
Address :: address(),
Port :: pos_integer(),
Options :: list(),
Time :: non_neg_integer() | 'infinity'
) -> {ok, socket()} | {error, any()}.
connect(tcp, Address, Port, Opts, Time) ->
gen_tcp:connect(Address, Port, tcp_connect_options(Opts), Time);
connect(ssl, Address, Port, Opts, Time) ->
ssl:connect(Address, Port, ssl_connect_options(Opts), Time).
-spec listen(Protocol :: protocol(), Port :: pos_integer()) -> {ok, socket()} | {error, any()}.
listen(Protocol, Port) ->
listen(Protocol, Port, []).
-spec listen(Protocol :: protocol(), Port :: pos_integer(), Options :: list()) ->
{ok, socket()} | {error, any()}.
listen(ssl, Port, Options) ->
ssl:listen(Port, ssl_listen_options(Options));
listen(tcp, Port, Options) ->
gen_tcp:listen(Port, tcp_listen_options(Options)).
-spec accept(Socket :: socket()) -> {'ok', socket()} | {'error', any()}.
accept(Socket) ->
accept(Socket, infinity).
-spec accept(Socket :: socket(), Timeout :: pos_integer() | 'infinity') ->
{'ok', socket()} | {'error', any()}.
accept(Socket, Timeout) when is_port(Socket) ->
case gen_tcp:accept(Socket, Timeout) of
{ok, NewSocket} ->
{ok, Opts} = inet:getopts(Socket, [active, keepalive, packet, reuseaddr]),
inet:setopts(NewSocket, Opts),
{ok, NewSocket};
{error, _} = Error ->
Error
end;
accept(Socket, Timeout) ->
case ssl:transport_accept(Socket, Timeout) of
{ok, NewSocket} ->
ssl:handshake(NewSocket);
{error, _} = Error ->
Error
end.
-spec send(Socket :: socket(), Data :: binary() | string() | iolist()) -> 'ok' | {'error', any()}.
send(Socket, Data) when is_port(Socket) ->
gen_tcp:send(Socket, Data);
send(Socket, Data) ->
ssl:send(Socket, Data).
-spec recv(Socket :: socket(), Length :: non_neg_integer()) -> {'ok', any()} | {'error', any()}.
recv(Socket, Length) ->
recv(Socket, Length, infinity).
-spec recv(
Socket :: socket(), Length :: non_neg_integer(), Timeout :: non_neg_integer() | 'infinity'
) -> {'ok', any()} | {'error', any()}.
recv(Socket, Length, Timeout) when is_port(Socket) ->
gen_tcp:recv(Socket, Length, Timeout);
recv(Socket, Length, Timeout) ->
ssl:recv(Socket, Length, Timeout).
-spec controlling_process(Socket :: socket(), NewOwner :: pid()) -> 'ok' | {'error', any()}.
controlling_process(Socket, NewOwner) when is_port(Socket) ->
gen_tcp:controlling_process(Socket, NewOwner);
controlling_process(Socket, NewOwner) ->
ssl:controlling_process(Socket, NewOwner).
-spec peername(Socket :: socket()) ->
{ok, {inet:ip_address(), non_neg_integer()}} | {'error', any()}.
peername(Socket) when is_port(Socket) ->
inet:peername(Socket);
peername(Socket) ->
ssl:peername(Socket).
-spec close(Socket :: socket()) -> 'ok'.
close(Socket) when is_port(Socket) ->
gen_tcp:close(Socket);
close(Socket) ->
ssl:close(Socket).
-spec shutdown(Socket :: socket(), How :: 'read' | 'write' | 'read_write') ->
'ok' | {'error', any()}.
shutdown(Socket, How) when is_port(Socket) ->
gen_tcp:shutdown(Socket, How);
shutdown(Socket, How) ->
ssl:shutdown(Socket, How).
-spec active_once(Socket :: socket()) -> 'ok' | {'error', any()}.
active_once(Socket) when is_port(Socket) ->
inet:setopts(Socket, [{active, once}]);
active_once(Socket) ->
ssl:setopts(Socket, [{active, once}]).
-spec setopts(Socket :: socket(), Options :: list()) -> 'ok' | {'error', any()}.
setopts(Socket, Options) when is_port(Socket) ->
inet:setopts(Socket, Options);
setopts(Socket, Options) ->
ssl:setopts(Socket, Options).
-spec get_proto(Socket :: any()) -> 'tcp' | 'ssl'.
get_proto(Socket) when is_port(Socket) ->
tcp;
get_proto(_Socket) ->
ssl.
%% @doc {inet_async,...} will be sent to current process when a client connects
-spec begin_inet_async(Socket :: socket()) -> any().
begin_inet_async(Socket) when is_port(Socket) ->
prim_inet:async_accept(Socket, -1);
begin_inet_async(Socket) ->
Port = extract_port_from_socket(Socket),
begin_inet_async(Port).
%% @doc handle the {inet_async,...} message
-spec handle_inet_async(Message :: {'inet_async', socket(), any(), {'ok', socket()}}) ->
{'ok', socket()}.
handle_inet_async({inet_async, ListenSocket, _, {ok, ClientSocket}}) ->
handle_inet_async(ListenSocket, ClientSocket, []).
-spec handle_inet_async(ListenSocket :: socket(), ClientSocket :: socket()) -> {'ok', socket()}.
handle_inet_async(ListenObject, ClientSocket) ->
handle_inet_async(ListenObject, ClientSocket, []).
-spec handle_inet_async(ListenSocket :: socket(), ClientSocket :: socket(), Options :: list()) ->
{'ok', socket()}.
handle_inet_async(ListenObject, ClientSocket, Options) ->
ListenSocket = extract_port_from_socket(ListenObject),
case set_sockopt(ListenSocket, ClientSocket) of
ok -> ok;
Error -> erlang:error(set_sockopt, Error)
end,
Signal the network driver that we are ready to accept another connection
begin_inet_async(ListenSocket),
%% If the listening socket is SSL then negotiate the client socket
case is_port(ListenObject) of
true ->
{ok, ClientSocket};
false ->
{ok, UpgradedClientSocket} = to_ssl_server(ClientSocket, Options),
{ok, UpgradedClientSocket}
end.
%% @doc Upgrade a TCP connection to SSL
-spec to_ssl_server(Socket :: socket()) -> {'ok', ssl:sslsocket()} | {'error', any()}.
to_ssl_server(Socket) ->
to_ssl_server(Socket, []).
-spec to_ssl_server(Socket :: socket(), Options :: list()) ->
{'ok', ssl:sslsocket()} | {'error', any()}.
to_ssl_server(Socket, Options) ->
to_ssl_server(Socket, Options, infinity).
-spec to_ssl_server(
Socket :: socket(), Options :: list(), Timeout :: non_neg_integer() | 'infinity'
) -> {'ok', ssl:sslsocket()} | {'error', any()}.
to_ssl_server(Socket, Options, Timeout) when is_port(Socket) ->
ssl:handshake(Socket, ssl_listen_options(Options), Timeout);
to_ssl_server(_Socket, _Options, _Timeout) ->
{error, already_ssl}.
-spec to_ssl_client(Socket :: socket()) -> {'ok', ssl:sslsocket()} | {'error', 'already_ssl'}.
to_ssl_client(Socket) ->
to_ssl_client(Socket, []).
-spec to_ssl_client(Socket :: socket(), Options :: list()) ->
{'ok', ssl:sslsocket()} | {'error', 'already_ssl'}.
to_ssl_client(Socket, Options) ->
to_ssl_client(Socket, Options, infinity).
-spec to_ssl_client(
Socket :: socket(), Options :: list(), Timeout :: non_neg_integer() | 'infinity'
) -> {'ok', ssl:sslsocket()} | {'error', 'already_ssl'}.
to_ssl_client(Socket, Options, Timeout) when is_port(Socket) ->
ssl:connect(Socket, ssl_connect_options(Options), Timeout);
to_ssl_client(_Socket, _Options, _Timeout) ->
{error, already_ssl}.
-spec type(Socket :: socket()) -> protocol().
type(Socket) when is_port(Socket) ->
tcp;
type(_Socket) ->
ssl.
%%%-----------------------------------------------------------------
%%% Internal functions (OS_Mon configuration)
%%%-----------------------------------------------------------------
tcp_listen_options([Format | Options]) when Format =:= list; Format =:= binary ->
tcp_listen_options(Options, Format);
tcp_listen_options(Options) ->
tcp_listen_options(Options, list).
tcp_listen_options(Options, Format) ->
parse_address([Format | proplist_merge(Options, ?TCP_LISTEN_OPTIONS)]).
ssl_listen_options([Format | Options]) when Format =:= list; Format =:= binary ->
ssl_listen_options(Options, Format);
ssl_listen_options(Options) ->
ssl_listen_options(Options, list).
ssl_listen_options(Options, Format) ->
parse_address([Format | proplist_merge(Options, ?SSL_LISTEN_OPTIONS)]).
tcp_connect_options([Format | Options]) when Format =:= list; Format =:= binary ->
tcp_connect_options(Options, Format);
tcp_connect_options(Options) ->
tcp_connect_options(Options, list).
tcp_connect_options(Options, Format) ->
parse_address([Format | proplist_merge(Options, ?TCP_CONNECT_OPTIONS)]).
ssl_connect_options([Format | Options]) when Format =:= list; Format =:= binary ->
ssl_connect_options(Options, Format);
ssl_connect_options(Options) ->
ssl_connect_options(Options, list).
ssl_connect_options(Options, Format) ->
parse_address([Format | proplist_merge(Options, ?SSL_CONNECT_OPTIONS)]).
proplist_merge(PrimaryList, DefaultList) ->
{PrimaryTuples, PrimaryOther} = lists:partition(fun(X) -> is_tuple(X) end, PrimaryList),
{DefaultTuples, DefaultOther} = lists:partition(fun(X) -> is_tuple(X) end, DefaultList),
MergedTuples = lists:ukeymerge(
1,
lists:keysort(1, PrimaryTuples),
lists:keysort(1, DefaultTuples)
),
MergedOther = lists:umerge(lists:sort(PrimaryOther), lists:sort(DefaultOther)),
MergedTuples ++ MergedOther.
parse_address(Options) ->
case proplists:get_value(ip, Options) of
X when is_tuple(X) ->
Options;
X when is_list(X) ->
case inet_parse:address(X) of
{error, _} = Error ->
erlang:error(Error);
{ok, IP} ->
proplists:delete(ip, Options) ++ [{ip, IP}]
end;
_ ->
Options
end.
-spec extract_port_from_socket(Socket :: socket()) -> port().
extract_port_from_socket({sslsocket, _, {SSLPort, _}}) ->
SSLPort;
extract_port_from_socket(Socket) ->
Socket.
-spec set_sockopt(ListSock :: port(), CliSocket :: port()) -> 'ok' | any().
set_sockopt(ListenObject, ClientSocket) ->
ListenSocket = extract_port_from_socket(ListenObject),
true = inet_db:register_socket(ClientSocket, inet_tcp),
case prim_inet:getopts(ListenSocket, [active, nodelay, keepalive, delay_send, priority, tos]) of
{ok, Opts} ->
case prim_inet:setopts(ClientSocket, Opts) of
ok ->
ok;
Error ->
smtp_socket:close(ClientSocket),
Error
end;
Error ->
smtp_socket:close(ClientSocket),
Error
end.
-ifdef(TEST).
-define(TEST_PORT, 7586).
connect_test_() ->
[
{"listen and connect via tcp", fun() ->
Self = self(),
Port = ?TEST_PORT + 1,
Ref = make_ref(),
spawn(fun() ->
{ok, ListenSocket} = listen(tcp, Port),
?assert(is_port(ListenSocket)),
Self ! {Ref, listen},
{ok, ServerSocket} = accept(ListenSocket),
controlling_process(ServerSocket, Self),
Self ! {Ref, ListenSocket}
end),
receive
{Ref, listen} -> ok
end,
{ok, ClientSocket} = connect(tcp, "localhost", Port),
receive
{Ref, ListenSocket} when is_port(ListenSocket) -> ok
end,
?assert(is_port(ClientSocket)),
close(ListenSocket)
end},
{"listen and connect via ssl", fun() ->
Self = self(),
Port = ?TEST_PORT + 2,
Ref = make_ref(),
application:ensure_all_started(gen_smtp),
spawn(fun() ->
{ok, ListenSocket} = listen(ssl, Port, [
{keyfile, "test/fixtures/mx1.example.com-server.key"},
{certfile, "test/fixtures/mx1.example.com-server.crt"}
]),
?assertMatch([sslsocket | _], tuple_to_list(ListenSocket)),
Self ! {Ref, listen},
{ok, ServerSocket} = accept(ListenSocket),
controlling_process(ServerSocket, Self),
Self ! {Ref, ListenSocket}
end),
receive
{Ref, listen} -> ok
end,
{ok, ClientSocket} = connect(ssl, "localhost", Port, []),
receive
{Ref, {sslsocket, _, _} = ListenSocket} -> ok
end,
?assertMatch([sslsocket | _], tuple_to_list(ClientSocket)),
close(ListenSocket)
end}
].
evented_connections_test_() ->
[
{"current process receives connection to TCP listen sockets", fun() ->
Port = ?TEST_PORT + 3,
{ok, ListenSocket} = listen(tcp, Port),
begin_inet_async(ListenSocket),
spawn(fun() -> connect(tcp, "localhost", Port) end),
receive
{inet_async, ListenSocket, _, {ok, ServerSocket}} -> ok
end,
{ok, NewServerSocket} = handle_inet_async(ListenSocket, ServerSocket),
?assert(is_port(ServerSocket)),
%% only true for TCP
?assertEqual(ServerSocket, NewServerSocket),
?assert(is_port(ListenSocket)),
% Stop the async
spawn(fun() -> connect(tcp, "localhost", Port) end),
receive
_Ignored -> ok
end,
close(NewServerSocket),
close(ListenSocket)
end},
{"current process receives connection to SSL listen sockets", fun() ->
Port = ?TEST_PORT + 4,
application:ensure_all_started(gen_smtp),
{ok, ListenSocket} = listen(ssl, Port, [
{keyfile, "test/fixtures/mx1.example.com-server.key"},
{certfile, "test/fixtures/mx1.example.com-server.crt"}
]),
begin_inet_async(ListenSocket),
spawn(fun() -> connect(ssl, "localhost", Port) end),
receive
{inet_async, _ListenPort, _, {ok, ServerSocket}} -> ok
end,
{ok, NewServerSocket} = handle_inet_async(ListenSocket, ServerSocket, [
{keyfile, "test/fixtures/mx1.example.com-server.key"},
{certfile, "test/fixtures/mx1.example.com-server.crt"}
]),
?assert(is_port(ServerSocket)),
?assertMatch([sslsocket | _], tuple_to_list(NewServerSocket)),
?assertMatch([sslsocket | _], tuple_to_list(ListenSocket)),
%Stop the async
spawn(fun() -> connect(ssl, "localhost", Port) end),
receive
_Ignored -> ok
end,
close(ListenSocket),
close(NewServerSocket),
ok
end},
%% TODO: figure out if the following passes because
%% of an incomplete test case or if this really is
%% a magical feature where a single listener
%% can respond to either ssl or tcp connections.
{"current TCP listener receives SSL connection", fun() ->
Port = ?TEST_PORT + 5,
application:ensure_all_started(gen_smtp),
{ok, ListenSocket} = listen(tcp, Port),
begin_inet_async(ListenSocket),
spawn(fun() -> connect(ssl, "localhost", Port) end),
ServerSocket =
receive
{inet_async, _ListenPort, _, {ok, ServerSocket0}} -> ServerSocket0
end,
?assertMatch({ok, ServerSocket}, handle_inet_async(ListenSocket, ServerSocket)),
?assert(is_port(ListenSocket)),
?assert(is_port(ServerSocket)),
{ok, NewServerSocket} = to_ssl_server(ServerSocket, [
{certfile, "test/fixtures/mx1.example.com-server.crt"},
{keyfile, "test/fixtures/mx1.example.com-server.key"}
]),
?assertMatch([sslsocket | _], tuple_to_list(NewServerSocket)),
% Stop the async
spawn(fun() -> connect(ssl, "localhost", Port) end),
receive
_Ignored -> ok
end,
close(ListenSocket),
close(NewServerSocket)
end}
].
accept_test_() ->
[
{"Accept via tcp", fun() ->
Port = ?TEST_PORT + 6,
{ok, ListenSocket} = listen(tcp, Port, tcp_listen_options([])),
?assert(is_port(ListenSocket)),
spawn(fun() -> connect(ssl, "localhost", Port, tcp_connect_options([])) end),
{ok, ServerSocket} = accept(ListenSocket),
?assert(is_port(ListenSocket)),
close(ServerSocket),
close(ListenSocket)
end},
{"Accept via ssl", fun() ->
Port = ?TEST_PORT + 7,
application:ensure_all_started(gen_smtp),
{ok, ListenSocket} = listen(ssl, Port, [
{keyfile, "test/fixtures/mx1.example.com-server.key"},
{certfile, "test/fixtures/mx1.example.com-server.crt"}
]),
?assertMatch([sslsocket | _], tuple_to_list(ListenSocket)),
spawn(fun() -> connect(ssl, "localhost", Port) end),
accept(ListenSocket),
close(ListenSocket)
end}
].
type_test_() ->
[
{"a tcp socket returns 'tcp'", fun() ->
{ok, ListenSocket} = listen(tcp, ?TEST_PORT + 8),
?assertMatch(tcp, type(ListenSocket)),
close(ListenSocket)
end},
{"an ssl socket returns 'ssl'", fun() ->
application:ensure_all_started(gen_smtp),
{ok, ListenSocket} = listen(ssl, ?TEST_PORT + 9, [
{keyfile, "test/fixtures/mx1.example.com-server.key"},
{certfile, "test/fixtures/mx1.example.com-server.crt"}
]),
?assertMatch(ssl, type(ListenSocket)),
close(ListenSocket)
end}
].
active_once_test_() ->
[
{"socket is set to active:once on tcp", fun() ->
{ok, ListenSocket} = listen(tcp, ?TEST_PORT + 10, tcp_listen_options([])),
?assertEqual({ok, [{active, false}]}, inet:getopts(ListenSocket, [active])),
active_once(ListenSocket),
?assertEqual({ok, [{active, once}]}, inet:getopts(ListenSocket, [active])),
close(ListenSocket)
end},
{"socket is set to active:once on ssl", fun() ->
{ok, ListenSocket} = listen(
ssl,
?TEST_PORT + 11,
ssl_listen_options([
{keyfile, "test/fixtures/mx1.example.com-server.key"},
{certfile, "test/fixtures/mx1.example.com-server.crt"}
])
),
?assertEqual({ok, [{active, false}]}, ssl:getopts(ListenSocket, [active])),
active_once(ListenSocket),
?assertEqual({ok, [{active, once}]}, ssl:getopts(ListenSocket, [active])),
close(ListenSocket)
end}
].
option_test_() ->
[
{"tcp_listen_options has defaults", fun() ->
?assertEqual(
lists:sort([list | ?TCP_LISTEN_OPTIONS]), lists:sort(tcp_listen_options([]))
)
end},
{"tcp_connect_options has defaults", fun() ->
?assertEqual(
lists:sort([list | ?TCP_CONNECT_OPTIONS]), lists:sort(tcp_connect_options([]))
)
end},
{"ssl_listen_options has defaults", fun() ->
?assertEqual(
lists:sort([list | ?SSL_LISTEN_OPTIONS]), lists:sort(ssl_listen_options([]))
)
end},
{"ssl_connect_options has defaults", fun() ->
?assertEqual(
lists:sort([list | ?SSL_CONNECT_OPTIONS]), lists:sort(ssl_connect_options([]))
)
end},
{"tcp_listen_options defaults to list type", fun() ->
?assertEqual(
lists:sort([list | ?TCP_LISTEN_OPTIONS]),
lists:sort(tcp_listen_options([{active, false}]))
),
?assertEqual(
lists:sort([binary | ?TCP_LISTEN_OPTIONS]),
lists:sort(tcp_listen_options([binary, {active, false}]))
)
end},
{"tcp_connect_options defaults to list type", fun() ->
?assertEqual(
lists:sort([list | ?TCP_CONNECT_OPTIONS]),
lists:sort(tcp_connect_options([{active, false}]))
),
?assertEqual(
lists:sort([binary | ?TCP_CONNECT_OPTIONS]),
lists:sort(tcp_connect_options([binary, {active, false}]))
)
end},
{"ssl_listen_options defaults to list type", fun() ->
?assertEqual(
lists:sort([list | ?SSL_LISTEN_OPTIONS]),
lists:sort(ssl_listen_options([{active, false}]))
),
?assertEqual(
lists:sort([binary | ?SSL_LISTEN_OPTIONS]),
lists:sort(ssl_listen_options([binary, {active, false}]))
)
end},
{"ssl_connect_options defaults to list type", fun() ->
?assertEqual(
lists:sort([list | ?SSL_CONNECT_OPTIONS]),
lists:sort(ssl_connect_options([{active, false}]))
),
?assertEqual(
lists:sort([binary | ?SSL_CONNECT_OPTIONS]),
lists:sort(ssl_connect_options([binary, {active, false}]))
)
end},
{"tcp_listen_options merges provided proplist", fun() ->
?assertEqual(
[
list
| lists:keysort(1, [
{active, true},
{backlog, 30},
{ip, {0, 0, 0, 0}},
{keepalive, true},
{packet, 2},
{reuseaddr, true}
])
],
tcp_listen_options([{active, true}, {packet, 2}])
)
end},
{"tcp_connect_options merges provided proplist", fun() ->
?assertEqual(
lists:sort([
list,
{active, true},
{packet, 2},
{ip, {0, 0, 0, 0}},
{port, 0}
]),
lists:sort(tcp_connect_options([{active, true}, {packet, 2}]))
)
end},
{"ssl_listen_options merges provided proplist", fun() ->
?assertEqual(
[
list
| lists:keysort(1, [
{active, true},
{backlog, 30},
{certfile, "server.crt"},
{depth, 0},
{keepalive, true},
{keyfile, "server.key"},
{packet, 2},
{reuse_sessions, false},
{reuseaddr, true}
])
],
ssl_listen_options([{active, true}, {packet, 2}])
),
?assertEqual(
[
list
| lists:keysort(1, [
{active, false},
{backlog, 30},
{certfile, "../server.crt"},
{depth, 0},
{keepalive, true},
{keyfile, "../server.key"},
{packet, line},
{reuse_sessions, false},
{reuseaddr, true}
])
],
ssl_listen_options([{certfile, "../server.crt"}, {keyfile, "../server.key"}])
)
end},
{"ssl_connect_options merges provided proplist", fun() ->
?assertEqual(
lists:sort([
list,
{active, true},
{depth, 0},
{ip, {0, 0, 0, 0}},
{port, 0},
{packet, 2}
]),
lists:sort(ssl_connect_options([{active, true}, {packet, 2}]))
)
end}
].
ssl_upgrade_test_() ->
[
{"TCP connection can be upgraded to ssl", fun() ->
Self = self(),
Port = ?TEST_PORT + 12,
application:ensure_all_started(gen_smtp),
spawn(fun() ->
{ok, ListenSocket} = listen(tcp, Port),
Self ! listening,
{ok, ServerSocket} = accept(ListenSocket),
{ok, NewServerSocket} = smtp_socket:to_ssl_server(
ServerSocket,
[
{keyfile, "test/fixtures/mx1.example.com-server.key"},
{certfile, "test/fixtures/mx1.example.com-server.crt"}
]
),
Self ! {sock, NewServerSocket}
end),
receive
listening -> ok
end,
erlang:yield(),
{ok, ClientSocket} = connect(tcp, "localhost", Port),
?assert(is_port(ClientSocket)),
{ok, NewClientSocket} = to_ssl_client(ClientSocket),
?assertMatch([sslsocket | _], tuple_to_list(NewClientSocket)),
receive
{sock, NewServerSocket} -> ok
end,
?assertMatch({sslsocket, _, _}, NewServerSocket),
close(NewClientSocket),
close(NewServerSocket)
end},
{"SSL server connection can't be upgraded again", fun() ->
Self = self(),
Port = ?TEST_PORT + 13,
application:ensure_all_started(gen_smtp),
spawn(fun() ->
{ok, ListenSocket} = listen(ssl, Port, [
{keyfile, "test/fixtures/mx1.example.com-server.key"},
{certfile, "test/fixtures/mx1.example.com-server.crt"}
]),
Self ! listening,
{ok, ServerSocket} = accept(ListenSocket),
?assertMatch({error, already_ssl}, to_ssl_server(ServerSocket)),
close(ServerSocket)
end),
receive
listening -> ok
end,
erlang:yield(),
{ok, ClientSocket} = connect(ssl, "localhost", Port),
close(ClientSocket)
end},
{"SSL client connection can't be upgraded again", fun() ->
Self = self(),
Port = ?TEST_PORT + 14,
application:ensure_all_started(gen_smtp),
spawn(fun() ->
{ok, ListenSocket} = listen(ssl, Port, [
{keyfile, "test/fixtures/mx1.example.com-server.key"},
{certfile, "test/fixtures/mx1.example.com-server.crt"}
]),
Self ! listening,
{ok, ServerSocket} = accept(ListenSocket),
Self ! {sock, ServerSocket}
end),
receive
listening -> ok
end,
erlang:yield(),
{ok, ClientSocket} = connect(ssl, "localhost", Port),
receive
{sock, ServerSocket} -> ok
end,
?assertMatch({error, already_ssl}, to_ssl_client(ClientSocket)),
close(ClientSocket),
close(ServerSocket)
end}
].
-endif.
| null | https://raw.githubusercontent.com/gen-smtp/gen_smtp/1bd8d085ec5ca355b880b678d19a739ab6334640/src/smtp_socket.erl | erlang |
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
without limitation the rights to use, copy, modify, merge, publish,
the following conditions:
The above copyright notice and this permission notice shall be
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
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
@doc Facilitates transparent gen_tcp/ssl socket handling
API
-----------------------------------------------------------------
API
-----------------------------------------------------------------
@doc {inet_async,...} will be sent to current process when a client connects
@doc handle the {inet_async,...} message
If the listening socket is SSL then negotiate the client socket
@doc Upgrade a TCP connection to SSL
-----------------------------------------------------------------
Internal functions (OS_Mon configuration)
-----------------------------------------------------------------
only true for TCP
Stop the async
Stop the async
TODO: figure out if the following passes because
of an incomplete test case or if this really is
a magical feature where a single listener
can respond to either ssl or tcp connections.
Stop the async | Copyright 2009 < > . All rights reserved .
" Software " ) , to deal in the Software without restriction , including
distribute , sublicense , and/or sell copies of the Software , and to
permit persons to whom the Software is furnished to do so , subject to
included in all copies or substantial portions of the Software .
THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND ,
LIABLE FOR ANY CLAIM , DAMAGES OR OTHER LIABILITY , WHETHER IN AN ACTION
-module(smtp_socket).
-define(TCP_LISTEN_OPTIONS, [
{active, false},
{backlog, 30},
{ip, {0, 0, 0, 0}},
{keepalive, true},
{packet, line},
{reuseaddr, true}
]).
-define(TCP_CONNECT_OPTIONS, [
{active, false},
{packet, line},
{ip, {0, 0, 0, 0}},
{port, 0}
]).
-define(SSL_LISTEN_OPTIONS, [
{active, false},
{backlog, 30},
{certfile, "server.crt"},
{depth, 0},
{keepalive, true},
{keyfile, "server.key"},
{packet, line},
{reuse_sessions, false},
{reuseaddr, true}
]).
-define(SSL_CONNECT_OPTIONS, [
{active, false},
{depth, 0},
{packet, line},
{ip, {0, 0, 0, 0}},
{port, 0}
]).
-ifdef(TEST).
-include_lib("eunit/include/eunit.hrl").
-endif.
-export([connect/3, connect/4, connect/5]).
-export([listen/2, listen/3, accept/1, accept/2]).
-export([send/2, recv/2, recv/3]).
-export([controlling_process/2]).
-export([peername/1]).
-export([close/1, shutdown/2]).
-export([active_once/1]).
-export([setopts/2]).
-export([get_proto/1]).
-export([begin_inet_async/1]).
-export([handle_inet_async/1, handle_inet_async/2, handle_inet_async/3]).
-export([extract_port_from_socket/1]).
-export([to_ssl_server/1, to_ssl_server/2, to_ssl_server/3]).
-export([to_ssl_client/1, to_ssl_client/2, to_ssl_client/3]).
-export([type/1]).
-type protocol() :: 'tcp' | 'ssl'.
-type address() :: inet:ip_address() | string() | binary().
-type socket() :: ssl:sslsocket() | gen_tcp:socket().
-export_type([socket/0]).
-spec connect(Protocol :: protocol(), Address :: address(), Port :: pos_integer()) ->
{ok, socket()} | {error, any()}.
connect(Protocol, Address, Port) ->
connect(Protocol, Address, Port, [], infinity).
-spec connect(
Protocol :: protocol(), Address :: address(), Port :: pos_integer(), Options :: list()
) -> {ok, socket()} | {error, any()}.
connect(Protocol, Address, Port, Opts) ->
connect(Protocol, Address, Port, Opts, infinity).
-spec connect(
Protocol :: protocol(),
Address :: address(),
Port :: pos_integer(),
Options :: list(),
Time :: non_neg_integer() | 'infinity'
) -> {ok, socket()} | {error, any()}.
connect(tcp, Address, Port, Opts, Time) ->
gen_tcp:connect(Address, Port, tcp_connect_options(Opts), Time);
connect(ssl, Address, Port, Opts, Time) ->
ssl:connect(Address, Port, ssl_connect_options(Opts), Time).
-spec listen(Protocol :: protocol(), Port :: pos_integer()) -> {ok, socket()} | {error, any()}.
listen(Protocol, Port) ->
listen(Protocol, Port, []).
-spec listen(Protocol :: protocol(), Port :: pos_integer(), Options :: list()) ->
{ok, socket()} | {error, any()}.
listen(ssl, Port, Options) ->
ssl:listen(Port, ssl_listen_options(Options));
listen(tcp, Port, Options) ->
gen_tcp:listen(Port, tcp_listen_options(Options)).
-spec accept(Socket :: socket()) -> {'ok', socket()} | {'error', any()}.
accept(Socket) ->
accept(Socket, infinity).
-spec accept(Socket :: socket(), Timeout :: pos_integer() | 'infinity') ->
{'ok', socket()} | {'error', any()}.
accept(Socket, Timeout) when is_port(Socket) ->
case gen_tcp:accept(Socket, Timeout) of
{ok, NewSocket} ->
{ok, Opts} = inet:getopts(Socket, [active, keepalive, packet, reuseaddr]),
inet:setopts(NewSocket, Opts),
{ok, NewSocket};
{error, _} = Error ->
Error
end;
accept(Socket, Timeout) ->
case ssl:transport_accept(Socket, Timeout) of
{ok, NewSocket} ->
ssl:handshake(NewSocket);
{error, _} = Error ->
Error
end.
-spec send(Socket :: socket(), Data :: binary() | string() | iolist()) -> 'ok' | {'error', any()}.
send(Socket, Data) when is_port(Socket) ->
gen_tcp:send(Socket, Data);
send(Socket, Data) ->
ssl:send(Socket, Data).
-spec recv(Socket :: socket(), Length :: non_neg_integer()) -> {'ok', any()} | {'error', any()}.
recv(Socket, Length) ->
recv(Socket, Length, infinity).
-spec recv(
Socket :: socket(), Length :: non_neg_integer(), Timeout :: non_neg_integer() | 'infinity'
) -> {'ok', any()} | {'error', any()}.
recv(Socket, Length, Timeout) when is_port(Socket) ->
gen_tcp:recv(Socket, Length, Timeout);
recv(Socket, Length, Timeout) ->
ssl:recv(Socket, Length, Timeout).
-spec controlling_process(Socket :: socket(), NewOwner :: pid()) -> 'ok' | {'error', any()}.
controlling_process(Socket, NewOwner) when is_port(Socket) ->
gen_tcp:controlling_process(Socket, NewOwner);
controlling_process(Socket, NewOwner) ->
ssl:controlling_process(Socket, NewOwner).
-spec peername(Socket :: socket()) ->
{ok, {inet:ip_address(), non_neg_integer()}} | {'error', any()}.
peername(Socket) when is_port(Socket) ->
inet:peername(Socket);
peername(Socket) ->
ssl:peername(Socket).
-spec close(Socket :: socket()) -> 'ok'.
close(Socket) when is_port(Socket) ->
gen_tcp:close(Socket);
close(Socket) ->
ssl:close(Socket).
-spec shutdown(Socket :: socket(), How :: 'read' | 'write' | 'read_write') ->
'ok' | {'error', any()}.
shutdown(Socket, How) when is_port(Socket) ->
gen_tcp:shutdown(Socket, How);
shutdown(Socket, How) ->
ssl:shutdown(Socket, How).
-spec active_once(Socket :: socket()) -> 'ok' | {'error', any()}.
active_once(Socket) when is_port(Socket) ->
inet:setopts(Socket, [{active, once}]);
active_once(Socket) ->
ssl:setopts(Socket, [{active, once}]).
-spec setopts(Socket :: socket(), Options :: list()) -> 'ok' | {'error', any()}.
setopts(Socket, Options) when is_port(Socket) ->
inet:setopts(Socket, Options);
setopts(Socket, Options) ->
ssl:setopts(Socket, Options).
-spec get_proto(Socket :: any()) -> 'tcp' | 'ssl'.
get_proto(Socket) when is_port(Socket) ->
tcp;
get_proto(_Socket) ->
ssl.
-spec begin_inet_async(Socket :: socket()) -> any().
begin_inet_async(Socket) when is_port(Socket) ->
prim_inet:async_accept(Socket, -1);
begin_inet_async(Socket) ->
Port = extract_port_from_socket(Socket),
begin_inet_async(Port).
-spec handle_inet_async(Message :: {'inet_async', socket(), any(), {'ok', socket()}}) ->
{'ok', socket()}.
handle_inet_async({inet_async, ListenSocket, _, {ok, ClientSocket}}) ->
handle_inet_async(ListenSocket, ClientSocket, []).
-spec handle_inet_async(ListenSocket :: socket(), ClientSocket :: socket()) -> {'ok', socket()}.
handle_inet_async(ListenObject, ClientSocket) ->
handle_inet_async(ListenObject, ClientSocket, []).
-spec handle_inet_async(ListenSocket :: socket(), ClientSocket :: socket(), Options :: list()) ->
{'ok', socket()}.
handle_inet_async(ListenObject, ClientSocket, Options) ->
ListenSocket = extract_port_from_socket(ListenObject),
case set_sockopt(ListenSocket, ClientSocket) of
ok -> ok;
Error -> erlang:error(set_sockopt, Error)
end,
Signal the network driver that we are ready to accept another connection
begin_inet_async(ListenSocket),
case is_port(ListenObject) of
true ->
{ok, ClientSocket};
false ->
{ok, UpgradedClientSocket} = to_ssl_server(ClientSocket, Options),
{ok, UpgradedClientSocket}
end.
-spec to_ssl_server(Socket :: socket()) -> {'ok', ssl:sslsocket()} | {'error', any()}.
to_ssl_server(Socket) ->
to_ssl_server(Socket, []).
-spec to_ssl_server(Socket :: socket(), Options :: list()) ->
{'ok', ssl:sslsocket()} | {'error', any()}.
to_ssl_server(Socket, Options) ->
to_ssl_server(Socket, Options, infinity).
-spec to_ssl_server(
Socket :: socket(), Options :: list(), Timeout :: non_neg_integer() | 'infinity'
) -> {'ok', ssl:sslsocket()} | {'error', any()}.
to_ssl_server(Socket, Options, Timeout) when is_port(Socket) ->
ssl:handshake(Socket, ssl_listen_options(Options), Timeout);
to_ssl_server(_Socket, _Options, _Timeout) ->
{error, already_ssl}.
-spec to_ssl_client(Socket :: socket()) -> {'ok', ssl:sslsocket()} | {'error', 'already_ssl'}.
to_ssl_client(Socket) ->
to_ssl_client(Socket, []).
-spec to_ssl_client(Socket :: socket(), Options :: list()) ->
{'ok', ssl:sslsocket()} | {'error', 'already_ssl'}.
to_ssl_client(Socket, Options) ->
to_ssl_client(Socket, Options, infinity).
-spec to_ssl_client(
Socket :: socket(), Options :: list(), Timeout :: non_neg_integer() | 'infinity'
) -> {'ok', ssl:sslsocket()} | {'error', 'already_ssl'}.
to_ssl_client(Socket, Options, Timeout) when is_port(Socket) ->
ssl:connect(Socket, ssl_connect_options(Options), Timeout);
to_ssl_client(_Socket, _Options, _Timeout) ->
{error, already_ssl}.
-spec type(Socket :: socket()) -> protocol().
type(Socket) when is_port(Socket) ->
tcp;
type(_Socket) ->
ssl.
tcp_listen_options([Format | Options]) when Format =:= list; Format =:= binary ->
tcp_listen_options(Options, Format);
tcp_listen_options(Options) ->
tcp_listen_options(Options, list).
tcp_listen_options(Options, Format) ->
parse_address([Format | proplist_merge(Options, ?TCP_LISTEN_OPTIONS)]).
ssl_listen_options([Format | Options]) when Format =:= list; Format =:= binary ->
ssl_listen_options(Options, Format);
ssl_listen_options(Options) ->
ssl_listen_options(Options, list).
ssl_listen_options(Options, Format) ->
parse_address([Format | proplist_merge(Options, ?SSL_LISTEN_OPTIONS)]).
tcp_connect_options([Format | Options]) when Format =:= list; Format =:= binary ->
tcp_connect_options(Options, Format);
tcp_connect_options(Options) ->
tcp_connect_options(Options, list).
tcp_connect_options(Options, Format) ->
parse_address([Format | proplist_merge(Options, ?TCP_CONNECT_OPTIONS)]).
ssl_connect_options([Format | Options]) when Format =:= list; Format =:= binary ->
ssl_connect_options(Options, Format);
ssl_connect_options(Options) ->
ssl_connect_options(Options, list).
ssl_connect_options(Options, Format) ->
parse_address([Format | proplist_merge(Options, ?SSL_CONNECT_OPTIONS)]).
proplist_merge(PrimaryList, DefaultList) ->
{PrimaryTuples, PrimaryOther} = lists:partition(fun(X) -> is_tuple(X) end, PrimaryList),
{DefaultTuples, DefaultOther} = lists:partition(fun(X) -> is_tuple(X) end, DefaultList),
MergedTuples = lists:ukeymerge(
1,
lists:keysort(1, PrimaryTuples),
lists:keysort(1, DefaultTuples)
),
MergedOther = lists:umerge(lists:sort(PrimaryOther), lists:sort(DefaultOther)),
MergedTuples ++ MergedOther.
parse_address(Options) ->
case proplists:get_value(ip, Options) of
X when is_tuple(X) ->
Options;
X when is_list(X) ->
case inet_parse:address(X) of
{error, _} = Error ->
erlang:error(Error);
{ok, IP} ->
proplists:delete(ip, Options) ++ [{ip, IP}]
end;
_ ->
Options
end.
-spec extract_port_from_socket(Socket :: socket()) -> port().
extract_port_from_socket({sslsocket, _, {SSLPort, _}}) ->
SSLPort;
extract_port_from_socket(Socket) ->
Socket.
-spec set_sockopt(ListSock :: port(), CliSocket :: port()) -> 'ok' | any().
set_sockopt(ListenObject, ClientSocket) ->
ListenSocket = extract_port_from_socket(ListenObject),
true = inet_db:register_socket(ClientSocket, inet_tcp),
case prim_inet:getopts(ListenSocket, [active, nodelay, keepalive, delay_send, priority, tos]) of
{ok, Opts} ->
case prim_inet:setopts(ClientSocket, Opts) of
ok ->
ok;
Error ->
smtp_socket:close(ClientSocket),
Error
end;
Error ->
smtp_socket:close(ClientSocket),
Error
end.
-ifdef(TEST).
-define(TEST_PORT, 7586).
connect_test_() ->
[
{"listen and connect via tcp", fun() ->
Self = self(),
Port = ?TEST_PORT + 1,
Ref = make_ref(),
spawn(fun() ->
{ok, ListenSocket} = listen(tcp, Port),
?assert(is_port(ListenSocket)),
Self ! {Ref, listen},
{ok, ServerSocket} = accept(ListenSocket),
controlling_process(ServerSocket, Self),
Self ! {Ref, ListenSocket}
end),
receive
{Ref, listen} -> ok
end,
{ok, ClientSocket} = connect(tcp, "localhost", Port),
receive
{Ref, ListenSocket} when is_port(ListenSocket) -> ok
end,
?assert(is_port(ClientSocket)),
close(ListenSocket)
end},
{"listen and connect via ssl", fun() ->
Self = self(),
Port = ?TEST_PORT + 2,
Ref = make_ref(),
application:ensure_all_started(gen_smtp),
spawn(fun() ->
{ok, ListenSocket} = listen(ssl, Port, [
{keyfile, "test/fixtures/mx1.example.com-server.key"},
{certfile, "test/fixtures/mx1.example.com-server.crt"}
]),
?assertMatch([sslsocket | _], tuple_to_list(ListenSocket)),
Self ! {Ref, listen},
{ok, ServerSocket} = accept(ListenSocket),
controlling_process(ServerSocket, Self),
Self ! {Ref, ListenSocket}
end),
receive
{Ref, listen} -> ok
end,
{ok, ClientSocket} = connect(ssl, "localhost", Port, []),
receive
{Ref, {sslsocket, _, _} = ListenSocket} -> ok
end,
?assertMatch([sslsocket | _], tuple_to_list(ClientSocket)),
close(ListenSocket)
end}
].
evented_connections_test_() ->
[
{"current process receives connection to TCP listen sockets", fun() ->
Port = ?TEST_PORT + 3,
{ok, ListenSocket} = listen(tcp, Port),
begin_inet_async(ListenSocket),
spawn(fun() -> connect(tcp, "localhost", Port) end),
receive
{inet_async, ListenSocket, _, {ok, ServerSocket}} -> ok
end,
{ok, NewServerSocket} = handle_inet_async(ListenSocket, ServerSocket),
?assert(is_port(ServerSocket)),
?assertEqual(ServerSocket, NewServerSocket),
?assert(is_port(ListenSocket)),
spawn(fun() -> connect(tcp, "localhost", Port) end),
receive
_Ignored -> ok
end,
close(NewServerSocket),
close(ListenSocket)
end},
{"current process receives connection to SSL listen sockets", fun() ->
Port = ?TEST_PORT + 4,
application:ensure_all_started(gen_smtp),
{ok, ListenSocket} = listen(ssl, Port, [
{keyfile, "test/fixtures/mx1.example.com-server.key"},
{certfile, "test/fixtures/mx1.example.com-server.crt"}
]),
begin_inet_async(ListenSocket),
spawn(fun() -> connect(ssl, "localhost", Port) end),
receive
{inet_async, _ListenPort, _, {ok, ServerSocket}} -> ok
end,
{ok, NewServerSocket} = handle_inet_async(ListenSocket, ServerSocket, [
{keyfile, "test/fixtures/mx1.example.com-server.key"},
{certfile, "test/fixtures/mx1.example.com-server.crt"}
]),
?assert(is_port(ServerSocket)),
?assertMatch([sslsocket | _], tuple_to_list(NewServerSocket)),
?assertMatch([sslsocket | _], tuple_to_list(ListenSocket)),
spawn(fun() -> connect(ssl, "localhost", Port) end),
receive
_Ignored -> ok
end,
close(ListenSocket),
close(NewServerSocket),
ok
end},
{"current TCP listener receives SSL connection", fun() ->
Port = ?TEST_PORT + 5,
application:ensure_all_started(gen_smtp),
{ok, ListenSocket} = listen(tcp, Port),
begin_inet_async(ListenSocket),
spawn(fun() -> connect(ssl, "localhost", Port) end),
ServerSocket =
receive
{inet_async, _ListenPort, _, {ok, ServerSocket0}} -> ServerSocket0
end,
?assertMatch({ok, ServerSocket}, handle_inet_async(ListenSocket, ServerSocket)),
?assert(is_port(ListenSocket)),
?assert(is_port(ServerSocket)),
{ok, NewServerSocket} = to_ssl_server(ServerSocket, [
{certfile, "test/fixtures/mx1.example.com-server.crt"},
{keyfile, "test/fixtures/mx1.example.com-server.key"}
]),
?assertMatch([sslsocket | _], tuple_to_list(NewServerSocket)),
spawn(fun() -> connect(ssl, "localhost", Port) end),
receive
_Ignored -> ok
end,
close(ListenSocket),
close(NewServerSocket)
end}
].
accept_test_() ->
[
{"Accept via tcp", fun() ->
Port = ?TEST_PORT + 6,
{ok, ListenSocket} = listen(tcp, Port, tcp_listen_options([])),
?assert(is_port(ListenSocket)),
spawn(fun() -> connect(ssl, "localhost", Port, tcp_connect_options([])) end),
{ok, ServerSocket} = accept(ListenSocket),
?assert(is_port(ListenSocket)),
close(ServerSocket),
close(ListenSocket)
end},
{"Accept via ssl", fun() ->
Port = ?TEST_PORT + 7,
application:ensure_all_started(gen_smtp),
{ok, ListenSocket} = listen(ssl, Port, [
{keyfile, "test/fixtures/mx1.example.com-server.key"},
{certfile, "test/fixtures/mx1.example.com-server.crt"}
]),
?assertMatch([sslsocket | _], tuple_to_list(ListenSocket)),
spawn(fun() -> connect(ssl, "localhost", Port) end),
accept(ListenSocket),
close(ListenSocket)
end}
].
type_test_() ->
[
{"a tcp socket returns 'tcp'", fun() ->
{ok, ListenSocket} = listen(tcp, ?TEST_PORT + 8),
?assertMatch(tcp, type(ListenSocket)),
close(ListenSocket)
end},
{"an ssl socket returns 'ssl'", fun() ->
application:ensure_all_started(gen_smtp),
{ok, ListenSocket} = listen(ssl, ?TEST_PORT + 9, [
{keyfile, "test/fixtures/mx1.example.com-server.key"},
{certfile, "test/fixtures/mx1.example.com-server.crt"}
]),
?assertMatch(ssl, type(ListenSocket)),
close(ListenSocket)
end}
].
active_once_test_() ->
[
{"socket is set to active:once on tcp", fun() ->
{ok, ListenSocket} = listen(tcp, ?TEST_PORT + 10, tcp_listen_options([])),
?assertEqual({ok, [{active, false}]}, inet:getopts(ListenSocket, [active])),
active_once(ListenSocket),
?assertEqual({ok, [{active, once}]}, inet:getopts(ListenSocket, [active])),
close(ListenSocket)
end},
{"socket is set to active:once on ssl", fun() ->
{ok, ListenSocket} = listen(
ssl,
?TEST_PORT + 11,
ssl_listen_options([
{keyfile, "test/fixtures/mx1.example.com-server.key"},
{certfile, "test/fixtures/mx1.example.com-server.crt"}
])
),
?assertEqual({ok, [{active, false}]}, ssl:getopts(ListenSocket, [active])),
active_once(ListenSocket),
?assertEqual({ok, [{active, once}]}, ssl:getopts(ListenSocket, [active])),
close(ListenSocket)
end}
].
option_test_() ->
[
{"tcp_listen_options has defaults", fun() ->
?assertEqual(
lists:sort([list | ?TCP_LISTEN_OPTIONS]), lists:sort(tcp_listen_options([]))
)
end},
{"tcp_connect_options has defaults", fun() ->
?assertEqual(
lists:sort([list | ?TCP_CONNECT_OPTIONS]), lists:sort(tcp_connect_options([]))
)
end},
{"ssl_listen_options has defaults", fun() ->
?assertEqual(
lists:sort([list | ?SSL_LISTEN_OPTIONS]), lists:sort(ssl_listen_options([]))
)
end},
{"ssl_connect_options has defaults", fun() ->
?assertEqual(
lists:sort([list | ?SSL_CONNECT_OPTIONS]), lists:sort(ssl_connect_options([]))
)
end},
{"tcp_listen_options defaults to list type", fun() ->
?assertEqual(
lists:sort([list | ?TCP_LISTEN_OPTIONS]),
lists:sort(tcp_listen_options([{active, false}]))
),
?assertEqual(
lists:sort([binary | ?TCP_LISTEN_OPTIONS]),
lists:sort(tcp_listen_options([binary, {active, false}]))
)
end},
{"tcp_connect_options defaults to list type", fun() ->
?assertEqual(
lists:sort([list | ?TCP_CONNECT_OPTIONS]),
lists:sort(tcp_connect_options([{active, false}]))
),
?assertEqual(
lists:sort([binary | ?TCP_CONNECT_OPTIONS]),
lists:sort(tcp_connect_options([binary, {active, false}]))
)
end},
{"ssl_listen_options defaults to list type", fun() ->
?assertEqual(
lists:sort([list | ?SSL_LISTEN_OPTIONS]),
lists:sort(ssl_listen_options([{active, false}]))
),
?assertEqual(
lists:sort([binary | ?SSL_LISTEN_OPTIONS]),
lists:sort(ssl_listen_options([binary, {active, false}]))
)
end},
{"ssl_connect_options defaults to list type", fun() ->
?assertEqual(
lists:sort([list | ?SSL_CONNECT_OPTIONS]),
lists:sort(ssl_connect_options([{active, false}]))
),
?assertEqual(
lists:sort([binary | ?SSL_CONNECT_OPTIONS]),
lists:sort(ssl_connect_options([binary, {active, false}]))
)
end},
{"tcp_listen_options merges provided proplist", fun() ->
?assertEqual(
[
list
| lists:keysort(1, [
{active, true},
{backlog, 30},
{ip, {0, 0, 0, 0}},
{keepalive, true},
{packet, 2},
{reuseaddr, true}
])
],
tcp_listen_options([{active, true}, {packet, 2}])
)
end},
{"tcp_connect_options merges provided proplist", fun() ->
?assertEqual(
lists:sort([
list,
{active, true},
{packet, 2},
{ip, {0, 0, 0, 0}},
{port, 0}
]),
lists:sort(tcp_connect_options([{active, true}, {packet, 2}]))
)
end},
{"ssl_listen_options merges provided proplist", fun() ->
?assertEqual(
[
list
| lists:keysort(1, [
{active, true},
{backlog, 30},
{certfile, "server.crt"},
{depth, 0},
{keepalive, true},
{keyfile, "server.key"},
{packet, 2},
{reuse_sessions, false},
{reuseaddr, true}
])
],
ssl_listen_options([{active, true}, {packet, 2}])
),
?assertEqual(
[
list
| lists:keysort(1, [
{active, false},
{backlog, 30},
{certfile, "../server.crt"},
{depth, 0},
{keepalive, true},
{keyfile, "../server.key"},
{packet, line},
{reuse_sessions, false},
{reuseaddr, true}
])
],
ssl_listen_options([{certfile, "../server.crt"}, {keyfile, "../server.key"}])
)
end},
{"ssl_connect_options merges provided proplist", fun() ->
?assertEqual(
lists:sort([
list,
{active, true},
{depth, 0},
{ip, {0, 0, 0, 0}},
{port, 0},
{packet, 2}
]),
lists:sort(ssl_connect_options([{active, true}, {packet, 2}]))
)
end}
].
ssl_upgrade_test_() ->
[
{"TCP connection can be upgraded to ssl", fun() ->
Self = self(),
Port = ?TEST_PORT + 12,
application:ensure_all_started(gen_smtp),
spawn(fun() ->
{ok, ListenSocket} = listen(tcp, Port),
Self ! listening,
{ok, ServerSocket} = accept(ListenSocket),
{ok, NewServerSocket} = smtp_socket:to_ssl_server(
ServerSocket,
[
{keyfile, "test/fixtures/mx1.example.com-server.key"},
{certfile, "test/fixtures/mx1.example.com-server.crt"}
]
),
Self ! {sock, NewServerSocket}
end),
receive
listening -> ok
end,
erlang:yield(),
{ok, ClientSocket} = connect(tcp, "localhost", Port),
?assert(is_port(ClientSocket)),
{ok, NewClientSocket} = to_ssl_client(ClientSocket),
?assertMatch([sslsocket | _], tuple_to_list(NewClientSocket)),
receive
{sock, NewServerSocket} -> ok
end,
?assertMatch({sslsocket, _, _}, NewServerSocket),
close(NewClientSocket),
close(NewServerSocket)
end},
{"SSL server connection can't be upgraded again", fun() ->
Self = self(),
Port = ?TEST_PORT + 13,
application:ensure_all_started(gen_smtp),
spawn(fun() ->
{ok, ListenSocket} = listen(ssl, Port, [
{keyfile, "test/fixtures/mx1.example.com-server.key"},
{certfile, "test/fixtures/mx1.example.com-server.crt"}
]),
Self ! listening,
{ok, ServerSocket} = accept(ListenSocket),
?assertMatch({error, already_ssl}, to_ssl_server(ServerSocket)),
close(ServerSocket)
end),
receive
listening -> ok
end,
erlang:yield(),
{ok, ClientSocket} = connect(ssl, "localhost", Port),
close(ClientSocket)
end},
{"SSL client connection can't be upgraded again", fun() ->
Self = self(),
Port = ?TEST_PORT + 14,
application:ensure_all_started(gen_smtp),
spawn(fun() ->
{ok, ListenSocket} = listen(ssl, Port, [
{keyfile, "test/fixtures/mx1.example.com-server.key"},
{certfile, "test/fixtures/mx1.example.com-server.crt"}
]),
Self ! listening,
{ok, ServerSocket} = accept(ListenSocket),
Self ! {sock, ServerSocket}
end),
receive
listening -> ok
end,
erlang:yield(),
{ok, ClientSocket} = connect(ssl, "localhost", Port),
receive
{sock, ServerSocket} -> ok
end,
?assertMatch({error, already_ssl}, to_ssl_client(ClientSocket)),
close(ClientSocket),
close(ServerSocket)
end}
].
-endif.
|
022f838ce6676d64ae2c5a1fc73e21c6894845e173745ada39d96bb858dfeed4 | grin-compiler/ghc-wpc-sample-programs | Encoding.hs | -- |
-- Module : Basement.String.Encoding.Encoding
-- License : BSD-style
-- Maintainer : Foundation
-- Stability : experimental
-- Portability : portable
--
# LANGUAGE FlexibleContexts #
module Basement.String.Encoding.Encoding
( Encoding(..)
, convertFromTo
) where
import Basement.Compat.Base
import Basement.Types.OffsetSize
import Basement.Monad
import Basement.PrimType
import Basement.MutableBuilder
import Basement.Numerical.Additive
import Basement.UArray (UArray)
import Basement.UArray.Mutable (MUArray)
import qualified Basement.UArray as Vec
class Encoding encoding where
-- | the unit element use for the encoding.
i.e. Word8 for ASCII7 or UTF8 , ...
--
type Unit encoding
-- | define the type of error handling you want to use for the
-- next function.
--
> type Error UTF8 = Either UTF8_Invalid
--
type Error encoding
| consume an ` Unit encoding ` and return the Unicode point and the position
-- of the next possible `Unit encoding`
--
encodingNext :: encoding
-- ^ only used for type deduction
-> (Offset (Unit encoding) -> Unit encoding)
-- ^ method to access a given `Unit encoding`
-- (see `unsafeIndexer`)
-> Offset (Unit encoding)
-- ^ offset of the `Unit encoding` where starts the
-- encoding of a given unicode
-> Either (Error encoding) (Char, Offset (Unit encoding)) -- ^ either successfully validated the `Unit encoding`
-- and returned the next offset or fail with an
-- `Error encoding`
Write a unicode point encoded into one or multiple ` Unit encoding `
--
> build 64 $ sequence _ ( write UTF8 ) " this is a simple list of char ... "
--
encodingWrite :: (PrimMonad st, Monad st)
=> encoding
-- ^ only used for type deduction
-> Char
-- ^ the unicode character to encode
-> Builder (UArray (Unit encoding))
(MUArray (Unit encoding))
(Unit encoding) st err ()
-- | helper to convert a given Array in a given encoding into an array
-- with another encoding.
--
This is a helper to convert from one String encoding to another .
-- This function is (quite) slow and needs some work.
--
-- ```
let s16 = ... -- string in UTF16
-- create s8 , a UTF8 String
let s8 = runST $ convertWith UTF16 UTF8 ( toBytes s16 )
--
print s8
-- ```
--
convertFromTo :: ( PrimMonad st, Monad st
, Encoding input, PrimType (Unit input)
, Encoding output, PrimType (Unit output)
)
=> input
-- ^ Input's encoding type
-> output
-- ^ Output's encoding type
-> UArray (Unit input)
-- ^ the input raw array
-> st (Either (Offset (Unit input), Error input) (UArray (Unit output)))
convertFromTo inputEncodingTy outputEncodingTy bytes
| Vec.null bytes = return . return $ mempty
| otherwise = Vec.unsafeIndexer bytes $ \t -> Vec.builderBuild 64 (loop azero t)
where
lastUnit = Vec.length bytes
loop off getter
| off .==# lastUnit = return ()
| otherwise = case encodingNext inputEncodingTy getter off of
Left err -> mFail (off, err)
Right (c, noff) -> encodingWrite outputEncodingTy c >> loop noff getter
| null | https://raw.githubusercontent.com/grin-compiler/ghc-wpc-sample-programs/0e3a9b8b7cc3fa0da7c77fb7588dd4830fb087f7/basement-0.0.11/Basement/String/Encoding/Encoding.hs | haskell | |
Module : Basement.String.Encoding.Encoding
License : BSD-style
Maintainer : Foundation
Stability : experimental
Portability : portable
| the unit element use for the encoding.
| define the type of error handling you want to use for the
next function.
of the next possible `Unit encoding`
^ only used for type deduction
^ method to access a given `Unit encoding`
(see `unsafeIndexer`)
^ offset of the `Unit encoding` where starts the
encoding of a given unicode
^ either successfully validated the `Unit encoding`
and returned the next offset or fail with an
`Error encoding`
^ only used for type deduction
^ the unicode character to encode
| helper to convert a given Array in a given encoding into an array
with another encoding.
This function is (quite) slow and needs some work.
```
string in UTF16
create s8 , a UTF8 String
```
^ Input's encoding type
^ Output's encoding type
^ the input raw array |
# LANGUAGE FlexibleContexts #
module Basement.String.Encoding.Encoding
( Encoding(..)
, convertFromTo
) where
import Basement.Compat.Base
import Basement.Types.OffsetSize
import Basement.Monad
import Basement.PrimType
import Basement.MutableBuilder
import Basement.Numerical.Additive
import Basement.UArray (UArray)
import Basement.UArray.Mutable (MUArray)
import qualified Basement.UArray as Vec
class Encoding encoding where
i.e. Word8 for ASCII7 or UTF8 , ...
type Unit encoding
> type Error UTF8 = Either UTF8_Invalid
type Error encoding
| consume an ` Unit encoding ` and return the Unicode point and the position
encodingNext :: encoding
-> (Offset (Unit encoding) -> Unit encoding)
-> Offset (Unit encoding)
Write a unicode point encoded into one or multiple ` Unit encoding `
> build 64 $ sequence _ ( write UTF8 ) " this is a simple list of char ... "
encodingWrite :: (PrimMonad st, Monad st)
=> encoding
-> Char
-> Builder (UArray (Unit encoding))
(MUArray (Unit encoding))
(Unit encoding) st err ()
This is a helper to convert from one String encoding to another .
let s8 = runST $ convertWith UTF16 UTF8 ( toBytes s16 )
print s8
convertFromTo :: ( PrimMonad st, Monad st
, Encoding input, PrimType (Unit input)
, Encoding output, PrimType (Unit output)
)
=> input
-> output
-> UArray (Unit input)
-> st (Either (Offset (Unit input), Error input) (UArray (Unit output)))
convertFromTo inputEncodingTy outputEncodingTy bytes
| Vec.null bytes = return . return $ mempty
| otherwise = Vec.unsafeIndexer bytes $ \t -> Vec.builderBuild 64 (loop azero t)
where
lastUnit = Vec.length bytes
loop off getter
| off .==# lastUnit = return ()
| otherwise = case encodingNext inputEncodingTy getter off of
Left err -> mFail (off, err)
Right (c, noff) -> encodingWrite outputEncodingTy c >> loop noff getter
|
3ef4c8ab72815f66c78acb70d2b12fcfd957df431424fdb8b101bbde8c688d92 | GaloisInc/tower | Options.hs | {-# LANGUAGE RankNTypes #-}
module Ivory.Tower.Options
( TOpts(..)
, towerGetOpts
, parseOpts
, getOpts
, finalizeOpts
) where
import Prelude ()
import Prelude.Compat
import System.Console.GetOpt
(ArgOrder(Permute), OptDescr(..), getOpt', usageInfo)
import System.Exit (exitFailure)
import System.Environment (getArgs)
import qualified Ivory.Compile.C.CmdlineFrontend.Options as C
data TOpts = TOpts
{ topts_outdir :: Maybe FilePath
, topts_help :: Bool
, topts_args :: [String]
, topts_error :: forall a . String -> IO a
}
towerGetOpts :: IO (C.Opts, TOpts)
towerGetOpts = getArgs >>= getOpts
finalizeOpts :: TOpts -> IO ()
finalizeOpts topts = case topts_args topts of
[] -> case topts_help topts of
True -> topts_error topts "Usage:"
False -> return ()
as -> topts_error topts ("Unrecognized arguments:\n" ++ unlines as)
parseOpts :: [OptDescr (C.OptParser opt)] -> [String]
-> ([String], (Either [String] (opt -> opt)))
parseOpts opts args =
let (fs, ns, us, es) = getOpt' Permute opts args
(C.OptParser errs f) = mconcat fs
unused = ns ++ us
in case errs ++ es of
[] -> (unused, Right f)
e' -> (unused, Left e')
getOpts :: [String] -> IO (C.Opts, TOpts)
getOpts args = case mkCOpts of
Left es -> err (unlines es)
Right mkc -> do
let copts = mkc C.initialOpts
return (copts, TOpts
{ topts_outdir = C.outDir copts
, topts_help = C.help copts
, topts_args = unusedArgs
, topts_error = err
})
where
(unusedArgs, mkCOpts) = parseOpts C.options args
err s = do
putStrLn s
putStrLn ""
putStrLn "ivory-backend-c options:"
putStrLn $ usageInfo "" C.options
exitFailure
| null | https://raw.githubusercontent.com/GaloisInc/tower/a43f5e36c6443472ea2dc15bbd49faf8643a6f87/tower/src/Ivory/Tower/Options.hs | haskell | # LANGUAGE RankNTypes # |
module Ivory.Tower.Options
( TOpts(..)
, towerGetOpts
, parseOpts
, getOpts
, finalizeOpts
) where
import Prelude ()
import Prelude.Compat
import System.Console.GetOpt
(ArgOrder(Permute), OptDescr(..), getOpt', usageInfo)
import System.Exit (exitFailure)
import System.Environment (getArgs)
import qualified Ivory.Compile.C.CmdlineFrontend.Options as C
data TOpts = TOpts
{ topts_outdir :: Maybe FilePath
, topts_help :: Bool
, topts_args :: [String]
, topts_error :: forall a . String -> IO a
}
towerGetOpts :: IO (C.Opts, TOpts)
towerGetOpts = getArgs >>= getOpts
finalizeOpts :: TOpts -> IO ()
finalizeOpts topts = case topts_args topts of
[] -> case topts_help topts of
True -> topts_error topts "Usage:"
False -> return ()
as -> topts_error topts ("Unrecognized arguments:\n" ++ unlines as)
parseOpts :: [OptDescr (C.OptParser opt)] -> [String]
-> ([String], (Either [String] (opt -> opt)))
parseOpts opts args =
let (fs, ns, us, es) = getOpt' Permute opts args
(C.OptParser errs f) = mconcat fs
unused = ns ++ us
in case errs ++ es of
[] -> (unused, Right f)
e' -> (unused, Left e')
getOpts :: [String] -> IO (C.Opts, TOpts)
getOpts args = case mkCOpts of
Left es -> err (unlines es)
Right mkc -> do
let copts = mkc C.initialOpts
return (copts, TOpts
{ topts_outdir = C.outDir copts
, topts_help = C.help copts
, topts_args = unusedArgs
, topts_error = err
})
where
(unusedArgs, mkCOpts) = parseOpts C.options args
err s = do
putStrLn s
putStrLn ""
putStrLn "ivory-backend-c options:"
putStrLn $ usageInfo "" C.options
exitFailure
|
1952d814d2d101d493a9e897f45b9f6803eff74ac0f42249c56aab1a8f3094ac | pedropramos/PyonR | cpy-importing.rkt | (module cpy-importing racket
(require "runtime.rkt"
"libpython.rkt"
(for-syntax "libpython.rkt")
ffi/unsafe)
(provide (all-defined-out))
(define (cpy->racket x)
(let ([type (PyString_AsString
(PyObject_GetAttrString
(PyObject_Type x) "__name__"))])
(case type
[("bool") (bool-from-cpy x)]
[("int") (int-from-cpy x)]
[("long") (long-from-cpy x)]
[("float") (float-from-cpy x)]
[("complex") (complex-from-cpy x)]
[("str") (str-from-cpy x)]
;[("list") (list-from-cpy x)]
;[("tuple") (tuple-from-cpy x)]
;[("dict") (dict-from-cpy x)]
;[("dictproxy") (dictproxy-from-cpy x)]
[("type") (type-from-cpy x)]
[("module") (module-from-cpy x)]
[("NoneType") py-None]
[else ;(printf "cpy->racket: wrapping value ~a of type ~a\n" (PyString_AsString (PyObject_Repr x)) type)
(proxy-obj-from-cpy x)])))
(define (racket->cpy x)
(cond
[(boolean? x) (make-cpy-bool x)]
[(exact-integer? x) (if (and (<= x 2147483647)
(>= x -2147483648))
(make-cpy-int x)
(make-cpy-long x))]
[(flonum? x) (make-cpy-float x)]
[(complex? x) (make-cpy-complex x)]
[(string? x) (make-cpy-str x)]
[(vector? x) (make-cpy-tuple x)]
[(void? x) cpy-none]
[(proxy-type-object? x) (unwrap-proxy-type-object x)]
[(proxy-object? x) (unwrap-proxy-object x)]
[else (error "racket->cpy: value not supported:" x)]))
(define-for-syntax (check-cpyimport-for-error stx)
(cond
[(not path-to-cpython-lib)
(raise-syntax-error 'cpyimport "The 'cpyimport' statement is not available because PyonR could not find Python 2.7 installed on your system." stx)]
[(not cpyimport-enabled)
(raise-syntax-error 'cpyimport "The 'cpyimport' statement is disabled.\n To enable it, require the module 'python/config' from Racket and run (enable-cpyimport!)" stx)]))
(define-syntax (cpy-import stx)
(check-cpyimport-for-error stx)
(syntax-case stx (as)
[(_ module-name as id)
(begin
(Py_Initialize)
#'(define id (module-from-cpy
(PyImport_Import
(PyString_FromString module-name)))))]))
(define-syntax (cpy-from stx)
(check-cpyimport-for-error stx)
(syntax-case stx (import as)
[(_ module-name import ((orig-name as bind-id) ...))
(begin
(Py_Initialize)
#'(begin
(define bind-id 'undefined)
...
(let ([cpy-module (PyImport_Import
(PyString_FromString module-name))])
(set! bind-id (cpy->racket
(PyObject_GetAttrString cpy-module orig-name)))
...)))]))
(require (for-syntax (only-in "name-mangling.rkt" string->colon-symbol)))
(define-syntax (cpy-from-import-* stx)
(check-cpyimport-for-error stx)
(syntax-case stx ()
[(_ module-name)
(begin
(Py_Initialize)
(let* ([bindings-names (cpy-module-exports (syntax->datum #'module-name))]
[bindings (map string->colon-symbol bindings-names)])
#`(begin
(define cpy-module (PyImport_Import (PyString_FromString module-name)))
#,@(for/list ([binding/str bindings-names]
[binding/sym bindings])
(with-syntax ([id (datum->syntax stx binding/sym)]
[id-name (datum->syntax stx binding/str)])
#'(define id (cpy->racket
(PyObject_GetAttrString cpy-module id-name))))))))]))
(require (for-syntax "libpython.rkt"))
(define-for-syntax (cpy-module-exports module-name)
(let* ([cpy-module (PyImport_Import (PyString_FromString module-name))]
[cpy-exports (PyDict_Keys (PyModule_GetDict cpy-module))]
[len (PyList_Size cpy-exports)])
(filter (lambda (str) (not (eq? (string-ref str 0) #\_)))
(for/list ([i (in-range len)])
(PyString_AsString (PyList_GetItem cpy-exports i))))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(define (make-cpy-bool b)
(PyBool_FromLong (if b 1 0)))
(define (make-cpy-int i)
(PyInt_FromLong i))
(define (make-cpy-long l)
(PyLong_FromString (number->string l) 0 10))
(define (make-cpy-float f)
(PyFloat_FromDouble (+ f 0.0)))
(define (make-cpy-complex c)
(PyComplex_FromCComplex (make-Py_complex (+ (real-part c) 0.0)
(+ (imag-part c) 0.0))))
(define (make-cpy-str s)
(PyString_FromString s))
(define (make-cpy-tuple v)
(let* ([len (vector-length v)]
[cpy-tuple (PyTuple_New len)])
(for ([i (in-range len)]
[item (in-vector v)])
(PyTuple_SetItem cpy-tuple i (racket->cpy item)))
cpy-tuple))
(define cpy-none (get_PyNone))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(define recursion-cache (make-parameter (hash)))
(define (bool-from-cpy x)
(= (PyObject_IsTrue x) 1))
(define (int-from-cpy x)
(PyInt_AsLong x))
(define (long-from-cpy x)
(string->number
(PyString_AsString
(PyObject_Str x))))
(define (float-from-cpy x)
(PyFloat_AsDouble x))
(define (complex-from-cpy x)
(let ([ccomplex (PyComplex_AsCComplex x)])
(make-rectangular (Py_complex-real ccomplex)
(Py_complex-imag ccomplex))))
(define (str-from-cpy x)
(with-handlers ([exn:fail?
(lambda (e) "ERROR")])
(PyString_AsString x)))
(define (list-from-cpy x)
(let* ([id-x (cpointer-id x)]
[cached (hash-ref (recursion-cache) id-x #f)])
(or cached
(let* ([len (PyList_Size x)]
[result (vector->py-list (make-vector len))])
(parameterize ([recursion-cache (hash-set (recursion-cache) id-x result)])
(for ([i (in-range len)])
(py-list-setitem! result i (cpy->racket (PyList_GetItem x i))))
result)))))
(define (tuple-from-cpy x)
(let* ([id-x (cpointer-id x)]
[cached (hash-ref (recursion-cache) id-x #f)])
(or cached
(let* ([len (PyTuple_Size x)]
[result (make-vector len)])
(parameterize ([recursion-cache (hash-set (recursion-cache) id-x result)])
(for ([i (in-range len)])
(vector-set! result i (cpy->racket (PyTuple_GetItem x i))))
result)))))
;; used only for holding attribute/method names as keys (implemented as symbols)
(define (symdict-from-cpy x)
(let* ([id-x (cpointer-id x)]
[cached (hash-ref (recursion-cache) id-x #f)])
(or cached
(let* ([cpy-keys (PyDict_Keys x)]
[size (PyList_Size cpy-keys)]
[result (make-hasheq)])
(parameterize ([recursion-cache (hash-set (recursion-cache) id-x result)])
(for ([i (in-range size)])
(let ([cpy-key (PyList_GetItem cpy-keys i)])
(hash-set! result
(string->symbol (cpy->racket cpy-key))
(cpy->racket (PyDict_GetItem x cpy-key)))))
result)))))
;; used only for holding attribute/method names as keys (implemented as strings)
(define (strdict-from-cpy x)
(let* ([id-x (cpointer-id x)]
[cached (hash-ref (recursion-cache) id-x #f)])
(or cached
(let* ([cpy-keys (PyDict_Keys x)]
[size (PyList_Size cpy-keys)]
[result (make-hash)])
(parameterize ([recursion-cache (hash-set (recursion-cache) id-x result)])
(for ([i (in-range size)])
(let ([cpy-key (PyList_GetItem cpy-keys i)])
(hash-set! result
(cpy->racket cpy-key)
(cpy->racket (PyDict_GetItem x cpy-key)))))
result)))))
(define (module-from-cpy x)
(make-py-module (str-from-cpy (PyObject_GetAttrString x "__name__"))
(strdict-from-cpy (PyObject_GetAttrString x "__dict__"))))
(define (exception-from-cpy x)
(exception_obj (cpy->racket (PyObject_Type x))
(let ([args (PyObject_GetAttrString x "args")])
(if args (cpy->racket args) (make-py-tuple)))
(let ([message (PyObject_GetAttrString x "message")])
(if message
(cpy->racket message)
(PyString_AsString (PyObject_Repr x))))
(current-continuation-marks)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(struct proxy-object python-object
(ffi-object)
#:transparent
#:property prop:procedure
(cpy-call-generator #:unwrapper unwrap-proxy-object))
(define-syntax-rule (cpy-call-generator #:unwrapper unwrapper)
(lambda (f . args)
(let ([ffi_call_result
(PyObject_CallObject (unwrapper f)
(list->cpy-tuple (map racket->cpy args)))])
(if ffi_call_result
(cpy->racket ffi_call_result)
(let ([cpy-exception (second (apply PyErr_NormalizeException (PyErr_Fetch)))])
(raise (exception-from-cpy cpy-exception)))))))
(define (proxy-obj-from-cpy x)
(proxy-object (cpy->racket (PyObject_Type x)) x))
(define (unwrap-proxy-object proxy)
(proxy-object-ffi-object proxy))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(define type-cache (make-custom-hash ptr-equal? cpointer-id))
(struct proxy-type-object type_obj
(ffi-object)
#:mutable
#:property prop:procedure
(cpy-call-generator #:unwrapper unwrap-proxy-type-object))
(define (empty-proxy-type)
(proxy-type-object #f
#f #f #f #f #f #f
#f #f
#f))
(define-syntax-rule (fill-proxy-type! (id ffi-obj))
(begin
(set-python-object-type! id py-type)
(set-type_obj-name! id (str-from-cpy (PyObject_GetAttrString ffi-obj "__name__")))
(set-type_obj-module! id (str-from-cpy (PyObject_GetAttrString ffi-obj "__module__")))
(set-type_obj-bases! id (tuple-from-cpy (PyObject_GetAttrString ffi-obj "__bases__")))
(set-type_obj-doc! id (cpy->racket (PyObject_GetAttrString ffi-obj "__doc__")))
(set-type_obj-dict! id (symdict-from-cpy (PyType_Dict ffi-obj)))
(set-type_obj-mro! id (tuple-from-cpy (PyObject_GetAttrString ffi-obj "__mro__")))
;(set-type_obj-getter! id (let ([getter (PyObject_GetAttrString ffi-obj "__get__")])
; (if getter (cpy->racket getter) getter)))
;(set-type_obj-setter! id (let ([setter (PyObject_GetAttrString ffi-obj "__set__")])
; (if setter (cpy->racket setter) setter)))
(set-proxy-type-object-ffi-object! id ffi-obj)))
(define (type-from-cpy x)
(let* ([cached (dict-ref type-cache x #f)])
(or cached
(let ([result (empty-proxy-type)])
(dict-set! type-cache x result)
(fill-proxy-type! (result x))
result))))
(define (unwrap-proxy-type-object proxy)
(proxy-type-object-ffi-object proxy))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(define (list->cpy-tuple lst)
(let* ([len (length lst)]
[cpy-tuple (PyTuple_New len)])
(for ([i (in-range len)]
[item (in-list lst)])
(PyTuple_SetItem cpy-tuple i item))
cpy-tuple))
) | null | https://raw.githubusercontent.com/pedropramos/PyonR/16edd14f3950fd5a01f8b0237e023536ef48d17b/cpy-importing.rkt | racket | [("list") (list-from-cpy x)]
[("tuple") (tuple-from-cpy x)]
[("dict") (dict-from-cpy x)]
[("dictproxy") (dictproxy-from-cpy x)]
(printf "cpy->racket: wrapping value ~a of type ~a\n" (PyString_AsString (PyObject_Repr x)) type)
used only for holding attribute/method names as keys (implemented as symbols)
used only for holding attribute/method names as keys (implemented as strings)
(set-type_obj-getter! id (let ([getter (PyObject_GetAttrString ffi-obj "__get__")])
(if getter (cpy->racket getter) getter)))
(set-type_obj-setter! id (let ([setter (PyObject_GetAttrString ffi-obj "__set__")])
(if setter (cpy->racket setter) setter)))
| (module cpy-importing racket
(require "runtime.rkt"
"libpython.rkt"
(for-syntax "libpython.rkt")
ffi/unsafe)
(provide (all-defined-out))
(define (cpy->racket x)
(let ([type (PyString_AsString
(PyObject_GetAttrString
(PyObject_Type x) "__name__"))])
(case type
[("bool") (bool-from-cpy x)]
[("int") (int-from-cpy x)]
[("long") (long-from-cpy x)]
[("float") (float-from-cpy x)]
[("complex") (complex-from-cpy x)]
[("str") (str-from-cpy x)]
[("type") (type-from-cpy x)]
[("module") (module-from-cpy x)]
[("NoneType") py-None]
(proxy-obj-from-cpy x)])))
(define (racket->cpy x)
(cond
[(boolean? x) (make-cpy-bool x)]
[(exact-integer? x) (if (and (<= x 2147483647)
(>= x -2147483648))
(make-cpy-int x)
(make-cpy-long x))]
[(flonum? x) (make-cpy-float x)]
[(complex? x) (make-cpy-complex x)]
[(string? x) (make-cpy-str x)]
[(vector? x) (make-cpy-tuple x)]
[(void? x) cpy-none]
[(proxy-type-object? x) (unwrap-proxy-type-object x)]
[(proxy-object? x) (unwrap-proxy-object x)]
[else (error "racket->cpy: value not supported:" x)]))
(define-for-syntax (check-cpyimport-for-error stx)
(cond
[(not path-to-cpython-lib)
(raise-syntax-error 'cpyimport "The 'cpyimport' statement is not available because PyonR could not find Python 2.7 installed on your system." stx)]
[(not cpyimport-enabled)
(raise-syntax-error 'cpyimport "The 'cpyimport' statement is disabled.\n To enable it, require the module 'python/config' from Racket and run (enable-cpyimport!)" stx)]))
(define-syntax (cpy-import stx)
(check-cpyimport-for-error stx)
(syntax-case stx (as)
[(_ module-name as id)
(begin
(Py_Initialize)
#'(define id (module-from-cpy
(PyImport_Import
(PyString_FromString module-name)))))]))
(define-syntax (cpy-from stx)
(check-cpyimport-for-error stx)
(syntax-case stx (import as)
[(_ module-name import ((orig-name as bind-id) ...))
(begin
(Py_Initialize)
#'(begin
(define bind-id 'undefined)
...
(let ([cpy-module (PyImport_Import
(PyString_FromString module-name))])
(set! bind-id (cpy->racket
(PyObject_GetAttrString cpy-module orig-name)))
...)))]))
(require (for-syntax (only-in "name-mangling.rkt" string->colon-symbol)))
(define-syntax (cpy-from-import-* stx)
(check-cpyimport-for-error stx)
(syntax-case stx ()
[(_ module-name)
(begin
(Py_Initialize)
(let* ([bindings-names (cpy-module-exports (syntax->datum #'module-name))]
[bindings (map string->colon-symbol bindings-names)])
#`(begin
(define cpy-module (PyImport_Import (PyString_FromString module-name)))
#,@(for/list ([binding/str bindings-names]
[binding/sym bindings])
(with-syntax ([id (datum->syntax stx binding/sym)]
[id-name (datum->syntax stx binding/str)])
#'(define id (cpy->racket
(PyObject_GetAttrString cpy-module id-name))))))))]))
(require (for-syntax "libpython.rkt"))
(define-for-syntax (cpy-module-exports module-name)
(let* ([cpy-module (PyImport_Import (PyString_FromString module-name))]
[cpy-exports (PyDict_Keys (PyModule_GetDict cpy-module))]
[len (PyList_Size cpy-exports)])
(filter (lambda (str) (not (eq? (string-ref str 0) #\_)))
(for/list ([i (in-range len)])
(PyString_AsString (PyList_GetItem cpy-exports i))))))
(define (make-cpy-bool b)
(PyBool_FromLong (if b 1 0)))
(define (make-cpy-int i)
(PyInt_FromLong i))
(define (make-cpy-long l)
(PyLong_FromString (number->string l) 0 10))
(define (make-cpy-float f)
(PyFloat_FromDouble (+ f 0.0)))
(define (make-cpy-complex c)
(PyComplex_FromCComplex (make-Py_complex (+ (real-part c) 0.0)
(+ (imag-part c) 0.0))))
(define (make-cpy-str s)
(PyString_FromString s))
(define (make-cpy-tuple v)
(let* ([len (vector-length v)]
[cpy-tuple (PyTuple_New len)])
(for ([i (in-range len)]
[item (in-vector v)])
(PyTuple_SetItem cpy-tuple i (racket->cpy item)))
cpy-tuple))
(define cpy-none (get_PyNone))
(define recursion-cache (make-parameter (hash)))
(define (bool-from-cpy x)
(= (PyObject_IsTrue x) 1))
(define (int-from-cpy x)
(PyInt_AsLong x))
(define (long-from-cpy x)
(string->number
(PyString_AsString
(PyObject_Str x))))
(define (float-from-cpy x)
(PyFloat_AsDouble x))
(define (complex-from-cpy x)
(let ([ccomplex (PyComplex_AsCComplex x)])
(make-rectangular (Py_complex-real ccomplex)
(Py_complex-imag ccomplex))))
(define (str-from-cpy x)
(with-handlers ([exn:fail?
(lambda (e) "ERROR")])
(PyString_AsString x)))
(define (list-from-cpy x)
(let* ([id-x (cpointer-id x)]
[cached (hash-ref (recursion-cache) id-x #f)])
(or cached
(let* ([len (PyList_Size x)]
[result (vector->py-list (make-vector len))])
(parameterize ([recursion-cache (hash-set (recursion-cache) id-x result)])
(for ([i (in-range len)])
(py-list-setitem! result i (cpy->racket (PyList_GetItem x i))))
result)))))
(define (tuple-from-cpy x)
(let* ([id-x (cpointer-id x)]
[cached (hash-ref (recursion-cache) id-x #f)])
(or cached
(let* ([len (PyTuple_Size x)]
[result (make-vector len)])
(parameterize ([recursion-cache (hash-set (recursion-cache) id-x result)])
(for ([i (in-range len)])
(vector-set! result i (cpy->racket (PyTuple_GetItem x i))))
result)))))
(define (symdict-from-cpy x)
(let* ([id-x (cpointer-id x)]
[cached (hash-ref (recursion-cache) id-x #f)])
(or cached
(let* ([cpy-keys (PyDict_Keys x)]
[size (PyList_Size cpy-keys)]
[result (make-hasheq)])
(parameterize ([recursion-cache (hash-set (recursion-cache) id-x result)])
(for ([i (in-range size)])
(let ([cpy-key (PyList_GetItem cpy-keys i)])
(hash-set! result
(string->symbol (cpy->racket cpy-key))
(cpy->racket (PyDict_GetItem x cpy-key)))))
result)))))
(define (strdict-from-cpy x)
(let* ([id-x (cpointer-id x)]
[cached (hash-ref (recursion-cache) id-x #f)])
(or cached
(let* ([cpy-keys (PyDict_Keys x)]
[size (PyList_Size cpy-keys)]
[result (make-hash)])
(parameterize ([recursion-cache (hash-set (recursion-cache) id-x result)])
(for ([i (in-range size)])
(let ([cpy-key (PyList_GetItem cpy-keys i)])
(hash-set! result
(cpy->racket cpy-key)
(cpy->racket (PyDict_GetItem x cpy-key)))))
result)))))
(define (module-from-cpy x)
(make-py-module (str-from-cpy (PyObject_GetAttrString x "__name__"))
(strdict-from-cpy (PyObject_GetAttrString x "__dict__"))))
(define (exception-from-cpy x)
(exception_obj (cpy->racket (PyObject_Type x))
(let ([args (PyObject_GetAttrString x "args")])
(if args (cpy->racket args) (make-py-tuple)))
(let ([message (PyObject_GetAttrString x "message")])
(if message
(cpy->racket message)
(PyString_AsString (PyObject_Repr x))))
(current-continuation-marks)))
(struct proxy-object python-object
(ffi-object)
#:transparent
#:property prop:procedure
(cpy-call-generator #:unwrapper unwrap-proxy-object))
(define-syntax-rule (cpy-call-generator #:unwrapper unwrapper)
(lambda (f . args)
(let ([ffi_call_result
(PyObject_CallObject (unwrapper f)
(list->cpy-tuple (map racket->cpy args)))])
(if ffi_call_result
(cpy->racket ffi_call_result)
(let ([cpy-exception (second (apply PyErr_NormalizeException (PyErr_Fetch)))])
(raise (exception-from-cpy cpy-exception)))))))
(define (proxy-obj-from-cpy x)
(proxy-object (cpy->racket (PyObject_Type x)) x))
(define (unwrap-proxy-object proxy)
(proxy-object-ffi-object proxy))
(define type-cache (make-custom-hash ptr-equal? cpointer-id))
(struct proxy-type-object type_obj
(ffi-object)
#:mutable
#:property prop:procedure
(cpy-call-generator #:unwrapper unwrap-proxy-type-object))
(define (empty-proxy-type)
(proxy-type-object #f
#f #f #f #f #f #f
#f #f
#f))
(define-syntax-rule (fill-proxy-type! (id ffi-obj))
(begin
(set-python-object-type! id py-type)
(set-type_obj-name! id (str-from-cpy (PyObject_GetAttrString ffi-obj "__name__")))
(set-type_obj-module! id (str-from-cpy (PyObject_GetAttrString ffi-obj "__module__")))
(set-type_obj-bases! id (tuple-from-cpy (PyObject_GetAttrString ffi-obj "__bases__")))
(set-type_obj-doc! id (cpy->racket (PyObject_GetAttrString ffi-obj "__doc__")))
(set-type_obj-dict! id (symdict-from-cpy (PyType_Dict ffi-obj)))
(set-type_obj-mro! id (tuple-from-cpy (PyObject_GetAttrString ffi-obj "__mro__")))
(set-proxy-type-object-ffi-object! id ffi-obj)))
(define (type-from-cpy x)
(let* ([cached (dict-ref type-cache x #f)])
(or cached
(let ([result (empty-proxy-type)])
(dict-set! type-cache x result)
(fill-proxy-type! (result x))
result))))
(define (unwrap-proxy-type-object proxy)
(proxy-type-object-ffi-object proxy))
(define (list->cpy-tuple lst)
(let* ([len (length lst)]
[cpy-tuple (PyTuple_New len)])
(for ([i (in-range len)]
[item (in-list lst)])
(PyTuple_SetItem cpy-tuple i item))
cpy-tuple))
) |
404dd518fb13c198f7b8e511c8b18835e68b5f454644770465d8e7f4be299bb5 | janestreet/async_ssl | ffi__library_must_be_initialized.ml | open Core
open Poly
open Async
open Import
module Ssl_method = Bindings.Ssl_method
module Ssl_error = struct
type t =
| Zero_return
| Want_read
| Want_write
| Want_connect
| Want_accept
| Want_X509_lookup
| Syscall_error
| Ssl_error
[@@deriving sexp_of]
let of_int n =
let open Types.Ssl_error in
if n = none
then Ok ()
else if n = zero_return
then Error Zero_return
else if n = want_read
then Error Want_read
else if n = want_write
then Error Want_write
else if n = want_connect
then Error Want_connect
else if n = want_accept
then Error Want_accept
else if n = want_x509_lookup
then Error Want_X509_lookup
else if n = syscall
then Error Syscall_error
else if n = ssl
then Error Ssl_error
else failwithf "Unrecognized result of SSL_get_error: %d" n ()
;;
end
module Verify_mode = struct
include Verify_mode
let to_int t =
let open Types.Verify_mode in
match t with
| Verify_none -> verify_none
| Verify_peer -> verify_peer
| Verify_fail_if_no_peer_cert -> verify_fail_if_no_peer_cert
| Verify_client_once -> verify_client_once
;;
end
let bigstring_strlen bigstr =
let len = Bigstring.length bigstr in
let idx = ref 0 in
while !idx < len && bigstr.{!idx} <> '\x00' do
incr idx
done;
!idx
;;
let get_error_stack =
let err_error_string =
We need to write error strings from C into bigstrings . To reduce allocation , reuse
scratch space for this .
scratch space for this. *)
let scratch_space = Bigstring.create 1024 in
fun err ->
Bindings.err_error_string_n
err
(Ctypes.bigarray_start Ctypes.array1 scratch_space)
(Bigstring.length scratch_space);
Bigstring.to_string ~len:(bigstring_strlen scratch_space) scratch_space
in
fun () ->
iter_while_rev ~iter:Bindings.err_get_error ~cond:(fun x -> x <> Unsigned.ULong.zero)
|> List.rev_map ~f:err_error_string
;;
module Ssl_ctx = struct
type t = Bindings.Ssl_ctx.t [@@deriving sexp_of]
(* for use in ctypes type signatures *)
let create_exn ver =
let ver_method =
let module V = Version in
match ver with
| V.Sslv23 -> Ssl_method.sslv23 ()
| V.Tls -> Ssl_method.tls ()
| V.Sslv3 -> Ssl_method.sslv3 ()
| V.Tlsv1 -> Ssl_method.tlsv1 ()
| V.Tlsv1_1 -> Ssl_method.tlsv1_1 ()
| V.Tlsv1_2 -> Ssl_method.tlsv1_2 ()
| V.Tlsv1_3 -> Ssl_method.tlsv1_3 ()
in
match Bindings.Ssl_ctx.new_ ver_method with
| None -> failwith "Could not allocate a new SSL context."
| Some p ->
Gc.add_finalizer_exn p Bindings.Ssl_ctx.free;
p
;;
let override_default_insecure__set_security_level t level =
Bindings.Ssl_ctx.override_default_insecure__set_security_level t level
;;
let set_options context options =
let module O = Types.Ssl_op in
let default_options =
List.fold
[ O.single_dh_use; O.single_ecdh_use ]
~init:Unsigned.ULong.zero
~f:Unsigned.ULong.logor
in
let opts =
List.fold options ~init:default_options ~f:(fun acc (opt : Opt.t) ->
let o =
match opt with
| No_sslv2 -> O.no_sslv2
| No_sslv3 -> O.no_sslv3
| No_tlsv1 -> O.no_tlsv1
| No_tlsv1_1 -> O.no_tlsv1_1
| No_tlsv1_2 -> O.no_tlsv1_2
| No_tlsv1_3 -> O.no_tlsv1_3
in
Unsigned.ULong.logor acc o)
in
(* SSL_CTX_set_options(3) returns the new options bitmask after adding options. We
don't really have a use for this, so ignore. *)
let (_ : Unsigned.ULong.t) = Bindings.Ssl_ctx.set_options context opts in
()
;;
let set_session_id_context context sid_ctx =
let session_id_ctx = Ctypes.(coerce string (ptr char)) sid_ctx in
match
Bindings.Ssl_ctx.set_session_id_context
context
session_id_ctx
(Unsigned.UInt.of_int (String.length sid_ctx))
with
| 1 -> ()
| x ->
failwiths
~here:[%here]
"Could not set session id context."
(`Return_value x, `Errors (get_error_stack ()))
[%sexp_of: [ `Return_value of int ] * [ `Errors of string list ]]
;;
let load_verify_locations ?ca_file ?ca_path ctx =
match%bind
In_thread.run (fun () -> Bindings.Ssl_ctx.load_verify_locations ctx ca_file ca_path)
with
Yep , 1 means success .
| 1 -> Deferred.return (Or_error.return ())
| _ ->
Deferred.return
(match ca_file, ca_path with
| None, None -> Or_error.error_string "No CA files given."
| _ -> Or_error.error "CA load error" (get_error_stack ()) [%sexp_of: string list])
;;
let set_default_verify_paths ctx =
match Bindings.Ssl_ctx.set_default_verify_paths ctx with
| 1 -> ()
| x ->
failwiths
~here:[%here]
"Could not set default verify paths."
(`Return_value x, `Errors (get_error_stack ()))
[%sexp_of: [ `Return_value of int ] * [ `Errors of string list ]]
;;
let try_certificate_chain_and_failover_to_asn1 ctx crt_file =
match Bindings.Ssl_ctx.use_certificate_chain_file ctx crt_file with
| 1 -> 1
| _ -> Bindings.Ssl_ctx.use_certificate_file ctx crt_file Types.X509_filetype.asn1
;;
let try_both_private_key_formats ctx key_file =
match Bindings.Ssl_ctx.use_private_key_file ctx key_file Types.X509_filetype.pem with
| 1 -> 1
| _ -> Bindings.Ssl_ctx.use_private_key_file ctx key_file Types.X509_filetype.asn1
;;
let use_certificate_chain_and_key_files ~crt_file ~key_file ctx =
let error i =
Deferred.Or_error.error
"Could not set default verify paths."
(`Return_value i, `Errors (get_error_stack ()))
[%sexp_of: [ `Return_value of int ] * [ `Errors of string list ]]
in
match%bind
In_thread.run (fun () -> try_certificate_chain_and_failover_to_asn1 ctx crt_file)
with
| 1 ->
(match%bind In_thread.run (fun () -> try_both_private_key_formats ctx key_file) with
| 1 -> Deferred.Or_error.return ()
| x -> error x)
| x -> error x
;;
end
module Bio = struct
type t = Bindings.Bio.t [@@deriving sexp_of]
for use in ctypes signatures
let create () = Bindings.Bio.s_mem () |> Bindings.Bio.new_
let read bio ~buf ~len =
let retval = Bindings.Bio.read bio buf len in
if verbose then Debug.amf [%here] "BIO_read(%i) -> %i" len retval;
retval
;;
let write bio ~buf ~len =
let retval = Bindings.Bio.write bio buf len in
if verbose then Debug.amf [%here] "BIO_write(%i) -> %i" len retval;
retval
;;
end
module ASN1_object = struct
type t = Bindings.ASN1_object.t
let obj2nid = Bindings.ASN1_object.obj2nid
let nid2sn n =
Option.value
(Bindings.ASN1_object.nid2sn n)
~default:(sprintf "unknown object nid (%d)" n)
;;
end
module ASN1_string = struct
type t = Bindings.ASN1_string.t
let data t = Bindings.ASN1_string.data t
end
module X509_name_entry = struct
type t = Bindings.X509_name_entry.t
let get_object = Bindings.X509_name_entry.get_object
let get_data = Bindings.X509_name_entry.get_data
end
module X509_name = struct
type t = Bindings.X509_name.t
let entry_count = Bindings.X509_name.entry_count
let get_entry = Bindings.X509_name.get_entry
end
module X509 = struct
type t = Bindings.X509.t
let get_subject_name t =
match Bindings.X509.get_subject_name t with
| Some name -> name
| None -> failwith "Certificate contains no subject name."
;;
let get_subject_alt_names t =
let open Ctypes in
match Bindings.X509.subject_alt_names t with
| None -> failwith "Failed to allocate memory in subject_alt_names()"
| Some results_p_p ->
protect
~f:(fun () ->
let rec loop acc p =
match !@p with
| None -> List.rev acc
| Some san ->
(match coerce (ptr char) string_opt san with
| None -> failwith "Coercion of subjectAltName string failed"
| Some s -> loop (s :: acc) (p +@ 1))
in
loop [] results_p_p)
~finally:(fun () -> Bindings.X509.free_subject_alt_names results_p_p)
;;
let fingerprint t algo =
let open Ctypes in
let buf = allocate_n char ~count:Types.Evp.max_md_size in
let len = allocate int 0 in
let algo =
match algo with
| `SHA1 -> Bindings.EVP.sha1 ()
in
if Bindings.X509.digest t algo buf len
then Ctypes.string_from_ptr buf ~length:!@len
else raise_s [%message "Failed to compute digest"]
;;
end
module Ssl_session = struct
type t = Bindings.Ssl_session.t
let create_exn () =
match Bindings.Ssl_session.new_ () with
| Some p ->
Gc.add_finalizer_exn p Bindings.Ssl_session.free;
p
| None -> failwith "Unable to allocate an SSL session."
;;
end
module Bignum = struct
type t = Bindings.Bignum.t
let create_no_gc (`hex hex) =
let p_ref = Ctypes.(allocate Bindings.Bignum.t_opt None) in
let _len = Bindings.Bignum.hex2bn p_ref hex in
match Ctypes.( !@ ) p_ref with
| Some p -> p
| None -> failwith "Unable to allocate/init Bignum."
;;
end
module Dh = struct
type t = Bindings.Dh.t
let create ~prime ~generator : t =
match Bindings.Dh.new_ () with
| None -> failwith "Unable to allocate/generate DH parameters."
| Some p ->
Gc.add_finalizer_exn p Bindings.Dh.free;
let p_struct =
Ctypes.( !@ ) Ctypes.(coerce Bindings.Dh.t (ptr Bindings.Dh.Struct.t) p)
in
Ctypes.setf p_struct Bindings.Dh.Struct.p (Bignum.create_no_gc prime);
Ctypes.setf p_struct Bindings.Dh.Struct.g (Bignum.create_no_gc generator);
p
;;
let generate_parameters ~prime_len ~generator () : t =
match Bindings.Dh.generate_parameters prime_len generator None Ctypes.null with
| None -> failwith "Unable to allocate/generate DH parameters."
| Some p ->
Gc.add_finalizer_exn p Bindings.Dh.free;
p
;;
end
module Ssl = struct
type t = Bindings.Ssl.t [@@deriving sexp_of]
for use in ctypes signatures
let create_exn ctx =
match Bindings.Ssl.new_ ctx with
| None -> failwith "Unable to allocate an SSL connection."
| Some p ->
Gc.add_finalizer_exn p Bindings.Ssl.free;
p
;;
let set_method t version =
let version_method =
let open Version in
match version with
| Sslv23 -> Ssl_method.sslv23 ()
| Tls -> Ssl_method.tls ()
| Sslv3 -> Ssl_method.sslv3 ()
| Tlsv1 -> Ssl_method.tlsv1 ()
| Tlsv1_1 -> Ssl_method.tlsv1_1 ()
| Tlsv1_2 -> Ssl_method.tlsv1_2 ()
| Tlsv1_3 -> Ssl_method.tlsv1_3 ()
in
match Bindings.Ssl.set_method t version_method with
| 1 -> ()
| e -> failwithf "Failed to set SSL version: %i" e ()
;;
let get_connect_accept_error ssl ~retval =
if retval = 1
then Ok ()
else if retval <= 0
then (
let error = Bindings.Ssl.get_error ssl retval in
match Ssl_error.of_int error with
| Ok () ->
failwithf
"OpenSSL bug: SSL_connect or SSL_accept returned %d, but get_error returned \
SSL_ERROR_NONE"
retval
()
| Error error -> Error error)
else failwithf "OpenSSL bug: get_error returned %d, should be <= 1" retval ()
;;
let get_read_write_error ssl ~retval =
if retval > 0
then Ok retval
else (
let error = Bindings.Ssl.get_error ssl retval in
match Ssl_error.of_int error with
| Ok () ->
failwithf
"OpenSSL bug: SSL_read or SSL_write returned %d, but get_error returned \
SSL_ERROR_NONE"
retval
()
| Error error -> Error error)
;;
let set_initial_state ssl = function
| `Connect -> Bindings.Ssl.set_connect_state ssl
| `Accept -> Bindings.Ssl.set_accept_state ssl
;;
let connect ssl =
let open Result.Let_syntax in
let retval = Bindings.Ssl.connect ssl in
let%bind () = get_connect_accept_error ssl ~retval in
if verbose then Debug.amf [%here] "SSL_connect -> %i" retval;
return ()
;;
let accept ssl =
let open Result.Let_syntax in
let retval = Bindings.Ssl.accept ssl in
let%bind () = get_connect_accept_error ssl ~retval in
if verbose then Debug.amf [%here] "SSL_accept -> %i" retval;
return ()
;;
let set_bio ssl ~input ~output = Bindings.Ssl.set_bio ssl input output
let read ssl ~buf ~len =
let retval = Bindings.Ssl.read ssl buf len in
if verbose then Debug.amf [%here] "SSL_read(%i) -> %i" len retval;
get_read_write_error ssl ~retval
;;
let write ssl ~buf ~len =
let retval = Bindings.Ssl.write ssl buf len in
if verbose then Debug.amf [%here] "SSL_write(%i) -> %i" len retval;
get_read_write_error ssl ~retval
;;
let set_verify t flags =
let mode = List.map flags ~f:Verify_mode.to_int |> List.fold ~init:0 ~f:Int.bit_or in
Bindings.Ssl.set_verify t mode Ctypes.null
;;
let get_peer_certificate t =
let cert = Bindings.Ssl.get_peer_certificate t in
Option.iter cert ~f:(fun cert -> Gc.add_finalizer_exn cert Bindings.X509.free);
cert
;;
let get_peer_certificate_fingerprint t algo =
Option.map (Bindings.Ssl.get_peer_certificate t) ~f:(fun cert ->
protect
~f:(fun () -> X509.fingerprint cert algo)
~finally:(fun () -> Bindings.X509.free cert))
;;
let get_verify_result t =
let result = Bindings.Ssl.get_verify_result t in
if result = Types.Verify_result.ok
then Ok ()
else
Option.value
(Bindings.X509.verify_cert_error_string result)
~default:
(sprintf "unknown verification error (%s)" (Signed.Long.to_string result))
|> Or_error.error_string
;;
let get_version t =
let open Version in
match Bindings.Ssl.get_version t with
| "SSLv3" -> Sslv3
| "TLSv1" -> Tlsv1
| "TLSv1.1" -> Tlsv1_1
| "TLSv1.2" -> Tlsv1_2
| "TLSv1.3" -> Tlsv1_3
| "unknown" ->
failwith "SSL_get_version returned 'unknown', your session is not established"
| s -> failwithf "bug: SSL_get_version returned %s" s ()
;;
let session_reused t =
match Bindings.Ssl.session_reused t with
| 0 -> false
| 1 -> true
| n -> failwithf "OpenSSL bug: SSL_session_reused returned %d" n ()
;;
let set_session t sess =
match Bindings.Ssl.set_session t sess with
| 1 -> Ok ()
| 0 ->
Or_error.error "SSL_set_session error" (get_error_stack ()) [%sexp_of: string list]
| n -> failwithf "OpenSSL bug: SSL_set_session returned %d" n ()
;;
let get1_session t =
let sess = Bindings.Ssl.get1_session t in
Option.iter sess ~f:(fun sess ->
(* get1_session increments the reference count *)
Gc.add_finalizer_exn sess Bindings.Ssl_session.free);
sess
;;
let check_private_key t =
match Bindings.Ssl.check_private_key t with
| 1 -> Ok ()
| _ ->
Or_error.error
"SSL_check_private_key error"
(get_error_stack ())
[%sexp_of: string list]
;;
let set_tlsext_host_name context hostname =
let hostname = Ctypes.(coerce string (ptr char)) hostname in
match Bindings.Ssl.set_tlsext_host_name context hostname with
| 1 -> Ok ()
| 0 ->
Or_error.error
"SSL_set_tlsext_host_name error"
(get_error_stack ())
[%sexp_of: string list]
| n -> failwithf "OpenSSL bug: SSL_set_tlsext_host_name returned %d" n ()
;;
let set_cipher_list_exn t ciphers =
match Bindings.Ssl.set_cipher_list t (String.concat ~sep:":" ("-ALL" :: ciphers)) with
| 1 -> ()
| 0 ->
failwithf !"SSL_set_cipher_list error: %{sexp:string list}" (get_error_stack ()) ()
| n -> failwithf "OpenSSL bug: SSL_set_cipher_list returned %d" n ()
;;
let set1_groups_list_exn t groups =
match Bindings.Ssl.set1_groups_list t (String.concat ~sep:":" groups) with
| 1 -> ()
| 0 ->
failwithf !"SSL_set1_groups_list error: %{sexp:string list}" (get_error_stack ()) ()
| n -> failwithf "OpenSSL bug: SSL_set1_groups_list returned %d" n ()
;;
let get_cipher_list t =
let rec loop i acc =
match Bindings.Ssl.get_cipher_list t i with
| Some c -> loop (i + 1) (c :: acc)
| None -> List.rev acc
in
loop 0 []
;;
let get_peer_certificate_chain t =
let open Ctypes in
match Bindings.Ssl.pem_peer_certificate_chain t with
| None -> None
| Some results_p ->
protect
~f:(fun () ->
match coerce (ptr char) string_opt results_p with
| None -> failwith "Coercion of certificate chain failed"
| Some s -> Some s)
~finally:(fun () -> Bindings.Ssl.free_pem_peer_certificate_chain results_p)
;;
end
| null | https://raw.githubusercontent.com/janestreet/async_ssl/37b9c26674affb4018e24e56ba7b04f4a372863a/src/ffi__library_must_be_initialized.ml | ocaml | for use in ctypes type signatures
SSL_CTX_set_options(3) returns the new options bitmask after adding options. We
don't really have a use for this, so ignore.
get1_session increments the reference count | open Core
open Poly
open Async
open Import
module Ssl_method = Bindings.Ssl_method
module Ssl_error = struct
type t =
| Zero_return
| Want_read
| Want_write
| Want_connect
| Want_accept
| Want_X509_lookup
| Syscall_error
| Ssl_error
[@@deriving sexp_of]
let of_int n =
let open Types.Ssl_error in
if n = none
then Ok ()
else if n = zero_return
then Error Zero_return
else if n = want_read
then Error Want_read
else if n = want_write
then Error Want_write
else if n = want_connect
then Error Want_connect
else if n = want_accept
then Error Want_accept
else if n = want_x509_lookup
then Error Want_X509_lookup
else if n = syscall
then Error Syscall_error
else if n = ssl
then Error Ssl_error
else failwithf "Unrecognized result of SSL_get_error: %d" n ()
;;
end
module Verify_mode = struct
include Verify_mode
let to_int t =
let open Types.Verify_mode in
match t with
| Verify_none -> verify_none
| Verify_peer -> verify_peer
| Verify_fail_if_no_peer_cert -> verify_fail_if_no_peer_cert
| Verify_client_once -> verify_client_once
;;
end
let bigstring_strlen bigstr =
let len = Bigstring.length bigstr in
let idx = ref 0 in
while !idx < len && bigstr.{!idx} <> '\x00' do
incr idx
done;
!idx
;;
let get_error_stack =
let err_error_string =
We need to write error strings from C into bigstrings . To reduce allocation , reuse
scratch space for this .
scratch space for this. *)
let scratch_space = Bigstring.create 1024 in
fun err ->
Bindings.err_error_string_n
err
(Ctypes.bigarray_start Ctypes.array1 scratch_space)
(Bigstring.length scratch_space);
Bigstring.to_string ~len:(bigstring_strlen scratch_space) scratch_space
in
fun () ->
iter_while_rev ~iter:Bindings.err_get_error ~cond:(fun x -> x <> Unsigned.ULong.zero)
|> List.rev_map ~f:err_error_string
;;
module Ssl_ctx = struct
type t = Bindings.Ssl_ctx.t [@@deriving sexp_of]
let create_exn ver =
let ver_method =
let module V = Version in
match ver with
| V.Sslv23 -> Ssl_method.sslv23 ()
| V.Tls -> Ssl_method.tls ()
| V.Sslv3 -> Ssl_method.sslv3 ()
| V.Tlsv1 -> Ssl_method.tlsv1 ()
| V.Tlsv1_1 -> Ssl_method.tlsv1_1 ()
| V.Tlsv1_2 -> Ssl_method.tlsv1_2 ()
| V.Tlsv1_3 -> Ssl_method.tlsv1_3 ()
in
match Bindings.Ssl_ctx.new_ ver_method with
| None -> failwith "Could not allocate a new SSL context."
| Some p ->
Gc.add_finalizer_exn p Bindings.Ssl_ctx.free;
p
;;
let override_default_insecure__set_security_level t level =
Bindings.Ssl_ctx.override_default_insecure__set_security_level t level
;;
let set_options context options =
let module O = Types.Ssl_op in
let default_options =
List.fold
[ O.single_dh_use; O.single_ecdh_use ]
~init:Unsigned.ULong.zero
~f:Unsigned.ULong.logor
in
let opts =
List.fold options ~init:default_options ~f:(fun acc (opt : Opt.t) ->
let o =
match opt with
| No_sslv2 -> O.no_sslv2
| No_sslv3 -> O.no_sslv3
| No_tlsv1 -> O.no_tlsv1
| No_tlsv1_1 -> O.no_tlsv1_1
| No_tlsv1_2 -> O.no_tlsv1_2
| No_tlsv1_3 -> O.no_tlsv1_3
in
Unsigned.ULong.logor acc o)
in
let (_ : Unsigned.ULong.t) = Bindings.Ssl_ctx.set_options context opts in
()
;;
let set_session_id_context context sid_ctx =
let session_id_ctx = Ctypes.(coerce string (ptr char)) sid_ctx in
match
Bindings.Ssl_ctx.set_session_id_context
context
session_id_ctx
(Unsigned.UInt.of_int (String.length sid_ctx))
with
| 1 -> ()
| x ->
failwiths
~here:[%here]
"Could not set session id context."
(`Return_value x, `Errors (get_error_stack ()))
[%sexp_of: [ `Return_value of int ] * [ `Errors of string list ]]
;;
let load_verify_locations ?ca_file ?ca_path ctx =
match%bind
In_thread.run (fun () -> Bindings.Ssl_ctx.load_verify_locations ctx ca_file ca_path)
with
Yep , 1 means success .
| 1 -> Deferred.return (Or_error.return ())
| _ ->
Deferred.return
(match ca_file, ca_path with
| None, None -> Or_error.error_string "No CA files given."
| _ -> Or_error.error "CA load error" (get_error_stack ()) [%sexp_of: string list])
;;
let set_default_verify_paths ctx =
match Bindings.Ssl_ctx.set_default_verify_paths ctx with
| 1 -> ()
| x ->
failwiths
~here:[%here]
"Could not set default verify paths."
(`Return_value x, `Errors (get_error_stack ()))
[%sexp_of: [ `Return_value of int ] * [ `Errors of string list ]]
;;
let try_certificate_chain_and_failover_to_asn1 ctx crt_file =
match Bindings.Ssl_ctx.use_certificate_chain_file ctx crt_file with
| 1 -> 1
| _ -> Bindings.Ssl_ctx.use_certificate_file ctx crt_file Types.X509_filetype.asn1
;;
let try_both_private_key_formats ctx key_file =
match Bindings.Ssl_ctx.use_private_key_file ctx key_file Types.X509_filetype.pem with
| 1 -> 1
| _ -> Bindings.Ssl_ctx.use_private_key_file ctx key_file Types.X509_filetype.asn1
;;
let use_certificate_chain_and_key_files ~crt_file ~key_file ctx =
let error i =
Deferred.Or_error.error
"Could not set default verify paths."
(`Return_value i, `Errors (get_error_stack ()))
[%sexp_of: [ `Return_value of int ] * [ `Errors of string list ]]
in
match%bind
In_thread.run (fun () -> try_certificate_chain_and_failover_to_asn1 ctx crt_file)
with
| 1 ->
(match%bind In_thread.run (fun () -> try_both_private_key_formats ctx key_file) with
| 1 -> Deferred.Or_error.return ()
| x -> error x)
| x -> error x
;;
end
module Bio = struct
type t = Bindings.Bio.t [@@deriving sexp_of]
for use in ctypes signatures
let create () = Bindings.Bio.s_mem () |> Bindings.Bio.new_
let read bio ~buf ~len =
let retval = Bindings.Bio.read bio buf len in
if verbose then Debug.amf [%here] "BIO_read(%i) -> %i" len retval;
retval
;;
let write bio ~buf ~len =
let retval = Bindings.Bio.write bio buf len in
if verbose then Debug.amf [%here] "BIO_write(%i) -> %i" len retval;
retval
;;
end
module ASN1_object = struct
type t = Bindings.ASN1_object.t
let obj2nid = Bindings.ASN1_object.obj2nid
let nid2sn n =
Option.value
(Bindings.ASN1_object.nid2sn n)
~default:(sprintf "unknown object nid (%d)" n)
;;
end
module ASN1_string = struct
type t = Bindings.ASN1_string.t
let data t = Bindings.ASN1_string.data t
end
module X509_name_entry = struct
type t = Bindings.X509_name_entry.t
let get_object = Bindings.X509_name_entry.get_object
let get_data = Bindings.X509_name_entry.get_data
end
module X509_name = struct
type t = Bindings.X509_name.t
let entry_count = Bindings.X509_name.entry_count
let get_entry = Bindings.X509_name.get_entry
end
module X509 = struct
type t = Bindings.X509.t
let get_subject_name t =
match Bindings.X509.get_subject_name t with
| Some name -> name
| None -> failwith "Certificate contains no subject name."
;;
let get_subject_alt_names t =
let open Ctypes in
match Bindings.X509.subject_alt_names t with
| None -> failwith "Failed to allocate memory in subject_alt_names()"
| Some results_p_p ->
protect
~f:(fun () ->
let rec loop acc p =
match !@p with
| None -> List.rev acc
| Some san ->
(match coerce (ptr char) string_opt san with
| None -> failwith "Coercion of subjectAltName string failed"
| Some s -> loop (s :: acc) (p +@ 1))
in
loop [] results_p_p)
~finally:(fun () -> Bindings.X509.free_subject_alt_names results_p_p)
;;
let fingerprint t algo =
let open Ctypes in
let buf = allocate_n char ~count:Types.Evp.max_md_size in
let len = allocate int 0 in
let algo =
match algo with
| `SHA1 -> Bindings.EVP.sha1 ()
in
if Bindings.X509.digest t algo buf len
then Ctypes.string_from_ptr buf ~length:!@len
else raise_s [%message "Failed to compute digest"]
;;
end
module Ssl_session = struct
type t = Bindings.Ssl_session.t
let create_exn () =
match Bindings.Ssl_session.new_ () with
| Some p ->
Gc.add_finalizer_exn p Bindings.Ssl_session.free;
p
| None -> failwith "Unable to allocate an SSL session."
;;
end
module Bignum = struct
type t = Bindings.Bignum.t
let create_no_gc (`hex hex) =
let p_ref = Ctypes.(allocate Bindings.Bignum.t_opt None) in
let _len = Bindings.Bignum.hex2bn p_ref hex in
match Ctypes.( !@ ) p_ref with
| Some p -> p
| None -> failwith "Unable to allocate/init Bignum."
;;
end
module Dh = struct
type t = Bindings.Dh.t
let create ~prime ~generator : t =
match Bindings.Dh.new_ () with
| None -> failwith "Unable to allocate/generate DH parameters."
| Some p ->
Gc.add_finalizer_exn p Bindings.Dh.free;
let p_struct =
Ctypes.( !@ ) Ctypes.(coerce Bindings.Dh.t (ptr Bindings.Dh.Struct.t) p)
in
Ctypes.setf p_struct Bindings.Dh.Struct.p (Bignum.create_no_gc prime);
Ctypes.setf p_struct Bindings.Dh.Struct.g (Bignum.create_no_gc generator);
p
;;
let generate_parameters ~prime_len ~generator () : t =
match Bindings.Dh.generate_parameters prime_len generator None Ctypes.null with
| None -> failwith "Unable to allocate/generate DH parameters."
| Some p ->
Gc.add_finalizer_exn p Bindings.Dh.free;
p
;;
end
module Ssl = struct
type t = Bindings.Ssl.t [@@deriving sexp_of]
for use in ctypes signatures
let create_exn ctx =
match Bindings.Ssl.new_ ctx with
| None -> failwith "Unable to allocate an SSL connection."
| Some p ->
Gc.add_finalizer_exn p Bindings.Ssl.free;
p
;;
let set_method t version =
let version_method =
let open Version in
match version with
| Sslv23 -> Ssl_method.sslv23 ()
| Tls -> Ssl_method.tls ()
| Sslv3 -> Ssl_method.sslv3 ()
| Tlsv1 -> Ssl_method.tlsv1 ()
| Tlsv1_1 -> Ssl_method.tlsv1_1 ()
| Tlsv1_2 -> Ssl_method.tlsv1_2 ()
| Tlsv1_3 -> Ssl_method.tlsv1_3 ()
in
match Bindings.Ssl.set_method t version_method with
| 1 -> ()
| e -> failwithf "Failed to set SSL version: %i" e ()
;;
let get_connect_accept_error ssl ~retval =
if retval = 1
then Ok ()
else if retval <= 0
then (
let error = Bindings.Ssl.get_error ssl retval in
match Ssl_error.of_int error with
| Ok () ->
failwithf
"OpenSSL bug: SSL_connect or SSL_accept returned %d, but get_error returned \
SSL_ERROR_NONE"
retval
()
| Error error -> Error error)
else failwithf "OpenSSL bug: get_error returned %d, should be <= 1" retval ()
;;
let get_read_write_error ssl ~retval =
if retval > 0
then Ok retval
else (
let error = Bindings.Ssl.get_error ssl retval in
match Ssl_error.of_int error with
| Ok () ->
failwithf
"OpenSSL bug: SSL_read or SSL_write returned %d, but get_error returned \
SSL_ERROR_NONE"
retval
()
| Error error -> Error error)
;;
let set_initial_state ssl = function
| `Connect -> Bindings.Ssl.set_connect_state ssl
| `Accept -> Bindings.Ssl.set_accept_state ssl
;;
let connect ssl =
let open Result.Let_syntax in
let retval = Bindings.Ssl.connect ssl in
let%bind () = get_connect_accept_error ssl ~retval in
if verbose then Debug.amf [%here] "SSL_connect -> %i" retval;
return ()
;;
let accept ssl =
let open Result.Let_syntax in
let retval = Bindings.Ssl.accept ssl in
let%bind () = get_connect_accept_error ssl ~retval in
if verbose then Debug.amf [%here] "SSL_accept -> %i" retval;
return ()
;;
let set_bio ssl ~input ~output = Bindings.Ssl.set_bio ssl input output
let read ssl ~buf ~len =
let retval = Bindings.Ssl.read ssl buf len in
if verbose then Debug.amf [%here] "SSL_read(%i) -> %i" len retval;
get_read_write_error ssl ~retval
;;
let write ssl ~buf ~len =
let retval = Bindings.Ssl.write ssl buf len in
if verbose then Debug.amf [%here] "SSL_write(%i) -> %i" len retval;
get_read_write_error ssl ~retval
;;
let set_verify t flags =
let mode = List.map flags ~f:Verify_mode.to_int |> List.fold ~init:0 ~f:Int.bit_or in
Bindings.Ssl.set_verify t mode Ctypes.null
;;
let get_peer_certificate t =
let cert = Bindings.Ssl.get_peer_certificate t in
Option.iter cert ~f:(fun cert -> Gc.add_finalizer_exn cert Bindings.X509.free);
cert
;;
let get_peer_certificate_fingerprint t algo =
Option.map (Bindings.Ssl.get_peer_certificate t) ~f:(fun cert ->
protect
~f:(fun () -> X509.fingerprint cert algo)
~finally:(fun () -> Bindings.X509.free cert))
;;
let get_verify_result t =
let result = Bindings.Ssl.get_verify_result t in
if result = Types.Verify_result.ok
then Ok ()
else
Option.value
(Bindings.X509.verify_cert_error_string result)
~default:
(sprintf "unknown verification error (%s)" (Signed.Long.to_string result))
|> Or_error.error_string
;;
let get_version t =
let open Version in
match Bindings.Ssl.get_version t with
| "SSLv3" -> Sslv3
| "TLSv1" -> Tlsv1
| "TLSv1.1" -> Tlsv1_1
| "TLSv1.2" -> Tlsv1_2
| "TLSv1.3" -> Tlsv1_3
| "unknown" ->
failwith "SSL_get_version returned 'unknown', your session is not established"
| s -> failwithf "bug: SSL_get_version returned %s" s ()
;;
let session_reused t =
match Bindings.Ssl.session_reused t with
| 0 -> false
| 1 -> true
| n -> failwithf "OpenSSL bug: SSL_session_reused returned %d" n ()
;;
let set_session t sess =
match Bindings.Ssl.set_session t sess with
| 1 -> Ok ()
| 0 ->
Or_error.error "SSL_set_session error" (get_error_stack ()) [%sexp_of: string list]
| n -> failwithf "OpenSSL bug: SSL_set_session returned %d" n ()
;;
let get1_session t =
let sess = Bindings.Ssl.get1_session t in
Option.iter sess ~f:(fun sess ->
Gc.add_finalizer_exn sess Bindings.Ssl_session.free);
sess
;;
let check_private_key t =
match Bindings.Ssl.check_private_key t with
| 1 -> Ok ()
| _ ->
Or_error.error
"SSL_check_private_key error"
(get_error_stack ())
[%sexp_of: string list]
;;
let set_tlsext_host_name context hostname =
let hostname = Ctypes.(coerce string (ptr char)) hostname in
match Bindings.Ssl.set_tlsext_host_name context hostname with
| 1 -> Ok ()
| 0 ->
Or_error.error
"SSL_set_tlsext_host_name error"
(get_error_stack ())
[%sexp_of: string list]
| n -> failwithf "OpenSSL bug: SSL_set_tlsext_host_name returned %d" n ()
;;
let set_cipher_list_exn t ciphers =
match Bindings.Ssl.set_cipher_list t (String.concat ~sep:":" ("-ALL" :: ciphers)) with
| 1 -> ()
| 0 ->
failwithf !"SSL_set_cipher_list error: %{sexp:string list}" (get_error_stack ()) ()
| n -> failwithf "OpenSSL bug: SSL_set_cipher_list returned %d" n ()
;;
let set1_groups_list_exn t groups =
match Bindings.Ssl.set1_groups_list t (String.concat ~sep:":" groups) with
| 1 -> ()
| 0 ->
failwithf !"SSL_set1_groups_list error: %{sexp:string list}" (get_error_stack ()) ()
| n -> failwithf "OpenSSL bug: SSL_set1_groups_list returned %d" n ()
;;
let get_cipher_list t =
let rec loop i acc =
match Bindings.Ssl.get_cipher_list t i with
| Some c -> loop (i + 1) (c :: acc)
| None -> List.rev acc
in
loop 0 []
;;
let get_peer_certificate_chain t =
let open Ctypes in
match Bindings.Ssl.pem_peer_certificate_chain t with
| None -> None
| Some results_p ->
protect
~f:(fun () ->
match coerce (ptr char) string_opt results_p with
| None -> failwith "Coercion of certificate chain failed"
| Some s -> Some s)
~finally:(fun () -> Bindings.Ssl.free_pem_peer_certificate_chain results_p)
;;
end
|
51469b2b6b392f76ecd3ad32e65ba91a30dfef49ee2de5a34201c486dfe0ff39 | doomeer/kalandralang | id.ml | module M =
struct
type t = { int: int; string: string }
let compare a b = Int.compare a.int b.int
end
include M
let string_table: (string, t) Hashtbl.t = Hashtbl.create 512
let next = ref 0
let make string =
match Hashtbl.find_opt string_table string with
| None ->
let int = !next in
incr next;
let id = { int; string } in
Hashtbl.replace string_table string id;
id
| Some id ->
id
let empty = make ""
let show id = id.string
let pp id =
Pretext.OCaml.string (show id)
module Set =
struct
include Set.Make (M)
let show set = String.concat ", " (List.map show (elements set))
let pp set = Pretext.OCaml.list pp (elements set)
end
module Map = Map.Make (M)
| null | https://raw.githubusercontent.com/doomeer/kalandralang/1d0fa5340cd8cbfec881838efc06c2fb9035d1b0/src/id.ml | ocaml | module M =
struct
type t = { int: int; string: string }
let compare a b = Int.compare a.int b.int
end
include M
let string_table: (string, t) Hashtbl.t = Hashtbl.create 512
let next = ref 0
let make string =
match Hashtbl.find_opt string_table string with
| None ->
let int = !next in
incr next;
let id = { int; string } in
Hashtbl.replace string_table string id;
id
| Some id ->
id
let empty = make ""
let show id = id.string
let pp id =
Pretext.OCaml.string (show id)
module Set =
struct
include Set.Make (M)
let show set = String.concat ", " (List.map show (elements set))
let pp set = Pretext.OCaml.list pp (elements set)
end
module Map = Map.Make (M)
| |
22781983146f14af4305fc2e93184c3a9f4af98c804b0ebe785227ad1a8db3b4 | databrary/databrary | Comment.hs | {-# LANGUAGE OverloadedStrings #-}
module Controller.Comment
( postComment
) where
import Control.Monad (forM_, when)
import Control.Monad.Trans.Class (lift)
import Data.Function (on)
import Data.Text (Text)
import Ops
import qualified JSON
import Model.Permission
import Model.Id
import Model.Container
import Model.Slot
import Model.Notification.Types
import Model.Party.Types
import Model.Comment
import HTTP.Form.Deform
import HTTP.Path.Parser
import Action
import Controller.Paths
import Controller.Permission
import Controller.Form
import Controller.Slot
import Controller.Notification
import View.Form (FormHtml)
data CreateOrUpdateCommentRequest = CreateOrUpdateCommentRequest Text (Maybe (Id Comment))
postComment :: ActionRoute (Id Slot)
postComment = action POST (pathJSON >/> pathSlotId </< "comment") $ \si -> withAuth $ do
u <- authAccount
s <- getSlot PermissionSHARED si
(c, p) <- runForm (Nothing :: Maybe (RequestContext -> FormHtml a)) $ do
csrfForm
text <- "text" .:> (deformRequired =<< deform)
parent <- "parent" .:> deformNonEmpty (deformMaybe' "comment not found" =<< lift . lookupComment =<< deform)
let _ = CreateOrUpdateCommentRequest text (fmap commentId parent)
return ((blankComment u s)
{ commentText = text
, commentParents = maybe [] (return . commentId) parent
}, parent)
c' <- addComment c
top <- containerIsVolumeTop (slotContainer s)
forM_ p $ \r -> when (on (/=) (partyId . partyRow . accountParty) (commentWho r) u) $
createNotification (blankNotification (commentWho r) NoticeCommentReply)
{ notificationContainerId = top `unlessUse` (containerId . containerRow . slotContainer . commentSlot) c'
, notificationSegment = Just $ (slotSegment . commentSlot) c'
, notificationCommentId = Just $ commentId c'
}
createVolumeNotification ((containerVolume . slotContainer . commentSlot) c') $ \n -> (n NoticeCommentVolume)
{ notificationContainerId = top `unlessUse` (containerId . containerRow . slotContainer . commentSlot) c'
, notificationSegment = Just $ (slotSegment . commentSlot) c'
, notificationCommentId = Just $ commentId c'
}
return $ okResponse [] $ JSON.recordEncoding $ commentJSON c'
| null | https://raw.githubusercontent.com/databrary/databrary/685f3c625b960268f5d9b04e3d7c6146bea5afda/src/Controller/Comment.hs | haskell | # LANGUAGE OverloadedStrings # | module Controller.Comment
( postComment
) where
import Control.Monad (forM_, when)
import Control.Monad.Trans.Class (lift)
import Data.Function (on)
import Data.Text (Text)
import Ops
import qualified JSON
import Model.Permission
import Model.Id
import Model.Container
import Model.Slot
import Model.Notification.Types
import Model.Party.Types
import Model.Comment
import HTTP.Form.Deform
import HTTP.Path.Parser
import Action
import Controller.Paths
import Controller.Permission
import Controller.Form
import Controller.Slot
import Controller.Notification
import View.Form (FormHtml)
data CreateOrUpdateCommentRequest = CreateOrUpdateCommentRequest Text (Maybe (Id Comment))
postComment :: ActionRoute (Id Slot)
postComment = action POST (pathJSON >/> pathSlotId </< "comment") $ \si -> withAuth $ do
u <- authAccount
s <- getSlot PermissionSHARED si
(c, p) <- runForm (Nothing :: Maybe (RequestContext -> FormHtml a)) $ do
csrfForm
text <- "text" .:> (deformRequired =<< deform)
parent <- "parent" .:> deformNonEmpty (deformMaybe' "comment not found" =<< lift . lookupComment =<< deform)
let _ = CreateOrUpdateCommentRequest text (fmap commentId parent)
return ((blankComment u s)
{ commentText = text
, commentParents = maybe [] (return . commentId) parent
}, parent)
c' <- addComment c
top <- containerIsVolumeTop (slotContainer s)
forM_ p $ \r -> when (on (/=) (partyId . partyRow . accountParty) (commentWho r) u) $
createNotification (blankNotification (commentWho r) NoticeCommentReply)
{ notificationContainerId = top `unlessUse` (containerId . containerRow . slotContainer . commentSlot) c'
, notificationSegment = Just $ (slotSegment . commentSlot) c'
, notificationCommentId = Just $ commentId c'
}
createVolumeNotification ((containerVolume . slotContainer . commentSlot) c') $ \n -> (n NoticeCommentVolume)
{ notificationContainerId = top `unlessUse` (containerId . containerRow . slotContainer . commentSlot) c'
, notificationSegment = Just $ (slotSegment . commentSlot) c'
, notificationCommentId = Just $ commentId c'
}
return $ okResponse [] $ JSON.recordEncoding $ commentJSON c'
|
59988e718644d997015bf2da206bad7d77d1d925c5a4346b3a160e85fdaa71d2 | fredrikt/yxa | targetlist.erl | %%%-------------------------------------------------------------------
%%% File : targetlist.erl
@author < >
@doc is a module for managing a list of ongoing
%%% client transactions for sipproxy.
@since 28 Jun 2003 by < >
%%% @end
@private
%%%-------------------------------------------------------------------
-module(targetlist).
%%--------------------------------------------------------------------
%% External exports
%%--------------------------------------------------------------------
-export([
add/8,
empty/0,
get_length/1,
debugfriendly/1,
get_using_pid/2,
get_using_branch/2,
get_targets_in_state/2,
get_responses/1,
extract/2,
set_pid/2,
set_state/2,
set_endresult/2,
set_dstlist/2,
set_cancelled/2,
update_target/2,
test/0
]).
%%--------------------------------------------------------------------
%% Include files
%%--------------------------------------------------------------------
-include("siprecords.hrl").
-include("sipproxy.hrl").
%%--------------------------------------------------------------------
Records
%%--------------------------------------------------------------------
@type ( ) = # targetlist { } .
%% Container record to make sure noone tries to modify our
%% records.
-record(targetlist, {list}).
%% @type target() = #target{}.
%% no description
-record(target, {
ref, %% ref(), unique reference
branch, %% string(), this clients branch
request, %% request record()
pid, %% pid() of client transaction ???
state, %% atom(), SIP state of this target
timeout, %% integer()
endresult = none, %% none | sp_response record()
dstlist, %% list() of sipdst record(), more destinations if this one fail
cancelled = false, %% true | false, is this branch cancelled?
user_instance %% none | {User, Instance}
}).
%%--------------------------------------------------------------------
Macros
%%--------------------------------------------------------------------
%%====================================================================
%% External functions
%%====================================================================
%%--------------------------------------------------------------------
@spec ( Branch , Request , Pid , State , Timeout , DstList , UserInst ,
TargetList ) - >
%% NewTargetList
%%
%% Branch = string()
%% Request = #request{}
Pid = pid ( )
%% State = atom()
%% Timeout = integer()
DstList = [ # sipdst { } ]
%% UserInst = none | {User, Instance}
TargetList = # targetlist { }
%%
NewTargetList = # targetlist { }
%%
@doc Add a new entry to TargetList , after verifying that a
%% target with this branch is not already in the list.
%% @end
%%--------------------------------------------------------------------
add(Branch, Request, Pid, State, Timeout, DstList, UserInst, TargetList)
when is_list(Branch), is_record(Request, request), is_pid(Pid), is_atom(State), is_integer(Timeout),
is_list(DstList), is_record(TargetList, targetlist), (is_tuple(UserInst) orelse UserInst == none) ->
case get_using_branch(Branch, TargetList) of
none ->
NewTarget = #target{ref = make_ref(),
branch = Branch,
request = Request,
pid = Pid,
state = State,
dstlist = DstList,
timeout = Timeout,
user_instance = UserInst
},
#targetlist{list = lists:append(TargetList#targetlist.list, [NewTarget])};
T when is_record(T, target) ->
logger:log(error, "targetlist: Asked to add target with duplicate branch ~p to list :~n~p",
[branch, debugfriendly(TargetList)]),
TargetList
end.
%%--------------------------------------------------------------------
%% @spec () ->
TargetList
%%
TargetList = # targetlist { }
%%
@doc Return empty record . For initialization .
%% @end
%%--------------------------------------------------------------------
empty() ->
#targetlist{list = []}.
%%--------------------------------------------------------------------
@spec ( TargetList ) - >
%% Length
%%
TargetList = # targetlist { }
%%
%% Length = integer()
%%
@doc Return length of list encapsulated in the TargetList
%% record.
%% @end
%%--------------------------------------------------------------------
get_length(TargetList) when is_record(TargetList, targetlist) ->
length(TargetList#targetlist.list).
%%--------------------------------------------------------------------
@spec ( Target , TargetList ) - >
%% NewTargetList
%%
%% Target = #target{}
TargetList = # targetlist { }
%%
%% NewTargetList = [#target{}]
%%
%% @throws {error, update_of_non_existin_target}
%%
@doc Locate the old instance of the target Target in the
TargetList and exchange it with Target .
%% @end
%%--------------------------------------------------------------------
update_target(Target, TargetList) when is_record(Target, target), is_record(TargetList, targetlist) ->
Ref = Target#target.ref,
NewList = update_target2(Ref, Target, TargetList#targetlist.list, []),
#targetlist{list = NewList}.
update_target2(Ref, _NewT, [], Res) ->
logger:log(error, "Targetlist: Asked to update a target, but I can't find it"),
logger:log(debug, "Targetlist: Asked to update a target with ref=~p, but I can't find it in list :~n~p",
[Ref, debugfriendly2( lists:reverse(Res), [])]),
throw({error, update_of_non_existin_target});
update_target2(Ref, NewT, [#target{ref=Ref} | T], Res) ->
%% Match
Head = lists:reverse([NewT | Res]),
Head ++ T;
update_target2(Ref, NewT, [H | T], Res) when is_record(H, target) ->
%% No match
update_target2(Ref, NewT, T, [H | Res]).
%%--------------------------------------------------------------------
@spec ( TargetList ) - >
%% Data
%%
TargetList = # targetlist { }
%%
%% Data = term()
%%
@doc Format the entrys in TargetList in a way that is suitable
%% for logging using ~p.
%% @end
%%--------------------------------------------------------------------
debugfriendly(TargetList) when is_record(TargetList, targetlist) ->
debugfriendly2(TargetList#targetlist.list, []).
debugfriendly2([], Res) ->
lists:reverse(Res);
debugfriendly2([H | T], Res) when is_record(H, target) ->
#request{method = Method, uri = URI} = H#target.request,
RespStr = case H#target.endresult of
none -> "no response";
R when is_record(R, sp_response) ->
lists:concat(["response=", R#sp_response.status, " ", R#sp_response.reason]);
_ -> "INVALID response"
end,
Str = lists:concat(["pid=", pid_to_list(H#target.pid),
", branch=", H#target.branch,
", request=", Method, " ",
sipurl:print(URI), ", ",
RespStr,
", cancelled=", H#target.cancelled,
", state=" , H#target.state]),
debugfriendly2(T, [binary_to_list(list_to_binary(Str)) | Res]).
%%--------------------------------------------------------------------
@spec ( Pid , TargetList ) - >
%% Target
%%
Pid = pid ( )
TargetList = # targetlist { }
%%
%% Target = #target{} | none
%%
@doc Get the target with pid matching Pid from TargetList .
%% @end
%%--------------------------------------------------------------------
get_using_pid(Pid, TargetList) when is_pid(Pid), is_record(TargetList, targetlist) ->
get_using_pid2(Pid, TargetList#targetlist.list).
get_using_pid2(_Pid, []) ->
none;
get_using_pid2(Pid, [H | _T]) when is_record(H, target), H#target.pid == Pid ->
H;
get_using_pid2(Pid, [H | T]) when is_record(H, target) ->
get_using_pid2(Pid, T).
%%--------------------------------------------------------------------
@spec ( Branch , TargetList ) - >
%% Target
%%
%% Branch = string()
TargetList = # targetlist { }
%%
%% Target = #target{} | none
%%
@doc Get the target with branch matching Branch .
%% @end
%%--------------------------------------------------------------------
get_using_branch(Branch, TargetList) when is_list(Branch), is_record(TargetList, targetlist) ->
get_using_branch2(Branch, TargetList#targetlist.list).
get_using_branch2(_Branch, []) ->
none;
get_using_branch2(Branch, [#target{branch=Branch}=H | _T]) ->
H;
get_using_branch2(Branch, [H | T]) when is_record(H, target) ->
get_using_branch2(Branch, T).
%%--------------------------------------------------------------------
@spec ( State , TargetList ) - >
TargetList
%%
%% State = term()
TargetList = # targetlist { }
%%
TargetList = [ # target { } ]
%%
@doc Get all targets with state matching State .
%% @end
%%--------------------------------------------------------------------
get_targets_in_state(State, TargetList) when is_record(TargetList, targetlist) ->
get_targets_in_state2(State, TargetList#targetlist.list, []).
get_targets_in_state2(_State, [], Res) ->
lists:reverse(Res);
get_targets_in_state2(State, [H | T], Res) when is_record(H, target), H#target.state == State ->
get_targets_in_state2(State, T, [H | Res]);
get_targets_in_state2(State, [H | T], Res) when is_record(H, target) ->
get_targets_in_state2(State, T, Res).
%%--------------------------------------------------------------------
@spec ( TargetList ) - >
%% [Response]
%%
TargetList = # targetlist { }
%%
%% Response = #sp_response{} | {Status, Reason}
%% Status = integer() "SIP status code"
%% Reason = string() "SIP reason phrase"
%%
%% @doc Get all responses that has been set (i.e. not undefined).
%% @end
%%--------------------------------------------------------------------
get_responses(TargetList) when is_record(TargetList, targetlist) ->
get_responses2(TargetList#targetlist.list, []).
get_responses2([], Res) ->
lists:reverse(Res);
get_responses2([#target{endresult = H} | T], Res) when is_record(H, sp_response) ->
%% endresult is an sp_response record, add it to Res
get_responses2(T, [H | Res]);
get_responses2([#target{endresult = none} | T], Res) ->
%% endresult is 'none'
get_responses2(T, Res).
%%--------------------------------------------------------------------
%% @spec (Keys, Target) -> [term()]
%%
%% Keys = [pid |
%% branch |
%% request |
%% state |
%% timeout |
%% dstlist |
endresult |
%% cancelled]
%% Target = #target{}
%%
@doc Extract one or more values from a target record . Return
%% the values in a list of the same order as Keys.
%% @end
%%--------------------------------------------------------------------
extract(Values, Target) when is_record(Target, target) ->
extract(Values, Target, []).
extract([pid | T], #target{pid = Value} = Ta, Res) -> extract(T, Ta, [Value | Res]);
extract([branch | T], #target{branch = Value} = Ta, Res) -> extract(T, Ta, [Value | Res]);
extract([request | T], #target{request = Value} = Ta, Res) -> extract(T, Ta, [Value | Res]);
extract([state | T], #target{state = Value} = Ta, Res) -> extract(T, Ta, [Value | Res]);
extract([timeout | T], #target{timeout = Value} = Ta, Res) -> extract(T, Ta, [Value | Res]);
extract([dstlist | T], #target{dstlist = Value} = Ta, Res) -> extract(T, Ta, [Value | Res]);
extract([endresult | T], #target{endresult = Value} = Ta, Res) -> extract(T, Ta, [Value | Res]);
extract([cancelled | T], #target{cancelled = Value} = Ta, Res) -> extract(T, Ta, [Value | Res]);
extract([user_instance | T], #target{user_instance = Value} = Ta, Res) -> extract(T, Ta, [Value | Res]);
extract([], #target{}, Res) -> lists:reverse(Res).
%%--------------------------------------------------------------------
@spec ( Target , Value ) - >
NewTarget
%%
%% Target = #target{}
%% Value = pid()
%%
NewTarget = # target { }
%%
%% @doc Update an element in a target.
%% @end
%%--------------------------------------------------------------------
set_pid(Target, Value) when is_record(Target, target), is_pid(Value) ->
Target#target{pid = Value}.
%%--------------------------------------------------------------------
@spec ( Target , Value ) - >
NewTarget
%%
%% Target = #target{}
%% Value = atom()
%%
NewTarget = # target { }
%%
%% @doc Update an element in a target.
%% @end
%%--------------------------------------------------------------------
set_state(Target, Value) when is_record(Target, target), is_atom(Value) ->
Target#target{state = Value}.
%%--------------------------------------------------------------------
@spec ( Target , Value ) - >
NewTarget
%%
%% Target = #target{}
%% Value = #sp_response{}
%%
NewTarget = # target { }
%%
%% @doc Update an element in a target.
%% @end
%%--------------------------------------------------------------------
set_endresult(Target, Value) when is_record(Target, target), is_record(Value, sp_response) ->
Target#target{endresult = Value}.
%%--------------------------------------------------------------------
@spec ( Target , Value ) - >
NewTarget
%%
%% Target = #target{}
%% Value = [term()]
%%
NewTarget = # target { }
%%
%% @doc Update an element in a target.
%% @end
%%--------------------------------------------------------------------
set_dstlist(Target, Value) when is_record(Target, target), is_list(Value) ->
Target#target{dstlist = Value}.
%%--------------------------------------------------------------------
@spec ( Target , Value ) - >
NewTarget
%%
%% Target = #target{}
%% Value = true | false
%%
NewTarget = # target { }
%%
%% @doc Update an element in a target.
%% @end
%%--------------------------------------------------------------------
set_cancelled(Target, Value) when is_record(Target, target), is_boolean(Value) ->
Target#target{cancelled = Value}.
%%====================================================================
Internal functions
%%====================================================================
%%====================================================================
%% Test functions
%%====================================================================
%%--------------------------------------------------------------------
%% @spec () -> ok
%%
%% @doc autotest callback
%% @hidden
%% @end
%%--------------------------------------------------------------------
-ifdef( YXA_NO_UNITTEST ).
test() ->
{error, "Unit test code disabled at compile time"}.
-else.
test() ->
%% test empty/0
%%--------------------------------------------------------------------
autotest:mark(?LINE, "emtpy/0 - 1"),
#targetlist{list = []} = EmptyList = empty(),
test add/7
%%--------------------------------------------------------------------
AddReq = #request{method = "TEST",
uri = sipurl:parse("sip:")
},
autotest:mark(?LINE, "add/7 - 1"),
%% just add an element
List1 = add("branch1", AddReq, self(), trying, 4711, [123], {"user", "instance"}, EmptyList),
autotest:mark(?LINE, "add/7 - 2"),
%% test that we can't add another element with the same branch
List1 = add("branch1", AddReq, self(), calling, 123, [234], none, List1),
autotest:mark(?LINE, "add/7 - 3"),
%% add another target
List2 = add("branch2", AddReq, whereis(logger), completed, 123, [], {"user", "instance2"}, List1),
autotest:mark(?LINE, "add/7 - 4"),
%% another element
List3 = add("branch3", AddReq, whereis(init), terminated, 345, [], {"user2", "instance"}, List2),
autotest:mark(?LINE, "add/7 - 5"),
%% another element
List4 = add("branch4", AddReq, self(), trying, 345, [456], {"user2", "instance2"}, List3),
%% test length/1
%%--------------------------------------------------------------------
autotest:mark(?LINE, "get_length/1 - 1"),
%% check length
1 = get_length(List1),
autotest:mark(?LINE, "get_length/1 - 2"),
%% check length
4 = get_length(List4),
test get_using_branch/2
%%--------------------------------------------------------------------
autotest:mark(?LINE, "get_using_branch/2 - 1"),
%% check that we can get targets using branch
Target1 = get_using_branch("branch1", List4),
autotest:mark(?LINE, "get_using_branch/2 - 2"),
%% check that we can get targets using branch
none = get_using_branch("branch9", List4),
%% test extract/2
%%--------------------------------------------------------------------
autotest:mark(?LINE, "extract/2 - 1"),
check all the elements we added in the first target
Extract_Me = self(),
["branch1", AddReq, Extract_Me, trying, 4711, [123], {"user", "instance"}] =
extract([branch, request, pid, state, timeout, dstlist, user_instance], Target1),
test
%%--------------------------------------------------------------------
autotest:mark(?LINE, "get_using_pid/2 - 1"),
%% check that we can get targets using pid
Target1 = get_using_pid(self(), List4),
autotest:mark(?LINE, "get_using_pid/2 - 2"),
check that we can get targets using pid ( note : List2 does not have target 3 )
none = get_using_pid(whereis(init), List2),
%% test get_targets_in_state/2
%%--------------------------------------------------------------------
autotest:mark(?LINE, "get_targets_in_state/2 - 1"),
[#target{branch="branch3"}] = get_targets_in_state(terminated, List4),
autotest:mark(?LINE, "get_targets_in_state/2 - 2"),
[#target{branch="branch1"}, #target{branch="branch4"}] = get_targets_in_state(trying, List4),
autotest:mark(?LINE, "get_targets_in_state/2 - 3"),
[] = get_targets_in_state(none, List4),
%% test debugfriendly/1
%%--------------------------------------------------------------------
autotest:mark(?LINE, "debugfriendly/1 - 1"),
Debug1 = debugfriendly(List4),
autotest:mark(?LINE, "debugfriendly/1 - 2"),
%% check length of result, nothing more
4 = length(Debug1),
test update_target/2
%%--------------------------------------------------------------------
autotest:mark(?LINE, "update_target/2 - 1"),
%% test update with no change
List4 = update_target(Target1, List4),
autotest:mark(?LINE, "update_target/2 - 2.1"),
%% test update with small change
Target1Response = #sp_response{status=404, reason="Not Found"},
UpdatedTarget1 = set_endresult(Target1, Target1Response),
UpdatedList1 = update_target(UpdatedTarget1, List4),
autotest:mark(?LINE, "update_target/2 - 2.2"),
%% verify that target was updated
UpdatedTarget1 = get_using_branch("branch1", UpdatedList1),
autotest:mark(?LINE, "update_target/2 - 3.1"),
%% modify last target in the middle of list
Target3 = get_using_branch("branch3", UpdatedList1),
Target3Response = #sp_response{status=100, reason="Trying"},
UpdatedTarget3 = set_endresult(Target3, Target3Response),
autotest:mark(?LINE, "update_target/2 - 3.2"),
%% verify that we can update last target in list
UpdatedList3 = update_target(UpdatedTarget3, UpdatedList1),
autotest:mark(?LINE, "update_target/2 - 3.3"),
%% verify that target was updated
UpdatedTarget3 = get_using_branch("branch3", UpdatedList3),
autotest:mark(?LINE, "update_target/2 - 4.1"),
%% modify last target in list
Target4 = get_using_branch("branch4", UpdatedList3),
Target4Response = #sp_response{status=400, reason="Bad Request"},
UpdatedTarget4 = set_endresult(Target4, Target4Response),
autotest:mark(?LINE, "update_target/2 - 4.2"),
%% verify that we can update last target in list
UpdatedList4 = update_target(UpdatedTarget4, UpdatedList3),
autotest:mark(?LINE, "update_target/2 - 4.3"),
%% verify that target was updated
UpdatedTarget4 = get_using_branch("branch4", UpdatedList4),
autotest:mark(?LINE, "update_target/2 - 5"),
%% verify that we get an exception if we try to update non-existing target
{error, update_of_non_existin_target} = (catch update_target(UpdatedTarget4#target{ref="update_target test 5"}, UpdatedList4)),
%% test get_responses/1
%%--------------------------------------------------------------------
autotest:mark(?LINE, "update_target/2 - 1"),
check that we get the valid response , but not the invalid one ( ' 123 ' ) for target # 2
[Target1Response, Target3Response, Target4Response] = get_responses(UpdatedList4),
ok.
-endif.
| null | https://raw.githubusercontent.com/fredrikt/yxa/85da46a999d083e6f00b5f156a634ca9be65645b/src/targetlist.erl | erlang | -------------------------------------------------------------------
File : targetlist.erl
client transactions for sipproxy.
@end
-------------------------------------------------------------------
--------------------------------------------------------------------
External exports
--------------------------------------------------------------------
--------------------------------------------------------------------
Include files
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
Container record to make sure noone tries to modify our
records.
@type target() = #target{}.
no description
ref(), unique reference
string(), this clients branch
request record()
pid() of client transaction ???
atom(), SIP state of this target
integer()
none | sp_response record()
list() of sipdst record(), more destinations if this one fail
true | false, is this branch cancelled?
none | {User, Instance}
--------------------------------------------------------------------
--------------------------------------------------------------------
====================================================================
External functions
====================================================================
--------------------------------------------------------------------
NewTargetList
Branch = string()
Request = #request{}
State = atom()
Timeout = integer()
UserInst = none | {User, Instance}
target with this branch is not already in the list.
@end
--------------------------------------------------------------------
--------------------------------------------------------------------
@spec () ->
@end
--------------------------------------------------------------------
--------------------------------------------------------------------
Length
Length = integer()
record.
@end
--------------------------------------------------------------------
--------------------------------------------------------------------
NewTargetList
Target = #target{}
NewTargetList = [#target{}]
@throws {error, update_of_non_existin_target}
@end
--------------------------------------------------------------------
Match
No match
--------------------------------------------------------------------
Data
Data = term()
for logging using ~p.
@end
--------------------------------------------------------------------
--------------------------------------------------------------------
Target
Target = #target{} | none
@end
--------------------------------------------------------------------
--------------------------------------------------------------------
Target
Branch = string()
Target = #target{} | none
@end
--------------------------------------------------------------------
--------------------------------------------------------------------
State = term()
@end
--------------------------------------------------------------------
--------------------------------------------------------------------
[Response]
Response = #sp_response{} | {Status, Reason}
Status = integer() "SIP status code"
Reason = string() "SIP reason phrase"
@doc Get all responses that has been set (i.e. not undefined).
@end
--------------------------------------------------------------------
endresult is an sp_response record, add it to Res
endresult is 'none'
--------------------------------------------------------------------
@spec (Keys, Target) -> [term()]
Keys = [pid |
branch |
request |
state |
timeout |
dstlist |
cancelled]
Target = #target{}
the values in a list of the same order as Keys.
@end
--------------------------------------------------------------------
--------------------------------------------------------------------
Target = #target{}
Value = pid()
@doc Update an element in a target.
@end
--------------------------------------------------------------------
--------------------------------------------------------------------
Target = #target{}
Value = atom()
@doc Update an element in a target.
@end
--------------------------------------------------------------------
--------------------------------------------------------------------
Target = #target{}
Value = #sp_response{}
@doc Update an element in a target.
@end
--------------------------------------------------------------------
--------------------------------------------------------------------
Target = #target{}
Value = [term()]
@doc Update an element in a target.
@end
--------------------------------------------------------------------
--------------------------------------------------------------------
Target = #target{}
Value = true | false
@doc Update an element in a target.
@end
--------------------------------------------------------------------
====================================================================
====================================================================
====================================================================
Test functions
====================================================================
--------------------------------------------------------------------
@spec () -> ok
@doc autotest callback
@hidden
@end
--------------------------------------------------------------------
test empty/0
--------------------------------------------------------------------
--------------------------------------------------------------------
just add an element
test that we can't add another element with the same branch
add another target
another element
another element
test length/1
--------------------------------------------------------------------
check length
check length
--------------------------------------------------------------------
check that we can get targets using branch
check that we can get targets using branch
test extract/2
--------------------------------------------------------------------
--------------------------------------------------------------------
check that we can get targets using pid
test get_targets_in_state/2
--------------------------------------------------------------------
test debugfriendly/1
--------------------------------------------------------------------
check length of result, nothing more
--------------------------------------------------------------------
test update with no change
test update with small change
verify that target was updated
modify last target in the middle of list
verify that we can update last target in list
verify that target was updated
modify last target in list
verify that we can update last target in list
verify that target was updated
verify that we get an exception if we try to update non-existing target
test get_responses/1
-------------------------------------------------------------------- | @author < >
@doc is a module for managing a list of ongoing
@since 28 Jun 2003 by < >
@private
-module(targetlist).
-export([
add/8,
empty/0,
get_length/1,
debugfriendly/1,
get_using_pid/2,
get_using_branch/2,
get_targets_in_state/2,
get_responses/1,
extract/2,
set_pid/2,
set_state/2,
set_endresult/2,
set_dstlist/2,
set_cancelled/2,
update_target/2,
test/0
]).
-include("siprecords.hrl").
-include("sipproxy.hrl").
Records
@type ( ) = # targetlist { } .
-record(targetlist, {list}).
-record(target, {
}).
Macros
@spec ( Branch , Request , Pid , State , Timeout , DstList , UserInst ,
TargetList ) - >
Pid = pid ( )
DstList = [ # sipdst { } ]
TargetList = # targetlist { }
NewTargetList = # targetlist { }
@doc Add a new entry to TargetList , after verifying that a
add(Branch, Request, Pid, State, Timeout, DstList, UserInst, TargetList)
when is_list(Branch), is_record(Request, request), is_pid(Pid), is_atom(State), is_integer(Timeout),
is_list(DstList), is_record(TargetList, targetlist), (is_tuple(UserInst) orelse UserInst == none) ->
case get_using_branch(Branch, TargetList) of
none ->
NewTarget = #target{ref = make_ref(),
branch = Branch,
request = Request,
pid = Pid,
state = State,
dstlist = DstList,
timeout = Timeout,
user_instance = UserInst
},
#targetlist{list = lists:append(TargetList#targetlist.list, [NewTarget])};
T when is_record(T, target) ->
logger:log(error, "targetlist: Asked to add target with duplicate branch ~p to list :~n~p",
[branch, debugfriendly(TargetList)]),
TargetList
end.
TargetList
TargetList = # targetlist { }
@doc Return empty record . For initialization .
empty() ->
#targetlist{list = []}.
@spec ( TargetList ) - >
TargetList = # targetlist { }
@doc Return length of list encapsulated in the TargetList
get_length(TargetList) when is_record(TargetList, targetlist) ->
length(TargetList#targetlist.list).
@spec ( Target , TargetList ) - >
TargetList = # targetlist { }
@doc Locate the old instance of the target Target in the
TargetList and exchange it with Target .
update_target(Target, TargetList) when is_record(Target, target), is_record(TargetList, targetlist) ->
Ref = Target#target.ref,
NewList = update_target2(Ref, Target, TargetList#targetlist.list, []),
#targetlist{list = NewList}.
update_target2(Ref, _NewT, [], Res) ->
logger:log(error, "Targetlist: Asked to update a target, but I can't find it"),
logger:log(debug, "Targetlist: Asked to update a target with ref=~p, but I can't find it in list :~n~p",
[Ref, debugfriendly2( lists:reverse(Res), [])]),
throw({error, update_of_non_existin_target});
update_target2(Ref, NewT, [#target{ref=Ref} | T], Res) ->
Head = lists:reverse([NewT | Res]),
Head ++ T;
update_target2(Ref, NewT, [H | T], Res) when is_record(H, target) ->
update_target2(Ref, NewT, T, [H | Res]).
@spec ( TargetList ) - >
TargetList = # targetlist { }
@doc Format the entrys in TargetList in a way that is suitable
debugfriendly(TargetList) when is_record(TargetList, targetlist) ->
debugfriendly2(TargetList#targetlist.list, []).
debugfriendly2([], Res) ->
lists:reverse(Res);
debugfriendly2([H | T], Res) when is_record(H, target) ->
#request{method = Method, uri = URI} = H#target.request,
RespStr = case H#target.endresult of
none -> "no response";
R when is_record(R, sp_response) ->
lists:concat(["response=", R#sp_response.status, " ", R#sp_response.reason]);
_ -> "INVALID response"
end,
Str = lists:concat(["pid=", pid_to_list(H#target.pid),
", branch=", H#target.branch,
", request=", Method, " ",
sipurl:print(URI), ", ",
RespStr,
", cancelled=", H#target.cancelled,
", state=" , H#target.state]),
debugfriendly2(T, [binary_to_list(list_to_binary(Str)) | Res]).
@spec ( Pid , TargetList ) - >
Pid = pid ( )
TargetList = # targetlist { }
@doc Get the target with pid matching Pid from TargetList .
get_using_pid(Pid, TargetList) when is_pid(Pid), is_record(TargetList, targetlist) ->
get_using_pid2(Pid, TargetList#targetlist.list).
get_using_pid2(_Pid, []) ->
none;
get_using_pid2(Pid, [H | _T]) when is_record(H, target), H#target.pid == Pid ->
H;
get_using_pid2(Pid, [H | T]) when is_record(H, target) ->
get_using_pid2(Pid, T).
@spec ( Branch , TargetList ) - >
TargetList = # targetlist { }
@doc Get the target with branch matching Branch .
get_using_branch(Branch, TargetList) when is_list(Branch), is_record(TargetList, targetlist) ->
get_using_branch2(Branch, TargetList#targetlist.list).
get_using_branch2(_Branch, []) ->
none;
get_using_branch2(Branch, [#target{branch=Branch}=H | _T]) ->
H;
get_using_branch2(Branch, [H | T]) when is_record(H, target) ->
get_using_branch2(Branch, T).
@spec ( State , TargetList ) - >
TargetList
TargetList = # targetlist { }
TargetList = [ # target { } ]
@doc Get all targets with state matching State .
get_targets_in_state(State, TargetList) when is_record(TargetList, targetlist) ->
get_targets_in_state2(State, TargetList#targetlist.list, []).
get_targets_in_state2(_State, [], Res) ->
lists:reverse(Res);
get_targets_in_state2(State, [H | T], Res) when is_record(H, target), H#target.state == State ->
get_targets_in_state2(State, T, [H | Res]);
get_targets_in_state2(State, [H | T], Res) when is_record(H, target) ->
get_targets_in_state2(State, T, Res).
@spec ( TargetList ) - >
TargetList = # targetlist { }
get_responses(TargetList) when is_record(TargetList, targetlist) ->
get_responses2(TargetList#targetlist.list, []).
get_responses2([], Res) ->
lists:reverse(Res);
get_responses2([#target{endresult = H} | T], Res) when is_record(H, sp_response) ->
get_responses2(T, [H | Res]);
get_responses2([#target{endresult = none} | T], Res) ->
get_responses2(T, Res).
endresult |
@doc Extract one or more values from a target record . Return
extract(Values, Target) when is_record(Target, target) ->
extract(Values, Target, []).
extract([pid | T], #target{pid = Value} = Ta, Res) -> extract(T, Ta, [Value | Res]);
extract([branch | T], #target{branch = Value} = Ta, Res) -> extract(T, Ta, [Value | Res]);
extract([request | T], #target{request = Value} = Ta, Res) -> extract(T, Ta, [Value | Res]);
extract([state | T], #target{state = Value} = Ta, Res) -> extract(T, Ta, [Value | Res]);
extract([timeout | T], #target{timeout = Value} = Ta, Res) -> extract(T, Ta, [Value | Res]);
extract([dstlist | T], #target{dstlist = Value} = Ta, Res) -> extract(T, Ta, [Value | Res]);
extract([endresult | T], #target{endresult = Value} = Ta, Res) -> extract(T, Ta, [Value | Res]);
extract([cancelled | T], #target{cancelled = Value} = Ta, Res) -> extract(T, Ta, [Value | Res]);
extract([user_instance | T], #target{user_instance = Value} = Ta, Res) -> extract(T, Ta, [Value | Res]);
extract([], #target{}, Res) -> lists:reverse(Res).
@spec ( Target , Value ) - >
NewTarget
NewTarget = # target { }
set_pid(Target, Value) when is_record(Target, target), is_pid(Value) ->
Target#target{pid = Value}.
@spec ( Target , Value ) - >
NewTarget
NewTarget = # target { }
set_state(Target, Value) when is_record(Target, target), is_atom(Value) ->
Target#target{state = Value}.
@spec ( Target , Value ) - >
NewTarget
NewTarget = # target { }
set_endresult(Target, Value) when is_record(Target, target), is_record(Value, sp_response) ->
Target#target{endresult = Value}.
@spec ( Target , Value ) - >
NewTarget
NewTarget = # target { }
set_dstlist(Target, Value) when is_record(Target, target), is_list(Value) ->
Target#target{dstlist = Value}.
@spec ( Target , Value ) - >
NewTarget
NewTarget = # target { }
set_cancelled(Target, Value) when is_record(Target, target), is_boolean(Value) ->
Target#target{cancelled = Value}.
Internal functions
-ifdef( YXA_NO_UNITTEST ).
test() ->
{error, "Unit test code disabled at compile time"}.
-else.
test() ->
autotest:mark(?LINE, "emtpy/0 - 1"),
#targetlist{list = []} = EmptyList = empty(),
test add/7
AddReq = #request{method = "TEST",
uri = sipurl:parse("sip:")
},
autotest:mark(?LINE, "add/7 - 1"),
List1 = add("branch1", AddReq, self(), trying, 4711, [123], {"user", "instance"}, EmptyList),
autotest:mark(?LINE, "add/7 - 2"),
List1 = add("branch1", AddReq, self(), calling, 123, [234], none, List1),
autotest:mark(?LINE, "add/7 - 3"),
List2 = add("branch2", AddReq, whereis(logger), completed, 123, [], {"user", "instance2"}, List1),
autotest:mark(?LINE, "add/7 - 4"),
List3 = add("branch3", AddReq, whereis(init), terminated, 345, [], {"user2", "instance"}, List2),
autotest:mark(?LINE, "add/7 - 5"),
List4 = add("branch4", AddReq, self(), trying, 345, [456], {"user2", "instance2"}, List3),
autotest:mark(?LINE, "get_length/1 - 1"),
1 = get_length(List1),
autotest:mark(?LINE, "get_length/1 - 2"),
4 = get_length(List4),
test get_using_branch/2
autotest:mark(?LINE, "get_using_branch/2 - 1"),
Target1 = get_using_branch("branch1", List4),
autotest:mark(?LINE, "get_using_branch/2 - 2"),
none = get_using_branch("branch9", List4),
autotest:mark(?LINE, "extract/2 - 1"),
check all the elements we added in the first target
Extract_Me = self(),
["branch1", AddReq, Extract_Me, trying, 4711, [123], {"user", "instance"}] =
extract([branch, request, pid, state, timeout, dstlist, user_instance], Target1),
test
autotest:mark(?LINE, "get_using_pid/2 - 1"),
Target1 = get_using_pid(self(), List4),
autotest:mark(?LINE, "get_using_pid/2 - 2"),
check that we can get targets using pid ( note : List2 does not have target 3 )
none = get_using_pid(whereis(init), List2),
autotest:mark(?LINE, "get_targets_in_state/2 - 1"),
[#target{branch="branch3"}] = get_targets_in_state(terminated, List4),
autotest:mark(?LINE, "get_targets_in_state/2 - 2"),
[#target{branch="branch1"}, #target{branch="branch4"}] = get_targets_in_state(trying, List4),
autotest:mark(?LINE, "get_targets_in_state/2 - 3"),
[] = get_targets_in_state(none, List4),
autotest:mark(?LINE, "debugfriendly/1 - 1"),
Debug1 = debugfriendly(List4),
autotest:mark(?LINE, "debugfriendly/1 - 2"),
4 = length(Debug1),
test update_target/2
autotest:mark(?LINE, "update_target/2 - 1"),
List4 = update_target(Target1, List4),
autotest:mark(?LINE, "update_target/2 - 2.1"),
Target1Response = #sp_response{status=404, reason="Not Found"},
UpdatedTarget1 = set_endresult(Target1, Target1Response),
UpdatedList1 = update_target(UpdatedTarget1, List4),
autotest:mark(?LINE, "update_target/2 - 2.2"),
UpdatedTarget1 = get_using_branch("branch1", UpdatedList1),
autotest:mark(?LINE, "update_target/2 - 3.1"),
Target3 = get_using_branch("branch3", UpdatedList1),
Target3Response = #sp_response{status=100, reason="Trying"},
UpdatedTarget3 = set_endresult(Target3, Target3Response),
autotest:mark(?LINE, "update_target/2 - 3.2"),
UpdatedList3 = update_target(UpdatedTarget3, UpdatedList1),
autotest:mark(?LINE, "update_target/2 - 3.3"),
UpdatedTarget3 = get_using_branch("branch3", UpdatedList3),
autotest:mark(?LINE, "update_target/2 - 4.1"),
Target4 = get_using_branch("branch4", UpdatedList3),
Target4Response = #sp_response{status=400, reason="Bad Request"},
UpdatedTarget4 = set_endresult(Target4, Target4Response),
autotest:mark(?LINE, "update_target/2 - 4.2"),
UpdatedList4 = update_target(UpdatedTarget4, UpdatedList3),
autotest:mark(?LINE, "update_target/2 - 4.3"),
UpdatedTarget4 = get_using_branch("branch4", UpdatedList4),
autotest:mark(?LINE, "update_target/2 - 5"),
{error, update_of_non_existin_target} = (catch update_target(UpdatedTarget4#target{ref="update_target test 5"}, UpdatedList4)),
autotest:mark(?LINE, "update_target/2 - 1"),
check that we get the valid response , but not the invalid one ( ' 123 ' ) for target # 2
[Target1Response, Target3Response, Target4Response] = get_responses(UpdatedList4),
ok.
-endif.
|
2236dc5c92ff3acf2e12260cf095033e88f1edd79721940f3e2e1248791efd31 | awslabs/s2n-bignum | bignum_sub_p256.ml |
* Copyright Amazon.com , Inc. or its affiliates . All Rights Reserved .
* SPDX - License - Identifier : Apache-2.0 OR ISC
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0 OR ISC
*)
(* ========================================================================= *)
Subtraction modulo p_256 , the field characteristic for NIST P-256 curve .
(* ========================================================================= *)
(**** print_literal_from_elf "arm/p256/bignum_sub_p256.o";;
****)
let bignum_sub_p256_mc = define_assert_from_elf "bignum_sub_p256_mc" "arm/p256/bignum_sub_p256.o"
[
arm_LDP X5 X6 X1 ( Immediate_Offset ( iword ( & 0 ) ) )
arm_LDP X4 X3 X2 ( Immediate_Offset ( iword ( & 0 ) ) )
arm_SUBS X5 X5 X4
arm_SBCS X6 X6 X3
arm_LDP X7 X8 X1 ( Immediate_Offset ( iword ( & 16 ) ) )
arm_LDP X4 X3 X2 ( Immediate_Offset ( iword ( & 16 ) ) )
arm_SBCS X7 X7 X4
arm_SBCS X8 X8 X3
0xda9f23e3; (* arm_CSETM X3 Condition_CC *)
arm_ADDS X5 X5 X3
arm_AND ( rvalue ( word 4294967295 ) )
arm_ADCS X6 X6 X4
arm_ADCS X7 X7 XZR
arm_AND ( rvalue ( word 18446744069414584321 ) )
arm_ADC X8 X8 X4
arm_STP X5 ( Immediate_Offset ( iword ( & 0 ) ) )
arm_STP X7 ( Immediate_Offset ( iword ( & 16 ) ) )
arm_RET X30
];;
let BIGNUM_SUB_P256_EXEC = ARM_MK_EXEC_RULE bignum_sub_p256_mc;;
(* ------------------------------------------------------------------------- *)
(* Proof. *)
(* ------------------------------------------------------------------------- *)
let p_256 = new_definition `p_256 = 115792089210356248762697446949407573530086143415290314195533631308867097853951`;;
let BIGNUM_SUB_P256_CORRECT = time prove
(`!z x y m n pc.
nonoverlapping (word pc,0x48) (z,8 * 4)
==> ensures arm
(\s. aligned_bytes_loaded s (word pc) bignum_sub_p256_mc /\
read PC s = word pc /\
C_ARGUMENTS [z; x; y] s /\
bignum_from_memory (x,4) s = m /\
bignum_from_memory (y,4) s = n)
(\s. read PC s = word (pc + 0x44) /\
(m < p_256 /\ n < p_256
==> &(bignum_from_memory (z,4) s) = (&m - &n) rem &p_256))
(MAYCHANGE [PC; X3; X4; X5; X6; X7; X8] ,,
MAYCHANGE SOME_FLAGS ,,
MAYCHANGE [memory :> bignum(z,4)])`,
MAP_EVERY X_GEN_TAC
[`z:int64`; `x:int64`; `y:int64`; `m:num`; `n:num`; `pc:num`] THEN
REWRITE_TAC[C_ARGUMENTS; C_RETURN; SOME_FLAGS; NONOVERLAPPING_CLAUSES] THEN
DISCH_THEN(REPEAT_TCL CONJUNCTS_THEN ASSUME_TAC) THEN
REWRITE_TAC[BIGNUM_FROM_MEMORY_BYTES] THEN ENSURES_INIT_TAC "s0" THEN
BIGNUM_DIGITIZE_TAC "m_" `read (memory :> bytes (x,8 * 4)) s0` THEN
BIGNUM_DIGITIZE_TAC "n_" `read (memory :> bytes (y,8 * 4)) s0` THEN
ARM_ACCSTEPS_TAC BIGNUM_SUB_P256_EXEC (1--8) (1--8) THEN
SUBGOAL_THEN `carry_s8 <=> m < n` SUBST_ALL_TAC THENL
[MATCH_MP_TAC FLAG_FROM_CARRY_LT THEN EXISTS_TAC `256` THEN
MAP_EVERY EXPAND_TAC ["m"; "n"] THEN REWRITE_TAC[GSYM REAL_OF_NUM_ADD] THEN
REWRITE_TAC[GSYM REAL_OF_NUM_MUL; GSYM REAL_OF_NUM_POW] THEN
ACCUMULATOR_ASSUM_LIST(MP_TAC o end_itlist CONJ o DECARRY_RULE) THEN
DISCH_THEN(fun th -> REWRITE_TAC[th]) THEN BOUNDER_TAC[];
ALL_TAC] THEN
ARM_STEPS_TAC BIGNUM_SUB_P256_EXEC [9] THEN
RULE_ASSUM_TAC(REWRITE_RULE[WORD_UNMASK_64; NOT_LE]) THEN
ARM_ACCSTEPS_TAC BIGNUM_SUB_P256_EXEC (10--17) (10--17) THEN
ENSURES_FINAL_STATE_TAC THEN ASM_REWRITE_TAC[] THEN STRIP_TAC THEN
CONV_TAC(LAND_CONV(RAND_CONV BIGNUM_EXPAND_CONV)) THEN
ASM_REWRITE_TAC[] THEN DISCARD_STATE_TAC "s17" THEN
CONV_TAC SYM_CONV THEN MATCH_MP_TAC INT_REM_UNIQ THEN
EXISTS_TAC `--(&(bitval(m < n))):int` THEN REWRITE_TAC[INT_ABS_NUM] THEN
REWRITE_TAC[INT_ARITH `m - n:int = --b * p + z <=> z = b * p + m - n`] THEN
REWRITE_TAC[int_eq; int_le; int_lt] THEN
REWRITE_TAC[int_add_th; int_mul_th; int_of_num_th; int_sub_th] THEN
REWRITE_TAC[GSYM REAL_OF_NUM_ADD; GSYM REAL_OF_NUM_MUL;
GSYM REAL_OF_NUM_POW] THEN
MATCH_MP_TAC(REAL_ARITH
`!t:real. p < t /\
(&0 <= a /\ a < p) /\
(&0 <= z /\ z < t) /\
((&0 <= z /\ z < t) /\ (&0 <= a /\ a < t) ==> z = a)
==> z = a /\ &0 <= z /\ z < p`) THEN
EXISTS_TAC `(&2:real) pow 256` THEN
CONJ_TAC THENL [REWRITE_TAC[p_256] THEN REAL_ARITH_TAC; ALL_TAC] THEN
CONJ_TAC THENL
[MAP_EVERY UNDISCH_TAC [`m < p_256`; `n < p_256`] THEN
REWRITE_TAC[GSYM REAL_OF_NUM_LT] THEN
ASM_CASES_TAC `&m:real < &n` THEN ASM_REWRITE_TAC[BITVAL_CLAUSES] THEN
POP_ASSUM MP_TAC THEN REWRITE_TAC[p_256] THEN REAL_ARITH_TAC;
ALL_TAC] THEN
CONJ_TAC THENL [BOUNDER_TAC[]; STRIP_TAC] THEN
MATCH_MP_TAC EQUAL_FROM_CONGRUENT_REAL THEN
MAP_EVERY EXISTS_TAC [`256`; `&0:real`] THEN
ASM_REWRITE_TAC[] THEN
CONJ_TAC THENL [REAL_INTEGER_TAC; ALL_TAC] THEN
ACCUMULATOR_POP_ASSUM_LIST(MP_TAC o end_itlist CONJ o DESUM_RULE) THEN
REWRITE_TAC[WORD_AND_MASK] THEN
COND_CASES_TAC THEN ASM_REWRITE_TAC[BITVAL_CLAUSES] THEN
CONV_TAC WORD_REDUCE_CONV THEN
MAP_EVERY EXPAND_TAC ["m"; "n"] THEN REWRITE_TAC[GSYM REAL_OF_NUM_ADD] THEN
REWRITE_TAC[GSYM REAL_OF_NUM_MUL; GSYM REAL_OF_NUM_POW; p_256] THEN
DISCH_THEN(fun th -> REWRITE_TAC[th]) THEN
CONV_TAC(RAND_CONV REAL_POLY_CONV) THEN REAL_INTEGER_TAC);;
let BIGNUM_SUB_P256_SUBROUTINE_CORRECT = time prove
(`!z x y m n pc returnaddress.
nonoverlapping (word pc,0x48) (z,8 * 4)
==> ensures arm
(\s. aligned_bytes_loaded s (word pc) bignum_sub_p256_mc /\
read PC s = word pc /\
read X30 s = returnaddress /\
C_ARGUMENTS [z; x; y] s /\
bignum_from_memory (x,4) s = m /\
bignum_from_memory (y,4) s = n)
(\s. read PC s = returnaddress /\
(m < p_256 /\ n < p_256
==> &(bignum_from_memory (z,4) s) = (&m - &n) rem &p_256))
(MAYCHANGE [PC; X3; X4; X5; X6; X7; X8] ,,
MAYCHANGE SOME_FLAGS ,,
MAYCHANGE [memory :> bignum(z,4)])`,
ARM_ADD_RETURN_NOSTACK_TAC BIGNUM_SUB_P256_EXEC BIGNUM_SUB_P256_CORRECT);;
| null | https://raw.githubusercontent.com/awslabs/s2n-bignum/824c15f908d7a343af1b2f378cfedd36e880bdde/arm/proofs/bignum_sub_p256.ml | ocaml | =========================================================================
=========================================================================
*** print_literal_from_elf "arm/p256/bignum_sub_p256.o";;
***
arm_CSETM X3 Condition_CC
-------------------------------------------------------------------------
Proof.
------------------------------------------------------------------------- |
* Copyright Amazon.com , Inc. or its affiliates . All Rights Reserved .
* SPDX - License - Identifier : Apache-2.0 OR ISC
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0 OR ISC
*)
Subtraction modulo p_256 , the field characteristic for NIST P-256 curve .
let bignum_sub_p256_mc = define_assert_from_elf "bignum_sub_p256_mc" "arm/p256/bignum_sub_p256.o"
[
arm_LDP X5 X6 X1 ( Immediate_Offset ( iword ( & 0 ) ) )
arm_LDP X4 X3 X2 ( Immediate_Offset ( iword ( & 0 ) ) )
arm_SUBS X5 X5 X4
arm_SBCS X6 X6 X3
arm_LDP X7 X8 X1 ( Immediate_Offset ( iword ( & 16 ) ) )
arm_LDP X4 X3 X2 ( Immediate_Offset ( iword ( & 16 ) ) )
arm_SBCS X7 X7 X4
arm_SBCS X8 X8 X3
arm_ADDS X5 X5 X3
arm_AND ( rvalue ( word 4294967295 ) )
arm_ADCS X6 X6 X4
arm_ADCS X7 X7 XZR
arm_AND ( rvalue ( word 18446744069414584321 ) )
arm_ADC X8 X8 X4
arm_STP X5 ( Immediate_Offset ( iword ( & 0 ) ) )
arm_STP X7 ( Immediate_Offset ( iword ( & 16 ) ) )
arm_RET X30
];;
let BIGNUM_SUB_P256_EXEC = ARM_MK_EXEC_RULE bignum_sub_p256_mc;;
let p_256 = new_definition `p_256 = 115792089210356248762697446949407573530086143415290314195533631308867097853951`;;
let BIGNUM_SUB_P256_CORRECT = time prove
(`!z x y m n pc.
nonoverlapping (word pc,0x48) (z,8 * 4)
==> ensures arm
(\s. aligned_bytes_loaded s (word pc) bignum_sub_p256_mc /\
read PC s = word pc /\
C_ARGUMENTS [z; x; y] s /\
bignum_from_memory (x,4) s = m /\
bignum_from_memory (y,4) s = n)
(\s. read PC s = word (pc + 0x44) /\
(m < p_256 /\ n < p_256
==> &(bignum_from_memory (z,4) s) = (&m - &n) rem &p_256))
(MAYCHANGE [PC; X3; X4; X5; X6; X7; X8] ,,
MAYCHANGE SOME_FLAGS ,,
MAYCHANGE [memory :> bignum(z,4)])`,
MAP_EVERY X_GEN_TAC
[`z:int64`; `x:int64`; `y:int64`; `m:num`; `n:num`; `pc:num`] THEN
REWRITE_TAC[C_ARGUMENTS; C_RETURN; SOME_FLAGS; NONOVERLAPPING_CLAUSES] THEN
DISCH_THEN(REPEAT_TCL CONJUNCTS_THEN ASSUME_TAC) THEN
REWRITE_TAC[BIGNUM_FROM_MEMORY_BYTES] THEN ENSURES_INIT_TAC "s0" THEN
BIGNUM_DIGITIZE_TAC "m_" `read (memory :> bytes (x,8 * 4)) s0` THEN
BIGNUM_DIGITIZE_TAC "n_" `read (memory :> bytes (y,8 * 4)) s0` THEN
ARM_ACCSTEPS_TAC BIGNUM_SUB_P256_EXEC (1--8) (1--8) THEN
SUBGOAL_THEN `carry_s8 <=> m < n` SUBST_ALL_TAC THENL
[MATCH_MP_TAC FLAG_FROM_CARRY_LT THEN EXISTS_TAC `256` THEN
MAP_EVERY EXPAND_TAC ["m"; "n"] THEN REWRITE_TAC[GSYM REAL_OF_NUM_ADD] THEN
REWRITE_TAC[GSYM REAL_OF_NUM_MUL; GSYM REAL_OF_NUM_POW] THEN
ACCUMULATOR_ASSUM_LIST(MP_TAC o end_itlist CONJ o DECARRY_RULE) THEN
DISCH_THEN(fun th -> REWRITE_TAC[th]) THEN BOUNDER_TAC[];
ALL_TAC] THEN
ARM_STEPS_TAC BIGNUM_SUB_P256_EXEC [9] THEN
RULE_ASSUM_TAC(REWRITE_RULE[WORD_UNMASK_64; NOT_LE]) THEN
ARM_ACCSTEPS_TAC BIGNUM_SUB_P256_EXEC (10--17) (10--17) THEN
ENSURES_FINAL_STATE_TAC THEN ASM_REWRITE_TAC[] THEN STRIP_TAC THEN
CONV_TAC(LAND_CONV(RAND_CONV BIGNUM_EXPAND_CONV)) THEN
ASM_REWRITE_TAC[] THEN DISCARD_STATE_TAC "s17" THEN
CONV_TAC SYM_CONV THEN MATCH_MP_TAC INT_REM_UNIQ THEN
EXISTS_TAC `--(&(bitval(m < n))):int` THEN REWRITE_TAC[INT_ABS_NUM] THEN
REWRITE_TAC[INT_ARITH `m - n:int = --b * p + z <=> z = b * p + m - n`] THEN
REWRITE_TAC[int_eq; int_le; int_lt] THEN
REWRITE_TAC[int_add_th; int_mul_th; int_of_num_th; int_sub_th] THEN
REWRITE_TAC[GSYM REAL_OF_NUM_ADD; GSYM REAL_OF_NUM_MUL;
GSYM REAL_OF_NUM_POW] THEN
MATCH_MP_TAC(REAL_ARITH
`!t:real. p < t /\
(&0 <= a /\ a < p) /\
(&0 <= z /\ z < t) /\
((&0 <= z /\ z < t) /\ (&0 <= a /\ a < t) ==> z = a)
==> z = a /\ &0 <= z /\ z < p`) THEN
EXISTS_TAC `(&2:real) pow 256` THEN
CONJ_TAC THENL [REWRITE_TAC[p_256] THEN REAL_ARITH_TAC; ALL_TAC] THEN
CONJ_TAC THENL
[MAP_EVERY UNDISCH_TAC [`m < p_256`; `n < p_256`] THEN
REWRITE_TAC[GSYM REAL_OF_NUM_LT] THEN
ASM_CASES_TAC `&m:real < &n` THEN ASM_REWRITE_TAC[BITVAL_CLAUSES] THEN
POP_ASSUM MP_TAC THEN REWRITE_TAC[p_256] THEN REAL_ARITH_TAC;
ALL_TAC] THEN
CONJ_TAC THENL [BOUNDER_TAC[]; STRIP_TAC] THEN
MATCH_MP_TAC EQUAL_FROM_CONGRUENT_REAL THEN
MAP_EVERY EXISTS_TAC [`256`; `&0:real`] THEN
ASM_REWRITE_TAC[] THEN
CONJ_TAC THENL [REAL_INTEGER_TAC; ALL_TAC] THEN
ACCUMULATOR_POP_ASSUM_LIST(MP_TAC o end_itlist CONJ o DESUM_RULE) THEN
REWRITE_TAC[WORD_AND_MASK] THEN
COND_CASES_TAC THEN ASM_REWRITE_TAC[BITVAL_CLAUSES] THEN
CONV_TAC WORD_REDUCE_CONV THEN
MAP_EVERY EXPAND_TAC ["m"; "n"] THEN REWRITE_TAC[GSYM REAL_OF_NUM_ADD] THEN
REWRITE_TAC[GSYM REAL_OF_NUM_MUL; GSYM REAL_OF_NUM_POW; p_256] THEN
DISCH_THEN(fun th -> REWRITE_TAC[th]) THEN
CONV_TAC(RAND_CONV REAL_POLY_CONV) THEN REAL_INTEGER_TAC);;
let BIGNUM_SUB_P256_SUBROUTINE_CORRECT = time prove
(`!z x y m n pc returnaddress.
nonoverlapping (word pc,0x48) (z,8 * 4)
==> ensures arm
(\s. aligned_bytes_loaded s (word pc) bignum_sub_p256_mc /\
read PC s = word pc /\
read X30 s = returnaddress /\
C_ARGUMENTS [z; x; y] s /\
bignum_from_memory (x,4) s = m /\
bignum_from_memory (y,4) s = n)
(\s. read PC s = returnaddress /\
(m < p_256 /\ n < p_256
==> &(bignum_from_memory (z,4) s) = (&m - &n) rem &p_256))
(MAYCHANGE [PC; X3; X4; X5; X6; X7; X8] ,,
MAYCHANGE SOME_FLAGS ,,
MAYCHANGE [memory :> bignum(z,4)])`,
ARM_ADD_RETURN_NOSTACK_TAC BIGNUM_SUB_P256_EXEC BIGNUM_SUB_P256_CORRECT);;
|
39b11c30b8ab5b74f9eebe1a8963b6a3cc201859027b33d9a0eeb895cb84ef90 | HunterYIboHu/htdp2-solution | ex88-VPC-Struct-define.rkt | The first three lines of this file were inserted by . They record metadata
;; about the language level of this file in a form that our tools can easily process.
#reader(lib "htdp-beginner-abbr-reader.ss" "lang")((modname ex88-VPC-Struct-define) (read-case-sensitive #t) (teachpacks ((lib "image.rkt" "teachpack" "2htdp") (lib "universe.rkt" "teachpack" "2htdp"))) (htdp-settings #(#t constructor repeating-decimal #f #t none #f ((lib "image.rkt" "teachpack" "2htdp") (lib "universe.rkt" "teachpack" "2htdp")) #f)))
(define-struct vcat [pos hp])
VCat = ( make - vcat Number Number )
; interpretation (make-cat p h) means the cat's x-coordinate and
; cat's happiness point.
(define vc-1 (make-vcat 45 50))
; Full cat-program
VCat - > VCat
; consume a initial state and return the next one.
(define (cat-prog vcat)
(big-bang vcat
[on-tick tock]
[on-key press-key]
[to-draw render]))
| null | https://raw.githubusercontent.com/HunterYIboHu/htdp2-solution/6182b4c2ef650ac7059f3c143f639d09cd708516/Chapter1/Section5/ex88-VPC-Struct-define.rkt | racket | about the language level of this file in a form that our tools can easily process.
interpretation (make-cat p h) means the cat's x-coordinate and
cat's happiness point.
Full cat-program
consume a initial state and return the next one. | The first three lines of this file were inserted by . They record metadata
#reader(lib "htdp-beginner-abbr-reader.ss" "lang")((modname ex88-VPC-Struct-define) (read-case-sensitive #t) (teachpacks ((lib "image.rkt" "teachpack" "2htdp") (lib "universe.rkt" "teachpack" "2htdp"))) (htdp-settings #(#t constructor repeating-decimal #f #t none #f ((lib "image.rkt" "teachpack" "2htdp") (lib "universe.rkt" "teachpack" "2htdp")) #f)))
(define-struct vcat [pos hp])
VCat = ( make - vcat Number Number )
(define vc-1 (make-vcat 45 50))
VCat - > VCat
(define (cat-prog vcat)
(big-bang vcat
[on-tick tock]
[on-key press-key]
[to-draw render]))
|
2bdea44db7c3cace7d48ffbb89d332f3f4155812f674d1fbb1e62128b8c9d2ae | erlyaws/yaws | rewritetest.erl | -module(rewritetest).
-export([arg_rewrite/1]).
-include("../../include/yaws.hrl").
-include("../../include/yaws_api.hrl").
arg_rewrite(Arg) ->
Url = yaws_api:request_url(Arg),
case Url#url.path of
"/rewrite" ++ Rest ->
Req0 = Arg#arg.req,
Req1 = Req0#http_request{path={abs_path,Rest}},
Arg#arg{req=Req1};
_ ->
Arg
end.
| null | https://raw.githubusercontent.com/erlyaws/yaws/da198c828e9d95ca2137da7884cddadd73941d13/testsuite/revproxy_SUITE_data/rewritetest.erl | erlang | -module(rewritetest).
-export([arg_rewrite/1]).
-include("../../include/yaws.hrl").
-include("../../include/yaws_api.hrl").
arg_rewrite(Arg) ->
Url = yaws_api:request_url(Arg),
case Url#url.path of
"/rewrite" ++ Rest ->
Req0 = Arg#arg.req,
Req1 = Req0#http_request{path={abs_path,Rest}},
Arg#arg{req=Req1};
_ ->
Arg
end.
| |
03ec1bfb287df88961c9100443bd12b6b61532200e4c0aed6c6e19125dd07253 | FranklinChen/hugs98-plus-Sep2006 | PickSquare.hs |
PickSquare.hs ( adapted from picksquare.c which is ( c ) Silicon Graphics , Inc. )
Copyright ( c ) 2002 - 2005 < >
This file is part of HOpenGL and distributed under a BSD - style license
See the file libraries / GLUT / LICENSE
Use of multiple names and picking are demonstrated . A 3x3 grid of squares is
drawn . When the left mouse button is pressed , all squares under the cursor
position have their color changed .
PickSquare.hs (adapted from picksquare.c which is (c) Silicon Graphics, Inc.)
Copyright (c) Sven Panne 2002-2005 <>
This file is part of HOpenGL and distributed under a BSD-style license
See the file libraries/GLUT/LICENSE
Use of multiple names and picking are demonstrated. A 3x3 grid of squares is
drawn. When the left mouse button is pressed, all squares under the cursor
position have their color changed.
-}
import Data.Array ( Array, listArray, (!) )
import Data.IORef ( IORef, newIORef )
import System.Exit ( exitWith, ExitCode(ExitSuccess) )
import Graphics.UI.GLUT
type Board = Array (GLint,GLint) (IORef Int)
data State = State { board :: Board }
makeState :: IO State
makeState = do
refs <- sequence . replicate 9 . newIORef $ 0
return $ State { board = listArray ((0,0),(2,2)) refs }
-- Clear color value for every square on the board
myInit :: IO ()
myInit = do
clearColor $= Color4 0 0 0 0
The nine squares are drawn . Each square is given two names : one for the row
-- and the other for the column on the grid. The color of each square is
-- determined by its position on the grid, and the value in the board array.
-- Note: In contrast to the the original example, we always give names to
-- squares, regardless of the render mode. This simplifies the code a bit and
is even suggested by the Red Book .
drawSquares :: State -> IO ()
drawSquares state =
flip mapM_ [ 0 .. 2 ] $ \i -> do
loadName (Name (fromIntegral i))
flip mapM_ [ 0 .. 2 ] $ \j ->
withName (Name (fromIntegral j)) $ do
val <- get (board state ! (i,j))
-- resolve overloading, not needed in "real" programs
let color3f = color :: Color3 GLfloat -> IO ()
color3f (Color3 (fromIntegral i / 3.0)
(fromIntegral j / 3.0)
(fromIntegral val / 3.0))
rect (Vertex2 i j) (Vertex2 (i + 1) (j + 1))
-- processHits prints the hit records and updates the board array.
processHits :: Maybe[HitRecord] -> State -> IO ()
processHits Nothing _ = putStrLn "selection buffer overflow"
processHits (Just hitRecords) state = do
putStrLn ("hits = " ++ show (length hitRecords))
mapM_ (\(HitRecord z1 z2 names) -> do
putStrLn (" number of names for this hit = " ++ show (length names))
putStr (" z1 is " ++ show z1)
putStrLn ("; z2 is " ++ show z2)
putStr " names are"
sequence_ [ putStr (" " ++ show n) | Name n <- names ]
putChar '\n'
let [i, j] = [ fromIntegral n | Name n <- names ]
(board state ! (i,j)) $~ (\x -> (x + 1) `mod` 3))
hitRecords
-- pickSquares sets up selection mode, name stack, and projection matrix for
-- picking. Then the objects are drawn.
bufSize :: GLsizei
bufSize = 512
pickSquares :: State -> KeyboardMouseCallback
pickSquares state (MouseButton LeftButton) Down _ (Position x y) = do
vp@(_, (Size _ height)) <- get viewport
(_, maybeHitRecords) <- getHitRecords bufSize $
withName (Name 0) $ do
matrixMode $= Projection
preservingMatrix $ do
loadIdentity
create 5x5 pixel picking region near cursor location
pickMatrix (fromIntegral x, fromIntegral height - fromIntegral y) (5, 5) vp
ortho2D 0 3 0 3
drawSquares state
flush
processHits maybeHitRecords state
postRedisplay Nothing
pickSquares _ (Char '\27') Down _ _ = exitWith ExitSuccess
pickSquares _ _ _ _ _ = return ()
display :: State -> DisplayCallback
display state = do
clear [ ColorBuffer ]
drawSquares state
flush
reshape :: ReshapeCallback
reshape size = do
viewport $= (Position 0 0, size)
matrixMode $= Projection
loadIdentity
ortho2D 0 3 0 3
matrixMode $= Modelview 0
loadIdentity
Main Loop
main :: IO ()
main = do
(progName, _args) <- getArgsAndInitialize
initialDisplayMode $= [ SingleBuffered, RGBMode ]
initialWindowSize $= Size 100 100
initialWindowPosition $= Position 100 100
createWindow progName
state <- makeState
myInit
reshapeCallback $= Just reshape
displayCallback $= display state
keyboardMouseCallback $= Just (pickSquares state)
mainLoop
| null | https://raw.githubusercontent.com/FranklinChen/hugs98-plus-Sep2006/54ab69bd6313adbbed1d790b46aca2a0305ea67e/packages/GLUT/examples/RedBook/PickSquare.hs | haskell | Clear color value for every square on the board
and the other for the column on the grid. The color of each square is
determined by its position on the grid, and the value in the board array.
Note: In contrast to the the original example, we always give names to
squares, regardless of the render mode. This simplifies the code a bit and
resolve overloading, not needed in "real" programs
processHits prints the hit records and updates the board array.
pickSquares sets up selection mode, name stack, and projection matrix for
picking. Then the objects are drawn. |
PickSquare.hs ( adapted from picksquare.c which is ( c ) Silicon Graphics , Inc. )
Copyright ( c ) 2002 - 2005 < >
This file is part of HOpenGL and distributed under a BSD - style license
See the file libraries / GLUT / LICENSE
Use of multiple names and picking are demonstrated . A 3x3 grid of squares is
drawn . When the left mouse button is pressed , all squares under the cursor
position have their color changed .
PickSquare.hs (adapted from picksquare.c which is (c) Silicon Graphics, Inc.)
Copyright (c) Sven Panne 2002-2005 <>
This file is part of HOpenGL and distributed under a BSD-style license
See the file libraries/GLUT/LICENSE
Use of multiple names and picking are demonstrated. A 3x3 grid of squares is
drawn. When the left mouse button is pressed, all squares under the cursor
position have their color changed.
-}
import Data.Array ( Array, listArray, (!) )
import Data.IORef ( IORef, newIORef )
import System.Exit ( exitWith, ExitCode(ExitSuccess) )
import Graphics.UI.GLUT
type Board = Array (GLint,GLint) (IORef Int)
data State = State { board :: Board }
makeState :: IO State
makeState = do
refs <- sequence . replicate 9 . newIORef $ 0
return $ State { board = listArray ((0,0),(2,2)) refs }
myInit :: IO ()
myInit = do
clearColor $= Color4 0 0 0 0
The nine squares are drawn . Each square is given two names : one for the row
is even suggested by the Red Book .
drawSquares :: State -> IO ()
drawSquares state =
flip mapM_ [ 0 .. 2 ] $ \i -> do
loadName (Name (fromIntegral i))
flip mapM_ [ 0 .. 2 ] $ \j ->
withName (Name (fromIntegral j)) $ do
val <- get (board state ! (i,j))
let color3f = color :: Color3 GLfloat -> IO ()
color3f (Color3 (fromIntegral i / 3.0)
(fromIntegral j / 3.0)
(fromIntegral val / 3.0))
rect (Vertex2 i j) (Vertex2 (i + 1) (j + 1))
processHits :: Maybe[HitRecord] -> State -> IO ()
processHits Nothing _ = putStrLn "selection buffer overflow"
processHits (Just hitRecords) state = do
putStrLn ("hits = " ++ show (length hitRecords))
mapM_ (\(HitRecord z1 z2 names) -> do
putStrLn (" number of names for this hit = " ++ show (length names))
putStr (" z1 is " ++ show z1)
putStrLn ("; z2 is " ++ show z2)
putStr " names are"
sequence_ [ putStr (" " ++ show n) | Name n <- names ]
putChar '\n'
let [i, j] = [ fromIntegral n | Name n <- names ]
(board state ! (i,j)) $~ (\x -> (x + 1) `mod` 3))
hitRecords
bufSize :: GLsizei
bufSize = 512
pickSquares :: State -> KeyboardMouseCallback
pickSquares state (MouseButton LeftButton) Down _ (Position x y) = do
vp@(_, (Size _ height)) <- get viewport
(_, maybeHitRecords) <- getHitRecords bufSize $
withName (Name 0) $ do
matrixMode $= Projection
preservingMatrix $ do
loadIdentity
create 5x5 pixel picking region near cursor location
pickMatrix (fromIntegral x, fromIntegral height - fromIntegral y) (5, 5) vp
ortho2D 0 3 0 3
drawSquares state
flush
processHits maybeHitRecords state
postRedisplay Nothing
pickSquares _ (Char '\27') Down _ _ = exitWith ExitSuccess
pickSquares _ _ _ _ _ = return ()
display :: State -> DisplayCallback
display state = do
clear [ ColorBuffer ]
drawSquares state
flush
reshape :: ReshapeCallback
reshape size = do
viewport $= (Position 0 0, size)
matrixMode $= Projection
loadIdentity
ortho2D 0 3 0 3
matrixMode $= Modelview 0
loadIdentity
Main Loop
main :: IO ()
main = do
(progName, _args) <- getArgsAndInitialize
initialDisplayMode $= [ SingleBuffered, RGBMode ]
initialWindowSize $= Size 100 100
initialWindowPosition $= Position 100 100
createWindow progName
state <- makeState
myInit
reshapeCallback $= Just reshape
displayCallback $= display state
keyboardMouseCallback $= Just (pickSquares state)
mainLoop
|
120874f774e65a6c0000955b1cfebf8dec8a8b038ad820fafbf6b9f85a767203 | awkay/om-tutorial | A_Introduction.cljs | (ns om-tutorial.A-Introduction
(:require-macros
[cljs.test :refer [is]]
)
(:require [om.next :as om :refer-macros [defui]]
[om.dom :as dom]
[devcards.core :as dc :refer-macros [defcard defcard-doc]]
))
(defcard-doc
"# Introduction
This tutorial will walk you through the various parts of Om 1.0 (alpha). In order to get the most from this
tutorial, you should understand the general goals of Om (next):
- Make it possible to localize application state in a single client database abstraction (e.g. single top-level atom
holding a map)
- Provide a mechanism whereby clients can make precise non-trivial reads simply and communicate non-trivial operations simply.
- Eliminate the need for event models
- Provide a synchronous programming model
There are others, but this is sufficient for a starting point.
Note that you can navigate to the table of contents any time using the `devcards` link at the top of the page.
## About This Tutorial
This tutorial is written in Bruce Hauman's excellent Devcards. As such, these documents are live code!
This file, for example, is in `src/tutorial/om_tutorial/A_Introduction.cljs`. If you followed the README to start
up this project, then you're reading this file through your browser and Bruce's other great tool Figwheel. The
combination of the two bring you documentation that runs and also hot reloads whenever the files are saved.
If you open this file in an editor, edit it and save, you'll see the browser automatically refresh the view.
The box below, for example, if generated by a devcard:
")
(defcard sample-card
(dom/div nil "The following number is calculated: " (+ 3 4))
)
(defcard-doc
"
Open up the A_Introduction.cljs, search for `sample-card`, edit the numbers, save, and watch this page refresh. You
are encouraged to play with the source code and examples in the tutorial to verify your understanding as you read.
Devcards support state as well, and will track it in an atom for you. Thus, you can generate UI that actually responds
to user interaction:
")
(defcard interactive-card
(fn [state-atom owner] ;wrapper function that can accept a state atom
(dom/div nil "A single top-level element."
(dom/span nil (str "value of x: " (:x @state-atom)))
(dom/br nil)
(dom/button #js {:onClick #(swap! state-atom update-in [:x] inc)} "Click me")
))
This is a map of initial state that devcards puts in an atom
{:inspect-data true} ; options....show me the current value of the data
)
(defcard-doc
"
Notice that if you edit the code in the card above and save that it *does not* lose track of state. Figwheel does hot
code reloading and devcards is therefore able to hold onto the state of the component. Thus, if you make dramatic
changes to something and the saved state no longer makes sense then you will need to reload the page via the browser
to clear that state.
# IMPORTANT IF YOU GET STUCK:
First, if there is no obvious error in the browser try reloading the page.
If you make a typo or language error Figwheel will usually describe it pretty well in the browser.
However, it is possible to get the whole thing stuck. Typing `(reset-autobuild)` in the REPL will clean the sources and
rebuild (and you'll see compile errors there). Correct the errors and everything should start
working again. DO NOT kill the REPL and restart, as that will cause you a lot of waiting as
you get compile errors, edit, and restart. (If you do kill the REPL,
you might even consider using git to undo your changes so that it will restart cleanly).
## Notes on documentation:
Om wrappers on plain DOM elements take as their second parameter a javascript map (not a cljs one) or nil. As such, you
usually write your UI like this:
```
(dom/div #js {:onClick (fn [evt] ...) })
```
but in many of the examples you'll see this instead:
```
(dom/div (clj->js {:onClick (fn [evt] ...) }))
```
Devcards has a really cool feature where you can pull live source into the documentation. Unfortunately, the
mechanism it uses to do this (the `cljs.repl/source` function) cannot currently handle reader tags. So, in
some examples I'm using the `cljs->js` function instead to make sure the docs and source stay in sync. I
feel the latter is more important than the former, and once the source pulling is fixed it will be easy to
fix the source and have all of the documentation automatically update.
## General Components of Om
The following significant areas of Om must be understood in order to write a non-trivial application.
- Building the UI.
- Queries and the Query Grammar.
- Colocating query fragments on stateful UI component (for composition and local reasoning).
- The client-local app state database.
- Turning the Queries into data for your UI.
- Turning the Queries into remote requests for data.
- Processing incoming responses to remote requests.
- Dynamically changing Queries
[Let's start with the UI.](#!/om_tutorial.B_UI)
")
| null | https://raw.githubusercontent.com/awkay/om-tutorial/83ca10d91380ba62458b98ccaa80fd11b9c8321d/src/tutorial/om_tutorial/A_Introduction.cljs | clojure | wrapper function that can accept a state atom
options....show me the current value of the data | (ns om-tutorial.A-Introduction
(:require-macros
[cljs.test :refer [is]]
)
(:require [om.next :as om :refer-macros [defui]]
[om.dom :as dom]
[devcards.core :as dc :refer-macros [defcard defcard-doc]]
))
(defcard-doc
"# Introduction
This tutorial will walk you through the various parts of Om 1.0 (alpha). In order to get the most from this
tutorial, you should understand the general goals of Om (next):
- Make it possible to localize application state in a single client database abstraction (e.g. single top-level atom
holding a map)
- Provide a mechanism whereby clients can make precise non-trivial reads simply and communicate non-trivial operations simply.
- Eliminate the need for event models
- Provide a synchronous programming model
There are others, but this is sufficient for a starting point.
Note that you can navigate to the table of contents any time using the `devcards` link at the top of the page.
## About This Tutorial
This tutorial is written in Bruce Hauman's excellent Devcards. As such, these documents are live code!
This file, for example, is in `src/tutorial/om_tutorial/A_Introduction.cljs`. If you followed the README to start
up this project, then you're reading this file through your browser and Bruce's other great tool Figwheel. The
combination of the two bring you documentation that runs and also hot reloads whenever the files are saved.
If you open this file in an editor, edit it and save, you'll see the browser automatically refresh the view.
The box below, for example, if generated by a devcard:
")
(defcard sample-card
(dom/div nil "The following number is calculated: " (+ 3 4))
)
(defcard-doc
"
Open up the A_Introduction.cljs, search for `sample-card`, edit the numbers, save, and watch this page refresh. You
are encouraged to play with the source code and examples in the tutorial to verify your understanding as you read.
Devcards support state as well, and will track it in an atom for you. Thus, you can generate UI that actually responds
to user interaction:
")
(defcard interactive-card
(dom/div nil "A single top-level element."
(dom/span nil (str "value of x: " (:x @state-atom)))
(dom/br nil)
(dom/button #js {:onClick #(swap! state-atom update-in [:x] inc)} "Click me")
))
This is a map of initial state that devcards puts in an atom
)
(defcard-doc
"
Notice that if you edit the code in the card above and save that it *does not* lose track of state. Figwheel does hot
code reloading and devcards is therefore able to hold onto the state of the component. Thus, if you make dramatic
changes to something and the saved state no longer makes sense then you will need to reload the page via the browser
to clear that state.
# IMPORTANT IF YOU GET STUCK:
First, if there is no obvious error in the browser try reloading the page.
If you make a typo or language error Figwheel will usually describe it pretty well in the browser.
However, it is possible to get the whole thing stuck. Typing `(reset-autobuild)` in the REPL will clean the sources and
rebuild (and you'll see compile errors there). Correct the errors and everything should start
working again. DO NOT kill the REPL and restart, as that will cause you a lot of waiting as
you get compile errors, edit, and restart. (If you do kill the REPL,
you might even consider using git to undo your changes so that it will restart cleanly).
## Notes on documentation:
Om wrappers on plain DOM elements take as their second parameter a javascript map (not a cljs one) or nil. As such, you
usually write your UI like this:
```
(dom/div #js {:onClick (fn [evt] ...) })
```
but in many of the examples you'll see this instead:
```
(dom/div (clj->js {:onClick (fn [evt] ...) }))
```
Devcards has a really cool feature where you can pull live source into the documentation. Unfortunately, the
mechanism it uses to do this (the `cljs.repl/source` function) cannot currently handle reader tags. So, in
some examples I'm using the `cljs->js` function instead to make sure the docs and source stay in sync. I
feel the latter is more important than the former, and once the source pulling is fixed it will be easy to
fix the source and have all of the documentation automatically update.
## General Components of Om
The following significant areas of Om must be understood in order to write a non-trivial application.
- Building the UI.
- Queries and the Query Grammar.
- Colocating query fragments on stateful UI component (for composition and local reasoning).
- The client-local app state database.
- Turning the Queries into data for your UI.
- Turning the Queries into remote requests for data.
- Processing incoming responses to remote requests.
- Dynamically changing Queries
[Let's start with the UI.](#!/om_tutorial.B_UI)
")
|
2272f42b02f40fa6fa8998586cd6c10f56b5217d613be1090f4233f5941204c3 | AeroNotix/lispkit | macros.lisp | (in-package :lispkit)
(defmacro destructuring-dolist (vars list &body body)
(let ((var (gensym))
(l (gensym)))
`(let ((,l ,list))
(dolist (,var ,l)
(destructuring-bind ,vars ,var
,@body)))))
(defun gdk-event-slot (slot)
(intern (format nil "GDK-EVENT-KEY-~a" slot) 'gdk))
(defmacro with-gdk-event-slots (slots gdk-event &body body)
`(let (,@(mapcar
#'(lambda (slot)
(let ((slot-name (gdk-event-slot slot)))
`(,slot (,slot-name ,gdk-event))))
slots))
,@body))
| null | https://raw.githubusercontent.com/AeroNotix/lispkit/2482dbeabc79667407dabe7765dfbffc16584b08/macros.lisp | lisp | (in-package :lispkit)
(defmacro destructuring-dolist (vars list &body body)
(let ((var (gensym))
(l (gensym)))
`(let ((,l ,list))
(dolist (,var ,l)
(destructuring-bind ,vars ,var
,@body)))))
(defun gdk-event-slot (slot)
(intern (format nil "GDK-EVENT-KEY-~a" slot) 'gdk))
(defmacro with-gdk-event-slots (slots gdk-event &body body)
`(let (,@(mapcar
#'(lambda (slot)
(let ((slot-name (gdk-event-slot slot)))
`(,slot (,slot-name ,gdk-event))))
slots))
,@body))
| |
42f9d8c682aa4a1d980891e626142326c07570100c643a0c430cc26bf2d6c28c | haskus/packages | Buffer.hs | # LANGUAGE DataKinds #
# LANGUAGE FlexibleInstances #
# LANGUAGE DerivingStrategies #
# LANGUAGE GeneralizedNewtypeDeriving #
{-# LANGUAGE BangPatterns #-}
# LANGUAGE BlockArguments #
-- | Serializer into a mutable buffer
--
> > > let w = do putWord8 0x01 ; putWord32BE 0x23456789 ; putWord32BE 0xAABBCCDD
> > > b < - newBuffer 10
-- >>> void $ runBufferPut b 0 overflowBufferFail w
-- >>> xs <- forM [0..4] (bufferReadWord8IO b)
> > > xs = = [ 0x01,0x23,0x45,0x67,0x89 ]
-- True
--
> > > b < - newBuffer 2 -- small buffer
> > > ( _ , b ' , _ ) < - runBufferPut b 0 overflowBufferDouble w
-- >>> xs <- forM [0..4] (bufferReadWord8IO b')
> > > xs = = [ 0x01,0x23,0x45,0x67,0x89 ]
-- True
> > > b '
16
--
module Haskus.Binary.Serialize.Buffer
( -- * Put
BufferPutT (..)
, BufferPut
, getPutOffset
, getPutBuffer
, setPutOffset
, runBufferPut
, liftBufferPut
-- * Get
, BufferGetT (..)
, BufferGet
, getGetOffset
, getGetBuffer
, setGetOffset
, runBufferGet
, liftBufferGet
-- * Buffer overflow
, OverflowStrategy (..)
, BufferOverflow (..)
, getPutOverflowStrategy
, getGetOverflowStrategy
, overflowBufferFail
, overflowBufferDouble
, overflowBufferDoublePinned
, overflowBufferAdd
, overflowBufferAddPinned
)
where
import Haskus.Binary.Serialize.Put
import Haskus.Binary.Serialize.Get
import Haskus.Memory.Buffer
import Haskus.Utils.Monad
import Haskus.Utils.Flow
import Haskus.Utils.Maybe
import Data.Functor.Identity
import Control.Monad.Trans.State.Strict as S
import Control.Monad.Fail as F
import Control.Monad.Fix
-- | Action to perform when the buffer isn't large enough to contain the
-- required data (extend the buffer, flush the data, etc.)
--
-- The returned buffer and offset replace the current ones.
newtype OverflowStrategy m b = OverflowStrategy (BufferOverflow b -> m (b,Word))
-- | Buffer overflow strategy: fails when there isn't enough space left
overflowBufferFail :: MonadFail m => OverflowStrategy m b
overflowBufferFail = OverflowStrategy \ex -> do
F.fail $ "Not enough space in the buffer (requiring "
++ show (overflowRequired ex) ++ " bytes)"
-- | Buffer extend strategy: double the buffer size each time and copy the
-- original contents in it
overflowBufferDouble :: OverflowStrategy IO Buffer
overflowBufferDouble = OverflowStrategy \ex -> do
sz <- bufferSize (overflowBuffer ex)
let off = overflowOffset ex
req = overflowRequired ex
b = overflowBuffer ex
makeSzs i = i*i : makeSzs (i*i) -- infinite list of doubling sizes
newSz = head <| filter (> req+off) (makeSzs sz)
newB <- newBuffer newSz
bufferCopy b 0 newB 0 off
pure (newB,off)
-- | Buffer extend strategy: double the buffer size each time and copy the
-- original contents in it
overflowBufferDoublePinned :: Maybe Word -> OverflowStrategy IO Buffer
overflowBufferDoublePinned malignment = OverflowStrategy \ex -> do
sz <- bufferSize (overflowBuffer ex)
let off = overflowOffset ex
req = overflowRequired ex
b = overflowBuffer ex
makeSzs i = i*i : makeSzs (i*i) -- infinite list of doubling sizes
newSz = head <| filter (> req+off) (makeSzs sz)
newB <- case malignment of
Nothing -> newPinnedBuffer newSz
Just al -> newAlignedPinnedBuffer newSz al
bufferCopy b 0 newB 0 off
pure (newB,off)
-- | Buffer extend strategy: add the given size each time and copy the
-- original contents in it
overflowBufferAdd :: Word -> OverflowStrategy IO Buffer
overflowBufferAdd addSz = OverflowStrategy \ex -> do
sz <- bufferSize (overflowBuffer ex)
let off = overflowOffset ex
req = overflowRequired ex
b = overflowBuffer ex
makeSzs i = i+addSz : makeSzs (i+addSz) -- infinite list of added sizes
newSz = head <| filter (> req+off) (makeSzs sz)
newB <- newBuffer newSz
bufferCopy b 0 newB 0 off
pure (newB,off)
-- | Buffer extend strategy: add the given size each time and copy the
-- original contents in it
overflowBufferAddPinned :: Maybe Word -> Word -> OverflowStrategy IO Buffer
overflowBufferAddPinned malignment addSz = OverflowStrategy \ex -> do
sz <- bufferSize (overflowBuffer ex)
let off = overflowOffset ex
req = overflowRequired ex
b = overflowBuffer ex
makeSzs i = i+addSz : makeSzs (i+addSz) -- infinite list of added sizes
newSz = head <| filter (> req+off) (makeSzs sz)
newB <- case malignment of
Nothing -> newPinnedBuffer newSz
Just al -> newAlignedPinnedBuffer newSz al
bufferCopy b 0 newB 0 off
pure (newB,off)
-- | Buffer extension information
data BufferOverflow b = BufferOverflow
{ overflowBuffer :: b -- ^ Current buffer
, overflowOffset :: Word -- ^ Current offset in buffer
, overflowRequired :: Word -- ^ Required size in bytes (don't take into account leftover bytes in the current buffer)
}
----------------------------------------------------------------------
BufferPut
----------------------------------------------------------------------
-- | BufferPutT state
data BufferPutState m b = BufferPutState
{ bufferPutBuffer :: !b -- ^ Buffer used for writing
, bufferPutOffset :: !Word -- ^ Current offset
, bufferPutStrat :: !(OverflowStrategy m b) -- ^ Extension strategy
}
-- | A Put monad than fails when there is not enough space in the target buffer
newtype BufferPutT b m a
= BufferPutT (StateT (BufferPutState m b) m a)
deriving newtype (Functor, Applicative, Monad, MonadFail, MonadFix, MonadIO)
type BufferPut b a = BufferPutT b Identity a
| Lift into BufferPutT
liftBufferPut :: Monad m => m a -> BufferPutT b m a
liftBufferPut act = BufferPutT (lift act)
-- | Run a buffer put
runBufferPut :: Monad m => b -> Word -> OverflowStrategy m b -> BufferPutT b m a -> m (a,b,Word)
runBufferPut b off strat (BufferPutT s) = do
(a,s') <- runStateT s (BufferPutState b off strat)
return (a,bufferPutBuffer s',bufferPutOffset s')
-- | Get current offset
getPutOffset :: Monad m => BufferPutT b m Word
getPutOffset = BufferPutT (bufferPutOffset <$> S.get)
-- | Get buffer
getPutBuffer :: Monad m => BufferPutT b m b
getPutBuffer = BufferPutT (bufferPutBuffer <$> S.get)
-- | Set buffer
setPutBuffer :: Monad m => b -> BufferPutT b m ()
setPutBuffer v = BufferPutT do
S.modify \s -> s { bufferPutBuffer = v }
-- | Get current offset
setPutOffset :: Monad m => Word -> BufferPutT b m ()
setPutOffset v = BufferPutT do
S.modify \s -> s { bufferPutOffset = v }
-- | Get extend strategy
getPutOverflowStrategy :: Monad m => BufferPutT b m (OverflowStrategy m b)
getPutOverflowStrategy = BufferPutT (bufferPutStrat <$> S.get)
-- | Helper to put something
putSomething
:: MonadIO m
=> Word
-> (Buffer -> Word -> t -> m ())
-> t
-> BufferPutT Buffer m ()
# INLINABLE putSomething #
putSomething sz act v = putSomeThings sz $ Just \b off -> act b off v
-- | Helper to put some things
putSomeThings
:: MonadIO m
=> Word
-> Maybe (Buffer -> Word -> m ())
-> BufferPutT Buffer m ()
{-# INLINABLE putSomeThings #-}
putSomeThings sz mact = do
off <- getPutOffset
b <- getPutBuffer
bs <- liftIO (bufferSize b)
let !newOff = off+sz
if (newOff > bs)
then do -- we need to extend/flush the buffer
OverflowStrategy strat <- getPutOverflowStrategy
(upB,upOff) <- liftBufferPut <| strat <| BufferOverflow
{ overflowBuffer = b
, overflowOffset = off
, overflowRequired = sz
}
setPutBuffer upB
setPutOffset upOff
putSomeThings sz mact
else case mact of
Nothing -> return () -- we only preallocate
Just act -> do -- we write something for real
liftBufferPut (act b off)
setPutOffset newOff
instance PutMonad (BufferPutT Buffer IO) where
putWord8 = putSomething 1 bufferWriteWord8
putWord16 = putSomething 2 bufferWriteWord16
putWord32 = putSomething 4 bufferWriteWord32
putWord64 = putSomething 8 bufferWriteWord64
putWord8s xs = putSomeThings (fromIntegral (length xs)) $ Just \b off -> do
forM_ ([off,(off+1)..] `zip` xs) $ \(boff,v) -> do
bufferWriteWord8 b boff v
putWord16s xs = putSomeThings (2*fromIntegral (length xs)) $ Just \b off -> do
forM_ ([off,(off+2)..] `zip` xs) $ \(boff,v) -> do
bufferWriteWord16 b boff v
putWord32s xs = putSomeThings (4*fromIntegral (length xs)) $ Just \b off -> do
forM_ ([off,(off+4)..] `zip` xs) $ \(boff,v) -> do
bufferWriteWord32 b boff v
putWord64s xs = putSomeThings (8*fromIntegral (length xs)) $ Just \b off -> do
forM_ ([off,(off+8)..] `zip` xs) $ \(boff,v) -> do
bufferWriteWord64 b boff v
preAllocateAtLeast l = putSomeThings l Nothing
putBuffer x = do
sz <- liftIO (bufferSize x)
putSomeThings sz $ Just \b off -> bufferCopy x 0 b off sz
----------------------------------------------------------------------
BufferGet
----------------------------------------------------------------------
-- | BufferGetT state
data BufferGetState m b = BufferGetState
{ bufferGetBuffer :: !b -- ^ Buffer used for reading
, bufferGetOffset :: !Word -- ^ Current offset
, bufferGetStrat :: !(OverflowStrategy m b) -- ^ Extension stretegy
}
-- | A Get monad over a Buffer
newtype BufferGetT b m a
= BufferGetT (StateT (BufferGetState m b) m a)
deriving newtype (Functor, Applicative, Monad, MonadFail, MonadFix, MonadIO)
type BufferGet b a = BufferGetT b Identity a
instance GetMonad (BufferGetT Buffer IO)
where
getSkipBytes n = getSomething n \_ _ -> return ()
getWord8 = getSomething 1 bufferReadWord8
getWord16 = getSomething 2 bufferReadWord16
getWord32 = getSomething 4 bufferReadWord32
getWord64 = getSomething 8 bufferReadWord64
getBuffer sz = getSomething sz \b off -> do
dest <- newBuffer sz
bufferCopy b off dest 0 sz
pure dest
getBufferInto sz dest mdoff = getSomething sz \b off -> do
bufferCopy b off dest (fromMaybe 0 mdoff) sz
-- | Lift into BufferGetT
liftBufferGet :: Monad m => m a -> BufferGetT b m a
liftBufferGet act = BufferGetT (lift act)
-- | Run a buffer get
runBufferGet :: Monad m => b -> Word -> OverflowStrategy m b -> BufferGetT b m a -> m (a,b,Word)
runBufferGet b off strat (BufferGetT s) = do
(a,s') <- runStateT s (BufferGetState b off strat)
return (a,bufferGetBuffer s',bufferGetOffset s')
-- | Get current offset
getGetOffset :: Monad m => BufferGetT b m Word
getGetOffset = BufferGetT (bufferGetOffset <$> S.get)
-- | Get buffer
getGetBuffer :: Monad m => BufferGetT b m b
getGetBuffer = BufferGetT (bufferGetBuffer <$> S.get)
-- | Set buffer
setGetBuffer :: Monad m => b -> BufferGetT b m ()
setGetBuffer v = BufferGetT do
S.modify \s -> s { bufferGetBuffer = v }
-- | Get current offset
setGetOffset :: Monad m => Word -> BufferGetT b m ()
setGetOffset v = BufferGetT do
S.modify \s -> s { bufferGetOffset = v }
-- | Get extend strategy
getGetOverflowStrategy :: Monad m => BufferGetT b m (OverflowStrategy m b)
getGetOverflowStrategy = BufferGetT (bufferGetStrat <$> S.get)
-- | Helper to get some things
getSomething ::
( Monad m
, MonadIO m
) => Word
-> (Buffer -> Word -> m a)
-> BufferGetT Buffer m a
getSomething sz act = do
off <- getGetOffset
b <- getGetBuffer
bsz <- liftIO (bufferSize b)
let !newOff = off+sz
if newOff > bsz
then do -- we need to extend the buffer or fail
OverflowStrategy strat <- getGetOverflowStrategy
(upB,upOff) <- liftBufferGet <| strat <| BufferOverflow
{ overflowBuffer = b
, overflowOffset = off
, overflowRequired = sz
}
setGetBuffer upB
setGetOffset upOff
getSomething sz act
else do
setGetOffset newOff
liftBufferGet (act b off)
| null | https://raw.githubusercontent.com/haskus/packages/6d4a64dc26b55622af86b8b45a30a10f61d52e4d/haskus-binary/src/lib/Haskus/Binary/Serialize/Buffer.hs | haskell | # LANGUAGE BangPatterns #
| Serializer into a mutable buffer
>>> void $ runBufferPut b 0 overflowBufferFail w
>>> xs <- forM [0..4] (bufferReadWord8IO b)
True
small buffer
>>> xs <- forM [0..4] (bufferReadWord8IO b')
True
* Put
* Get
* Buffer overflow
| Action to perform when the buffer isn't large enough to contain the
required data (extend the buffer, flush the data, etc.)
The returned buffer and offset replace the current ones.
| Buffer overflow strategy: fails when there isn't enough space left
| Buffer extend strategy: double the buffer size each time and copy the
original contents in it
infinite list of doubling sizes
| Buffer extend strategy: double the buffer size each time and copy the
original contents in it
infinite list of doubling sizes
| Buffer extend strategy: add the given size each time and copy the
original contents in it
infinite list of added sizes
| Buffer extend strategy: add the given size each time and copy the
original contents in it
infinite list of added sizes
| Buffer extension information
^ Current buffer
^ Current offset in buffer
^ Required size in bytes (don't take into account leftover bytes in the current buffer)
--------------------------------------------------------------------
--------------------------------------------------------------------
| BufferPutT state
^ Buffer used for writing
^ Current offset
^ Extension strategy
| A Put monad than fails when there is not enough space in the target buffer
| Run a buffer put
| Get current offset
| Get buffer
| Set buffer
| Get current offset
| Get extend strategy
| Helper to put something
| Helper to put some things
# INLINABLE putSomeThings #
we need to extend/flush the buffer
we only preallocate
we write something for real
--------------------------------------------------------------------
--------------------------------------------------------------------
| BufferGetT state
^ Buffer used for reading
^ Current offset
^ Extension stretegy
| A Get monad over a Buffer
| Lift into BufferGetT
| Run a buffer get
| Get current offset
| Get buffer
| Set buffer
| Get current offset
| Get extend strategy
| Helper to get some things
we need to extend the buffer or fail | # LANGUAGE DataKinds #
# LANGUAGE FlexibleInstances #
# LANGUAGE DerivingStrategies #
# LANGUAGE GeneralizedNewtypeDeriving #
# LANGUAGE BlockArguments #
> > > let w = do putWord8 0x01 ; putWord32BE 0x23456789 ; putWord32BE 0xAABBCCDD
> > > b < - newBuffer 10
> > > xs = = [ 0x01,0x23,0x45,0x67,0x89 ]
> > > ( _ , b ' , _ ) < - runBufferPut b 0 overflowBufferDouble w
> > > xs = = [ 0x01,0x23,0x45,0x67,0x89 ]
> > > b '
16
module Haskus.Binary.Serialize.Buffer
BufferPutT (..)
, BufferPut
, getPutOffset
, getPutBuffer
, setPutOffset
, runBufferPut
, liftBufferPut
, BufferGetT (..)
, BufferGet
, getGetOffset
, getGetBuffer
, setGetOffset
, runBufferGet
, liftBufferGet
, OverflowStrategy (..)
, BufferOverflow (..)
, getPutOverflowStrategy
, getGetOverflowStrategy
, overflowBufferFail
, overflowBufferDouble
, overflowBufferDoublePinned
, overflowBufferAdd
, overflowBufferAddPinned
)
where
import Haskus.Binary.Serialize.Put
import Haskus.Binary.Serialize.Get
import Haskus.Memory.Buffer
import Haskus.Utils.Monad
import Haskus.Utils.Flow
import Haskus.Utils.Maybe
import Data.Functor.Identity
import Control.Monad.Trans.State.Strict as S
import Control.Monad.Fail as F
import Control.Monad.Fix
newtype OverflowStrategy m b = OverflowStrategy (BufferOverflow b -> m (b,Word))
overflowBufferFail :: MonadFail m => OverflowStrategy m b
overflowBufferFail = OverflowStrategy \ex -> do
F.fail $ "Not enough space in the buffer (requiring "
++ show (overflowRequired ex) ++ " bytes)"
overflowBufferDouble :: OverflowStrategy IO Buffer
overflowBufferDouble = OverflowStrategy \ex -> do
sz <- bufferSize (overflowBuffer ex)
let off = overflowOffset ex
req = overflowRequired ex
b = overflowBuffer ex
newSz = head <| filter (> req+off) (makeSzs sz)
newB <- newBuffer newSz
bufferCopy b 0 newB 0 off
pure (newB,off)
overflowBufferDoublePinned :: Maybe Word -> OverflowStrategy IO Buffer
overflowBufferDoublePinned malignment = OverflowStrategy \ex -> do
sz <- bufferSize (overflowBuffer ex)
let off = overflowOffset ex
req = overflowRequired ex
b = overflowBuffer ex
newSz = head <| filter (> req+off) (makeSzs sz)
newB <- case malignment of
Nothing -> newPinnedBuffer newSz
Just al -> newAlignedPinnedBuffer newSz al
bufferCopy b 0 newB 0 off
pure (newB,off)
overflowBufferAdd :: Word -> OverflowStrategy IO Buffer
overflowBufferAdd addSz = OverflowStrategy \ex -> do
sz <- bufferSize (overflowBuffer ex)
let off = overflowOffset ex
req = overflowRequired ex
b = overflowBuffer ex
newSz = head <| filter (> req+off) (makeSzs sz)
newB <- newBuffer newSz
bufferCopy b 0 newB 0 off
pure (newB,off)
overflowBufferAddPinned :: Maybe Word -> Word -> OverflowStrategy IO Buffer
overflowBufferAddPinned malignment addSz = OverflowStrategy \ex -> do
sz <- bufferSize (overflowBuffer ex)
let off = overflowOffset ex
req = overflowRequired ex
b = overflowBuffer ex
newSz = head <| filter (> req+off) (makeSzs sz)
newB <- case malignment of
Nothing -> newPinnedBuffer newSz
Just al -> newAlignedPinnedBuffer newSz al
bufferCopy b 0 newB 0 off
pure (newB,off)
data BufferOverflow b = BufferOverflow
}
BufferPut
data BufferPutState m b = BufferPutState
}
newtype BufferPutT b m a
= BufferPutT (StateT (BufferPutState m b) m a)
deriving newtype (Functor, Applicative, Monad, MonadFail, MonadFix, MonadIO)
type BufferPut b a = BufferPutT b Identity a
| Lift into BufferPutT
liftBufferPut :: Monad m => m a -> BufferPutT b m a
liftBufferPut act = BufferPutT (lift act)
runBufferPut :: Monad m => b -> Word -> OverflowStrategy m b -> BufferPutT b m a -> m (a,b,Word)
runBufferPut b off strat (BufferPutT s) = do
(a,s') <- runStateT s (BufferPutState b off strat)
return (a,bufferPutBuffer s',bufferPutOffset s')
getPutOffset :: Monad m => BufferPutT b m Word
getPutOffset = BufferPutT (bufferPutOffset <$> S.get)
getPutBuffer :: Monad m => BufferPutT b m b
getPutBuffer = BufferPutT (bufferPutBuffer <$> S.get)
setPutBuffer :: Monad m => b -> BufferPutT b m ()
setPutBuffer v = BufferPutT do
S.modify \s -> s { bufferPutBuffer = v }
setPutOffset :: Monad m => Word -> BufferPutT b m ()
setPutOffset v = BufferPutT do
S.modify \s -> s { bufferPutOffset = v }
getPutOverflowStrategy :: Monad m => BufferPutT b m (OverflowStrategy m b)
getPutOverflowStrategy = BufferPutT (bufferPutStrat <$> S.get)
putSomething
:: MonadIO m
=> Word
-> (Buffer -> Word -> t -> m ())
-> t
-> BufferPutT Buffer m ()
# INLINABLE putSomething #
putSomething sz act v = putSomeThings sz $ Just \b off -> act b off v
putSomeThings
:: MonadIO m
=> Word
-> Maybe (Buffer -> Word -> m ())
-> BufferPutT Buffer m ()
putSomeThings sz mact = do
off <- getPutOffset
b <- getPutBuffer
bs <- liftIO (bufferSize b)
let !newOff = off+sz
if (newOff > bs)
OverflowStrategy strat <- getPutOverflowStrategy
(upB,upOff) <- liftBufferPut <| strat <| BufferOverflow
{ overflowBuffer = b
, overflowOffset = off
, overflowRequired = sz
}
setPutBuffer upB
setPutOffset upOff
putSomeThings sz mact
else case mact of
liftBufferPut (act b off)
setPutOffset newOff
instance PutMonad (BufferPutT Buffer IO) where
putWord8 = putSomething 1 bufferWriteWord8
putWord16 = putSomething 2 bufferWriteWord16
putWord32 = putSomething 4 bufferWriteWord32
putWord64 = putSomething 8 bufferWriteWord64
putWord8s xs = putSomeThings (fromIntegral (length xs)) $ Just \b off -> do
forM_ ([off,(off+1)..] `zip` xs) $ \(boff,v) -> do
bufferWriteWord8 b boff v
putWord16s xs = putSomeThings (2*fromIntegral (length xs)) $ Just \b off -> do
forM_ ([off,(off+2)..] `zip` xs) $ \(boff,v) -> do
bufferWriteWord16 b boff v
putWord32s xs = putSomeThings (4*fromIntegral (length xs)) $ Just \b off -> do
forM_ ([off,(off+4)..] `zip` xs) $ \(boff,v) -> do
bufferWriteWord32 b boff v
putWord64s xs = putSomeThings (8*fromIntegral (length xs)) $ Just \b off -> do
forM_ ([off,(off+8)..] `zip` xs) $ \(boff,v) -> do
bufferWriteWord64 b boff v
preAllocateAtLeast l = putSomeThings l Nothing
putBuffer x = do
sz <- liftIO (bufferSize x)
putSomeThings sz $ Just \b off -> bufferCopy x 0 b off sz
BufferGet
data BufferGetState m b = BufferGetState
}
newtype BufferGetT b m a
= BufferGetT (StateT (BufferGetState m b) m a)
deriving newtype (Functor, Applicative, Monad, MonadFail, MonadFix, MonadIO)
type BufferGet b a = BufferGetT b Identity a
instance GetMonad (BufferGetT Buffer IO)
where
getSkipBytes n = getSomething n \_ _ -> return ()
getWord8 = getSomething 1 bufferReadWord8
getWord16 = getSomething 2 bufferReadWord16
getWord32 = getSomething 4 bufferReadWord32
getWord64 = getSomething 8 bufferReadWord64
getBuffer sz = getSomething sz \b off -> do
dest <- newBuffer sz
bufferCopy b off dest 0 sz
pure dest
getBufferInto sz dest mdoff = getSomething sz \b off -> do
bufferCopy b off dest (fromMaybe 0 mdoff) sz
liftBufferGet :: Monad m => m a -> BufferGetT b m a
liftBufferGet act = BufferGetT (lift act)
runBufferGet :: Monad m => b -> Word -> OverflowStrategy m b -> BufferGetT b m a -> m (a,b,Word)
runBufferGet b off strat (BufferGetT s) = do
(a,s') <- runStateT s (BufferGetState b off strat)
return (a,bufferGetBuffer s',bufferGetOffset s')
getGetOffset :: Monad m => BufferGetT b m Word
getGetOffset = BufferGetT (bufferGetOffset <$> S.get)
getGetBuffer :: Monad m => BufferGetT b m b
getGetBuffer = BufferGetT (bufferGetBuffer <$> S.get)
setGetBuffer :: Monad m => b -> BufferGetT b m ()
setGetBuffer v = BufferGetT do
S.modify \s -> s { bufferGetBuffer = v }
setGetOffset :: Monad m => Word -> BufferGetT b m ()
setGetOffset v = BufferGetT do
S.modify \s -> s { bufferGetOffset = v }
getGetOverflowStrategy :: Monad m => BufferGetT b m (OverflowStrategy m b)
getGetOverflowStrategy = BufferGetT (bufferGetStrat <$> S.get)
getSomething ::
( Monad m
, MonadIO m
) => Word
-> (Buffer -> Word -> m a)
-> BufferGetT Buffer m a
getSomething sz act = do
off <- getGetOffset
b <- getGetBuffer
bsz <- liftIO (bufferSize b)
let !newOff = off+sz
if newOff > bsz
OverflowStrategy strat <- getGetOverflowStrategy
(upB,upOff) <- liftBufferGet <| strat <| BufferOverflow
{ overflowBuffer = b
, overflowOffset = off
, overflowRequired = sz
}
setGetBuffer upB
setGetOffset upOff
getSomething sz act
else do
setGetOffset newOff
liftBufferGet (act b off)
|
bf34569878b0fabc031bfdf634c627ca590989f8f58c266e8955984cb2634b20 | 8c6794b6/haskell-sc-scratch | SCDiff2.hs | {-# LANGUAGE GADTs #-}
# LANGUAGE KindSignatures #
# LANGUAGE FlexibleInstances #
# LANGUAGE MultiParamTypeClasses #
{-# LANGUAGE Rank2Types #-}
|
Module : $ Header$
License : :
Stability : unstable
Portability : non - portable
Yet another take to compare synth nodes .
Attempt to construct osc message from diff with using zipper and
moving around tree . Not working .
Module : $Header$
License : BSD3
Maintainer :
Stability : unstable
Portability : non-portable
Yet another take to compare synth nodes.
Attempt to construct osc message from diff with using zipper and
moving around tree. Not working.
-}
module SCDiff2 where
import Data.Tree
import Control.Monad
import Control.Monad.Writer
import Data.Tree.Zipper
import Sound.OpenSoundControl
import Sound.SC3.Lepton
import MyDiff
import Sample
data NodeType
= Grp Int
| Syn Int String
| Par [SynthParam]
deriving (Eq, Show)
toR :: SCNode -> Tree NodeType
toR (Group i ns) = Node (Grp i) (map toR ns)
toR (Synth i n ps) = Node (Syn i n) [Node (Par ps) []]
data SFamily :: * -> * -> * where
SFNode :: SFamily (Tree NodeType) (Cons NodeType (Cons [Tree NodeType] Nil))
SFNodeNil :: SFamily [Tree NodeType] Nil
SFNodeCons :: SFamily [Tree NodeType] (Cons (Tree NodeType) (Cons [Tree NodeType] Nil))
SFN :: NodeType -> SFamily NodeType Nil
instance Show (SFamily a b) where
show SFNode = "Node"
show SFNodeNil = "[]"
show SFNodeCons = ":"
show (SFN n) = show n
instance Family SFamily where
decEq SFNode SFNode = Just (Refl,Refl)
decEq SFNodeNil SFNodeNil = Just (Refl,Refl)
decEq SFNodeCons SFNodeCons = Just (Refl,Refl)
decEq (SFN a) (SFN b) | a == b = Just (Refl,Refl)
| otherwise = Nothing
decEq _ _ = Nothing
fields SFNode (Node x ts) = Just (CCons x (CCons ts CNil))
fields SFNodeNil [] = Just CNil
fields SFNodeCons (x:xs) = Just (CCons x (CCons xs CNil))
fields (SFN _) _ = Just CNil
fields _ _ = Nothing
apply SFNode (CCons x (CCons ts CNil)) = Node x ts
apply SFNodeNil CNil = []
apply SFNodeCons (CCons x (CCons xs CNil)) = x:xs
apply (SFN n) CNil = n
string = show
instance Type SFamily (Tree NodeType) where
constructors = [Concr SFNode]
instance Type SFamily [Tree NodeType] where
constructors = [Concr SFNodeNil, Concr SFNodeCons]
instance Type SFamily NodeType where
constructors = [Abstr SFN]
ddf :: SCNode -> SCNode -> IO ()
ddf a b = dumpSFDiff (diff (toR a) (toR b) :: EditScript SFamily (Tree NodeType) (Tree NodeType))
dumpSFDiff :: forall f txs tys . EditScriptL f txs tys -> IO ()
dumpSFDiff d = case d of
Ins n d -> putStrLn ("Ins " ++ string n) >> dumpSFDiff d
Cpy n d -> putStrLn ("Cpy " ++ string n) >> dumpSFDiff d
Del n d -> putStrLn ("Del " ++ string n) >> dumpSFDiff d
_ -> return ()
x .> f = f x
infixl 8 .>
movement1 :: Maybe (TreePos Full NodeType)
movement1 =
t02 .> toR .> fromTree -- Group 0
.> firstChild -- Group 2
>>= firstChild -- Group 20
Synth 2000
Synth 2001
Synth 2002
Par [ " amp":=0.3,"freq":=1320.0,"out":=0.0 ]
movement2 :: Maybe (TreePos Full NodeType)
movement2 =
Par [ " amp":=0.3,"freq":=1320.0,"out":=0.0 ] )
Synth 2002
Synth 2001
Synth 2000
>>= firstChild -- Just (Par ["amp":=0.3,"freq":=440.0,"out":=0.0])
d2m :: forall a f txs tys.
EditScriptL f txs tys -> [TreePos Full a -> Maybe (TreePos Full a)]
d2m d = case d of
_ -> []
st1 :: Int -> Writer [(Int,Bool)] ()
st1 k | k == 0 = return ()
| even k = tell [(k,True)] >> st1 (pred k)
| odd k = tell [(k,False)] >> st1 (pred k) | null | https://raw.githubusercontent.com/8c6794b6/haskell-sc-scratch/22de2199359fa56f256b544609cd6513b5e40f43/Scratch/Diff/SCDiff2.hs | haskell | # LANGUAGE GADTs #
# LANGUAGE Rank2Types #
Group 0
Group 2
Group 20
Just (Par ["amp":=0.3,"freq":=440.0,"out":=0.0]) | # LANGUAGE KindSignatures #
# LANGUAGE FlexibleInstances #
# LANGUAGE MultiParamTypeClasses #
|
Module : $ Header$
License : :
Stability : unstable
Portability : non - portable
Yet another take to compare synth nodes .
Attempt to construct osc message from diff with using zipper and
moving around tree . Not working .
Module : $Header$
License : BSD3
Maintainer :
Stability : unstable
Portability : non-portable
Yet another take to compare synth nodes.
Attempt to construct osc message from diff with using zipper and
moving around tree. Not working.
-}
module SCDiff2 where
import Data.Tree
import Control.Monad
import Control.Monad.Writer
import Data.Tree.Zipper
import Sound.OpenSoundControl
import Sound.SC3.Lepton
import MyDiff
import Sample
data NodeType
= Grp Int
| Syn Int String
| Par [SynthParam]
deriving (Eq, Show)
toR :: SCNode -> Tree NodeType
toR (Group i ns) = Node (Grp i) (map toR ns)
toR (Synth i n ps) = Node (Syn i n) [Node (Par ps) []]
data SFamily :: * -> * -> * where
SFNode :: SFamily (Tree NodeType) (Cons NodeType (Cons [Tree NodeType] Nil))
SFNodeNil :: SFamily [Tree NodeType] Nil
SFNodeCons :: SFamily [Tree NodeType] (Cons (Tree NodeType) (Cons [Tree NodeType] Nil))
SFN :: NodeType -> SFamily NodeType Nil
instance Show (SFamily a b) where
show SFNode = "Node"
show SFNodeNil = "[]"
show SFNodeCons = ":"
show (SFN n) = show n
instance Family SFamily where
decEq SFNode SFNode = Just (Refl,Refl)
decEq SFNodeNil SFNodeNil = Just (Refl,Refl)
decEq SFNodeCons SFNodeCons = Just (Refl,Refl)
decEq (SFN a) (SFN b) | a == b = Just (Refl,Refl)
| otherwise = Nothing
decEq _ _ = Nothing
fields SFNode (Node x ts) = Just (CCons x (CCons ts CNil))
fields SFNodeNil [] = Just CNil
fields SFNodeCons (x:xs) = Just (CCons x (CCons xs CNil))
fields (SFN _) _ = Just CNil
fields _ _ = Nothing
apply SFNode (CCons x (CCons ts CNil)) = Node x ts
apply SFNodeNil CNil = []
apply SFNodeCons (CCons x (CCons xs CNil)) = x:xs
apply (SFN n) CNil = n
string = show
instance Type SFamily (Tree NodeType) where
constructors = [Concr SFNode]
instance Type SFamily [Tree NodeType] where
constructors = [Concr SFNodeNil, Concr SFNodeCons]
instance Type SFamily NodeType where
constructors = [Abstr SFN]
ddf :: SCNode -> SCNode -> IO ()
ddf a b = dumpSFDiff (diff (toR a) (toR b) :: EditScript SFamily (Tree NodeType) (Tree NodeType))
dumpSFDiff :: forall f txs tys . EditScriptL f txs tys -> IO ()
dumpSFDiff d = case d of
Ins n d -> putStrLn ("Ins " ++ string n) >> dumpSFDiff d
Cpy n d -> putStrLn ("Cpy " ++ string n) >> dumpSFDiff d
Del n d -> putStrLn ("Del " ++ string n) >> dumpSFDiff d
_ -> return ()
x .> f = f x
infixl 8 .>
movement1 :: Maybe (TreePos Full NodeType)
movement1 =
Synth 2000
Synth 2001
Synth 2002
Par [ " amp":=0.3,"freq":=1320.0,"out":=0.0 ]
movement2 :: Maybe (TreePos Full NodeType)
movement2 =
Par [ " amp":=0.3,"freq":=1320.0,"out":=0.0 ] )
Synth 2002
Synth 2001
Synth 2000
d2m :: forall a f txs tys.
EditScriptL f txs tys -> [TreePos Full a -> Maybe (TreePos Full a)]
d2m d = case d of
_ -> []
st1 :: Int -> Writer [(Int,Bool)] ()
st1 k | k == 0 = return ()
| even k = tell [(k,True)] >> st1 (pred k)
| odd k = tell [(k,False)] >> st1 (pred k) |
dc3bf9147d1e78f8dcbadc05188faee333783ffef9e26a21a4df81808e832184 | typeclasses/dsv | FileStrictRead.hs | # LANGUAGE NoImplicitPrelude #
# LANGUAGE ScopedTypeVariables #
module DSV.FileStrictRead
( readDsvFileStrictWithZippedHeader
, readDsvFileStrictWithoutHeader
, readDsvFileStrictIgnoringHeader
) where
import DSV.ByteString
import DSV.DelimiterType
import DSV.Fold
import DSV.Header
import DSV.IO
import DSV.ParseStop
import DSV.Parsing
import DSV.Pipes
import DSV.Prelude
import DSV.Vector
readDsvFileStrictWithoutHeader ::
forall m .
MonadIO m
=> Delimiter -- ^ What character separates input values, e.g. 'comma' or 'tab'
-> FilePath -- ^ The path of a CSV file to read
-> m (ParseStop, Vector (Vector ByteString))
readDsvFileStrictWithoutHeader d fp =
liftIO $ runSafeT $
do
foldProducerM foldVectorM $
withFile fp ReadMode $ \h ->
handleDsvRowProducer d h
readDsvFileStrictWithZippedHeader ::
forall m .
MonadIO m
=> Delimiter -- ^ What character separates input values, e.g. 'comma' or 'tab'
-> FilePath -- ^ The path of a CSV file to read
-> m (ParseStop, Vector (Vector (ByteString, ByteString)))
readDsvFileStrictWithZippedHeader d fp =
liftIO $ runSafeT $
do
foldProducerM foldVectorM $
withFile fp ReadMode $ \h ->
handleDsvRowProducer d h >-> zipHeaderPipe
readDsvFileStrictIgnoringHeader ::
forall m .
MonadIO m
=> Delimiter -- ^ What character separates input values, e.g. 'comma' or 'tab'
-> FilePath -- ^ The path of a CSV file to read
-> m (ParseStop, Vector (Vector ByteString))
readDsvFileStrictIgnoringHeader d fp =
liftIO $ runSafeT $
do
foldProducerM (foldDropM 1 foldVectorM) $
withFile fp ReadMode $ \h ->
handleDsvRowProducer d h
| null | https://raw.githubusercontent.com/typeclasses/dsv/ae4eb823e27e4c569c4f9b097441985cf865fbab/dsv/library/DSV/FileStrictRead.hs | haskell | ^ What character separates input values, e.g. 'comma' or 'tab'
^ The path of a CSV file to read
^ What character separates input values, e.g. 'comma' or 'tab'
^ The path of a CSV file to read
^ What character separates input values, e.g. 'comma' or 'tab'
^ The path of a CSV file to read | # LANGUAGE NoImplicitPrelude #
# LANGUAGE ScopedTypeVariables #
module DSV.FileStrictRead
( readDsvFileStrictWithZippedHeader
, readDsvFileStrictWithoutHeader
, readDsvFileStrictIgnoringHeader
) where
import DSV.ByteString
import DSV.DelimiterType
import DSV.Fold
import DSV.Header
import DSV.IO
import DSV.ParseStop
import DSV.Parsing
import DSV.Pipes
import DSV.Prelude
import DSV.Vector
readDsvFileStrictWithoutHeader ::
forall m .
MonadIO m
-> m (ParseStop, Vector (Vector ByteString))
readDsvFileStrictWithoutHeader d fp =
liftIO $ runSafeT $
do
foldProducerM foldVectorM $
withFile fp ReadMode $ \h ->
handleDsvRowProducer d h
readDsvFileStrictWithZippedHeader ::
forall m .
MonadIO m
-> m (ParseStop, Vector (Vector (ByteString, ByteString)))
readDsvFileStrictWithZippedHeader d fp =
liftIO $ runSafeT $
do
foldProducerM foldVectorM $
withFile fp ReadMode $ \h ->
handleDsvRowProducer d h >-> zipHeaderPipe
readDsvFileStrictIgnoringHeader ::
forall m .
MonadIO m
-> m (ParseStop, Vector (Vector ByteString))
readDsvFileStrictIgnoringHeader d fp =
liftIO $ runSafeT $
do
foldProducerM (foldDropM 1 foldVectorM) $
withFile fp ReadMode $ \h ->
handleDsvRowProducer d h
|
e62ed65f7338820f29f7a9266c16a54580160b6a124d332273302e7d8324e102 | andrejbauer/alg | enum.ml | open Theory
open Algebra
open Util
module EPR=Enum_predicate_relation
(* General helper functions for partitioning axioms. *)
(* Select axioms that refer only to unary operations and constants. *)
let part_axioms axioms =
let rec no_binary = function
| Binary _ -> false
| Unary (_, t) -> no_binary t
| Var _ | Const _ | Elem _ -> true in
let no_binary_axiom (eq1, eq2) = no_binary eq1 && no_binary eq2 in
List.partition (apply_to_snd no_binary_axiom) axioms
Partition unary axioms . In the first part are the axioms of the form
f(a ) = b , where a and b are constants , and the rest in the second one .
Partition unary axioms. In the first part are the axioms of the form
f(a) = b, where a and b are constants, and the rest in the second one.
*)
let part_unary_axioms axioms =
let is_simple = function
| (Unary (_,Const _), Const _)
| (Const _, Unary (_,Const _)) -> true
| _ -> false
in List.partition (apply_to_snd is_simple) axioms
Partition binary axioms into two parts . In the first are axioms of the form
a + b = c , where a b and c are constants or unary applications , these are termed simple ,
and the rest are in the second part , these I call complicated .
Partition binary axioms into two parts. In the first are axioms of the form
a + b = c, where a b and c are constants or unary applications, these are termed simple,
and the rest are in the second part, these I call complicated.
*)
let part_binary_axioms axioms =
let rec const_and_unary = function
| (Unary (_,t)) -> const_and_unary t
| (Const _ ) -> true
| _ -> false in
let is_simple = function
| (Binary (_,t1,t2), Const _)
| (Const _, Binary (_,t1,t2)) -> const_and_unary t1 && const_and_unary t2
| _ -> false
in List.partition (apply_to_snd is_simple) axioms
Partition binary axioms into two parts .
The first :
axioms f(a ) * g(a ) = h(a ) or some of the expressions contain a constant
The second :
all the rest . :)
We can immediately apply the first kind .
Partition binary axioms into two parts.
The first:
axioms f(a) * g(a) = h(a) or some of the expressions contain a constant
The second:
all the rest. :)
We can immediately apply the first kind.
*)
let part_one_var_binary axioms =
let rec const_var_unary = function
| (Unary (_,t)) -> const_var_unary t
| (Const c ) -> Some (Const c)
| (Var v) -> Some (Var v)
| _ -> None in
let is_simple = function
| (num_vars, (Binary (_,t1,t2), t3))
| (num_vars, (t3, Binary (_,t1,t2))) ->
let v1 = const_var_unary t1 in
let v2 = const_var_unary t2 in
let v3 = const_var_unary t3 in
begin
match (v1,v2,v3) with
| (None,_,_) | (_,None,_) | (_,_,None) -> false
| _ -> num_vars <= 1
end
| _ -> false
in List.partition is_simple axioms
(* Select associativity axioms. *)
let partition_assoc axioms =
let is_assoc = function
| (Binary (op1, Binary (op2, Var a1, Var b1), Var c1), Binary (op3, Var a2, Binary (op4, Var b2, Var c2)))
| (Binary (op3, Var a2, Binary (op4, Var b2, Var c2)), Binary (op1, Binary (op2, Var a1, Var b1), Var c1))
when op1 = op2 && op2 = op3 && op3 = op4 &&
a1 = a2 && b1 = b2 && c1 = c2 &&
a1 <> b1 && a1 <> c1 && b1 <> c1 -> true
| _ -> false
in List.partition (apply_to_snd is_assoc) axioms
let make_3d_array x y z initial =
Array.init x (fun _ -> Array.make_matrix y z initial)
(*
List of distinct variables of a term.
*)
let rec eq_vars acc = function
| Const _ | Elem _ -> acc
| Var v -> if List.mem v acc then acc else (v :: acc)
| Binary (_,t1,t2) -> let lv = eq_vars acc t1 in
eq_vars lv t2
| Unary (_,t) -> eq_vars acc t
(*
List of distinct variables of an axiom.
*)
let dist_vars (_,(left, right)) =
let lv = eq_vars [] left in eq_vars lv right
(*
Number of distinct variables in an axiom.
Could also look for maximum variable index.
*)
let num_dist_vars (num_vars,_) = num_vars
(* Amenable axioms are the ones where left and right terms have binary op
as outermost operation and have exactly the same variables on left and right sides or
one outermost operation is binary and variables of the other side are a subset of
variables in binary operation. This restriction of variables is necessary as otherwise
we never get any information out of evaluation of the other side. *)
let partition_amenable axioms =
let is_amenable ((left, right) as axiom) =
match axiom with
| (Binary _, Binary _)->
List.sort compare (eq_vars [] left) = List.sort compare (eq_vars [] right)
| ((Binary _), _) -> Util.is_sublist (eq_vars [] right) (eq_vars [] left)
| (_, (Binary _)) -> Util.is_sublist (eq_vars [] left) (eq_vars [] right)
| _ -> false in
List.partition (apply_to_snd is_amenable) axioms
(*
Enumerate all algebras of a given size for the given theory
and pass them to the given continuation.
*)
let enum n ({th_const=const;
th_unary=unary;
th_binary=binary;
th_relations=relations;
th_predicates=predicates;
th_equations=axioms} as th) k =
if n >= Array.length const then
try begin
let lc = Array.length const in
let lu = Array.length unary in
let lb = Array.length binary in
let lp = Array.length predicates in
let lr = Array.length relations in
(* empty algebra *)
Main operation tables for unary operations .
let unary_arr = Array.make_matrix lu n (-1) in
(*
Main operation tables for binary operations.
*)
let binary_arr = make_3d_array lb n n (-1) in
Main operation tables for predicates .
let pred_arr = Array.make_matrix lp n (-1) in
(*
Main operation tables for relations.
*)
let rel_arr = make_3d_array lr n n (-1) in
let alg = {alg_size = n;
alg_name = None;
alg_prod = None;
alg_const = Array.init lc (fun k -> k);
alg_unary = unary_arr;
alg_binary = binary_arr;
alg_predicates = pred_arr;
alg_relations = rel_arr
} in
(* Auxiliary variables for generation of unary operations. *)
(* ******************************************************* *)
let (unary_axioms, binary_axioms) = part_axioms axioms in
(*
Simple and complicated unary axioms. Simple are the
ones of the form f(c) = d or f(d) = c for c and d constants. These
can be easily applied.
TODO: Axioms of the form f(x) = c for x variable and c constant
are also easily dispatched with.
Complicated are the complement of simple and cannot be so easily applied.
*)
let (simple', complicated') = part_unary_axioms unary_axioms in
let simple = List.map snd simple' in
let complicated = List.map snd complicated' in
let normal_axioms = Enum_unary.get_normal_axioms complicated in
let (unary_dos, unary_undos) = Enum_unary.get_unary_actions normal_axioms alg in
Enum_unary.apply_simple simple alg ;
for o=0 to lu - 1 do
for i=0 to n-1 do
if unary_arr.(o).(i) <> -1 && not (unary_dos (o,i)) then
Error.runtime_error "All of the axioms cannot be met." (* TODO: raise exception and catch it in main loop. *)
done
done ;
(* Auxiliary variables for generation of binary operations. *)
(* ******************************************************* *)
let (simple_binary, complicated_binary) = part_binary_axioms binary_axioms in
left are the axioms which can not be immediately applied
These include axioms of depth > 1 and those with more variables .
left are the axioms which cannot be immediately applied
These include axioms of depth > 1 and those with more variables.
*)
let (one_var_shallow, left) = part_one_var_binary complicated_binary in
Partition axioms . Assoc and amenable are naturally associativity and amenable axioms .
zippep_axioms are the rest that have to be checked differently than amenable .
Zipped means in the form ( number of distinct variables , axioms )
Partition axioms. Assoc and amenable are naturally associativity and amenable axioms.
zippep_axioms are the rest that have to be checked differently than amenable.
Zipped means in the form (number of distinct variables, axioms)
*)
let (assoc, amenable, stubborn) =
let (assoc, rest) = partition_assoc left in
let (amenable, rest) = partition_amenable rest in
(assoc,
amenable,
Check axioms with fewer free variables first .
List.sort (fun (n,_) (m,_) -> compare n m) rest
)
in
(*
Maximum distinct variables in any of the axioms left. This is needed so we can cache
all the ntuples.
*)
let max_vars = List.fold_left max 0 (List.map (fun (v,_) -> v) stubborn) in
(* This could potentially gobble up memory. TODO *)
let all_tuples = Array.init (max_vars + 1) (fun i -> ntuples n i) in
let check = Enum_binary.get_checks all_tuples alg stubborn in
let (binary_dos, binary_undos, reset_stack) = Enum_binary.get_binary_actions alg assoc amenable in
let reset_binary_arr () =
for o=0 to lb-1 do
for i=0 to n-1 do
for j=0 to n-1 do
binary_arr.(o).(i).(j) <- -1
done
done
done in
let check_after_add () =
for o=0 to lb-1 do
for i=0 to n-1 do
for j=0 to n-1 do
if binary_arr.(o).(i).(j) <> -1 && not (binary_dos (o,i,j) o i j) then
raise Enum_binary.Contradiction
done
done
done in
let reset_predicates () =
for o=0 to lp-1 do
for i=0 to n-1 do
pred_arr.(o).(i) <- -1
done
done in
let reset_relations () =
for o=0 to lr-1 do
for i=0 to n-1 do
for j=0 to n-1 do
rel_arr.(o).(i).(j) <- -1
done
done
done in
let cont_rel_pred () =
reset_predicates () ;
reset_relations () ;
EPR.gen_predicate th alg
(fun () -> EPR.gen_relation th alg (fun () -> k alg)) in
let cont_binary () =
try
reset_binary_arr () ;
reset_stack () ;
Enum_binary.apply_simple_binary simple_binary alg ;
Enum_binary.apply_one_var_shallow one_var_shallow alg ;
check_after_add () ; (* TODO: Move this into the above functions. *)
if not (check ()) then raise Enum_binary.Contradiction ; (* We might be lucky and fill everything already. *)
Enum_binary.gen_binary th alg binary_dos binary_undos check cont_rel_pred
with Enum_binary.Contradiction -> () in
Enum_unary.gen_unary th unary_dos unary_undos alg cont_binary
end
with InconsistentAxioms -> ()
| null | https://raw.githubusercontent.com/andrejbauer/alg/95715bb1bf93fcc534a8d6c7c96c8913dc03de0c/src/enum.ml | ocaml | General helper functions for partitioning axioms.
Select axioms that refer only to unary operations and constants.
Select associativity axioms.
List of distinct variables of a term.
List of distinct variables of an axiom.
Number of distinct variables in an axiom.
Could also look for maximum variable index.
Amenable axioms are the ones where left and right terms have binary op
as outermost operation and have exactly the same variables on left and right sides or
one outermost operation is binary and variables of the other side are a subset of
variables in binary operation. This restriction of variables is necessary as otherwise
we never get any information out of evaluation of the other side.
Enumerate all algebras of a given size for the given theory
and pass them to the given continuation.
empty algebra
Main operation tables for binary operations.
Main operation tables for relations.
Auxiliary variables for generation of unary operations.
*******************************************************
Simple and complicated unary axioms. Simple are the
ones of the form f(c) = d or f(d) = c for c and d constants. These
can be easily applied.
TODO: Axioms of the form f(x) = c for x variable and c constant
are also easily dispatched with.
Complicated are the complement of simple and cannot be so easily applied.
TODO: raise exception and catch it in main loop.
Auxiliary variables for generation of binary operations.
*******************************************************
Maximum distinct variables in any of the axioms left. This is needed so we can cache
all the ntuples.
This could potentially gobble up memory. TODO
TODO: Move this into the above functions.
We might be lucky and fill everything already. | open Theory
open Algebra
open Util
module EPR=Enum_predicate_relation
let part_axioms axioms =
let rec no_binary = function
| Binary _ -> false
| Unary (_, t) -> no_binary t
| Var _ | Const _ | Elem _ -> true in
let no_binary_axiom (eq1, eq2) = no_binary eq1 && no_binary eq2 in
List.partition (apply_to_snd no_binary_axiom) axioms
Partition unary axioms . In the first part are the axioms of the form
f(a ) = b , where a and b are constants , and the rest in the second one .
Partition unary axioms. In the first part are the axioms of the form
f(a) = b, where a and b are constants, and the rest in the second one.
*)
let part_unary_axioms axioms =
let is_simple = function
| (Unary (_,Const _), Const _)
| (Const _, Unary (_,Const _)) -> true
| _ -> false
in List.partition (apply_to_snd is_simple) axioms
Partition binary axioms into two parts . In the first are axioms of the form
a + b = c , where a b and c are constants or unary applications , these are termed simple ,
and the rest are in the second part , these I call complicated .
Partition binary axioms into two parts. In the first are axioms of the form
a + b = c, where a b and c are constants or unary applications, these are termed simple,
and the rest are in the second part, these I call complicated.
*)
let part_binary_axioms axioms =
let rec const_and_unary = function
| (Unary (_,t)) -> const_and_unary t
| (Const _ ) -> true
| _ -> false in
let is_simple = function
| (Binary (_,t1,t2), Const _)
| (Const _, Binary (_,t1,t2)) -> const_and_unary t1 && const_and_unary t2
| _ -> false
in List.partition (apply_to_snd is_simple) axioms
Partition binary axioms into two parts .
The first :
axioms f(a ) * g(a ) = h(a ) or some of the expressions contain a constant
The second :
all the rest . :)
We can immediately apply the first kind .
Partition binary axioms into two parts.
The first:
axioms f(a) * g(a) = h(a) or some of the expressions contain a constant
The second:
all the rest. :)
We can immediately apply the first kind.
*)
let part_one_var_binary axioms =
let rec const_var_unary = function
| (Unary (_,t)) -> const_var_unary t
| (Const c ) -> Some (Const c)
| (Var v) -> Some (Var v)
| _ -> None in
let is_simple = function
| (num_vars, (Binary (_,t1,t2), t3))
| (num_vars, (t3, Binary (_,t1,t2))) ->
let v1 = const_var_unary t1 in
let v2 = const_var_unary t2 in
let v3 = const_var_unary t3 in
begin
match (v1,v2,v3) with
| (None,_,_) | (_,None,_) | (_,_,None) -> false
| _ -> num_vars <= 1
end
| _ -> false
in List.partition is_simple axioms
let partition_assoc axioms =
let is_assoc = function
| (Binary (op1, Binary (op2, Var a1, Var b1), Var c1), Binary (op3, Var a2, Binary (op4, Var b2, Var c2)))
| (Binary (op3, Var a2, Binary (op4, Var b2, Var c2)), Binary (op1, Binary (op2, Var a1, Var b1), Var c1))
when op1 = op2 && op2 = op3 && op3 = op4 &&
a1 = a2 && b1 = b2 && c1 = c2 &&
a1 <> b1 && a1 <> c1 && b1 <> c1 -> true
| _ -> false
in List.partition (apply_to_snd is_assoc) axioms
let make_3d_array x y z initial =
Array.init x (fun _ -> Array.make_matrix y z initial)
let rec eq_vars acc = function
| Const _ | Elem _ -> acc
| Var v -> if List.mem v acc then acc else (v :: acc)
| Binary (_,t1,t2) -> let lv = eq_vars acc t1 in
eq_vars lv t2
| Unary (_,t) -> eq_vars acc t
let dist_vars (_,(left, right)) =
let lv = eq_vars [] left in eq_vars lv right
let num_dist_vars (num_vars,_) = num_vars
let partition_amenable axioms =
let is_amenable ((left, right) as axiom) =
match axiom with
| (Binary _, Binary _)->
List.sort compare (eq_vars [] left) = List.sort compare (eq_vars [] right)
| ((Binary _), _) -> Util.is_sublist (eq_vars [] right) (eq_vars [] left)
| (_, (Binary _)) -> Util.is_sublist (eq_vars [] left) (eq_vars [] right)
| _ -> false in
List.partition (apply_to_snd is_amenable) axioms
let enum n ({th_const=const;
th_unary=unary;
th_binary=binary;
th_relations=relations;
th_predicates=predicates;
th_equations=axioms} as th) k =
if n >= Array.length const then
try begin
let lc = Array.length const in
let lu = Array.length unary in
let lb = Array.length binary in
let lp = Array.length predicates in
let lr = Array.length relations in
Main operation tables for unary operations .
let unary_arr = Array.make_matrix lu n (-1) in
let binary_arr = make_3d_array lb n n (-1) in
Main operation tables for predicates .
let pred_arr = Array.make_matrix lp n (-1) in
let rel_arr = make_3d_array lr n n (-1) in
let alg = {alg_size = n;
alg_name = None;
alg_prod = None;
alg_const = Array.init lc (fun k -> k);
alg_unary = unary_arr;
alg_binary = binary_arr;
alg_predicates = pred_arr;
alg_relations = rel_arr
} in
let (unary_axioms, binary_axioms) = part_axioms axioms in
let (simple', complicated') = part_unary_axioms unary_axioms in
let simple = List.map snd simple' in
let complicated = List.map snd complicated' in
let normal_axioms = Enum_unary.get_normal_axioms complicated in
let (unary_dos, unary_undos) = Enum_unary.get_unary_actions normal_axioms alg in
Enum_unary.apply_simple simple alg ;
for o=0 to lu - 1 do
for i=0 to n-1 do
if unary_arr.(o).(i) <> -1 && not (unary_dos (o,i)) then
done
done ;
let (simple_binary, complicated_binary) = part_binary_axioms binary_axioms in
left are the axioms which can not be immediately applied
These include axioms of depth > 1 and those with more variables .
left are the axioms which cannot be immediately applied
These include axioms of depth > 1 and those with more variables.
*)
let (one_var_shallow, left) = part_one_var_binary complicated_binary in
Partition axioms . Assoc and amenable are naturally associativity and amenable axioms .
zippep_axioms are the rest that have to be checked differently than amenable .
Zipped means in the form ( number of distinct variables , axioms )
Partition axioms. Assoc and amenable are naturally associativity and amenable axioms.
zippep_axioms are the rest that have to be checked differently than amenable.
Zipped means in the form (number of distinct variables, axioms)
*)
let (assoc, amenable, stubborn) =
let (assoc, rest) = partition_assoc left in
let (amenable, rest) = partition_amenable rest in
(assoc,
amenable,
Check axioms with fewer free variables first .
List.sort (fun (n,_) (m,_) -> compare n m) rest
)
in
let max_vars = List.fold_left max 0 (List.map (fun (v,_) -> v) stubborn) in
let all_tuples = Array.init (max_vars + 1) (fun i -> ntuples n i) in
let check = Enum_binary.get_checks all_tuples alg stubborn in
let (binary_dos, binary_undos, reset_stack) = Enum_binary.get_binary_actions alg assoc amenable in
let reset_binary_arr () =
for o=0 to lb-1 do
for i=0 to n-1 do
for j=0 to n-1 do
binary_arr.(o).(i).(j) <- -1
done
done
done in
let check_after_add () =
for o=0 to lb-1 do
for i=0 to n-1 do
for j=0 to n-1 do
if binary_arr.(o).(i).(j) <> -1 && not (binary_dos (o,i,j) o i j) then
raise Enum_binary.Contradiction
done
done
done in
let reset_predicates () =
for o=0 to lp-1 do
for i=0 to n-1 do
pred_arr.(o).(i) <- -1
done
done in
let reset_relations () =
for o=0 to lr-1 do
for i=0 to n-1 do
for j=0 to n-1 do
rel_arr.(o).(i).(j) <- -1
done
done
done in
let cont_rel_pred () =
reset_predicates () ;
reset_relations () ;
EPR.gen_predicate th alg
(fun () -> EPR.gen_relation th alg (fun () -> k alg)) in
let cont_binary () =
try
reset_binary_arr () ;
reset_stack () ;
Enum_binary.apply_simple_binary simple_binary alg ;
Enum_binary.apply_one_var_shallow one_var_shallow alg ;
Enum_binary.gen_binary th alg binary_dos binary_undos check cont_rel_pred
with Enum_binary.Contradiction -> () in
Enum_unary.gen_unary th unary_dos unary_undos alg cont_binary
end
with InconsistentAxioms -> ()
|
fb17835cef3f3779c9a6d508e81f1f6fce3882ccbcaea09c3506805afc3f64af | spechub/Hets | Cleaning.hs | {-# LANGUAGE GADTs #-}
# LANGUAGE MultiParamTypeClasses #
# LANGUAGE TypeFamilies #
|
Module : ./Persistence . : ( c ) Uni Magdeburg 2017
License : GPLv2 or higher , see LICENSE.txt
Maintainer : < >
Stability : provisional
Portability : portable
Module : ./Persistence.DevGraph.hs
Copyright : (c) Uni Magdeburg 2017
License : GPLv2 or higher, see LICENSE.txt
Maintainer : Eugen Kuksa <>
Stability : provisional
Portability : portable
-}
module Persistence.DevGraph.Cleaning (clean) where
import Persistence.Database
import Persistence.Schema
import Control.Monad (when)
import Control.Monad.IO.Class (MonadIO (..))
import Database.Persist
import Database.Persist.Sql
import GHC.Int
clean :: MonadIO m => Entity LocIdBase -> DBMonad m ()
clean (Entity documentKey documentValue) = do
deleteDocument documentKey
deleteDiagnoses $ locIdBaseFileVersionId documentValue
deleteDiagnoses :: MonadIO m => FileVersionId -> DBMonad m ()
deleteDiagnoses key = deleteCascadeWhere [DiagnosisFileVersionId ==. key]
deleteDocument :: MonadIO m => LocIdBaseId -> DBMonad m ()
deleteDocument key = do
deleteDocumentLinks key
deleteOms key
deleteWhere [DocumentId ==. toSqlKey (fromSqlKey key)]
deleteWhere [LocIdBaseId ==. key]
deleteDocumentLinks :: MonadIO m => LocIdBaseId -> DBMonad m ()
deleteDocumentLinks documentKey =
deleteWhere ( [DocumentLinkSourceId ==. documentKey]
||. [DocumentLinkTargetId ==. documentKey]
)
deleteOms :: MonadIO m => LocIdBaseId -> DBMonad m ()
deleteOms documentKey = do
omsL <- selectList [OMSDocumentId ==. documentKey] []
mapM_ (\ (Entity omsKey omsValue) -> do
maybe (return ()) deleteOms $ oMSNormalFormId omsValue
maybe (return ()) deleteOms $ oMSFreeNormalFormId omsValue
deleteMappings $ toSqlKey $ fromSqlKey omsKey
deleteSentences $ toSqlKey $ fromSqlKey omsKey
deleteSymbols $ toSqlKey $ fromSqlKey omsKey
deleteConsistencyCheckAttempts $ toSqlKey $ fromSqlKey omsKey
deleteWhere [LocIdBaseId ==. toSqlKey (fromSqlKey omsKey)]
delete omsKey
deleteSignature $ oMSSignatureId omsValue
) omsL
deleteMappings :: MonadIO m => LocIdBaseId -> DBMonad m ()
deleteMappings omsKey = do
mappings <- selectList ( [MappingSourceId ==. omsKey]
||. [MappingTargetId ==. omsKey]
||. [MappingFreenessParameterOMSId ==. Just omsKey]
) []
mapM_ (\ (Entity mappingKey _) -> do
deleteWhere [LocIdBaseId ==. toSqlKey (fromSqlKey mappingKey)]
delete mappingKey
) mappings
deleteSentences :: MonadIO m => LocIdBaseId -> DBMonad m ()
deleteSentences omsKey = do
sentences <- selectList [SentenceOmsId ==. omsKey] []
mapM_ (\ (Entity sentenceKey _) -> do
deleteSentencesSymbols $ toSqlKey $ fromSqlKey sentenceKey
deletePremiseSelectedSentences $ toSqlKey $ fromSqlKey sentenceKey
deleteAxiom $ toSqlKey $ fromSqlKey sentenceKey
deleteConjecture $ toSqlKey $ fromSqlKey sentenceKey
deleteWhere [LocIdBaseId ==. toSqlKey (fromSqlKey sentenceKey)]
) sentences
deleteWhere [SentenceOmsId ==. omsKey]
deleteSentencesSymbols :: MonadIO m => LocIdBaseId -> DBMonad m ()
deleteSentencesSymbols sentenceKey =
deleteWhere [SentenceSymbolSentenceId ==. sentenceKey]
deletePremiseSelectedSentences :: MonadIO m => LocIdBaseId -> DBMonad m ()
deletePremiseSelectedSentences sentenceKey =
deleteWhere [PremiseSelectedSentencePremiseId ==. sentenceKey]
deleteAxiom :: MonadIO m => LocIdBaseId -> DBMonad m ()
deleteAxiom = delete
deleteConjecture :: MonadIO m => LocIdBaseId -> DBMonad m ()
deleteConjecture conjectureKey = do
deleteProofAttempts conjectureKey
delete conjectureKey
deleteProofAttempts :: MonadIO m => LocIdBaseId -> DBMonad m ()
deleteProofAttempts conjectureKey = do
proofAttempts <- selectList [ProofAttemptConjectureId ==. Just conjectureKey] []
mapM_ (\ (Entity proofAttemptKey _) ->
deleteReasoningAttempt $ fromSqlKey proofAttemptKey
) proofAttempts
deleteWhere [ProofAttemptConjectureId ==. Just conjectureKey]
deleteReasoningAttempt :: MonadIO m => GHC.Int.Int64 -> DBMonad m ()
deleteReasoningAttempt keyInt = do
let reasoningAttemptKey = toSqlKey keyInt
reasoningAttemptValueM <- get reasoningAttemptKey
deleteGeneratedAxioms reasoningAttemptKey
deleteReasonerOutputs reasoningAttemptKey
delete reasoningAttemptKey
case reasoningAttemptValueM of
Just reasoningAttemptValue -> deleteReasoningConfiguration $ reasoningAttemptReasonerConfigurationId reasoningAttemptValue
Nothing -> return ()
deleteGeneratedAxioms :: MonadIO m => ReasoningAttemptId -> DBMonad m ()
deleteGeneratedAxioms reasoningAttemptKey =
deleteWhere [GeneratedAxiomReasoningAttemptId ==. reasoningAttemptKey]
deleteReasonerOutputs :: MonadIO m => ReasoningAttemptId -> DBMonad m ()
deleteReasonerOutputs reasoningAttemptKey =
deleteWhere [ReasonerOutputReasoningAttemptId ==. reasoningAttemptKey]
deleteReasoningConfiguration :: MonadIO m
=> ReasonerConfigurationId -> DBMonad m ()
deleteReasoningConfiguration reasoningConfigurationKey = do
reasoningAttempts <- selectList [ReasoningAttemptReasonerConfigurationId ==. reasoningConfigurationKey] []
when (null reasoningAttempts) $ do
deletePremiseSelections reasoningConfigurationKey
delete reasoningConfigurationKey
deletePremiseSelections :: MonadIO m => ReasonerConfigurationId -> DBMonad m ()
deletePremiseSelections reasoningConfigurationKey = do
premiseSelections <- selectList [PremiseSelectionReasonerConfigurationId ==. reasoningConfigurationKey] []
mapM_ (\ (Entity premiseSelectionKey _) -> do
deleteManualPremiseSelection $ toSqlKey $ fromSqlKey premiseSelectionKey
deleteSinePremiseSelection $ toSqlKey $ fromSqlKey premiseSelectionKey
) premiseSelections
deleteWhere [PremiseSelectionReasonerConfigurationId ==. reasoningConfigurationKey]
deleteManualPremiseSelection :: MonadIO m => ManualPremiseSelectionId -> DBMonad m ()
deleteManualPremiseSelection = delete
deleteSinePremiseSelection :: MonadIO m => SinePremiseSelectionId -> DBMonad m ()
deleteSinePremiseSelection sinePremiseSelectionKey = do
deleteSineSymbolPremiseTriggers sinePremiseSelectionKey
deleteSineSymbolCommonnesses sinePremiseSelectionKey
delete sinePremiseSelectionKey
deleteSineSymbolPremiseTriggers :: MonadIO m => SinePremiseSelectionId -> DBMonad m ()
deleteSineSymbolPremiseTriggers sinePremiseSelectionKey =
deleteWhere [SineSymbolPremiseTriggerSinePremiseSelectionId ==. sinePremiseSelectionKey]
deleteSineSymbolCommonnesses :: MonadIO m => SinePremiseSelectionId -> DBMonad m ()
deleteSineSymbolCommonnesses sinePremiseSelectionKey =
deleteWhere [SineSymbolCommonnessSinePremiseSelectionId ==. sinePremiseSelectionKey]
deleteSymbols :: MonadIO m => LocIdBaseId -> DBMonad m ()
deleteSymbols omsKey = do
symbols <- selectList [SymbolOmsId ==. omsKey] []
mapM_ (\ (Entity symbolKey _) -> do
deleteSymbolMappings $ toSqlKey $ fromSqlKey symbolKey
deleteSignatureSymbols $ toSqlKey $ fromSqlKey symbolKey
deleteWhere [LocIdBaseId ==. toSqlKey (fromSqlKey symbolKey)]
) symbols
deleteWhere [SymbolOmsId ==. omsKey]
deleteSymbolMappings :: MonadIO m => LocIdBaseId -> DBMonad m ()
deleteSymbolMappings symbolKey =
deleteWhere ( [SymbolMappingSourceId ==. symbolKey]
||. [SymbolMappingTargetId ==. symbolKey]
)
deleteSignatureSymbols :: MonadIO m => LocIdBaseId -> DBMonad m ()
deleteSignatureSymbols symbolKey =
deleteWhere [SignatureSymbolSymbolId ==. symbolKey]
deleteConsistencyCheckAttempts :: MonadIO m => LocIdBaseId -> DBMonad m ()
deleteConsistencyCheckAttempts omsKey = do
consistencyCheckAttempts <-
selectList [ConsistencyCheckAttemptOmsId ==. Just omsKey] []
mapM_ (\ (Entity consistencyCheckAttemptKey _) ->
deleteReasoningAttempt $ fromSqlKey consistencyCheckAttemptKey
) consistencyCheckAttempts
deleteWhere [ConsistencyCheckAttemptOmsId ==. Just omsKey]
deleteSignature :: MonadIO m => SignatureId -> DBMonad m ()
deleteSignature signatureKey = do
oms <- selectList [OMSSignatureId ==. signatureKey] []
when (null oms) $ do
deleteSignatureMorphisms signatureKey
delete signatureKey
deleteSignatureMorphisms :: MonadIO m => SignatureId -> DBMonad m ()
deleteSignatureMorphisms signatureKey =
deleteWhere ( [SignatureMorphismSourceId ==. signatureKey]
||. [SignatureMorphismTargetId ==. signatureKey]
)
| null | https://raw.githubusercontent.com/spechub/Hets/af7b628a75aab0d510b8ae7f067a5c9bc48d0f9e/Persistence/DevGraph/Cleaning.hs | haskell | # LANGUAGE GADTs # | # LANGUAGE MultiParamTypeClasses #
# LANGUAGE TypeFamilies #
|
Module : ./Persistence . : ( c ) Uni Magdeburg 2017
License : GPLv2 or higher , see LICENSE.txt
Maintainer : < >
Stability : provisional
Portability : portable
Module : ./Persistence.DevGraph.hs
Copyright : (c) Uni Magdeburg 2017
License : GPLv2 or higher, see LICENSE.txt
Maintainer : Eugen Kuksa <>
Stability : provisional
Portability : portable
-}
module Persistence.DevGraph.Cleaning (clean) where
import Persistence.Database
import Persistence.Schema
import Control.Monad (when)
import Control.Monad.IO.Class (MonadIO (..))
import Database.Persist
import Database.Persist.Sql
import GHC.Int
clean :: MonadIO m => Entity LocIdBase -> DBMonad m ()
clean (Entity documentKey documentValue) = do
deleteDocument documentKey
deleteDiagnoses $ locIdBaseFileVersionId documentValue
deleteDiagnoses :: MonadIO m => FileVersionId -> DBMonad m ()
deleteDiagnoses key = deleteCascadeWhere [DiagnosisFileVersionId ==. key]
deleteDocument :: MonadIO m => LocIdBaseId -> DBMonad m ()
deleteDocument key = do
deleteDocumentLinks key
deleteOms key
deleteWhere [DocumentId ==. toSqlKey (fromSqlKey key)]
deleteWhere [LocIdBaseId ==. key]
deleteDocumentLinks :: MonadIO m => LocIdBaseId -> DBMonad m ()
deleteDocumentLinks documentKey =
deleteWhere ( [DocumentLinkSourceId ==. documentKey]
||. [DocumentLinkTargetId ==. documentKey]
)
deleteOms :: MonadIO m => LocIdBaseId -> DBMonad m ()
deleteOms documentKey = do
omsL <- selectList [OMSDocumentId ==. documentKey] []
mapM_ (\ (Entity omsKey omsValue) -> do
maybe (return ()) deleteOms $ oMSNormalFormId omsValue
maybe (return ()) deleteOms $ oMSFreeNormalFormId omsValue
deleteMappings $ toSqlKey $ fromSqlKey omsKey
deleteSentences $ toSqlKey $ fromSqlKey omsKey
deleteSymbols $ toSqlKey $ fromSqlKey omsKey
deleteConsistencyCheckAttempts $ toSqlKey $ fromSqlKey omsKey
deleteWhere [LocIdBaseId ==. toSqlKey (fromSqlKey omsKey)]
delete omsKey
deleteSignature $ oMSSignatureId omsValue
) omsL
deleteMappings :: MonadIO m => LocIdBaseId -> DBMonad m ()
deleteMappings omsKey = do
mappings <- selectList ( [MappingSourceId ==. omsKey]
||. [MappingTargetId ==. omsKey]
||. [MappingFreenessParameterOMSId ==. Just omsKey]
) []
mapM_ (\ (Entity mappingKey _) -> do
deleteWhere [LocIdBaseId ==. toSqlKey (fromSqlKey mappingKey)]
delete mappingKey
) mappings
deleteSentences :: MonadIO m => LocIdBaseId -> DBMonad m ()
deleteSentences omsKey = do
sentences <- selectList [SentenceOmsId ==. omsKey] []
mapM_ (\ (Entity sentenceKey _) -> do
deleteSentencesSymbols $ toSqlKey $ fromSqlKey sentenceKey
deletePremiseSelectedSentences $ toSqlKey $ fromSqlKey sentenceKey
deleteAxiom $ toSqlKey $ fromSqlKey sentenceKey
deleteConjecture $ toSqlKey $ fromSqlKey sentenceKey
deleteWhere [LocIdBaseId ==. toSqlKey (fromSqlKey sentenceKey)]
) sentences
deleteWhere [SentenceOmsId ==. omsKey]
deleteSentencesSymbols :: MonadIO m => LocIdBaseId -> DBMonad m ()
deleteSentencesSymbols sentenceKey =
deleteWhere [SentenceSymbolSentenceId ==. sentenceKey]
deletePremiseSelectedSentences :: MonadIO m => LocIdBaseId -> DBMonad m ()
deletePremiseSelectedSentences sentenceKey =
deleteWhere [PremiseSelectedSentencePremiseId ==. sentenceKey]
deleteAxiom :: MonadIO m => LocIdBaseId -> DBMonad m ()
deleteAxiom = delete
deleteConjecture :: MonadIO m => LocIdBaseId -> DBMonad m ()
deleteConjecture conjectureKey = do
deleteProofAttempts conjectureKey
delete conjectureKey
deleteProofAttempts :: MonadIO m => LocIdBaseId -> DBMonad m ()
deleteProofAttempts conjectureKey = do
proofAttempts <- selectList [ProofAttemptConjectureId ==. Just conjectureKey] []
mapM_ (\ (Entity proofAttemptKey _) ->
deleteReasoningAttempt $ fromSqlKey proofAttemptKey
) proofAttempts
deleteWhere [ProofAttemptConjectureId ==. Just conjectureKey]
deleteReasoningAttempt :: MonadIO m => GHC.Int.Int64 -> DBMonad m ()
deleteReasoningAttempt keyInt = do
let reasoningAttemptKey = toSqlKey keyInt
reasoningAttemptValueM <- get reasoningAttemptKey
deleteGeneratedAxioms reasoningAttemptKey
deleteReasonerOutputs reasoningAttemptKey
delete reasoningAttemptKey
case reasoningAttemptValueM of
Just reasoningAttemptValue -> deleteReasoningConfiguration $ reasoningAttemptReasonerConfigurationId reasoningAttemptValue
Nothing -> return ()
deleteGeneratedAxioms :: MonadIO m => ReasoningAttemptId -> DBMonad m ()
deleteGeneratedAxioms reasoningAttemptKey =
deleteWhere [GeneratedAxiomReasoningAttemptId ==. reasoningAttemptKey]
deleteReasonerOutputs :: MonadIO m => ReasoningAttemptId -> DBMonad m ()
deleteReasonerOutputs reasoningAttemptKey =
deleteWhere [ReasonerOutputReasoningAttemptId ==. reasoningAttemptKey]
deleteReasoningConfiguration :: MonadIO m
=> ReasonerConfigurationId -> DBMonad m ()
deleteReasoningConfiguration reasoningConfigurationKey = do
reasoningAttempts <- selectList [ReasoningAttemptReasonerConfigurationId ==. reasoningConfigurationKey] []
when (null reasoningAttempts) $ do
deletePremiseSelections reasoningConfigurationKey
delete reasoningConfigurationKey
deletePremiseSelections :: MonadIO m => ReasonerConfigurationId -> DBMonad m ()
deletePremiseSelections reasoningConfigurationKey = do
premiseSelections <- selectList [PremiseSelectionReasonerConfigurationId ==. reasoningConfigurationKey] []
mapM_ (\ (Entity premiseSelectionKey _) -> do
deleteManualPremiseSelection $ toSqlKey $ fromSqlKey premiseSelectionKey
deleteSinePremiseSelection $ toSqlKey $ fromSqlKey premiseSelectionKey
) premiseSelections
deleteWhere [PremiseSelectionReasonerConfigurationId ==. reasoningConfigurationKey]
deleteManualPremiseSelection :: MonadIO m => ManualPremiseSelectionId -> DBMonad m ()
deleteManualPremiseSelection = delete
deleteSinePremiseSelection :: MonadIO m => SinePremiseSelectionId -> DBMonad m ()
deleteSinePremiseSelection sinePremiseSelectionKey = do
deleteSineSymbolPremiseTriggers sinePremiseSelectionKey
deleteSineSymbolCommonnesses sinePremiseSelectionKey
delete sinePremiseSelectionKey
deleteSineSymbolPremiseTriggers :: MonadIO m => SinePremiseSelectionId -> DBMonad m ()
deleteSineSymbolPremiseTriggers sinePremiseSelectionKey =
deleteWhere [SineSymbolPremiseTriggerSinePremiseSelectionId ==. sinePremiseSelectionKey]
deleteSineSymbolCommonnesses :: MonadIO m => SinePremiseSelectionId -> DBMonad m ()
deleteSineSymbolCommonnesses sinePremiseSelectionKey =
deleteWhere [SineSymbolCommonnessSinePremiseSelectionId ==. sinePremiseSelectionKey]
deleteSymbols :: MonadIO m => LocIdBaseId -> DBMonad m ()
deleteSymbols omsKey = do
symbols <- selectList [SymbolOmsId ==. omsKey] []
mapM_ (\ (Entity symbolKey _) -> do
deleteSymbolMappings $ toSqlKey $ fromSqlKey symbolKey
deleteSignatureSymbols $ toSqlKey $ fromSqlKey symbolKey
deleteWhere [LocIdBaseId ==. toSqlKey (fromSqlKey symbolKey)]
) symbols
deleteWhere [SymbolOmsId ==. omsKey]
deleteSymbolMappings :: MonadIO m => LocIdBaseId -> DBMonad m ()
deleteSymbolMappings symbolKey =
deleteWhere ( [SymbolMappingSourceId ==. symbolKey]
||. [SymbolMappingTargetId ==. symbolKey]
)
deleteSignatureSymbols :: MonadIO m => LocIdBaseId -> DBMonad m ()
deleteSignatureSymbols symbolKey =
deleteWhere [SignatureSymbolSymbolId ==. symbolKey]
deleteConsistencyCheckAttempts :: MonadIO m => LocIdBaseId -> DBMonad m ()
deleteConsistencyCheckAttempts omsKey = do
consistencyCheckAttempts <-
selectList [ConsistencyCheckAttemptOmsId ==. Just omsKey] []
mapM_ (\ (Entity consistencyCheckAttemptKey _) ->
deleteReasoningAttempt $ fromSqlKey consistencyCheckAttemptKey
) consistencyCheckAttempts
deleteWhere [ConsistencyCheckAttemptOmsId ==. Just omsKey]
deleteSignature :: MonadIO m => SignatureId -> DBMonad m ()
deleteSignature signatureKey = do
oms <- selectList [OMSSignatureId ==. signatureKey] []
when (null oms) $ do
deleteSignatureMorphisms signatureKey
delete signatureKey
deleteSignatureMorphisms :: MonadIO m => SignatureId -> DBMonad m ()
deleteSignatureMorphisms signatureKey =
deleteWhere ( [SignatureMorphismSourceId ==. signatureKey]
||. [SignatureMorphismTargetId ==. signatureKey]
)
|
d0e8d82d16d3fe75102c09b772d9c1d372c9eef3eb599dd419a62b81b304cc56 | iffyio/pong.hs | pong.hs | import Haste
import Haste.DOM
import Haste.Events
import Haste.Graphics.Canvas
import Data.IORef
-- Type declarations
data GameState = GameState{
ballPos :: Point, -- position of ball
ballSpeed :: Point, -- how far will ball move in a single update
paddlePos:: Double, -- start position of paddle on x axis
score :: Int,
canvasElement :: Maybe Elem
}
data Paddle = Top | Bottom
-- Constants
width, height,ballRadius, paddleWidth, paddleHeight :: Double
width = 500 -- width of canvas
height = 600 -- height of canvas
ballRadius = 5 --radius of ball
paddleHeight = 5 -- height of paddle
paddleWidth = 150 -- width of paddle
halfWidth = width / 2
halfHeight = height / 2
--Dimensions for start and restart button
btnX1 = halfWidth - 50
btnY1 = halfHeight - 25
btnX2 = halfWidth + 60
btnY2 = halfHeight + 25
scoreLabel :: String
scoreLabel = "Score: "
defaultSpeed = (8,10)
initialState :: GameState
initialState = GameState{
ballPos = (20, 20),
ballSpeed = defaultSpeed,
paddlePos = (width / 2) - 75,
score = 0,
canvasElement = Nothing
}
-- Render game state on canvas
renderState :: Bool -> Canvas -> GameState -> IO ()
renderState gameover canvas state = render canvas $ do
gamePicture state
if gameover
then gameOver $ show (score state)
else return ()
where
x1 = paddlePos state
x2 = x1 + paddleWidth
-- blue color
blue :: Picture () -> Picture ()
blue = color (RGB 130 205 185)
-- Draw a ball
ball :: Point -> Picture ()
ball pt = color (RGB 243 114 89) $ do
fill $ circle pt ballRadius
-- Draw a paddle
paddle :: Rect -> Picture ()
paddle (Rect x1 y1 x2 y2) = blue $ do
fill $ rect (x1, y1) (x2, y2)
-- Draw a button with label
drawButton :: String -> Picture ()
drawButton note = blue $ do
stroke $ rect (btnX1, btnY1) (btnX2, btnY2)
font "20px italic Monospace" $ text ((btnX1 + btnX2) / 2 - 35 ,(btnY1 + btnY2) / 2 + 5) note
-- Draw text
drawText :: Point -> String -> Picture ()
drawText point s = blue $ do
text point s
-- Draw game state on screen / paddles, ball, score
gamePicture :: GameState -> Picture ()
gamePicture state = do
ball $ ballPos state
let x1 = paddlePos state
x2 = x1 + paddleWidth
paddle $ Rect x1 0 x2 paddleHeight
paddle $ Rect x1 (height - paddleHeight) x2 height
font "20px italic Monospace" $ drawText (30,50) $ scoreLabel ++ show (score state)
-- Create new canvas to draw on
mkCanvas :: Double -> Double -> IO Elem
mkCanvas width height = do
canvas <- newElem "canvas"
setProp canvas "width" (show width)
setProp canvas "height" (show height)
setStyle canvas "display" "block"
setStyle canvas "border" "1px solid #524F52"
setStyle canvas "margin" "0px auto 0 auto"
setStyle canvas "backgroundColor" "#524F52"
return canvas
-- move the ball / change ball coordinates
moveBall :: GameState -> GameState
moveBall state = state {ballPos = (x + vx, y + vy)}
where
(x, y) = ballPos state
(vx, vy) = ballSpeed state
-- Display game and Update screen
animate :: Canvas -> IORef GameState -> IO ()
animate canvas stateRef = do
state <- readIORef stateRef
let (x, y) = ballPos state
(Just canvasElem) = canvasElement state
renderState False canvas state
case gameEnded state of
Nothing -> do
atomicWriteIORef stateRef $ update state
_ <- setTimer (Once 30) $ animate canvas stateRef
return ()
Just Top -> do
let x' = paddlePos state
restartGame canvasElem canvas state {ballPos = (x' + paddleWidth / 2, 12)}
Just Bottom -> do
let x' = paddlePos state
restartGame canvasElem canvas state {ballPos = (x' + paddleWidth / 2, height - 12)}
where
update = paddleHit . moveBall . detectCollision
-- Redraw canvas and restart game
restartGame :: Elem -> Canvas -> GameState -> IO ()
restartGame canvasElem canvas state = do
let (x',y') = ballPos state
(vx,vy) = ballSpeed state
setTimer (Once 30) $ renderState True canvas $ state {ballPos = (x', y')}
_ <- onEvent canvasElem Click $ \mousedata -> btnEvent (mouseButton mousedata) (mouseCoords mousedata) canvasElem state {ballSpeed = (vx, -vy), score = 0}
return ()
-- move the paddles
movePaddles :: (Int, Int) -> IORef GameState -> IO ()
movePaddles (mouseX, mouseY) stateRef = do
atomicModifyIORef stateRef (\state -> ((state {paddlePos = (fromIntegral mouseX) - (paddleWidth / 2)}), ()))
-- change ball direction if ball hits paddle
paddleHit :: GameState -> GameState
paddleHit state =
if and [bx' >= px, bx'' <= pl, (by >= height-ph) || (by <= ph)]
then increaseSpeed state {ballSpeed = (vx, -vy), score = score state + 1}
else state
where
(bx,by) = ballPos state
bx' = bx + ballRadius
bx'' = bx - ballRadius
(vx,vy) = ballSpeed state
px = paddlePos state
ph = paddleHeight
pl = px + paddleWidth
-- Change ball direction if ball hits walls
detectCollision :: GameState -> GameState
detectCollision state
| (x + ballRadius) >= width = state {ballPos = (width - ballRadius,y), ballSpeed = (-vx, vy)}
| (x + ballRadius) <= 0 = state {ballPos = (ballRadius, y), ballSpeed = (-vx, vy)}
| otherwise = state
where
(x, y) = ballPos state
(vx,vy) = ballSpeed state
-- increment ball speed
increaseSpeed :: GameState -> GameState
increaseSpeed state = if score state `mod` 4 == 0 && (abs vx < 15)
then let
vx' = if vx < 0 then -1 else 1
vy' = if vy < 0 then -2 else 2
in state {ballSpeed = (vx+vx', vy+vy') }
else state
where
(vx,vy) = ballSpeed state
-- Check if ball is out / Has a paddle missed ?
gameEnded :: GameState -> Maybe Paddle
gameEnded state
| y >= height && (x < px || x > px + paddleWidth) = Just Bottom
| y <= 0 && (x < px || x > px + paddleWidth) = Just Top
| otherwise = Nothing
where
(x,y) = ballPos state
px = paddlePos state
-- Game over sequence
gameOver :: String -> Picture ()
gameOver score = do
drawButton "Restart"
color(RGB 255 255 255) $ do
let fnt = font "25px italic Monospace"
fnt $ text (btnX1, btnY1 - 30) "Game Over"
fnt $ text (btnX1 - 50, btnY2 + 30) $ "Your total score was " ++ score
-- start animation
startGame state = do
canvasElem <- mkCanvas width height
addChild canvasElem documentBody
Just canvas <- getCanvas canvasElem
stateRef <- newIORef $ state {canvasElement = Just canvasElem, ballSpeed = defaultSpeed}
onEvent canvasElem MouseMove $ \mousedata -> movePaddles (mouseCoords mousedata) stateRef
animate canvas stateRef
-- handle click event on button
btnEvent :: (Maybe MouseButton) -> (Int, Int) -> Elem -> GameState -> IO ()
btnEvent mbtn (x,y) canvasElem state | mbtn == Just MouseLeft =
let x' = fromIntegral x
y' = fromIntegral y
in
if and [mbtn == Just MouseLeft, x' >= btnX1, x' <= btnX2, y' >= btnY1, y' <= btnY2 ]
then do
removeChild canvasElem documentBody
startGame state
else
return ()
| otherwise = return ()
-- main
main :: IO Bool
main = do
canvasElem <- mkCanvas width height
addChild canvasElem documentBody
Just canvas <- getCanvas canvasElem
render canvas $ do
drawButton "Start"
gamePicture initialState
onEvent canvasElem Click $ \mousedata -> btnEvent (mouseButton mousedata) (mouseCoords mousedata) canvasElem initialState
return True
| null | https://raw.githubusercontent.com/iffyio/pong.hs/fd9fe6ca2d55862f952f93ef93b3f7a898b56b1f/pong.hs | haskell | Type declarations
position of ball
how far will ball move in a single update
start position of paddle on x axis
Constants
width of canvas
height of canvas
radius of ball
height of paddle
width of paddle
Dimensions for start and restart button
Render game state on canvas
blue color
Draw a ball
Draw a paddle
Draw a button with label
Draw text
Draw game state on screen / paddles, ball, score
Create new canvas to draw on
move the ball / change ball coordinates
Display game and Update screen
Redraw canvas and restart game
move the paddles
change ball direction if ball hits paddle
Change ball direction if ball hits walls
increment ball speed
Check if ball is out / Has a paddle missed ?
Game over sequence
start animation
handle click event on button
main | import Haste
import Haste.DOM
import Haste.Events
import Haste.Graphics.Canvas
import Data.IORef
data GameState = GameState{
score :: Int,
canvasElement :: Maybe Elem
}
data Paddle = Top | Bottom
width, height,ballRadius, paddleWidth, paddleHeight :: Double
halfWidth = width / 2
halfHeight = height / 2
btnX1 = halfWidth - 50
btnY1 = halfHeight - 25
btnX2 = halfWidth + 60
btnY2 = halfHeight + 25
scoreLabel :: String
scoreLabel = "Score: "
defaultSpeed = (8,10)
initialState :: GameState
initialState = GameState{
ballPos = (20, 20),
ballSpeed = defaultSpeed,
paddlePos = (width / 2) - 75,
score = 0,
canvasElement = Nothing
}
renderState :: Bool -> Canvas -> GameState -> IO ()
renderState gameover canvas state = render canvas $ do
gamePicture state
if gameover
then gameOver $ show (score state)
else return ()
where
x1 = paddlePos state
x2 = x1 + paddleWidth
blue :: Picture () -> Picture ()
blue = color (RGB 130 205 185)
ball :: Point -> Picture ()
ball pt = color (RGB 243 114 89) $ do
fill $ circle pt ballRadius
paddle :: Rect -> Picture ()
paddle (Rect x1 y1 x2 y2) = blue $ do
fill $ rect (x1, y1) (x2, y2)
drawButton :: String -> Picture ()
drawButton note = blue $ do
stroke $ rect (btnX1, btnY1) (btnX2, btnY2)
font "20px italic Monospace" $ text ((btnX1 + btnX2) / 2 - 35 ,(btnY1 + btnY2) / 2 + 5) note
drawText :: Point -> String -> Picture ()
drawText point s = blue $ do
text point s
gamePicture :: GameState -> Picture ()
gamePicture state = do
ball $ ballPos state
let x1 = paddlePos state
x2 = x1 + paddleWidth
paddle $ Rect x1 0 x2 paddleHeight
paddle $ Rect x1 (height - paddleHeight) x2 height
font "20px italic Monospace" $ drawText (30,50) $ scoreLabel ++ show (score state)
mkCanvas :: Double -> Double -> IO Elem
mkCanvas width height = do
canvas <- newElem "canvas"
setProp canvas "width" (show width)
setProp canvas "height" (show height)
setStyle canvas "display" "block"
setStyle canvas "border" "1px solid #524F52"
setStyle canvas "margin" "0px auto 0 auto"
setStyle canvas "backgroundColor" "#524F52"
return canvas
moveBall :: GameState -> GameState
moveBall state = state {ballPos = (x + vx, y + vy)}
where
(x, y) = ballPos state
(vx, vy) = ballSpeed state
animate :: Canvas -> IORef GameState -> IO ()
animate canvas stateRef = do
state <- readIORef stateRef
let (x, y) = ballPos state
(Just canvasElem) = canvasElement state
renderState False canvas state
case gameEnded state of
Nothing -> do
atomicWriteIORef stateRef $ update state
_ <- setTimer (Once 30) $ animate canvas stateRef
return ()
Just Top -> do
let x' = paddlePos state
restartGame canvasElem canvas state {ballPos = (x' + paddleWidth / 2, 12)}
Just Bottom -> do
let x' = paddlePos state
restartGame canvasElem canvas state {ballPos = (x' + paddleWidth / 2, height - 12)}
where
update = paddleHit . moveBall . detectCollision
restartGame :: Elem -> Canvas -> GameState -> IO ()
restartGame canvasElem canvas state = do
let (x',y') = ballPos state
(vx,vy) = ballSpeed state
setTimer (Once 30) $ renderState True canvas $ state {ballPos = (x', y')}
_ <- onEvent canvasElem Click $ \mousedata -> btnEvent (mouseButton mousedata) (mouseCoords mousedata) canvasElem state {ballSpeed = (vx, -vy), score = 0}
return ()
movePaddles :: (Int, Int) -> IORef GameState -> IO ()
movePaddles (mouseX, mouseY) stateRef = do
atomicModifyIORef stateRef (\state -> ((state {paddlePos = (fromIntegral mouseX) - (paddleWidth / 2)}), ()))
paddleHit :: GameState -> GameState
paddleHit state =
if and [bx' >= px, bx'' <= pl, (by >= height-ph) || (by <= ph)]
then increaseSpeed state {ballSpeed = (vx, -vy), score = score state + 1}
else state
where
(bx,by) = ballPos state
bx' = bx + ballRadius
bx'' = bx - ballRadius
(vx,vy) = ballSpeed state
px = paddlePos state
ph = paddleHeight
pl = px + paddleWidth
detectCollision :: GameState -> GameState
detectCollision state
| (x + ballRadius) >= width = state {ballPos = (width - ballRadius,y), ballSpeed = (-vx, vy)}
| (x + ballRadius) <= 0 = state {ballPos = (ballRadius, y), ballSpeed = (-vx, vy)}
| otherwise = state
where
(x, y) = ballPos state
(vx,vy) = ballSpeed state
increaseSpeed :: GameState -> GameState
increaseSpeed state = if score state `mod` 4 == 0 && (abs vx < 15)
then let
vx' = if vx < 0 then -1 else 1
vy' = if vy < 0 then -2 else 2
in state {ballSpeed = (vx+vx', vy+vy') }
else state
where
(vx,vy) = ballSpeed state
gameEnded :: GameState -> Maybe Paddle
gameEnded state
| y >= height && (x < px || x > px + paddleWidth) = Just Bottom
| y <= 0 && (x < px || x > px + paddleWidth) = Just Top
| otherwise = Nothing
where
(x,y) = ballPos state
px = paddlePos state
gameOver :: String -> Picture ()
gameOver score = do
drawButton "Restart"
color(RGB 255 255 255) $ do
let fnt = font "25px italic Monospace"
fnt $ text (btnX1, btnY1 - 30) "Game Over"
fnt $ text (btnX1 - 50, btnY2 + 30) $ "Your total score was " ++ score
startGame state = do
canvasElem <- mkCanvas width height
addChild canvasElem documentBody
Just canvas <- getCanvas canvasElem
stateRef <- newIORef $ state {canvasElement = Just canvasElem, ballSpeed = defaultSpeed}
onEvent canvasElem MouseMove $ \mousedata -> movePaddles (mouseCoords mousedata) stateRef
animate canvas stateRef
btnEvent :: (Maybe MouseButton) -> (Int, Int) -> Elem -> GameState -> IO ()
btnEvent mbtn (x,y) canvasElem state | mbtn == Just MouseLeft =
let x' = fromIntegral x
y' = fromIntegral y
in
if and [mbtn == Just MouseLeft, x' >= btnX1, x' <= btnX2, y' >= btnY1, y' <= btnY2 ]
then do
removeChild canvasElem documentBody
startGame state
else
return ()
| otherwise = return ()
main :: IO Bool
main = do
canvasElem <- mkCanvas width height
addChild canvasElem documentBody
Just canvas <- getCanvas canvasElem
render canvas $ do
drawButton "Start"
gamePicture initialState
onEvent canvasElem Click $ \mousedata -> btnEvent (mouseButton mousedata) (mouseCoords mousedata) canvasElem initialState
return True
|
be522ba162081109b76f51bd24e0d3b97a6fb420c781e5f1c13c648aa82f7f3a | mistupv/cauder | exPat.erl | -module(exPat).
-export([ack/2, main/0]).
main() ->
self() ! {1, 2},
ack(1, 2).
ack(N, M) ->
receive
{N, M} ->
true;
_ ->
false
end.
| null | https://raw.githubusercontent.com/mistupv/cauder/ff4955cca4b0aa6ae9d682e9f0532be188a5cc16/examples/exPat.erl | erlang | -module(exPat).
-export([ack/2, main/0]).
main() ->
self() ! {1, 2},
ack(1, 2).
ack(N, M) ->
receive
{N, M} ->
true;
_ ->
false
end.
| |
0f6eb7a1b2cfc2ecc107f2541d769a55ee6bba03969a3d6cc196a3c20282f5a1 | athensresearch/athens | core.cljs | (ns athens.types.core
"Athens Block/Entity Types")
(defprotocol BlockTypeProtocol
"Block/Entity Type Protocol for rendering aspects"
(text-view
[this block-data attr]
"Renders Block/Entity Type as textual representation.
Recursively resolves references and all.")
(inline-ref-view
[this block-data attr ref-uid uid callbacks with-breadcrumb?]
"Render Block/Entity Type as inline reference")
(outline-view
[this block-data callbacks]
"Render Block/Entity Type as outline representation")
(supported-transclusion-scopes
[this]
"Returns a set of supported `transclusion-scopes`")
(transclusion-view
[this block-el block-uid callback transclusion-scope]
"Render Block/Entity Type as transclusion")
(zoomed-in-view
[this block-data callbacks]
"Render Block/Entity Type as zoomed in")
(supported-breadcrumb-styles
[this]
"Returns a set of supported `breadcrumb-styles`")
(breadcrumbs-view
[this block-data callbacks breadcrumb-style]
"Render Block/Entity Type as breadcrumbs"))
| null | https://raw.githubusercontent.com/athensresearch/athens/04f83dfc6f6bced8debe1a13daf228154f0a9a80/src/cljs/athens/types/core.cljs | clojure | (ns athens.types.core
"Athens Block/Entity Types")
(defprotocol BlockTypeProtocol
"Block/Entity Type Protocol for rendering aspects"
(text-view
[this block-data attr]
"Renders Block/Entity Type as textual representation.
Recursively resolves references and all.")
(inline-ref-view
[this block-data attr ref-uid uid callbacks with-breadcrumb?]
"Render Block/Entity Type as inline reference")
(outline-view
[this block-data callbacks]
"Render Block/Entity Type as outline representation")
(supported-transclusion-scopes
[this]
"Returns a set of supported `transclusion-scopes`")
(transclusion-view
[this block-el block-uid callback transclusion-scope]
"Render Block/Entity Type as transclusion")
(zoomed-in-view
[this block-data callbacks]
"Render Block/Entity Type as zoomed in")
(supported-breadcrumb-styles
[this]
"Returns a set of supported `breadcrumb-styles`")
(breadcrumbs-view
[this block-data callbacks breadcrumb-style]
"Render Block/Entity Type as breadcrumbs"))
| |
845e12945b4b8f832515365dbab94de72b38c3635bba04ff4afa5fcdefd450d0 | facebook/infer | SourceFileGraph.ml |
* Copyright ( c ) Facebook , Inc. and its affiliates .
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree .
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*)
open! IStd
module F = Format
module L = Logging
let time_and_run ~f ~msg =
let result, duration_ms = Utils.timeit ~f in
L.debug Capture Medium "%s took %d ms.@\n" msg duration_ms ;
result
module Loader = struct
(** Build a hash table from procedure name to source file where it's defined, and a hash table
from source files to list of procedures defined. *)
let get_indexes () =
let counter = ref 0 in
let empties = ref 0 in
let proc_index = Procname.Hash.create 11 in
let source_index = SourceFile.Hash.create 11 in
let db = Database.get_database CaptureDatabase in
let stmt = Sqlite3.prepare db "SELECT source_file, procedure_names FROM source_files" in
SqliteUtils.result_fold_rows db ~log:"loading procname to source index" stmt ~init:()
~f:(fun () stmt ->
let source_file = Sqlite3.column stmt 0 |> SourceFile.SQLite.deserialize in
if SourceFile.is_invalid source_file then ()
else
let procedure_names = Sqlite3.column stmt 1 |> Procname.SQLiteList.deserialize in
SourceFile.Hash.replace source_index source_file procedure_names ;
List.iter procedure_names ~f:(fun proc_name ->
Procname.Hash.replace proc_index proc_name source_file ) ;
incr counter ;
if List.is_empty procedure_names then incr empties ) ;
L.debug Capture Medium "Processed %d source files, of which %d had no procedures.@\n" !counter
!empties ;
(proc_index, source_index)
(** build a hashtable from a procedure to all (static) callees *)
let get_call_map () =
let call_map = Procname.Hash.create 11 in
let f procname callees = Procname.Hash.replace call_map procname callees in
SyntacticCallGraph.iter_captured_procs_and_callees f ;
call_map
end
module G = struct
module Vertex = struct
include SourceFile
let hash = Caml.Hashtbl.hash
end
module Edge = struct
(** An edge labelled by the number of calls from procedures in the source file to procedures in
the destination file. *)
type t = int [@@deriving compare]
(** ocamlgraph requires a [default] edge label for labelled edges. *)
let default = 1
end
(* a graph where vertices are source files and edges are labelled with integers *)
include Graph.Imperative.Digraph.ConcreteBidirectionalLabeled (Vertex) (Edge)
(** load the source-file call graph, labelled by (over-approximate) number of calls from source
file to destination file. *)
let load_graph () =
let proc_index, source_index = Loader.get_indexes () in
let callee_map = Loader.get_call_map () in
let g = create () in
let max_label = ref 0 in
let unique_callees_of_file procedures =
List.fold procedures ~init:Procname.Set.empty ~f:(fun acc procname ->
let callees = Procname.Hash.find_opt callee_map procname |> Option.value ~default:[] in
List.fold callees ~init:acc ~f:(fun acc callee -> Procname.Set.add callee acc) )
in
(* update table of number of calls into each callee source file for a given callee *)
let process_callee_of_file source_counts source callee =
Procname.Hash.find_opt proc_index callee
|> Option.filter ~f:(fun callee_source ->
(* avoid self-loops *) not (SourceFile.equal source callee_source) )
|> Option.iter ~f:(fun callee_source ->
let previous_count =
SourceFile.Hash.find_opt source_counts callee_source |> Option.value ~default:0
in
SourceFile.Hash.replace source_counts callee_source (1 + previous_count) )
in
let create_callee_edges source callee_source count =
E.create source count callee_source |> add_edge_e g ;
max_label := max !max_label count
in
let process_source_file source procedures =
add_vertex g source ;
let source_counts = SourceFile.Hash.create 11 in
unique_callees_of_file procedures
|> Procname.Set.iter (process_callee_of_file source_counts source) ;
SourceFile.Hash.iter (create_callee_edges source) source_counts
in
SourceFile.Hash.iter process_source_file source_index ;
L.debug Capture Medium "Maximum edge weight = %d.@\n" !max_label ;
g
module Cache = Caml.Hashtbl.Make (Vertex)
let vertex_name =
hashtable from source files to strings of the form " N%d " . Used for dot conversion only .
let cache = Cache.create 11 in
fun v ->
match Cache.find_opt cache v with
| Some name ->
name
| None ->
let name = "N" ^ string_of_int (Cache.length cache) in
Cache.add cache v name ;
name
(* all functions below needed for dot output. *)
let get_subgraph _ = None
let graph_attributes _ = []
let default_vertex_attributes _ = []
let vertex_attributes v = [`Label (SourceFile.to_string v)]
let default_edge_attributes _ = []
let edge_attributes e = [`Label (string_of_int (E.label e))]
end
module Dot = Graph.Graphviz.Dot (G)
let to_dotty g filename =
Out_channel.with_file (Config.results_dir ^/ filename) ~f:(fun out -> Dot.output_graph out g)
module Dfs = Graph.Traverse.Dfs (G)
module Dagify = struct
* given a non - empty list of edges representing the reverse of a path with a cycle , where the
join node is the destination of the first edge , return a minimal edge inside the cycle .
join node is the destination of the first edge, return a minimal edge inside the cycle. *)
let find_min_edge =
let min_edge e e' = if G.E.compare e e' <= 0 then e else e' in
(* [v] is the joint point, [e] is the best edge found so far *)
let rec find_edge v e = function
| [] ->
e
| e' :: _ when G.Vertex.equal v (G.E.src e') ->
(* we found the origin of the cycle *)
min_edge e e'
| e' :: rest ->
find_edge v (min_edge e e') rest
in
function [] -> assert false | e :: rest -> find_edge (G.E.dst e) e rest
(** [finished] is a hashset of nodes known not to participate in cycles; [path] is a (reversed)
path of edges; [nodes_in_path] is the set of source nodes in [path] ; [v] is the node to
explore in DFS fashion *)
let rec find_cycle_min_edge g finished path nodes_in_path v =
if SourceFile.Hash.mem finished v then None
else if SourceFile.Set.mem v nodes_in_path then Some (find_min_edge path)
else
let nodes_in_path' = SourceFile.Set.add v nodes_in_path in
let res =
G.succ_e g v
|> List.find_map ~f:(fun e' ->
let v' = G.E.dst e' in
let path' = e' :: path in
find_cycle_min_edge g finished path' nodes_in_path' v' )
in
if Option.is_none res then SourceFile.Hash.add finished v () ;
res
exception CycleFound of G.E.t
let make_acyclic g =
let finished = SourceFile.Hash.create (G.nb_vertex g) in
(* given a node, find a cycle and return minimum edge in it, or mark all reachable nodes as [finished] *)
let start_dfs v =
if SourceFile.Hash.mem finished v then ()
else
find_cycle_min_edge g finished [] SourceFile.Set.empty v
|> Option.iter ~f:(fun edge -> raise (CycleFound edge))
in
let rec make_acyclic_inner () =
try G.iter_vertex start_dfs g
with CycleFound edge ->
if Config.debug_mode then assert (Dfs.has_cycle g) ;
(* we found a cycle, break it and restart dfs modulo [finished] nodes *)
L.debug Capture Medium "Found back edge, src=%a, dst=%a@, weight=%d." SourceFile.pp
(G.E.src edge) SourceFile.pp (G.E.dst edge) (G.E.label edge) ;
G.remove_edge_e g edge ;
make_acyclic_inner ()
in
make_acyclic_inner () ;
if Config.debug_mode then (
assert (not (Dfs.has_cycle g)) ;
to_dotty g "file-call-graph-dag.dot" )
end
module Tree = struct
(** trees are compared only by size *)
type t = {vertices: SourceFile.t list [@compare.ignore]; size: int} [@@deriving compare]
let size {size} = size
let iter_vertices {vertices} ~f = List.iter vertices ~f
* given a DAG [ g ] , split it into a set of trees by deleting all incoming edges but the heaviest
for every node
for every node *)
let make_forest g =
let is_forest g = G.fold_vertex (fun v acc -> acc && G.in_degree g v <= 1) g true in
let forestify_vertex g v =
let _max_edge_opt, edges_to_delete =
G.fold_pred_e
(fun e (max_edge_opt, edges_to_delete) ->
match max_edge_opt with
| None ->
(Some e, edges_to_delete)
| Some e' when G.E.compare e e' <= 0 ->
(max_edge_opt, e :: edges_to_delete)
| Some e' ->
(Some e, e' :: edges_to_delete) )
g v (None, [])
in
List.iter edges_to_delete ~f:(G.remove_edge_e g)
in
if Config.debug_mode then assert (not (Dfs.has_cycle g)) ;
G.iter_vertex (forestify_vertex g) g ;
if Config.debug_mode then (
assert (is_forest g) ;
to_dotty g "file-call-graph-forest.dot" )
(** given a graph that consists of a set of trees, make a list of [t]s sorted by increasing size *)
let get_sorted_tree_list g =
let roots =
G.fold_vertex (fun v acc -> if Int.equal 0 (G.in_degree g v) then v :: acc else acc) g []
in
let reachable_nodes v =
Dfs.fold_component
(fun v' acc -> {vertices= v' :: acc.vertices; size= 1 + acc.size})
{vertices= []; size= 0} g v
in
List.fold roots ~init:[] ~f:(fun acc v -> reachable_nodes v :: acc) |> List.stable_sort ~compare
(** given a [t] in a forest graph [g], find and delete a minimal edge from [t] *)
let split_tree g t =
let min_edge_of_tree =
List.fold t.vertices ~init:None ~f:(fun acc v ->
let parent_edge_opt = G.pred_e g v |> List.hd in
match (acc, parent_edge_opt) with
| None, None ->
None
| None, some_edge | some_edge, None ->
some_edge
| Some e, Some e' ->
if G.E.compare e e' <= 0 then acc else parent_edge_opt )
in
min_edge_of_tree |> Option.value_exn |> G.remove_edge_e g
end
module Bin = struct
(** a set of trees to send to a single worker, compared only by size *)
type t = {trees: Tree.t list [@compare.ignore]; bin_size: int} [@@deriving compare]
let empty = {trees= []; bin_size= 0}
let add_tree (tree : Tree.t) {trees; bin_size} =
{trees= tree :: trees; bin_size= tree.size + bin_size}
let iter_vertices bin ~f = List.iter bin.trees ~f:(Tree.iter_vertices ~f)
let size {bin_size} = bin_size
let find_max_tree init {trees} =
List.fold trees ~init ~f:(fun ((max_size, _) as acc) t ->
let m = max max_size (Tree.size t) in
if m > max_size then (m, Some t) else acc )
let max_tree_size t = find_max_tree (0, None) t |> fst
let pp fmt bin = F.fprintf fmt "%d(%d)" bin.bin_size (max_tree_size bin)
end
* a priority heap of [ Bin.t]s
module Heap = struct
include Binary_heap.Make (Bin)
let to_list bins = fold (fun bin acc -> bin :: acc) bins []
end
* a list of [ Bin.t]s of a predefined length ( equal to number of workers )
module Schedule = struct
let size schedule = List.fold ~init:0 schedule ~f:(fun acc bin -> Bin.size bin + acc)
let max_tree_size schedule =
List.fold schedule ~init:0 ~f:(fun acc c -> max acc (Bin.max_tree_size c))
let find_max_tree schedule = List.fold schedule ~init:(0, None) ~f:Bin.find_max_tree
let pp fmt t = F.fprintf fmt "Schedule: %a" (PrettyPrintable.pp_collection ~pp_item:Bin.pp) t
let histogram_bins = 10
let pp_histogram fmt schedule =
let max_size = max_tree_size schedule in
let histogram_bin_size = 1 + (max_size / (histogram_bins - 1)) in
let histogram = Array.init histogram_bins ~f:(fun _ -> 0) in
L.debug Capture Quiet "max_size=%d, histogram_bin_size=%d.@." max_size histogram_bin_size ;
List.iter schedule ~f:(fun (bin : Bin.t) ->
List.iter bin.trees ~f:(fun t ->
let size = Tree.size t in
let hist_bin = size / histogram_bin_size in
1 + Array.get histogram hist_bin |> Array.set histogram hist_bin ) ) ;
F.fprintf fmt "tree histogram:@\n" ;
Array.iteri histogram ~f:(fun i num ->
F.fprintf fmt "[%d - %d]: %d@\n" (i * histogram_bin_size)
(((i + 1) * histogram_bin_size) - 1)
num )
* schedule trees using " shortest processing time first "
let schedule_trees n_workers trees_list =
let bins = Heap.create ~dummy:Bin.empty n_workers in
for _ = 1 to n_workers do
Heap.add bins Bin.empty
done ;
List.iter trees_list ~f:(fun tree ->
Heap.pop_minimum bins |> Bin.add_tree tree |> Heap.add bins ) ;
Heap.to_list bins
* " error " is the difference between the average size of a bin and the actual one . The sum of
absolute errors divided by the total size ( as percentage ) is compared to [ max_error_pc ] .
absolute errors divided by the total size (as percentage) is compared to [max_error_pc]. *)
let is_error_leq_than_max ~n_workers ~max_error_pc schedule =
let total_size = size schedule in
let avg_size = total_size / n_workers in
let total_error =
List.fold ~init:0 schedule ~f:(fun acc bin -> abs (Bin.size bin - avg_size) + acc)
in
let avg_error_pc = 100 * total_error / total_size in
L.debug Capture Medium "Schedule error pc: %d@\n" avg_error_pc ;
avg_error_pc <= max_error_pc
* given a set of trees [ g ] produce a schedule that has error lower / equal to [ max_error_pc ]
let rec find ~orig_size ~n_workers ~max_error_pc g =
let schedule = Tree.get_sorted_tree_list g |> schedule_trees n_workers in
L.debug Capture Medium "Found schedule with bins: %a@\n" pp schedule ;
L.debug Capture Medium "%a" pp_histogram schedule ;
if Config.debug_mode then assert (Int.equal orig_size (size schedule)) ;
if is_error_leq_than_max ~n_workers ~max_error_pc schedule then schedule
else (
find_max_tree schedule |> snd |> Option.value_exn |> Tree.split_tree g ;
find ~orig_size ~n_workers ~max_error_pc g )
let find ~orig_size ~n_workers ~max_error_pc g =
time_and_run
~f:(fun () ->
Dagify.make_acyclic g ;
Tree.make_forest g ;
find ~orig_size ~n_workers ~max_error_pc g )
~msg:"Find"
let output ~n_workers schedule =
let width = string_of_int (n_workers - 1) |> String.length in
let schedule_filename = Config.results_dir ^/ "schedule.txt" in
List.mapi schedule ~f:(fun i bin ->
L.progress "Schedule for worker %i contains %i files.@\n" i (Bin.size bin) ;
let filename = Printf.sprintf "%s/worker%*d.idx" Config.results_dir width i in
Out_channel.with_file filename ~f:(fun out ->
Bin.iter_vertices bin ~f:(fun source_file ->
Out_channel.output_string out (SourceFile.to_string source_file) ;
Out_channel.newline out ) ) ;
filename )
|> Out_channel.write_lines schedule_filename
let find_and_output ~n_workers ~max_error_pc =
let g = G.load_graph () in
let orig_size = G.nb_vertex g in
find ~orig_size ~n_workers ~max_error_pc g |> output ~n_workers
end
let max_error_pc = 10
let partition_source_file_call_graph ~n_workers = Schedule.find_and_output ~n_workers ~max_error_pc
let to_dotty filename =
let g = G.load_graph () in
to_dotty g filename
| null | https://raw.githubusercontent.com/facebook/infer/74e3bb0edd7fd1192b6511c7e649bb0df36fef14/infer/src/backend/SourceFileGraph.ml | ocaml | * Build a hash table from procedure name to source file where it's defined, and a hash table
from source files to list of procedures defined.
* build a hashtable from a procedure to all (static) callees
* An edge labelled by the number of calls from procedures in the source file to procedures in
the destination file.
* ocamlgraph requires a [default] edge label for labelled edges.
a graph where vertices are source files and edges are labelled with integers
* load the source-file call graph, labelled by (over-approximate) number of calls from source
file to destination file.
update table of number of calls into each callee source file for a given callee
avoid self-loops
all functions below needed for dot output.
[v] is the joint point, [e] is the best edge found so far
we found the origin of the cycle
* [finished] is a hashset of nodes known not to participate in cycles; [path] is a (reversed)
path of edges; [nodes_in_path] is the set of source nodes in [path] ; [v] is the node to
explore in DFS fashion
given a node, find a cycle and return minimum edge in it, or mark all reachable nodes as [finished]
we found a cycle, break it and restart dfs modulo [finished] nodes
* trees are compared only by size
* given a graph that consists of a set of trees, make a list of [t]s sorted by increasing size
* given a [t] in a forest graph [g], find and delete a minimal edge from [t]
* a set of trees to send to a single worker, compared only by size |
* Copyright ( c ) Facebook , Inc. and its affiliates .
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree .
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*)
open! IStd
module F = Format
module L = Logging
let time_and_run ~f ~msg =
let result, duration_ms = Utils.timeit ~f in
L.debug Capture Medium "%s took %d ms.@\n" msg duration_ms ;
result
module Loader = struct
let get_indexes () =
let counter = ref 0 in
let empties = ref 0 in
let proc_index = Procname.Hash.create 11 in
let source_index = SourceFile.Hash.create 11 in
let db = Database.get_database CaptureDatabase in
let stmt = Sqlite3.prepare db "SELECT source_file, procedure_names FROM source_files" in
SqliteUtils.result_fold_rows db ~log:"loading procname to source index" stmt ~init:()
~f:(fun () stmt ->
let source_file = Sqlite3.column stmt 0 |> SourceFile.SQLite.deserialize in
if SourceFile.is_invalid source_file then ()
else
let procedure_names = Sqlite3.column stmt 1 |> Procname.SQLiteList.deserialize in
SourceFile.Hash.replace source_index source_file procedure_names ;
List.iter procedure_names ~f:(fun proc_name ->
Procname.Hash.replace proc_index proc_name source_file ) ;
incr counter ;
if List.is_empty procedure_names then incr empties ) ;
L.debug Capture Medium "Processed %d source files, of which %d had no procedures.@\n" !counter
!empties ;
(proc_index, source_index)
let get_call_map () =
let call_map = Procname.Hash.create 11 in
let f procname callees = Procname.Hash.replace call_map procname callees in
SyntacticCallGraph.iter_captured_procs_and_callees f ;
call_map
end
module G = struct
module Vertex = struct
include SourceFile
let hash = Caml.Hashtbl.hash
end
module Edge = struct
type t = int [@@deriving compare]
let default = 1
end
include Graph.Imperative.Digraph.ConcreteBidirectionalLabeled (Vertex) (Edge)
let load_graph () =
let proc_index, source_index = Loader.get_indexes () in
let callee_map = Loader.get_call_map () in
let g = create () in
let max_label = ref 0 in
let unique_callees_of_file procedures =
List.fold procedures ~init:Procname.Set.empty ~f:(fun acc procname ->
let callees = Procname.Hash.find_opt callee_map procname |> Option.value ~default:[] in
List.fold callees ~init:acc ~f:(fun acc callee -> Procname.Set.add callee acc) )
in
let process_callee_of_file source_counts source callee =
Procname.Hash.find_opt proc_index callee
|> Option.filter ~f:(fun callee_source ->
|> Option.iter ~f:(fun callee_source ->
let previous_count =
SourceFile.Hash.find_opt source_counts callee_source |> Option.value ~default:0
in
SourceFile.Hash.replace source_counts callee_source (1 + previous_count) )
in
let create_callee_edges source callee_source count =
E.create source count callee_source |> add_edge_e g ;
max_label := max !max_label count
in
let process_source_file source procedures =
add_vertex g source ;
let source_counts = SourceFile.Hash.create 11 in
unique_callees_of_file procedures
|> Procname.Set.iter (process_callee_of_file source_counts source) ;
SourceFile.Hash.iter (create_callee_edges source) source_counts
in
SourceFile.Hash.iter process_source_file source_index ;
L.debug Capture Medium "Maximum edge weight = %d.@\n" !max_label ;
g
module Cache = Caml.Hashtbl.Make (Vertex)
let vertex_name =
hashtable from source files to strings of the form " N%d " . Used for dot conversion only .
let cache = Cache.create 11 in
fun v ->
match Cache.find_opt cache v with
| Some name ->
name
| None ->
let name = "N" ^ string_of_int (Cache.length cache) in
Cache.add cache v name ;
name
let get_subgraph _ = None
let graph_attributes _ = []
let default_vertex_attributes _ = []
let vertex_attributes v = [`Label (SourceFile.to_string v)]
let default_edge_attributes _ = []
let edge_attributes e = [`Label (string_of_int (E.label e))]
end
module Dot = Graph.Graphviz.Dot (G)
let to_dotty g filename =
Out_channel.with_file (Config.results_dir ^/ filename) ~f:(fun out -> Dot.output_graph out g)
module Dfs = Graph.Traverse.Dfs (G)
module Dagify = struct
* given a non - empty list of edges representing the reverse of a path with a cycle , where the
join node is the destination of the first edge , return a minimal edge inside the cycle .
join node is the destination of the first edge, return a minimal edge inside the cycle. *)
let find_min_edge =
let min_edge e e' = if G.E.compare e e' <= 0 then e else e' in
let rec find_edge v e = function
| [] ->
e
| e' :: _ when G.Vertex.equal v (G.E.src e') ->
min_edge e e'
| e' :: rest ->
find_edge v (min_edge e e') rest
in
function [] -> assert false | e :: rest -> find_edge (G.E.dst e) e rest
let rec find_cycle_min_edge g finished path nodes_in_path v =
if SourceFile.Hash.mem finished v then None
else if SourceFile.Set.mem v nodes_in_path then Some (find_min_edge path)
else
let nodes_in_path' = SourceFile.Set.add v nodes_in_path in
let res =
G.succ_e g v
|> List.find_map ~f:(fun e' ->
let v' = G.E.dst e' in
let path' = e' :: path in
find_cycle_min_edge g finished path' nodes_in_path' v' )
in
if Option.is_none res then SourceFile.Hash.add finished v () ;
res
exception CycleFound of G.E.t
let make_acyclic g =
let finished = SourceFile.Hash.create (G.nb_vertex g) in
let start_dfs v =
if SourceFile.Hash.mem finished v then ()
else
find_cycle_min_edge g finished [] SourceFile.Set.empty v
|> Option.iter ~f:(fun edge -> raise (CycleFound edge))
in
let rec make_acyclic_inner () =
try G.iter_vertex start_dfs g
with CycleFound edge ->
if Config.debug_mode then assert (Dfs.has_cycle g) ;
L.debug Capture Medium "Found back edge, src=%a, dst=%a@, weight=%d." SourceFile.pp
(G.E.src edge) SourceFile.pp (G.E.dst edge) (G.E.label edge) ;
G.remove_edge_e g edge ;
make_acyclic_inner ()
in
make_acyclic_inner () ;
if Config.debug_mode then (
assert (not (Dfs.has_cycle g)) ;
to_dotty g "file-call-graph-dag.dot" )
end
module Tree = struct
type t = {vertices: SourceFile.t list [@compare.ignore]; size: int} [@@deriving compare]
let size {size} = size
let iter_vertices {vertices} ~f = List.iter vertices ~f
* given a DAG [ g ] , split it into a set of trees by deleting all incoming edges but the heaviest
for every node
for every node *)
let make_forest g =
let is_forest g = G.fold_vertex (fun v acc -> acc && G.in_degree g v <= 1) g true in
let forestify_vertex g v =
let _max_edge_opt, edges_to_delete =
G.fold_pred_e
(fun e (max_edge_opt, edges_to_delete) ->
match max_edge_opt with
| None ->
(Some e, edges_to_delete)
| Some e' when G.E.compare e e' <= 0 ->
(max_edge_opt, e :: edges_to_delete)
| Some e' ->
(Some e, e' :: edges_to_delete) )
g v (None, [])
in
List.iter edges_to_delete ~f:(G.remove_edge_e g)
in
if Config.debug_mode then assert (not (Dfs.has_cycle g)) ;
G.iter_vertex (forestify_vertex g) g ;
if Config.debug_mode then (
assert (is_forest g) ;
to_dotty g "file-call-graph-forest.dot" )
let get_sorted_tree_list g =
let roots =
G.fold_vertex (fun v acc -> if Int.equal 0 (G.in_degree g v) then v :: acc else acc) g []
in
let reachable_nodes v =
Dfs.fold_component
(fun v' acc -> {vertices= v' :: acc.vertices; size= 1 + acc.size})
{vertices= []; size= 0} g v
in
List.fold roots ~init:[] ~f:(fun acc v -> reachable_nodes v :: acc) |> List.stable_sort ~compare
let split_tree g t =
let min_edge_of_tree =
List.fold t.vertices ~init:None ~f:(fun acc v ->
let parent_edge_opt = G.pred_e g v |> List.hd in
match (acc, parent_edge_opt) with
| None, None ->
None
| None, some_edge | some_edge, None ->
some_edge
| Some e, Some e' ->
if G.E.compare e e' <= 0 then acc else parent_edge_opt )
in
min_edge_of_tree |> Option.value_exn |> G.remove_edge_e g
end
module Bin = struct
type t = {trees: Tree.t list [@compare.ignore]; bin_size: int} [@@deriving compare]
let empty = {trees= []; bin_size= 0}
let add_tree (tree : Tree.t) {trees; bin_size} =
{trees= tree :: trees; bin_size= tree.size + bin_size}
let iter_vertices bin ~f = List.iter bin.trees ~f:(Tree.iter_vertices ~f)
let size {bin_size} = bin_size
let find_max_tree init {trees} =
List.fold trees ~init ~f:(fun ((max_size, _) as acc) t ->
let m = max max_size (Tree.size t) in
if m > max_size then (m, Some t) else acc )
let max_tree_size t = find_max_tree (0, None) t |> fst
let pp fmt bin = F.fprintf fmt "%d(%d)" bin.bin_size (max_tree_size bin)
end
* a priority heap of [ Bin.t]s
module Heap = struct
include Binary_heap.Make (Bin)
let to_list bins = fold (fun bin acc -> bin :: acc) bins []
end
* a list of [ Bin.t]s of a predefined length ( equal to number of workers )
module Schedule = struct
let size schedule = List.fold ~init:0 schedule ~f:(fun acc bin -> Bin.size bin + acc)
let max_tree_size schedule =
List.fold schedule ~init:0 ~f:(fun acc c -> max acc (Bin.max_tree_size c))
let find_max_tree schedule = List.fold schedule ~init:(0, None) ~f:Bin.find_max_tree
let pp fmt t = F.fprintf fmt "Schedule: %a" (PrettyPrintable.pp_collection ~pp_item:Bin.pp) t
let histogram_bins = 10
let pp_histogram fmt schedule =
let max_size = max_tree_size schedule in
let histogram_bin_size = 1 + (max_size / (histogram_bins - 1)) in
let histogram = Array.init histogram_bins ~f:(fun _ -> 0) in
L.debug Capture Quiet "max_size=%d, histogram_bin_size=%d.@." max_size histogram_bin_size ;
List.iter schedule ~f:(fun (bin : Bin.t) ->
List.iter bin.trees ~f:(fun t ->
let size = Tree.size t in
let hist_bin = size / histogram_bin_size in
1 + Array.get histogram hist_bin |> Array.set histogram hist_bin ) ) ;
F.fprintf fmt "tree histogram:@\n" ;
Array.iteri histogram ~f:(fun i num ->
F.fprintf fmt "[%d - %d]: %d@\n" (i * histogram_bin_size)
(((i + 1) * histogram_bin_size) - 1)
num )
* schedule trees using " shortest processing time first "
let schedule_trees n_workers trees_list =
let bins = Heap.create ~dummy:Bin.empty n_workers in
for _ = 1 to n_workers do
Heap.add bins Bin.empty
done ;
List.iter trees_list ~f:(fun tree ->
Heap.pop_minimum bins |> Bin.add_tree tree |> Heap.add bins ) ;
Heap.to_list bins
* " error " is the difference between the average size of a bin and the actual one . The sum of
absolute errors divided by the total size ( as percentage ) is compared to [ max_error_pc ] .
absolute errors divided by the total size (as percentage) is compared to [max_error_pc]. *)
let is_error_leq_than_max ~n_workers ~max_error_pc schedule =
let total_size = size schedule in
let avg_size = total_size / n_workers in
let total_error =
List.fold ~init:0 schedule ~f:(fun acc bin -> abs (Bin.size bin - avg_size) + acc)
in
let avg_error_pc = 100 * total_error / total_size in
L.debug Capture Medium "Schedule error pc: %d@\n" avg_error_pc ;
avg_error_pc <= max_error_pc
* given a set of trees [ g ] produce a schedule that has error lower / equal to [ max_error_pc ]
let rec find ~orig_size ~n_workers ~max_error_pc g =
let schedule = Tree.get_sorted_tree_list g |> schedule_trees n_workers in
L.debug Capture Medium "Found schedule with bins: %a@\n" pp schedule ;
L.debug Capture Medium "%a" pp_histogram schedule ;
if Config.debug_mode then assert (Int.equal orig_size (size schedule)) ;
if is_error_leq_than_max ~n_workers ~max_error_pc schedule then schedule
else (
find_max_tree schedule |> snd |> Option.value_exn |> Tree.split_tree g ;
find ~orig_size ~n_workers ~max_error_pc g )
let find ~orig_size ~n_workers ~max_error_pc g =
time_and_run
~f:(fun () ->
Dagify.make_acyclic g ;
Tree.make_forest g ;
find ~orig_size ~n_workers ~max_error_pc g )
~msg:"Find"
let output ~n_workers schedule =
let width = string_of_int (n_workers - 1) |> String.length in
let schedule_filename = Config.results_dir ^/ "schedule.txt" in
List.mapi schedule ~f:(fun i bin ->
L.progress "Schedule for worker %i contains %i files.@\n" i (Bin.size bin) ;
let filename = Printf.sprintf "%s/worker%*d.idx" Config.results_dir width i in
Out_channel.with_file filename ~f:(fun out ->
Bin.iter_vertices bin ~f:(fun source_file ->
Out_channel.output_string out (SourceFile.to_string source_file) ;
Out_channel.newline out ) ) ;
filename )
|> Out_channel.write_lines schedule_filename
let find_and_output ~n_workers ~max_error_pc =
let g = G.load_graph () in
let orig_size = G.nb_vertex g in
find ~orig_size ~n_workers ~max_error_pc g |> output ~n_workers
end
let max_error_pc = 10
let partition_source_file_call_graph ~n_workers = Schedule.find_and_output ~n_workers ~max_error_pc
let to_dotty filename =
let g = G.load_graph () in
to_dotty g filename
|
86ecccb1eb367ccdc2d39ac5adc6b683a6d4d4a482e1f2be4a8fa5f15fc127d9 | mirage/metrics | metrics.mli |
* Copyright ( c ) 2018 < >
*
* Permission to use , copy , modify , and distribute this software for any
* purpose with or without fee is hereby granted , provided that the above
* copyright notice and this permission notice appear in all copies .
*
* THE SOFTWARE IS PROVIDED " AS IS " AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS . IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL , DIRECT , INDIRECT , OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE , DATA OR PROFITS , WHETHER IN AN
* ACTION OF CONTRACT , NEGLIGENCE OR OTHER TORTIOUS ACTION , ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE .
* Copyright (c) 2018 Thomas Gazagnaire <>
*
* Permission to use, copy, modify, and distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*)
(** Metrics Monitoring.
[Metrics] provides a basic infrastructure to monitor metrics using time
series. {{!func} Monitoring} is performed on {{!srcs} sources}, indexed by
{{!tags} tags}. Tags allow users to select at runtime which metric sources
are producing data points. Disabled data-sources have a low runtime cost
(only a closure allocation) which make [Metrics] suitable to instrument
production systems.
Both sources tags and data-points are built using dictionaries of typed
entries called {{!fields} fields}.
[Metrics] is heavily inspired by {{:} Logs}
as it decouples metric reporting from metric monitoring. This is handled by
custom {{!reporter} reporters}.
{e %%VERSION%% - {{:%%PKG_HOMEPAGE%%} homepage}} *)
* { 2 : fields Fields }
type graph
(** The type for metric {{!graphs} graphs}. *)
type field
(** The type for metric fields. *)
type key = string
(** The type for field keys. *)
type 'a field_f =
?doc:string ->
?unit:string ->
?graph:graph ->
?graphs:graph list ->
key ->
'a ->
field
(** The type for field functions. *)
val string : string field_f
(** [string ?doc k v] is the field whose key is [k] and value is [v]. *)
val int : int field_f
(** [int ?doc k i] is the field whose key is [k] and value is [i]. *)
val uint : int field_f
(** [uint ?doc k i] is the field whose key is [k] and value is [i]. *)
val int32 : int32 field_f
(** [int32 k i] is the field whose key is [k] and value is [i]. *)
val uint32 : int32 field_f
* [ uint32 ? doc k i ] is the field whose key is [ k ] and value is [ i ] .
val int64 : int64 field_f
* [ int64 ? doc k i ] is the field whose key is [ k ] and value is [ i ] .
val uint64 : int64 field_f
* [ uint64 ? doc k i ] is the field whose key is [ k ] and value is [ i ] .
val float : float field_f
(** [uint ?doc k f] is the field whose key is [k] and value is [i]. *)
val bool : bool field_f
(** [uint ?doc k b] is the field whose key is [k] and value is [i]. *)
val duration : int64 -> field
(** [duration t] is the field [("duration", t, "ns")]. *)
type status = [ `Ok | `Error ]
(** The type for process status. *)
val status : status -> field
(** [status t] is the field [("status", "ok")] or [("status", "error")]. *)
(** {3 Custom fields} *)
(** The type of supported values in metric fields. *)
type 'a ty =
| String : string ty
| Bool : bool ty
| Float : float ty
| Int : int ty
| Int32 : int32 ty
| Int64 : int64 ty
| Uint : int ty
| Uint32 : int32 ty
| Uint64 : int64 ty
| Other : 'a Fmt.t -> 'a ty
val field :
?doc:string ->
?unit:string ->
?graph:graph ->
?graphs:graph list ->
string ->
'a ty ->
'a ->
field
(** [field ?doc ?unit k ty v] is the field whose key is [k], value type is [ty]
and value is [v]. *)
* { 3 Reading Fields }
val key : field -> string
(** [key f] is [f]'s key. *)
val doc : field -> string option
(** [doc f] is [f]'s documentation. *)
val unit : field -> string option
(** [unit t] are [t]'s units. *)
val graphs : field -> graph list option
(** [graphs t] is the graphs where [t] appears. *)
type value = V : 'a ty * 'a -> value (** Type for values. *)
val value : field -> value
(** [value f] is [f]'s value. *)
val index : fields:string list -> field -> int
(** [index ~fields f] is [f]'s index in the list of field keys [fields]. Raise
[Not_found] if [f] is not a field of [t]. *)
val index_key : fields:string list -> string -> int
(** Same as {!index} but using field keys instead. *)
* { 3 Pretty - printing }
val pp_key : field Fmt.t
(** [pp_key] is the pretty-printer for field keys. *)
val pp_value : field Fmt.t
(** [pp_value] is the pretty-printer for field values, using sensible default. *)
* { 2 : data Data points }
(** [Data] defines what is stored in the time series. *)
module Data : sig
* { 2 Data }
[ Metric ] 's data points are a list of typed fields with an optional
timestamp . They are created with the { ! v } and { { ! fields } field }
constructors .
For instance , to create a data point with two values [ " % CPU " ] and [ " MEM " ] ,
respectively of type [ float ] and [ int ] :
{ [ let x = Data.v [ float " % CPU " 0.42 ; int " MEM " 27_000 ] ] }
[Metric]'s data points are a list of typed fields with an optional
timestamp. They are created with the {!v} and {{!fields} field}
constructors.
For instance, to create a data point with two values ["%CPU"] and ["MEM"],
respectively of type [float] and [int]:
{[ let x = Data.v [ float "%CPU" 0.42; int "MEM" 27_000 ] ]} *)
type t
(** The type for data points. *)
type timestamp = string
* The type for timestamp . A timestamp shows the date and time , in RFC3339
UTC , associated with particular data .
UTC, associated with particular data. *)
val timestamp : t -> timestamp option
(** [timestamp t] is [t]'s timestamp (if any). If it is [None], then the
reporter will add a new timestamp automatically. *)
val v : ?timestamp:timestamp -> field list -> t
(** [v ?timestamp f] is the measure [f], as a the list metric name and value,
and the timestamp [timestamp]. If [timestamp] is not provided, it will be
set be the reporter. Raise [Invalid_argument] is a key or a value contains
an invalid character. *)
val keys : t -> key list
(** [keys t] is [t]'s keys. *)
val fields : t -> field list
(** [fields t] is [t]'s fields. *)
val cons : field -> t -> t
(** [cons f t] is the new data having the same timestamp as [t] and the fields
[f :: fields t]. *)
end
type data = Data.t
(** The type for data points. *)
* { 2 : tags Tags }
(** [Tags] indexes metric sources, and allow to enable/disable data collection
at runtime. *)
module Tags : sig
* { 2 Tags }
[ Tags ] are heterogeneous { { ! t } lists } of key names and type of values ,
which are associated to data sources . Filters on key names allow to select
which data sources is { { ! enabling } enabled } at runtime . Disabled data
sources have a very low cost -- only allocating a closure .
For instance , to define the tags " PID " , " IP " and " host " , respectively of
type [ int ] , [ Ipaddr.t ] :
{ [
let ipaddr = Tags.v Ipaddr.pp_hum in
let t = Tags . [ int " PID " ; ipaddr " IP " ; string " host " ; ]
] }
[Tags] are heterogeneous {{!t} lists} of key names and type of values,
which are associated to data sources. Filters on key names allow to select
which data sources is {{!enabling} enabled} at runtime. Disabled data
sources have a very low cost -- only allocating a closure.
For instance, to define the tags "PID", "IP" and "host", respectively of
type [int], [Ipaddr.t]:
{[
let ipaddr = Tags.v Ipaddr.pp_hum in
let t = Tags.[ int "PID" ; ipaddr "IP" ; string "host"; ]
]} *)
type 'a v
(** The type for tag values. *)
(** The type tags: an heterogeneous list of names and types. *)
type 'a t = [] : field list t | ( :: ) : 'a v * 'b t -> ('a -> 'b) t
* { 3 Tag Values }
val v : 'a Fmt.t -> string -> 'a v
(** [ty pp] is a new typed tag. *)
val string : string -> string v
val float : string -> float v
val int : string -> int v
val uint : string -> int v
val int32 : string -> int32 v
val uint32 : string -> int32 v
val int64 : string -> int64 v
val uint64 : string -> int64 v
val bool : string -> bool v
end
type tags = field list
(** The type for metric tags. Used to distinguish the various entities that are
being measured. *)
val tags_enabled : unit -> key list
(** [tags_enabled ()] is the list of tags that are enabled. *)
val all_enabled : unit -> bool
(** [all_enabled ()] is true if all metric sources are enabled. *)
val enable_tag : key -> unit
(** [enable_tag t] enables all the registered metric sources having the tag [t]. *)
val disable_tag : key -> unit
(** [disable_tag t] disables all the registered metric sources having the tag
[t]. *)
val enable_all : unit -> unit
(** [enable_all ()] enables all registered metric sources. *)
val disable_all : unit -> unit
(** [disable_all ()] disables all registered metric sources. *)
* { 2 : srcs Sources }
type ('a, 'b) src
(** The type for metric sources. A source defines a named unit for a time
series. ['a] is the type of the function used to create new {{!data} data
points}. ['b] is the type for {!tags}. *)
(** Metric sources. *)
module Src : sig
* { 2 Sources }
val v :
?doc:string ->
?duration:bool ->
?status:bool ->
tags:'a Tags.t ->
data:'b ->
string ->
('a, 'b) src
* [ v ? doc name ] is a new source , accepting arbitrary data points .
[ name ] is the name of the source ; it does n't need to be unique but it is
good practice to prefix the name with the name of your package or library
( e.g. [ " mypkg.network " ] ) . [ doc ] is a documentation string describing the
source , defaults to [ " undocumented " ] . [ tags ] is the collection if ( typed )
tags which will be used to tag and index the measure and are used identify
the various metrics . The source will be enabled on creation iff one of tag
in [ tags ] has been enabled with { ! enable_tag } .
For instance , to create a metric to collect CPU and memory usage on
various machines , indexed by [ PID ] , [ host ] name and [ IP ] address :
{ [
let src =
let ipaddr = Tags.v Ipaddr.pp_hum in
let tags = Tags.[string " host " ; ipaddr " IP " ; int " PID " ; ] in
let data ( ) = Data.v [ float " % CPU " ( ... ) ; int " MEM " ( ... ) ; ] in
Src.v " top " ~tags ~data ~doc:"Information about processess "
] }
[name] is the name of the source; it doesn't need to be unique but it is
good practice to prefix the name with the name of your package or library
(e.g. ["mypkg.network"]). [doc] is a documentation string describing the
source, defaults to ["undocumented"]. [tags] is the collection if (typed)
tags which will be used to tag and index the measure and are used identify
the various metrics. The source will be enabled on creation iff one of tag
in [tags] has been enabled with {!enable_tag}.
For instance, to create a metric to collect CPU and memory usage on
various machines, indexed by [PID], [host] name and [IP] address:
{[
let src =
let ipaddr = Tags.v Ipaddr.pp_hum in
let tags = Tags.[string "host"; ipaddr "IP" ; int "PID" ; ] in
let data () = Data.v [float "%CPU" (...); int "MEM" (...); ] in
Src.v "top" ~tags ~data ~doc:"Information about processess"
]} *)
* { 3 Listing Sources }
type t = Src : ('a, 'b) src -> t (** The type for metric sources. *)
val list : unit -> t list
(** [list ()] is the current exisiting source list. *)
val name : t -> string
(** [name src] is [src]'s name. *)
val doc : t -> string
(** [doc src] is [src]'s documentation string. *)
val tags : t -> string list
(** [tags src] is the list of [src]'s tag names. *)
val data : t -> string list
* [ fields src ] is the list of [ src ] 's data field names . Note that these are
updated dynamically , so a monitoring function has to be called first .
updated dynamically, so a monitoring function has to be called first. *)
val equal : t -> t -> bool
(** [equal src src'] is [true] iff [src] and [src'] are the same source. *)
val compare : t -> t -> int
(** [compare src src'] is a total order on sources. *)
val duration : t -> bool
(** [duration t] is true iff [t] is a {!fn} source and [t] requires automatic
duration recording. *)
val status : t -> bool
(** [status t] is true iff [t] is a {!fn} source and [t] requires automatic
duration recording. *)
val pp : t Fmt.t
(** [pp ppf src] prints an unspecified representation of [src] on [ppf]. *)
val is_active : t -> bool
(** [is_active t] is true iff [t] is enabled. *)
val enable : t -> unit
(** [enable src] enables the metric source [src]. *)
val disable : t -> unit
(** [disable src] disables the metric source [src]. *)
end
* { 2 : graphs Metric Graphs }
module Graph : sig
type t = graph
(** The type for graphs. *)
val title : t -> string option
(** [title t] is [t]'s title. *)
val ylabel : t -> string option
(** [title t] is [t]'s Y label. *)
val yunit : t -> string option
(** [unit t] is [t]'s Y unit. *)
val id : t -> int
(** [id t] is [t]'s unit. *)
val v : ?title:string -> ?ylabel:string -> ?yunit:string -> unit -> t
(** [v ()] is a new graph. *)
val list : unit -> t list
(** [list ()] is the list of graphs. *)
val fields : t -> (Src.t * field) list
(** [fields t] is the list of [t]'s fields. Field names are unique for a given
source. *)
val add_field : t -> Src.t -> field -> unit
(** [add_field t src f] adds the field [f], generated by the source [src], to
the graph [t]. *)
val remove_field : t -> Src.t -> string -> unit
(** [remove_field t src f] removes the field named [f], generated from the
source [src], out of the graph [t]. *)
val enable : t -> unit
val disable : t -> unit
val is_active : t -> bool
end
module Key : sig
val duration : string
val status : string
val minor_words : string
val promoted_words : string
val major_words : string
val minor_collections : string
val major_collections : string
val heap_words : string
val heap_chunks : string
val compactions : string
val live_words : string
val live_blocks : string
val free_words : string
val free_blocks : string
val largest_free : string
val fragments : string
val top_heap_words : string
val stack_size : string
end
* { 2 : func Monitoring }
val is_active : ('a, 'b) src -> bool
(** [is_active src] is true iff [src] monitoring is enabled. *)
val add : ('a, 'b) src -> ('a -> tags) -> ('b -> Data.t) -> unit
(** [add src t f] adds a new data point to [src] for the tags [t]. *)
val run :
('a, ('b, exn) result -> Data.t) src -> ('a -> tags) -> (unit -> 'b) -> 'b
(** [run src t f] runs [f ()] and add a new data points.
Depending on [src] configuration, new data points might have duration
information (e.g. how long [g ()] took, in nano-seconds) and status
information (e.g. to check if an exception has been raised). *)
type ('a, 'b) rresult = ('a, [ `Exn of exn | `Error of 'b ]) result
(** The type for extended results. *)
val rrun :
('a, ('b, 'c) rresult -> Data.t) src ->
('a -> tags) ->
(unit -> ('b, 'c) result) ->
('b, 'c) result
(** Same as {!run} but also record if the result is [Ok] or [Error]. *)
* { 2 : reporter Reporters }
TODO : explain and give an example
TODO: explain and give an example *)
type reporter = {
now : unit -> int64;
at_exit : unit -> unit;
report :
'a.
tags:tags -> data:data -> over:(unit -> unit) -> Src.t -> (unit -> 'a) -> 'a;
}
(** The type for reporters. *)
val nop_reporter : reporter
(** [nop_reporter] is the initial reporter returned by {!reporter}, it does
nothing if a metric gets reported. *)
val reporter : unit -> reporter
(** [reporter ()] is the current reporter. *)
val set_reporter : reporter -> unit
(** [set_reporter r] sets the current reporter to [r]. *)
module SM : Map.S with type key = Src.t
val cache_reporter : unit -> (unit -> (tags * data) SM.t) * reporter
* [ cache_reporter now ( ) ] is a reporter that stores the last measurement from
each source in a map ( which can be retrieved by the returned function ) . This
is an initial attempt to overcome the push vs pull interface . Each
measurement _ event _ is sent at an arbitrary point in time , while reporting
over a communication channel may be rate - limited ( i.e. report every 10
seconds statistics , rather than whenever they appear ) .
This is only a good idea for counters , histograms etc . may be useful for
other numbers ( such as time consumed between receive and send - the
measurement should provide the information whether it 's a counter or sth
else ) .
each source in a map (which can be retrieved by the returned function). This
is an initial attempt to overcome the push vs pull interface. Each
measurement _event_ is sent at an arbitrary point in time, while reporting
over a communication channel may be rate-limited (i.e. report every 10
seconds statistics, rather than whenever they appear).
This is only a good idea for counters, histograms etc. may be useful for
other numbers (such as time consumed between receive and send - the
measurement should provide the information whether it's a counter or sth
else). *)
* { 2 : runtime sources }
The { { : -ocaml/libref/Gc.html } Gc } module
of the OCaml system provides
{ { : -ocaml/libref/Gc.html#TYPEstat }
counters } of the memory management via
{ { : -ocaml/libref/Gc.html#VALquick_stat }
Gc.quick_stat } and
{ { : -ocaml/libref/Gc.html#VALstat }
Gc.stat } function . Both are provided here .
The {{:-ocaml/libref/Gc.html} Gc} module
of the OCaml system provides
{{:-ocaml/libref/Gc.html#TYPEstat}
counters} of the memory management via
{{:-ocaml/libref/Gc.html#VALquick_stat}
Gc.quick_stat} and
{{:-ocaml/libref/Gc.html#VALstat}
Gc.stat} function. Both are provided here. *)
val gc_stat : tags:'a Tags.t -> ('a, unit -> data) src
* [ gc_stat ~tags ] is the source of 's [ Gc.stat ( ) ] memory management
counters .
counters. *)
val gc_quick_stat : tags:'a Tags.t -> ('a, unit -> data) src
* [ gc_quick_stat ] is the source of 's [ Gc.quick_stat ( ) ] memory
management counters .
management counters. *)
val report :
('a, 'b) src ->
over:(unit -> unit) ->
k:(unit -> 'c) ->
('a -> tags) ->
('b -> (data -> 'c) -> 'd) ->
'd
(**/*)
val init : ('a, 'b) src -> data -> unit
val now : unit -> int64
| null | https://raw.githubusercontent.com/mirage/metrics/be41443d0033f25f8ac5c459e150f6163436d064/src/core/metrics.mli | ocaml | * Metrics Monitoring.
[Metrics] provides a basic infrastructure to monitor metrics using time
series. {{!func} Monitoring} is performed on {{!srcs} sources}, indexed by
{{!tags} tags}. Tags allow users to select at runtime which metric sources
are producing data points. Disabled data-sources have a low runtime cost
(only a closure allocation) which make [Metrics] suitable to instrument
production systems.
Both sources tags and data-points are built using dictionaries of typed
entries called {{!fields} fields}.
[Metrics] is heavily inspired by {{:} Logs}
as it decouples metric reporting from metric monitoring. This is handled by
custom {{!reporter} reporters}.
{e %%VERSION%% - {{:%%PKG_HOMEPAGE%%} homepage}}
* The type for metric {{!graphs} graphs}.
* The type for metric fields.
* The type for field keys.
* The type for field functions.
* [string ?doc k v] is the field whose key is [k] and value is [v].
* [int ?doc k i] is the field whose key is [k] and value is [i].
* [uint ?doc k i] is the field whose key is [k] and value is [i].
* [int32 k i] is the field whose key is [k] and value is [i].
* [uint ?doc k f] is the field whose key is [k] and value is [i].
* [uint ?doc k b] is the field whose key is [k] and value is [i].
* [duration t] is the field [("duration", t, "ns")].
* The type for process status.
* [status t] is the field [("status", "ok")] or [("status", "error")].
* {3 Custom fields}
* The type of supported values in metric fields.
* [field ?doc ?unit k ty v] is the field whose key is [k], value type is [ty]
and value is [v].
* [key f] is [f]'s key.
* [doc f] is [f]'s documentation.
* [unit t] are [t]'s units.
* [graphs t] is the graphs where [t] appears.
* Type for values.
* [value f] is [f]'s value.
* [index ~fields f] is [f]'s index in the list of field keys [fields]. Raise
[Not_found] if [f] is not a field of [t].
* Same as {!index} but using field keys instead.
* [pp_key] is the pretty-printer for field keys.
* [pp_value] is the pretty-printer for field values, using sensible default.
* [Data] defines what is stored in the time series.
* The type for data points.
* [timestamp t] is [t]'s timestamp (if any). If it is [None], then the
reporter will add a new timestamp automatically.
* [v ?timestamp f] is the measure [f], as a the list metric name and value,
and the timestamp [timestamp]. If [timestamp] is not provided, it will be
set be the reporter. Raise [Invalid_argument] is a key or a value contains
an invalid character.
* [keys t] is [t]'s keys.
* [fields t] is [t]'s fields.
* [cons f t] is the new data having the same timestamp as [t] and the fields
[f :: fields t].
* The type for data points.
* [Tags] indexes metric sources, and allow to enable/disable data collection
at runtime.
* The type for tag values.
* The type tags: an heterogeneous list of names and types.
* [ty pp] is a new typed tag.
* The type for metric tags. Used to distinguish the various entities that are
being measured.
* [tags_enabled ()] is the list of tags that are enabled.
* [all_enabled ()] is true if all metric sources are enabled.
* [enable_tag t] enables all the registered metric sources having the tag [t].
* [disable_tag t] disables all the registered metric sources having the tag
[t].
* [enable_all ()] enables all registered metric sources.
* [disable_all ()] disables all registered metric sources.
* The type for metric sources. A source defines a named unit for a time
series. ['a] is the type of the function used to create new {{!data} data
points}. ['b] is the type for {!tags}.
* Metric sources.
* The type for metric sources.
* [list ()] is the current exisiting source list.
* [name src] is [src]'s name.
* [doc src] is [src]'s documentation string.
* [tags src] is the list of [src]'s tag names.
* [equal src src'] is [true] iff [src] and [src'] are the same source.
* [compare src src'] is a total order on sources.
* [duration t] is true iff [t] is a {!fn} source and [t] requires automatic
duration recording.
* [status t] is true iff [t] is a {!fn} source and [t] requires automatic
duration recording.
* [pp ppf src] prints an unspecified representation of [src] on [ppf].
* [is_active t] is true iff [t] is enabled.
* [enable src] enables the metric source [src].
* [disable src] disables the metric source [src].
* The type for graphs.
* [title t] is [t]'s title.
* [title t] is [t]'s Y label.
* [unit t] is [t]'s Y unit.
* [id t] is [t]'s unit.
* [v ()] is a new graph.
* [list ()] is the list of graphs.
* [fields t] is the list of [t]'s fields. Field names are unique for a given
source.
* [add_field t src f] adds the field [f], generated by the source [src], to
the graph [t].
* [remove_field t src f] removes the field named [f], generated from the
source [src], out of the graph [t].
* [is_active src] is true iff [src] monitoring is enabled.
* [add src t f] adds a new data point to [src] for the tags [t].
* [run src t f] runs [f ()] and add a new data points.
Depending on [src] configuration, new data points might have duration
information (e.g. how long [g ()] took, in nano-seconds) and status
information (e.g. to check if an exception has been raised).
* The type for extended results.
* Same as {!run} but also record if the result is [Ok] or [Error].
* The type for reporters.
* [nop_reporter] is the initial reporter returned by {!reporter}, it does
nothing if a metric gets reported.
* [reporter ()] is the current reporter.
* [set_reporter r] sets the current reporter to [r].
*/ |
* Copyright ( c ) 2018 < >
*
* Permission to use , copy , modify , and distribute this software for any
* purpose with or without fee is hereby granted , provided that the above
* copyright notice and this permission notice appear in all copies .
*
* THE SOFTWARE IS PROVIDED " AS IS " AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS . IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL , DIRECT , INDIRECT , OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE , DATA OR PROFITS , WHETHER IN AN
* ACTION OF CONTRACT , NEGLIGENCE OR OTHER TORTIOUS ACTION , ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE .
* Copyright (c) 2018 Thomas Gazagnaire <>
*
* Permission to use, copy, modify, and distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*)
* { 2 : fields Fields }
type graph
type field
type key = string
type 'a field_f =
?doc:string ->
?unit:string ->
?graph:graph ->
?graphs:graph list ->
key ->
'a ->
field
val string : string field_f
val int : int field_f
val uint : int field_f
val int32 : int32 field_f
val uint32 : int32 field_f
* [ uint32 ? doc k i ] is the field whose key is [ k ] and value is [ i ] .
val int64 : int64 field_f
* [ int64 ? doc k i ] is the field whose key is [ k ] and value is [ i ] .
val uint64 : int64 field_f
* [ uint64 ? doc k i ] is the field whose key is [ k ] and value is [ i ] .
val float : float field_f
val bool : bool field_f
val duration : int64 -> field
type status = [ `Ok | `Error ]
val status : status -> field
type 'a ty =
| String : string ty
| Bool : bool ty
| Float : float ty
| Int : int ty
| Int32 : int32 ty
| Int64 : int64 ty
| Uint : int ty
| Uint32 : int32 ty
| Uint64 : int64 ty
| Other : 'a Fmt.t -> 'a ty
val field :
?doc:string ->
?unit:string ->
?graph:graph ->
?graphs:graph list ->
string ->
'a ty ->
'a ->
field
* { 3 Reading Fields }
val key : field -> string
val doc : field -> string option
val unit : field -> string option
val graphs : field -> graph list option
val value : field -> value
val index : fields:string list -> field -> int
val index_key : fields:string list -> string -> int
* { 3 Pretty - printing }
val pp_key : field Fmt.t
val pp_value : field Fmt.t
* { 2 : data Data points }
module Data : sig
* { 2 Data }
[ Metric ] 's data points are a list of typed fields with an optional
timestamp . They are created with the { ! v } and { { ! fields } field }
constructors .
For instance , to create a data point with two values [ " % CPU " ] and [ " MEM " ] ,
respectively of type [ float ] and [ int ] :
{ [ let x = Data.v [ float " % CPU " 0.42 ; int " MEM " 27_000 ] ] }
[Metric]'s data points are a list of typed fields with an optional
timestamp. They are created with the {!v} and {{!fields} field}
constructors.
For instance, to create a data point with two values ["%CPU"] and ["MEM"],
respectively of type [float] and [int]:
{[ let x = Data.v [ float "%CPU" 0.42; int "MEM" 27_000 ] ]} *)
type t
type timestamp = string
* The type for timestamp . A timestamp shows the date and time , in RFC3339
UTC , associated with particular data .
UTC, associated with particular data. *)
val timestamp : t -> timestamp option
val v : ?timestamp:timestamp -> field list -> t
val keys : t -> key list
val fields : t -> field list
val cons : field -> t -> t
end
type data = Data.t
* { 2 : tags Tags }
module Tags : sig
* { 2 Tags }
[ Tags ] are heterogeneous { { ! t } lists } of key names and type of values ,
which are associated to data sources . Filters on key names allow to select
which data sources is { { ! enabling } enabled } at runtime . Disabled data
sources have a very low cost -- only allocating a closure .
For instance , to define the tags " PID " , " IP " and " host " , respectively of
type [ int ] , [ Ipaddr.t ] :
{ [
let ipaddr = Tags.v Ipaddr.pp_hum in
let t = Tags . [ int " PID " ; ipaddr " IP " ; string " host " ; ]
] }
[Tags] are heterogeneous {{!t} lists} of key names and type of values,
which are associated to data sources. Filters on key names allow to select
which data sources is {{!enabling} enabled} at runtime. Disabled data
sources have a very low cost -- only allocating a closure.
For instance, to define the tags "PID", "IP" and "host", respectively of
type [int], [Ipaddr.t]:
{[
let ipaddr = Tags.v Ipaddr.pp_hum in
let t = Tags.[ int "PID" ; ipaddr "IP" ; string "host"; ]
]} *)
type 'a v
type 'a t = [] : field list t | ( :: ) : 'a v * 'b t -> ('a -> 'b) t
* { 3 Tag Values }
val v : 'a Fmt.t -> string -> 'a v
val string : string -> string v
val float : string -> float v
val int : string -> int v
val uint : string -> int v
val int32 : string -> int32 v
val uint32 : string -> int32 v
val int64 : string -> int64 v
val uint64 : string -> int64 v
val bool : string -> bool v
end
type tags = field list
val tags_enabled : unit -> key list
val all_enabled : unit -> bool
val enable_tag : key -> unit
val disable_tag : key -> unit
val enable_all : unit -> unit
val disable_all : unit -> unit
* { 2 : srcs Sources }
type ('a, 'b) src
module Src : sig
* { 2 Sources }
val v :
?doc:string ->
?duration:bool ->
?status:bool ->
tags:'a Tags.t ->
data:'b ->
string ->
('a, 'b) src
* [ v ? doc name ] is a new source , accepting arbitrary data points .
[ name ] is the name of the source ; it does n't need to be unique but it is
good practice to prefix the name with the name of your package or library
( e.g. [ " mypkg.network " ] ) . [ doc ] is a documentation string describing the
source , defaults to [ " undocumented " ] . [ tags ] is the collection if ( typed )
tags which will be used to tag and index the measure and are used identify
the various metrics . The source will be enabled on creation iff one of tag
in [ tags ] has been enabled with { ! enable_tag } .
For instance , to create a metric to collect CPU and memory usage on
various machines , indexed by [ PID ] , [ host ] name and [ IP ] address :
{ [
let src =
let ipaddr = Tags.v Ipaddr.pp_hum in
let tags = Tags.[string " host " ; ipaddr " IP " ; int " PID " ; ] in
let data ( ) = Data.v [ float " % CPU " ( ... ) ; int " MEM " ( ... ) ; ] in
Src.v " top " ~tags ~data ~doc:"Information about processess "
] }
[name] is the name of the source; it doesn't need to be unique but it is
good practice to prefix the name with the name of your package or library
(e.g. ["mypkg.network"]). [doc] is a documentation string describing the
source, defaults to ["undocumented"]. [tags] is the collection if (typed)
tags which will be used to tag and index the measure and are used identify
the various metrics. The source will be enabled on creation iff one of tag
in [tags] has been enabled with {!enable_tag}.
For instance, to create a metric to collect CPU and memory usage on
various machines, indexed by [PID], [host] name and [IP] address:
{[
let src =
let ipaddr = Tags.v Ipaddr.pp_hum in
let tags = Tags.[string "host"; ipaddr "IP" ; int "PID" ; ] in
let data () = Data.v [float "%CPU" (...); int "MEM" (...); ] in
Src.v "top" ~tags ~data ~doc:"Information about processess"
]} *)
* { 3 Listing Sources }
val list : unit -> t list
val name : t -> string
val doc : t -> string
val tags : t -> string list
val data : t -> string list
* [ fields src ] is the list of [ src ] 's data field names . Note that these are
updated dynamically , so a monitoring function has to be called first .
updated dynamically, so a monitoring function has to be called first. *)
val equal : t -> t -> bool
val compare : t -> t -> int
val duration : t -> bool
val status : t -> bool
val pp : t Fmt.t
val is_active : t -> bool
val enable : t -> unit
val disable : t -> unit
end
* { 2 : graphs Metric Graphs }
module Graph : sig
type t = graph
val title : t -> string option
val ylabel : t -> string option
val yunit : t -> string option
val id : t -> int
val v : ?title:string -> ?ylabel:string -> ?yunit:string -> unit -> t
val list : unit -> t list
val fields : t -> (Src.t * field) list
val add_field : t -> Src.t -> field -> unit
val remove_field : t -> Src.t -> string -> unit
val enable : t -> unit
val disable : t -> unit
val is_active : t -> bool
end
module Key : sig
val duration : string
val status : string
val minor_words : string
val promoted_words : string
val major_words : string
val minor_collections : string
val major_collections : string
val heap_words : string
val heap_chunks : string
val compactions : string
val live_words : string
val live_blocks : string
val free_words : string
val free_blocks : string
val largest_free : string
val fragments : string
val top_heap_words : string
val stack_size : string
end
* { 2 : func Monitoring }
val is_active : ('a, 'b) src -> bool
val add : ('a, 'b) src -> ('a -> tags) -> ('b -> Data.t) -> unit
val run :
('a, ('b, exn) result -> Data.t) src -> ('a -> tags) -> (unit -> 'b) -> 'b
type ('a, 'b) rresult = ('a, [ `Exn of exn | `Error of 'b ]) result
val rrun :
('a, ('b, 'c) rresult -> Data.t) src ->
('a -> tags) ->
(unit -> ('b, 'c) result) ->
('b, 'c) result
* { 2 : reporter Reporters }
TODO : explain and give an example
TODO: explain and give an example *)
type reporter = {
now : unit -> int64;
at_exit : unit -> unit;
report :
'a.
tags:tags -> data:data -> over:(unit -> unit) -> Src.t -> (unit -> 'a) -> 'a;
}
val nop_reporter : reporter
val reporter : unit -> reporter
val set_reporter : reporter -> unit
module SM : Map.S with type key = Src.t
val cache_reporter : unit -> (unit -> (tags * data) SM.t) * reporter
* [ cache_reporter now ( ) ] is a reporter that stores the last measurement from
each source in a map ( which can be retrieved by the returned function ) . This
is an initial attempt to overcome the push vs pull interface . Each
measurement _ event _ is sent at an arbitrary point in time , while reporting
over a communication channel may be rate - limited ( i.e. report every 10
seconds statistics , rather than whenever they appear ) .
This is only a good idea for counters , histograms etc . may be useful for
other numbers ( such as time consumed between receive and send - the
measurement should provide the information whether it 's a counter or sth
else ) .
each source in a map (which can be retrieved by the returned function). This
is an initial attempt to overcome the push vs pull interface. Each
measurement _event_ is sent at an arbitrary point in time, while reporting
over a communication channel may be rate-limited (i.e. report every 10
seconds statistics, rather than whenever they appear).
This is only a good idea for counters, histograms etc. may be useful for
other numbers (such as time consumed between receive and send - the
measurement should provide the information whether it's a counter or sth
else). *)
* { 2 : runtime sources }
The { { : -ocaml/libref/Gc.html } Gc } module
of the OCaml system provides
{ { : -ocaml/libref/Gc.html#TYPEstat }
counters } of the memory management via
{ { : -ocaml/libref/Gc.html#VALquick_stat }
Gc.quick_stat } and
{ { : -ocaml/libref/Gc.html#VALstat }
Gc.stat } function . Both are provided here .
The {{:-ocaml/libref/Gc.html} Gc} module
of the OCaml system provides
{{:-ocaml/libref/Gc.html#TYPEstat}
counters} of the memory management via
{{:-ocaml/libref/Gc.html#VALquick_stat}
Gc.quick_stat} and
{{:-ocaml/libref/Gc.html#VALstat}
Gc.stat} function. Both are provided here. *)
val gc_stat : tags:'a Tags.t -> ('a, unit -> data) src
* [ gc_stat ~tags ] is the source of 's [ Gc.stat ( ) ] memory management
counters .
counters. *)
val gc_quick_stat : tags:'a Tags.t -> ('a, unit -> data) src
* [ gc_quick_stat ] is the source of 's [ Gc.quick_stat ( ) ] memory
management counters .
management counters. *)
val report :
('a, 'b) src ->
over:(unit -> unit) ->
k:(unit -> 'c) ->
('a -> tags) ->
('b -> (data -> 'c) -> 'd) ->
'd
val init : ('a, 'b) src -> data -> unit
val now : unit -> int64
|
b70f8bbf2e0e13e3092ed4be40d8fede8814fabc709106ca77393cd0cdcbd225 | geremih/xcljb | render_types.clj | This file is automatically generated . DO NOT MODIFY .
(clojure.core/ns
xcljb.gen.render-types
(:require [xcljb gen-common] [xcljb.gen xproto-types]))
(def GLYPH xcljb.gen.xproto-types/CARD32)
(def GLYPHSET (xcljb.gen-common/->Primitive :uint32))
(def PICTURE (xcljb.gen-common/->Primitive :uint32))
(def PICTFORMAT (xcljb.gen-common/->Primitive :uint32))
(def FIXED xcljb.gen.xproto-types/INT32)
(def
DIRECTFORMAT
(xcljb.gen-common/->Struct
[(xcljb.gen-common/->Field "red-shift" xcljb.gen.xproto-types/CARD16)
(xcljb.gen-common/->Field "red-mask" xcljb.gen.xproto-types/CARD16)
(xcljb.gen-common/->Field
"green-shift"
xcljb.gen.xproto-types/CARD16)
(xcljb.gen-common/->Field
"green-mask"
xcljb.gen.xproto-types/CARD16)
(xcljb.gen-common/->Field
"blue-shift"
xcljb.gen.xproto-types/CARD16)
(xcljb.gen-common/->Field "blue-mask" xcljb.gen.xproto-types/CARD16)
(xcljb.gen-common/->Field
"alpha-shift"
xcljb.gen.xproto-types/CARD16)
(xcljb.gen-common/->Field
"alpha-mask"
xcljb.gen.xproto-types/CARD16)]))
(def
PICTFORMINFO
(xcljb.gen-common/->Struct
[(xcljb.gen-common/->Field "id" xcljb.gen.render-types/PICTFORMAT)
(xcljb.gen-common/->Field "type" xcljb.gen.xproto-types/CARD8)
(xcljb.gen-common/->Field "depth" xcljb.gen.xproto-types/CARD8)
(xcljb.gen-common/->Pad 2)
(xcljb.gen-common/->Field
"direct"
xcljb.gen.render-types/DIRECTFORMAT)
(xcljb.gen-common/->Field
"colormap"
xcljb.gen.xproto-types/COLORMAP)]))
(def
PICTVISUAL
(xcljb.gen-common/->Struct
[(xcljb.gen-common/->Field "visual" xcljb.gen.xproto-types/VISUALID)
(xcljb.gen-common/->Field
"format"
xcljb.gen.render-types/PICTFORMAT)]))
(def
PICTDEPTH
(xcljb.gen-common/->Struct
[(xcljb.gen-common/->Field "depth" xcljb.gen.xproto-types/CARD8)
(xcljb.gen-common/->Pad 1)
(xcljb.gen-common/->Field
"num-visuals"
xcljb.gen.xproto-types/CARD16)
(xcljb.gen-common/->Pad 4)
(xcljb.gen-common/->List
"visuals"
xcljb.gen.render-types/PICTVISUAL
(xcljb.gen-common/->Fieldref "num-visuals"))]))
(def
PICTSCREEN
(xcljb.gen-common/->Struct
[(xcljb.gen-common/->Field
"num-depths"
xcljb.gen.xproto-types/CARD32)
(xcljb.gen-common/->Field
"fallback"
xcljb.gen.render-types/PICTFORMAT)
(xcljb.gen-common/->List
"depths"
xcljb.gen.render-types/PICTDEPTH
(xcljb.gen-common/->Fieldref "num-depths"))]))
(def
INDEXVALUE
(xcljb.gen-common/->Struct
[(xcljb.gen-common/->Field "pixel" xcljb.gen.xproto-types/CARD32)
(xcljb.gen-common/->Field "red" xcljb.gen.xproto-types/CARD16)
(xcljb.gen-common/->Field "green" xcljb.gen.xproto-types/CARD16)
(xcljb.gen-common/->Field "blue" xcljb.gen.xproto-types/CARD16)
(xcljb.gen-common/->Field "alpha" xcljb.gen.xproto-types/CARD16)]))
(def
COLOR
(xcljb.gen-common/->Struct
[(xcljb.gen-common/->Field "red" xcljb.gen.xproto-types/CARD16)
(xcljb.gen-common/->Field "green" xcljb.gen.xproto-types/CARD16)
(xcljb.gen-common/->Field "blue" xcljb.gen.xproto-types/CARD16)
(xcljb.gen-common/->Field "alpha" xcljb.gen.xproto-types/CARD16)]))
(def
POINTFIX
(xcljb.gen-common/->Struct
[(xcljb.gen-common/->Field "x" xcljb.gen.render-types/FIXED)
(xcljb.gen-common/->Field "y" xcljb.gen.render-types/FIXED)]))
(def
LINEFIX
(xcljb.gen-common/->Struct
[(xcljb.gen-common/->Field "p1" xcljb.gen.render-types/POINTFIX)
(xcljb.gen-common/->Field "p2" xcljb.gen.render-types/POINTFIX)]))
(def
TRIANGLE
(xcljb.gen-common/->Struct
[(xcljb.gen-common/->Field "p1" xcljb.gen.render-types/POINTFIX)
(xcljb.gen-common/->Field "p2" xcljb.gen.render-types/POINTFIX)
(xcljb.gen-common/->Field "p3" xcljb.gen.render-types/POINTFIX)]))
(def
TRAPEZOID
(xcljb.gen-common/->Struct
[(xcljb.gen-common/->Field "top" xcljb.gen.render-types/FIXED)
(xcljb.gen-common/->Field "bottom" xcljb.gen.render-types/FIXED)
(xcljb.gen-common/->Field "left" xcljb.gen.render-types/LINEFIX)
(xcljb.gen-common/->Field "right" xcljb.gen.render-types/LINEFIX)]))
(def
GLYPHINFO
(xcljb.gen-common/->Struct
[(xcljb.gen-common/->Field "width" xcljb.gen.xproto-types/CARD16)
(xcljb.gen-common/->Field "height" xcljb.gen.xproto-types/CARD16)
(xcljb.gen-common/->Field "x" xcljb.gen.xproto-types/INT16)
(xcljb.gen-common/->Field "y" xcljb.gen.xproto-types/INT16)
(xcljb.gen-common/->Field "x-off" xcljb.gen.xproto-types/INT16)
(xcljb.gen-common/->Field "y-off" xcljb.gen.xproto-types/INT16)]))
(def
TRANSFORM
(xcljb.gen-common/->Struct
[(xcljb.gen-common/->Field "matrix11" xcljb.gen.render-types/FIXED)
(xcljb.gen-common/->Field "matrix12" xcljb.gen.render-types/FIXED)
(xcljb.gen-common/->Field "matrix13" xcljb.gen.render-types/FIXED)
(xcljb.gen-common/->Field "matrix21" xcljb.gen.render-types/FIXED)
(xcljb.gen-common/->Field "matrix22" xcljb.gen.render-types/FIXED)
(xcljb.gen-common/->Field "matrix23" xcljb.gen.render-types/FIXED)
(xcljb.gen-common/->Field "matrix31" xcljb.gen.render-types/FIXED)
(xcljb.gen-common/->Field "matrix32" xcljb.gen.render-types/FIXED)
(xcljb.gen-common/->Field "matrix33" xcljb.gen.render-types/FIXED)]))
(def
ANIMCURSORELT
(xcljb.gen-common/->Struct
[(xcljb.gen-common/->Field "cursor" xcljb.gen.xproto-types/CURSOR)
(xcljb.gen-common/->Field "delay" xcljb.gen.xproto-types/CARD32)]))
(def
SPANFIX
(xcljb.gen-common/->Struct
[(xcljb.gen-common/->Field "l" xcljb.gen.render-types/FIXED)
(xcljb.gen-common/->Field "r" xcljb.gen.render-types/FIXED)
(xcljb.gen-common/->Field "y" xcljb.gen.render-types/FIXED)]))
(def
TRAP
(xcljb.gen-common/->Struct
[(xcljb.gen-common/->Field "top" xcljb.gen.render-types/SPANFIX)
(xcljb.gen-common/->Field "bot" xcljb.gen.render-types/SPANFIX)]))
(def
QueryVersionRequest
(xcljb.gen-common/->Request
"RENDER"
0
[(xcljb.gen-common/->Field
"client-major-version"
xcljb.gen.xproto-types/CARD32)
(xcljb.gen-common/->Field
"client-minor-version"
xcljb.gen.xproto-types/CARD32)]))
(def QueryPictFormatsRequest (xcljb.gen-common/->Request "RENDER" 1 []))
(def
QueryPictIndexValuesRequest
(xcljb.gen-common/->Request
"RENDER"
2
[(xcljb.gen-common/->Field
"format"
xcljb.gen.render-types/PICTFORMAT)]))
(def
CreatePictureRequest
(xcljb.gen-common/->Request
"RENDER"
4
[(xcljb.gen-common/->Field "pid" xcljb.gen.render-types/PICTURE)
(xcljb.gen-common/->Field
"drawable"
xcljb.gen.xproto-types/DRAWABLE)
(xcljb.gen-common/->Field
"format"
xcljb.gen.render-types/PICTFORMAT)
(xcljb.gen-common/->Valueparam
"value"
xcljb.gen.xproto-types/CARD32)]))
(def
ChangePictureRequest
(xcljb.gen-common/->Request
"RENDER"
5
[(xcljb.gen-common/->Field "picture" xcljb.gen.render-types/PICTURE)
(xcljb.gen-common/->Valueparam
"value"
xcljb.gen.xproto-types/CARD32)]))
(def
SetPictureClipRectanglesRequest
(xcljb.gen-common/->Request
"RENDER"
6
[(xcljb.gen-common/->Field "picture" xcljb.gen.render-types/PICTURE)
(xcljb.gen-common/->Field
"clip-x-origin"
xcljb.gen.xproto-types/INT16)
(xcljb.gen-common/->Field
"clip-y-origin"
xcljb.gen.xproto-types/INT16)
(xcljb.gen-common/->List
"rectangles"
xcljb.gen.xproto-types/RECTANGLE
nil)]))
(def
FreePictureRequest
(xcljb.gen-common/->Request
"RENDER"
7
[(xcljb.gen-common/->Field
"picture"
xcljb.gen.render-types/PICTURE)]))
(def
CompositeRequest
(xcljb.gen-common/->Request
"RENDER"
8
[(xcljb.gen-common/->Field "op" xcljb.gen.xproto-types/CARD8)
(xcljb.gen-common/->Pad 3)
(xcljb.gen-common/->Field "src" xcljb.gen.render-types/PICTURE)
(xcljb.gen-common/->Field "mask" xcljb.gen.render-types/PICTURE)
(xcljb.gen-common/->Field "dst" xcljb.gen.render-types/PICTURE)
(xcljb.gen-common/->Field "src-x" xcljb.gen.xproto-types/INT16)
(xcljb.gen-common/->Field "src-y" xcljb.gen.xproto-types/INT16)
(xcljb.gen-common/->Field "mask-x" xcljb.gen.xproto-types/INT16)
(xcljb.gen-common/->Field "mask-y" xcljb.gen.xproto-types/INT16)
(xcljb.gen-common/->Field "dst-x" xcljb.gen.xproto-types/INT16)
(xcljb.gen-common/->Field "dst-y" xcljb.gen.xproto-types/INT16)
(xcljb.gen-common/->Field "width" xcljb.gen.xproto-types/CARD16)
(xcljb.gen-common/->Field "height" xcljb.gen.xproto-types/CARD16)]))
(def
TrapezoidsRequest
(xcljb.gen-common/->Request
"RENDER"
10
[(xcljb.gen-common/->Field "op" xcljb.gen.xproto-types/CARD8)
(xcljb.gen-common/->Pad 3)
(xcljb.gen-common/->Field "src" xcljb.gen.render-types/PICTURE)
(xcljb.gen-common/->Field "dst" xcljb.gen.render-types/PICTURE)
(xcljb.gen-common/->Field
"mask-format"
xcljb.gen.render-types/PICTFORMAT)
(xcljb.gen-common/->Field "src-x" xcljb.gen.xproto-types/INT16)
(xcljb.gen-common/->Field "src-y" xcljb.gen.xproto-types/INT16)
(xcljb.gen-common/->List
"traps"
xcljb.gen.render-types/TRAPEZOID
nil)]))
(def
TrianglesRequest
(xcljb.gen-common/->Request
"RENDER"
11
[(xcljb.gen-common/->Field "op" xcljb.gen.xproto-types/CARD8)
(xcljb.gen-common/->Pad 3)
(xcljb.gen-common/->Field "src" xcljb.gen.render-types/PICTURE)
(xcljb.gen-common/->Field "dst" xcljb.gen.render-types/PICTURE)
(xcljb.gen-common/->Field
"mask-format"
xcljb.gen.render-types/PICTFORMAT)
(xcljb.gen-common/->Field "src-x" xcljb.gen.xproto-types/INT16)
(xcljb.gen-common/->Field "src-y" xcljb.gen.xproto-types/INT16)
(xcljb.gen-common/->List
"triangles"
xcljb.gen.render-types/TRIANGLE
nil)]))
(def
TriStripRequest
(xcljb.gen-common/->Request
"RENDER"
12
[(xcljb.gen-common/->Field "op" xcljb.gen.xproto-types/CARD8)
(xcljb.gen-common/->Pad 3)
(xcljb.gen-common/->Field "src" xcljb.gen.render-types/PICTURE)
(xcljb.gen-common/->Field "dst" xcljb.gen.render-types/PICTURE)
(xcljb.gen-common/->Field
"mask-format"
xcljb.gen.render-types/PICTFORMAT)
(xcljb.gen-common/->Field "src-x" xcljb.gen.xproto-types/INT16)
(xcljb.gen-common/->Field "src-y" xcljb.gen.xproto-types/INT16)
(xcljb.gen-common/->List
"points"
xcljb.gen.render-types/POINTFIX
nil)]))
(def
TriFanRequest
(xcljb.gen-common/->Request
"RENDER"
13
[(xcljb.gen-common/->Field "op" xcljb.gen.xproto-types/CARD8)
(xcljb.gen-common/->Pad 3)
(xcljb.gen-common/->Field "src" xcljb.gen.render-types/PICTURE)
(xcljb.gen-common/->Field "dst" xcljb.gen.render-types/PICTURE)
(xcljb.gen-common/->Field
"mask-format"
xcljb.gen.render-types/PICTFORMAT)
(xcljb.gen-common/->Field "src-x" xcljb.gen.xproto-types/INT16)
(xcljb.gen-common/->Field "src-y" xcljb.gen.xproto-types/INT16)
(xcljb.gen-common/->List
"points"
xcljb.gen.render-types/POINTFIX
nil)]))
(def
CreateGlyphSetRequest
(xcljb.gen-common/->Request
"RENDER"
17
[(xcljb.gen-common/->Field "gsid" xcljb.gen.render-types/GLYPHSET)
(xcljb.gen-common/->Field
"format"
xcljb.gen.render-types/PICTFORMAT)]))
(def
ReferenceGlyphSetRequest
(xcljb.gen-common/->Request
"RENDER"
18
[(xcljb.gen-common/->Field "gsid" xcljb.gen.render-types/GLYPHSET)
(xcljb.gen-common/->Field
"existing"
xcljb.gen.render-types/GLYPHSET)]))
(def
FreeGlyphSetRequest
(xcljb.gen-common/->Request
"RENDER"
19
[(xcljb.gen-common/->Field
"glyphset"
xcljb.gen.render-types/GLYPHSET)]))
(def
AddGlyphsRequest
(xcljb.gen-common/->Request
"RENDER"
20
[(xcljb.gen-common/->Field
"glyphset"
xcljb.gen.render-types/GLYPHSET)
(xcljb.gen-common/->Field
"glyphs-len"
xcljb.gen.xproto-types/CARD32)
(xcljb.gen-common/->List
"glyphids"
xcljb.gen.xproto-types/CARD32
(xcljb.gen-common/->Fieldref "glyphs-len"))
(xcljb.gen-common/->List
"glyphs"
xcljb.gen.render-types/GLYPHINFO
(xcljb.gen-common/->Fieldref "glyphs-len"))
(xcljb.gen-common/->List "data" xcljb.gen.xproto-types/BYTE nil)]))
(def
FreeGlyphsRequest
(xcljb.gen-common/->Request
"RENDER"
22
[(xcljb.gen-common/->Field
"glyphset"
xcljb.gen.render-types/GLYPHSET)
(xcljb.gen-common/->List
"glyphs"
xcljb.gen.render-types/GLYPH
nil)]))
(def
CompositeGlyphs8Request
(xcljb.gen-common/->Request
"RENDER"
23
[(xcljb.gen-common/->Field "op" xcljb.gen.xproto-types/CARD8)
(xcljb.gen-common/->Pad 3)
(xcljb.gen-common/->Field "src" xcljb.gen.render-types/PICTURE)
(xcljb.gen-common/->Field "dst" xcljb.gen.render-types/PICTURE)
(xcljb.gen-common/->Field
"mask-format"
xcljb.gen.render-types/PICTFORMAT)
(xcljb.gen-common/->Field
"glyphset"
xcljb.gen.render-types/GLYPHSET)
(xcljb.gen-common/->Field "src-x" xcljb.gen.xproto-types/INT16)
(xcljb.gen-common/->Field "src-y" xcljb.gen.xproto-types/INT16)
(xcljb.gen-common/->List
"glyphcmds"
xcljb.gen.xproto-types/BYTE
nil)]))
(def
CompositeGlyphs16Request
(xcljb.gen-common/->Request
"RENDER"
24
[(xcljb.gen-common/->Field "op" xcljb.gen.xproto-types/CARD8)
(xcljb.gen-common/->Pad 3)
(xcljb.gen-common/->Field "src" xcljb.gen.render-types/PICTURE)
(xcljb.gen-common/->Field "dst" xcljb.gen.render-types/PICTURE)
(xcljb.gen-common/->Field
"mask-format"
xcljb.gen.render-types/PICTFORMAT)
(xcljb.gen-common/->Field
"glyphset"
xcljb.gen.render-types/GLYPHSET)
(xcljb.gen-common/->Field "src-x" xcljb.gen.xproto-types/INT16)
(xcljb.gen-common/->Field "src-y" xcljb.gen.xproto-types/INT16)
(xcljb.gen-common/->List
"glyphcmds"
xcljb.gen.xproto-types/BYTE
nil)]))
(def
CompositeGlyphs32Request
(xcljb.gen-common/->Request
"RENDER"
25
[(xcljb.gen-common/->Field "op" xcljb.gen.xproto-types/CARD8)
(xcljb.gen-common/->Pad 3)
(xcljb.gen-common/->Field "src" xcljb.gen.render-types/PICTURE)
(xcljb.gen-common/->Field "dst" xcljb.gen.render-types/PICTURE)
(xcljb.gen-common/->Field
"mask-format"
xcljb.gen.render-types/PICTFORMAT)
(xcljb.gen-common/->Field
"glyphset"
xcljb.gen.render-types/GLYPHSET)
(xcljb.gen-common/->Field "src-x" xcljb.gen.xproto-types/INT16)
(xcljb.gen-common/->Field "src-y" xcljb.gen.xproto-types/INT16)
(xcljb.gen-common/->List
"glyphcmds"
xcljb.gen.xproto-types/BYTE
nil)]))
(def
FillRectanglesRequest
(xcljb.gen-common/->Request
"RENDER"
26
[(xcljb.gen-common/->Field "op" xcljb.gen.xproto-types/CARD8)
(xcljb.gen-common/->Pad 3)
(xcljb.gen-common/->Field "dst" xcljb.gen.render-types/PICTURE)
(xcljb.gen-common/->Field "color" xcljb.gen.render-types/COLOR)
(xcljb.gen-common/->List
"rects"
xcljb.gen.xproto-types/RECTANGLE
nil)]))
(def
CreateCursorRequest
(xcljb.gen-common/->Request
"RENDER"
27
[(xcljb.gen-common/->Field "cid" xcljb.gen.xproto-types/CURSOR)
(xcljb.gen-common/->Field "source" xcljb.gen.render-types/PICTURE)
(xcljb.gen-common/->Field "x" xcljb.gen.xproto-types/CARD16)
(xcljb.gen-common/->Field "y" xcljb.gen.xproto-types/CARD16)]))
(def
SetPictureTransformRequest
(xcljb.gen-common/->Request
"RENDER"
28
[(xcljb.gen-common/->Field "picture" xcljb.gen.render-types/PICTURE)
(xcljb.gen-common/->Field
"transform"
xcljb.gen.render-types/TRANSFORM)]))
(def
QueryFiltersRequest
(xcljb.gen-common/->Request
"RENDER"
29
[(xcljb.gen-common/->Field
"drawable"
xcljb.gen.xproto-types/DRAWABLE)]))
(def
SetPictureFilterRequest
(xcljb.gen-common/->Request
"RENDER"
30
[(xcljb.gen-common/->Field "picture" xcljb.gen.render-types/PICTURE)
(xcljb.gen-common/->Field
"filter-len"
xcljb.gen.xproto-types/CARD16)
(xcljb.gen-common/->Pad 2)
(xcljb.gen-common/->StringField
"filter"
(xcljb.gen-common/->Fieldref "filter-len"))
(xcljb.gen-common/->List
"values"
xcljb.gen.render-types/FIXED
nil)]))
(def
CreateAnimCursorRequest
(xcljb.gen-common/->Request
"RENDER"
31
[(xcljb.gen-common/->Field "cid" xcljb.gen.xproto-types/CURSOR)
(xcljb.gen-common/->List
"cursors"
xcljb.gen.render-types/ANIMCURSORELT
nil)]))
(def
AddTrapsRequest
(xcljb.gen-common/->Request
"RENDER"
32
[(xcljb.gen-common/->Field "picture" xcljb.gen.render-types/PICTURE)
(xcljb.gen-common/->Field "x-off" xcljb.gen.xproto-types/INT16)
(xcljb.gen-common/->Field "y-off" xcljb.gen.xproto-types/INT16)
(xcljb.gen-common/->List "traps" xcljb.gen.render-types/TRAP nil)]))
(def
CreateSolidFillRequest
(xcljb.gen-common/->Request
"RENDER"
33
[(xcljb.gen-common/->Field "picture" xcljb.gen.render-types/PICTURE)
(xcljb.gen-common/->Field "color" xcljb.gen.render-types/COLOR)]))
(def
CreateLinearGradientRequest
(xcljb.gen-common/->Request
"RENDER"
34
[(xcljb.gen-common/->Field "picture" xcljb.gen.render-types/PICTURE)
(xcljb.gen-common/->Field "p1" xcljb.gen.render-types/POINTFIX)
(xcljb.gen-common/->Field "p2" xcljb.gen.render-types/POINTFIX)
(xcljb.gen-common/->Field "num-stops" xcljb.gen.xproto-types/CARD32)
(xcljb.gen-common/->List
"stops"
xcljb.gen.render-types/FIXED
(xcljb.gen-common/->Fieldref "num-stops"))
(xcljb.gen-common/->List
"colors"
xcljb.gen.render-types/COLOR
(xcljb.gen-common/->Fieldref "num-stops"))]))
(def
CreateRadialGradientRequest
(xcljb.gen-common/->Request
"RENDER"
35
[(xcljb.gen-common/->Field "picture" xcljb.gen.render-types/PICTURE)
(xcljb.gen-common/->Field "inner" xcljb.gen.render-types/POINTFIX)
(xcljb.gen-common/->Field "outer" xcljb.gen.render-types/POINTFIX)
(xcljb.gen-common/->Field
"inner-radius"
xcljb.gen.render-types/FIXED)
(xcljb.gen-common/->Field
"outer-radius"
xcljb.gen.render-types/FIXED)
(xcljb.gen-common/->Field "num-stops" xcljb.gen.xproto-types/CARD32)
(xcljb.gen-common/->List
"stops"
xcljb.gen.render-types/FIXED
(xcljb.gen-common/->Fieldref "num-stops"))
(xcljb.gen-common/->List
"colors"
xcljb.gen.render-types/COLOR
(xcljb.gen-common/->Fieldref "num-stops"))]))
(def
CreateConicalGradientRequest
(xcljb.gen-common/->Request
"RENDER"
36
[(xcljb.gen-common/->Field "picture" xcljb.gen.render-types/PICTURE)
(xcljb.gen-common/->Field "center" xcljb.gen.render-types/POINTFIX)
(xcljb.gen-common/->Field "angle" xcljb.gen.render-types/FIXED)
(xcljb.gen-common/->Field "num-stops" xcljb.gen.xproto-types/CARD32)
(xcljb.gen-common/->List
"stops"
xcljb.gen.render-types/FIXED
(xcljb.gen-common/->Fieldref "num-stops"))
(xcljb.gen-common/->List
"colors"
xcljb.gen.render-types/COLOR
(xcljb.gen-common/->Fieldref "num-stops"))]))
(def
QueryVersionReply
(xcljb.gen-common/->Reply
[(xcljb.gen-common/->Pad 1)
(xcljb.gen-common/->Field
"major-version"
xcljb.gen.xproto-types/CARD32)
(xcljb.gen-common/->Field
"minor-version"
xcljb.gen.xproto-types/CARD32)
(xcljb.gen-common/->Pad 16)]))
(def
QueryPictFormatsReply
(xcljb.gen-common/->Reply
[(xcljb.gen-common/->Pad 1)
(xcljb.gen-common/->Field
"num-formats"
xcljb.gen.xproto-types/CARD32)
(xcljb.gen-common/->Field
"num-screens"
xcljb.gen.xproto-types/CARD32)
(xcljb.gen-common/->Field
"num-depths"
xcljb.gen.xproto-types/CARD32)
(xcljb.gen-common/->Field
"num-visuals"
xcljb.gen.xproto-types/CARD32)
(xcljb.gen-common/->Field
"num-subpixel"
xcljb.gen.xproto-types/CARD32)
(xcljb.gen-common/->Pad 4)
(xcljb.gen-common/->List
"formats"
xcljb.gen.render-types/PICTFORMINFO
(xcljb.gen-common/->Fieldref "num-formats"))
(xcljb.gen-common/->List
"screens"
xcljb.gen.render-types/PICTSCREEN
(xcljb.gen-common/->Fieldref "num-screens"))
(xcljb.gen-common/->List
"subpixels"
xcljb.gen.xproto-types/CARD32
(xcljb.gen-common/->Fieldref "num-subpixel"))]))
(def
QueryPictIndexValuesReply
(xcljb.gen-common/->Reply
[(xcljb.gen-common/->Pad 1)
(xcljb.gen-common/->Field
"num-values"
xcljb.gen.xproto-types/CARD32)
(xcljb.gen-common/->Pad 20)
(xcljb.gen-common/->List
"values"
xcljb.gen.render-types/INDEXVALUE
(xcljb.gen-common/->Fieldref "num-values"))]))
(def
QueryFiltersReply
(xcljb.gen-common/->Reply
[(xcljb.gen-common/->Pad 1)
(xcljb.gen-common/->Field
"num-aliases"
xcljb.gen.xproto-types/CARD32)
(xcljb.gen-common/->Field
"num-filters"
xcljb.gen.xproto-types/CARD32)
(xcljb.gen-common/->Pad 16)
(xcljb.gen-common/->List
"aliases"
xcljb.gen.xproto-types/CARD16
(xcljb.gen-common/->Fieldref "num-aliases"))
(xcljb.gen-common/->List
"filters"
xcljb.gen.xproto-types/STR
(xcljb.gen-common/->Fieldref "num-filters"))]))
(def
PictFormatError
(xcljb.gen-common/->Error' "RENDER" "PictFormat" 0 []))
(def PictureError (xcljb.gen-common/->Error' "RENDER" "Picture" 1 []))
(def PictOpError (xcljb.gen-common/->Error' "RENDER" "PictOp" 2 []))
(def GlyphSetError (xcljb.gen-common/->Error' "RENDER" "GlyphSet" 3 []))
(def GlyphError (xcljb.gen-common/->Error' "RENDER" "Glyph" 4 []))
;;; Manually written.
| null | https://raw.githubusercontent.com/geremih/xcljb/59e9ff795bf00595a3d46231a7bb4ec976852396/src/xcljb/gen/render_types.clj | clojure | Manually written. | This file is automatically generated . DO NOT MODIFY .
(clojure.core/ns
xcljb.gen.render-types
(:require [xcljb gen-common] [xcljb.gen xproto-types]))
(def GLYPH xcljb.gen.xproto-types/CARD32)
(def GLYPHSET (xcljb.gen-common/->Primitive :uint32))
(def PICTURE (xcljb.gen-common/->Primitive :uint32))
(def PICTFORMAT (xcljb.gen-common/->Primitive :uint32))
(def FIXED xcljb.gen.xproto-types/INT32)
(def
DIRECTFORMAT
(xcljb.gen-common/->Struct
[(xcljb.gen-common/->Field "red-shift" xcljb.gen.xproto-types/CARD16)
(xcljb.gen-common/->Field "red-mask" xcljb.gen.xproto-types/CARD16)
(xcljb.gen-common/->Field
"green-shift"
xcljb.gen.xproto-types/CARD16)
(xcljb.gen-common/->Field
"green-mask"
xcljb.gen.xproto-types/CARD16)
(xcljb.gen-common/->Field
"blue-shift"
xcljb.gen.xproto-types/CARD16)
(xcljb.gen-common/->Field "blue-mask" xcljb.gen.xproto-types/CARD16)
(xcljb.gen-common/->Field
"alpha-shift"
xcljb.gen.xproto-types/CARD16)
(xcljb.gen-common/->Field
"alpha-mask"
xcljb.gen.xproto-types/CARD16)]))
(def
PICTFORMINFO
(xcljb.gen-common/->Struct
[(xcljb.gen-common/->Field "id" xcljb.gen.render-types/PICTFORMAT)
(xcljb.gen-common/->Field "type" xcljb.gen.xproto-types/CARD8)
(xcljb.gen-common/->Field "depth" xcljb.gen.xproto-types/CARD8)
(xcljb.gen-common/->Pad 2)
(xcljb.gen-common/->Field
"direct"
xcljb.gen.render-types/DIRECTFORMAT)
(xcljb.gen-common/->Field
"colormap"
xcljb.gen.xproto-types/COLORMAP)]))
(def
PICTVISUAL
(xcljb.gen-common/->Struct
[(xcljb.gen-common/->Field "visual" xcljb.gen.xproto-types/VISUALID)
(xcljb.gen-common/->Field
"format"
xcljb.gen.render-types/PICTFORMAT)]))
(def
PICTDEPTH
(xcljb.gen-common/->Struct
[(xcljb.gen-common/->Field "depth" xcljb.gen.xproto-types/CARD8)
(xcljb.gen-common/->Pad 1)
(xcljb.gen-common/->Field
"num-visuals"
xcljb.gen.xproto-types/CARD16)
(xcljb.gen-common/->Pad 4)
(xcljb.gen-common/->List
"visuals"
xcljb.gen.render-types/PICTVISUAL
(xcljb.gen-common/->Fieldref "num-visuals"))]))
(def
PICTSCREEN
(xcljb.gen-common/->Struct
[(xcljb.gen-common/->Field
"num-depths"
xcljb.gen.xproto-types/CARD32)
(xcljb.gen-common/->Field
"fallback"
xcljb.gen.render-types/PICTFORMAT)
(xcljb.gen-common/->List
"depths"
xcljb.gen.render-types/PICTDEPTH
(xcljb.gen-common/->Fieldref "num-depths"))]))
(def
INDEXVALUE
(xcljb.gen-common/->Struct
[(xcljb.gen-common/->Field "pixel" xcljb.gen.xproto-types/CARD32)
(xcljb.gen-common/->Field "red" xcljb.gen.xproto-types/CARD16)
(xcljb.gen-common/->Field "green" xcljb.gen.xproto-types/CARD16)
(xcljb.gen-common/->Field "blue" xcljb.gen.xproto-types/CARD16)
(xcljb.gen-common/->Field "alpha" xcljb.gen.xproto-types/CARD16)]))
(def
COLOR
(xcljb.gen-common/->Struct
[(xcljb.gen-common/->Field "red" xcljb.gen.xproto-types/CARD16)
(xcljb.gen-common/->Field "green" xcljb.gen.xproto-types/CARD16)
(xcljb.gen-common/->Field "blue" xcljb.gen.xproto-types/CARD16)
(xcljb.gen-common/->Field "alpha" xcljb.gen.xproto-types/CARD16)]))
(def
POINTFIX
(xcljb.gen-common/->Struct
[(xcljb.gen-common/->Field "x" xcljb.gen.render-types/FIXED)
(xcljb.gen-common/->Field "y" xcljb.gen.render-types/FIXED)]))
(def
LINEFIX
(xcljb.gen-common/->Struct
[(xcljb.gen-common/->Field "p1" xcljb.gen.render-types/POINTFIX)
(xcljb.gen-common/->Field "p2" xcljb.gen.render-types/POINTFIX)]))
(def
TRIANGLE
(xcljb.gen-common/->Struct
[(xcljb.gen-common/->Field "p1" xcljb.gen.render-types/POINTFIX)
(xcljb.gen-common/->Field "p2" xcljb.gen.render-types/POINTFIX)
(xcljb.gen-common/->Field "p3" xcljb.gen.render-types/POINTFIX)]))
(def
TRAPEZOID
(xcljb.gen-common/->Struct
[(xcljb.gen-common/->Field "top" xcljb.gen.render-types/FIXED)
(xcljb.gen-common/->Field "bottom" xcljb.gen.render-types/FIXED)
(xcljb.gen-common/->Field "left" xcljb.gen.render-types/LINEFIX)
(xcljb.gen-common/->Field "right" xcljb.gen.render-types/LINEFIX)]))
(def
GLYPHINFO
(xcljb.gen-common/->Struct
[(xcljb.gen-common/->Field "width" xcljb.gen.xproto-types/CARD16)
(xcljb.gen-common/->Field "height" xcljb.gen.xproto-types/CARD16)
(xcljb.gen-common/->Field "x" xcljb.gen.xproto-types/INT16)
(xcljb.gen-common/->Field "y" xcljb.gen.xproto-types/INT16)
(xcljb.gen-common/->Field "x-off" xcljb.gen.xproto-types/INT16)
(xcljb.gen-common/->Field "y-off" xcljb.gen.xproto-types/INT16)]))
(def
TRANSFORM
(xcljb.gen-common/->Struct
[(xcljb.gen-common/->Field "matrix11" xcljb.gen.render-types/FIXED)
(xcljb.gen-common/->Field "matrix12" xcljb.gen.render-types/FIXED)
(xcljb.gen-common/->Field "matrix13" xcljb.gen.render-types/FIXED)
(xcljb.gen-common/->Field "matrix21" xcljb.gen.render-types/FIXED)
(xcljb.gen-common/->Field "matrix22" xcljb.gen.render-types/FIXED)
(xcljb.gen-common/->Field "matrix23" xcljb.gen.render-types/FIXED)
(xcljb.gen-common/->Field "matrix31" xcljb.gen.render-types/FIXED)
(xcljb.gen-common/->Field "matrix32" xcljb.gen.render-types/FIXED)
(xcljb.gen-common/->Field "matrix33" xcljb.gen.render-types/FIXED)]))
(def
ANIMCURSORELT
(xcljb.gen-common/->Struct
[(xcljb.gen-common/->Field "cursor" xcljb.gen.xproto-types/CURSOR)
(xcljb.gen-common/->Field "delay" xcljb.gen.xproto-types/CARD32)]))
(def
SPANFIX
(xcljb.gen-common/->Struct
[(xcljb.gen-common/->Field "l" xcljb.gen.render-types/FIXED)
(xcljb.gen-common/->Field "r" xcljb.gen.render-types/FIXED)
(xcljb.gen-common/->Field "y" xcljb.gen.render-types/FIXED)]))
(def
TRAP
(xcljb.gen-common/->Struct
[(xcljb.gen-common/->Field "top" xcljb.gen.render-types/SPANFIX)
(xcljb.gen-common/->Field "bot" xcljb.gen.render-types/SPANFIX)]))
(def
QueryVersionRequest
(xcljb.gen-common/->Request
"RENDER"
0
[(xcljb.gen-common/->Field
"client-major-version"
xcljb.gen.xproto-types/CARD32)
(xcljb.gen-common/->Field
"client-minor-version"
xcljb.gen.xproto-types/CARD32)]))
(def QueryPictFormatsRequest (xcljb.gen-common/->Request "RENDER" 1 []))
(def
QueryPictIndexValuesRequest
(xcljb.gen-common/->Request
"RENDER"
2
[(xcljb.gen-common/->Field
"format"
xcljb.gen.render-types/PICTFORMAT)]))
(def
CreatePictureRequest
(xcljb.gen-common/->Request
"RENDER"
4
[(xcljb.gen-common/->Field "pid" xcljb.gen.render-types/PICTURE)
(xcljb.gen-common/->Field
"drawable"
xcljb.gen.xproto-types/DRAWABLE)
(xcljb.gen-common/->Field
"format"
xcljb.gen.render-types/PICTFORMAT)
(xcljb.gen-common/->Valueparam
"value"
xcljb.gen.xproto-types/CARD32)]))
(def
ChangePictureRequest
(xcljb.gen-common/->Request
"RENDER"
5
[(xcljb.gen-common/->Field "picture" xcljb.gen.render-types/PICTURE)
(xcljb.gen-common/->Valueparam
"value"
xcljb.gen.xproto-types/CARD32)]))
(def
SetPictureClipRectanglesRequest
(xcljb.gen-common/->Request
"RENDER"
6
[(xcljb.gen-common/->Field "picture" xcljb.gen.render-types/PICTURE)
(xcljb.gen-common/->Field
"clip-x-origin"
xcljb.gen.xproto-types/INT16)
(xcljb.gen-common/->Field
"clip-y-origin"
xcljb.gen.xproto-types/INT16)
(xcljb.gen-common/->List
"rectangles"
xcljb.gen.xproto-types/RECTANGLE
nil)]))
(def
FreePictureRequest
(xcljb.gen-common/->Request
"RENDER"
7
[(xcljb.gen-common/->Field
"picture"
xcljb.gen.render-types/PICTURE)]))
(def
CompositeRequest
(xcljb.gen-common/->Request
"RENDER"
8
[(xcljb.gen-common/->Field "op" xcljb.gen.xproto-types/CARD8)
(xcljb.gen-common/->Pad 3)
(xcljb.gen-common/->Field "src" xcljb.gen.render-types/PICTURE)
(xcljb.gen-common/->Field "mask" xcljb.gen.render-types/PICTURE)
(xcljb.gen-common/->Field "dst" xcljb.gen.render-types/PICTURE)
(xcljb.gen-common/->Field "src-x" xcljb.gen.xproto-types/INT16)
(xcljb.gen-common/->Field "src-y" xcljb.gen.xproto-types/INT16)
(xcljb.gen-common/->Field "mask-x" xcljb.gen.xproto-types/INT16)
(xcljb.gen-common/->Field "mask-y" xcljb.gen.xproto-types/INT16)
(xcljb.gen-common/->Field "dst-x" xcljb.gen.xproto-types/INT16)
(xcljb.gen-common/->Field "dst-y" xcljb.gen.xproto-types/INT16)
(xcljb.gen-common/->Field "width" xcljb.gen.xproto-types/CARD16)
(xcljb.gen-common/->Field "height" xcljb.gen.xproto-types/CARD16)]))
(def
TrapezoidsRequest
(xcljb.gen-common/->Request
"RENDER"
10
[(xcljb.gen-common/->Field "op" xcljb.gen.xproto-types/CARD8)
(xcljb.gen-common/->Pad 3)
(xcljb.gen-common/->Field "src" xcljb.gen.render-types/PICTURE)
(xcljb.gen-common/->Field "dst" xcljb.gen.render-types/PICTURE)
(xcljb.gen-common/->Field
"mask-format"
xcljb.gen.render-types/PICTFORMAT)
(xcljb.gen-common/->Field "src-x" xcljb.gen.xproto-types/INT16)
(xcljb.gen-common/->Field "src-y" xcljb.gen.xproto-types/INT16)
(xcljb.gen-common/->List
"traps"
xcljb.gen.render-types/TRAPEZOID
nil)]))
(def
TrianglesRequest
(xcljb.gen-common/->Request
"RENDER"
11
[(xcljb.gen-common/->Field "op" xcljb.gen.xproto-types/CARD8)
(xcljb.gen-common/->Pad 3)
(xcljb.gen-common/->Field "src" xcljb.gen.render-types/PICTURE)
(xcljb.gen-common/->Field "dst" xcljb.gen.render-types/PICTURE)
(xcljb.gen-common/->Field
"mask-format"
xcljb.gen.render-types/PICTFORMAT)
(xcljb.gen-common/->Field "src-x" xcljb.gen.xproto-types/INT16)
(xcljb.gen-common/->Field "src-y" xcljb.gen.xproto-types/INT16)
(xcljb.gen-common/->List
"triangles"
xcljb.gen.render-types/TRIANGLE
nil)]))
(def
TriStripRequest
(xcljb.gen-common/->Request
"RENDER"
12
[(xcljb.gen-common/->Field "op" xcljb.gen.xproto-types/CARD8)
(xcljb.gen-common/->Pad 3)
(xcljb.gen-common/->Field "src" xcljb.gen.render-types/PICTURE)
(xcljb.gen-common/->Field "dst" xcljb.gen.render-types/PICTURE)
(xcljb.gen-common/->Field
"mask-format"
xcljb.gen.render-types/PICTFORMAT)
(xcljb.gen-common/->Field "src-x" xcljb.gen.xproto-types/INT16)
(xcljb.gen-common/->Field "src-y" xcljb.gen.xproto-types/INT16)
(xcljb.gen-common/->List
"points"
xcljb.gen.render-types/POINTFIX
nil)]))
(def
TriFanRequest
(xcljb.gen-common/->Request
"RENDER"
13
[(xcljb.gen-common/->Field "op" xcljb.gen.xproto-types/CARD8)
(xcljb.gen-common/->Pad 3)
(xcljb.gen-common/->Field "src" xcljb.gen.render-types/PICTURE)
(xcljb.gen-common/->Field "dst" xcljb.gen.render-types/PICTURE)
(xcljb.gen-common/->Field
"mask-format"
xcljb.gen.render-types/PICTFORMAT)
(xcljb.gen-common/->Field "src-x" xcljb.gen.xproto-types/INT16)
(xcljb.gen-common/->Field "src-y" xcljb.gen.xproto-types/INT16)
(xcljb.gen-common/->List
"points"
xcljb.gen.render-types/POINTFIX
nil)]))
(def
CreateGlyphSetRequest
(xcljb.gen-common/->Request
"RENDER"
17
[(xcljb.gen-common/->Field "gsid" xcljb.gen.render-types/GLYPHSET)
(xcljb.gen-common/->Field
"format"
xcljb.gen.render-types/PICTFORMAT)]))
(def
ReferenceGlyphSetRequest
(xcljb.gen-common/->Request
"RENDER"
18
[(xcljb.gen-common/->Field "gsid" xcljb.gen.render-types/GLYPHSET)
(xcljb.gen-common/->Field
"existing"
xcljb.gen.render-types/GLYPHSET)]))
(def
FreeGlyphSetRequest
(xcljb.gen-common/->Request
"RENDER"
19
[(xcljb.gen-common/->Field
"glyphset"
xcljb.gen.render-types/GLYPHSET)]))
(def
AddGlyphsRequest
(xcljb.gen-common/->Request
"RENDER"
20
[(xcljb.gen-common/->Field
"glyphset"
xcljb.gen.render-types/GLYPHSET)
(xcljb.gen-common/->Field
"glyphs-len"
xcljb.gen.xproto-types/CARD32)
(xcljb.gen-common/->List
"glyphids"
xcljb.gen.xproto-types/CARD32
(xcljb.gen-common/->Fieldref "glyphs-len"))
(xcljb.gen-common/->List
"glyphs"
xcljb.gen.render-types/GLYPHINFO
(xcljb.gen-common/->Fieldref "glyphs-len"))
(xcljb.gen-common/->List "data" xcljb.gen.xproto-types/BYTE nil)]))
(def
FreeGlyphsRequest
(xcljb.gen-common/->Request
"RENDER"
22
[(xcljb.gen-common/->Field
"glyphset"
xcljb.gen.render-types/GLYPHSET)
(xcljb.gen-common/->List
"glyphs"
xcljb.gen.render-types/GLYPH
nil)]))
(def
CompositeGlyphs8Request
(xcljb.gen-common/->Request
"RENDER"
23
[(xcljb.gen-common/->Field "op" xcljb.gen.xproto-types/CARD8)
(xcljb.gen-common/->Pad 3)
(xcljb.gen-common/->Field "src" xcljb.gen.render-types/PICTURE)
(xcljb.gen-common/->Field "dst" xcljb.gen.render-types/PICTURE)
(xcljb.gen-common/->Field
"mask-format"
xcljb.gen.render-types/PICTFORMAT)
(xcljb.gen-common/->Field
"glyphset"
xcljb.gen.render-types/GLYPHSET)
(xcljb.gen-common/->Field "src-x" xcljb.gen.xproto-types/INT16)
(xcljb.gen-common/->Field "src-y" xcljb.gen.xproto-types/INT16)
(xcljb.gen-common/->List
"glyphcmds"
xcljb.gen.xproto-types/BYTE
nil)]))
(def
CompositeGlyphs16Request
(xcljb.gen-common/->Request
"RENDER"
24
[(xcljb.gen-common/->Field "op" xcljb.gen.xproto-types/CARD8)
(xcljb.gen-common/->Pad 3)
(xcljb.gen-common/->Field "src" xcljb.gen.render-types/PICTURE)
(xcljb.gen-common/->Field "dst" xcljb.gen.render-types/PICTURE)
(xcljb.gen-common/->Field
"mask-format"
xcljb.gen.render-types/PICTFORMAT)
(xcljb.gen-common/->Field
"glyphset"
xcljb.gen.render-types/GLYPHSET)
(xcljb.gen-common/->Field "src-x" xcljb.gen.xproto-types/INT16)
(xcljb.gen-common/->Field "src-y" xcljb.gen.xproto-types/INT16)
(xcljb.gen-common/->List
"glyphcmds"
xcljb.gen.xproto-types/BYTE
nil)]))
(def
CompositeGlyphs32Request
(xcljb.gen-common/->Request
"RENDER"
25
[(xcljb.gen-common/->Field "op" xcljb.gen.xproto-types/CARD8)
(xcljb.gen-common/->Pad 3)
(xcljb.gen-common/->Field "src" xcljb.gen.render-types/PICTURE)
(xcljb.gen-common/->Field "dst" xcljb.gen.render-types/PICTURE)
(xcljb.gen-common/->Field
"mask-format"
xcljb.gen.render-types/PICTFORMAT)
(xcljb.gen-common/->Field
"glyphset"
xcljb.gen.render-types/GLYPHSET)
(xcljb.gen-common/->Field "src-x" xcljb.gen.xproto-types/INT16)
(xcljb.gen-common/->Field "src-y" xcljb.gen.xproto-types/INT16)
(xcljb.gen-common/->List
"glyphcmds"
xcljb.gen.xproto-types/BYTE
nil)]))
(def
FillRectanglesRequest
(xcljb.gen-common/->Request
"RENDER"
26
[(xcljb.gen-common/->Field "op" xcljb.gen.xproto-types/CARD8)
(xcljb.gen-common/->Pad 3)
(xcljb.gen-common/->Field "dst" xcljb.gen.render-types/PICTURE)
(xcljb.gen-common/->Field "color" xcljb.gen.render-types/COLOR)
(xcljb.gen-common/->List
"rects"
xcljb.gen.xproto-types/RECTANGLE
nil)]))
(def
CreateCursorRequest
(xcljb.gen-common/->Request
"RENDER"
27
[(xcljb.gen-common/->Field "cid" xcljb.gen.xproto-types/CURSOR)
(xcljb.gen-common/->Field "source" xcljb.gen.render-types/PICTURE)
(xcljb.gen-common/->Field "x" xcljb.gen.xproto-types/CARD16)
(xcljb.gen-common/->Field "y" xcljb.gen.xproto-types/CARD16)]))
(def
SetPictureTransformRequest
(xcljb.gen-common/->Request
"RENDER"
28
[(xcljb.gen-common/->Field "picture" xcljb.gen.render-types/PICTURE)
(xcljb.gen-common/->Field
"transform"
xcljb.gen.render-types/TRANSFORM)]))
(def
QueryFiltersRequest
(xcljb.gen-common/->Request
"RENDER"
29
[(xcljb.gen-common/->Field
"drawable"
xcljb.gen.xproto-types/DRAWABLE)]))
(def
SetPictureFilterRequest
(xcljb.gen-common/->Request
"RENDER"
30
[(xcljb.gen-common/->Field "picture" xcljb.gen.render-types/PICTURE)
(xcljb.gen-common/->Field
"filter-len"
xcljb.gen.xproto-types/CARD16)
(xcljb.gen-common/->Pad 2)
(xcljb.gen-common/->StringField
"filter"
(xcljb.gen-common/->Fieldref "filter-len"))
(xcljb.gen-common/->List
"values"
xcljb.gen.render-types/FIXED
nil)]))
(def
CreateAnimCursorRequest
(xcljb.gen-common/->Request
"RENDER"
31
[(xcljb.gen-common/->Field "cid" xcljb.gen.xproto-types/CURSOR)
(xcljb.gen-common/->List
"cursors"
xcljb.gen.render-types/ANIMCURSORELT
nil)]))
(def
AddTrapsRequest
(xcljb.gen-common/->Request
"RENDER"
32
[(xcljb.gen-common/->Field "picture" xcljb.gen.render-types/PICTURE)
(xcljb.gen-common/->Field "x-off" xcljb.gen.xproto-types/INT16)
(xcljb.gen-common/->Field "y-off" xcljb.gen.xproto-types/INT16)
(xcljb.gen-common/->List "traps" xcljb.gen.render-types/TRAP nil)]))
(def
CreateSolidFillRequest
(xcljb.gen-common/->Request
"RENDER"
33
[(xcljb.gen-common/->Field "picture" xcljb.gen.render-types/PICTURE)
(xcljb.gen-common/->Field "color" xcljb.gen.render-types/COLOR)]))
(def
CreateLinearGradientRequest
(xcljb.gen-common/->Request
"RENDER"
34
[(xcljb.gen-common/->Field "picture" xcljb.gen.render-types/PICTURE)
(xcljb.gen-common/->Field "p1" xcljb.gen.render-types/POINTFIX)
(xcljb.gen-common/->Field "p2" xcljb.gen.render-types/POINTFIX)
(xcljb.gen-common/->Field "num-stops" xcljb.gen.xproto-types/CARD32)
(xcljb.gen-common/->List
"stops"
xcljb.gen.render-types/FIXED
(xcljb.gen-common/->Fieldref "num-stops"))
(xcljb.gen-common/->List
"colors"
xcljb.gen.render-types/COLOR
(xcljb.gen-common/->Fieldref "num-stops"))]))
(def
CreateRadialGradientRequest
(xcljb.gen-common/->Request
"RENDER"
35
[(xcljb.gen-common/->Field "picture" xcljb.gen.render-types/PICTURE)
(xcljb.gen-common/->Field "inner" xcljb.gen.render-types/POINTFIX)
(xcljb.gen-common/->Field "outer" xcljb.gen.render-types/POINTFIX)
(xcljb.gen-common/->Field
"inner-radius"
xcljb.gen.render-types/FIXED)
(xcljb.gen-common/->Field
"outer-radius"
xcljb.gen.render-types/FIXED)
(xcljb.gen-common/->Field "num-stops" xcljb.gen.xproto-types/CARD32)
(xcljb.gen-common/->List
"stops"
xcljb.gen.render-types/FIXED
(xcljb.gen-common/->Fieldref "num-stops"))
(xcljb.gen-common/->List
"colors"
xcljb.gen.render-types/COLOR
(xcljb.gen-common/->Fieldref "num-stops"))]))
(def
CreateConicalGradientRequest
(xcljb.gen-common/->Request
"RENDER"
36
[(xcljb.gen-common/->Field "picture" xcljb.gen.render-types/PICTURE)
(xcljb.gen-common/->Field "center" xcljb.gen.render-types/POINTFIX)
(xcljb.gen-common/->Field "angle" xcljb.gen.render-types/FIXED)
(xcljb.gen-common/->Field "num-stops" xcljb.gen.xproto-types/CARD32)
(xcljb.gen-common/->List
"stops"
xcljb.gen.render-types/FIXED
(xcljb.gen-common/->Fieldref "num-stops"))
(xcljb.gen-common/->List
"colors"
xcljb.gen.render-types/COLOR
(xcljb.gen-common/->Fieldref "num-stops"))]))
(def
QueryVersionReply
(xcljb.gen-common/->Reply
[(xcljb.gen-common/->Pad 1)
(xcljb.gen-common/->Field
"major-version"
xcljb.gen.xproto-types/CARD32)
(xcljb.gen-common/->Field
"minor-version"
xcljb.gen.xproto-types/CARD32)
(xcljb.gen-common/->Pad 16)]))
(def
QueryPictFormatsReply
(xcljb.gen-common/->Reply
[(xcljb.gen-common/->Pad 1)
(xcljb.gen-common/->Field
"num-formats"
xcljb.gen.xproto-types/CARD32)
(xcljb.gen-common/->Field
"num-screens"
xcljb.gen.xproto-types/CARD32)
(xcljb.gen-common/->Field
"num-depths"
xcljb.gen.xproto-types/CARD32)
(xcljb.gen-common/->Field
"num-visuals"
xcljb.gen.xproto-types/CARD32)
(xcljb.gen-common/->Field
"num-subpixel"
xcljb.gen.xproto-types/CARD32)
(xcljb.gen-common/->Pad 4)
(xcljb.gen-common/->List
"formats"
xcljb.gen.render-types/PICTFORMINFO
(xcljb.gen-common/->Fieldref "num-formats"))
(xcljb.gen-common/->List
"screens"
xcljb.gen.render-types/PICTSCREEN
(xcljb.gen-common/->Fieldref "num-screens"))
(xcljb.gen-common/->List
"subpixels"
xcljb.gen.xproto-types/CARD32
(xcljb.gen-common/->Fieldref "num-subpixel"))]))
(def
QueryPictIndexValuesReply
(xcljb.gen-common/->Reply
[(xcljb.gen-common/->Pad 1)
(xcljb.gen-common/->Field
"num-values"
xcljb.gen.xproto-types/CARD32)
(xcljb.gen-common/->Pad 20)
(xcljb.gen-common/->List
"values"
xcljb.gen.render-types/INDEXVALUE
(xcljb.gen-common/->Fieldref "num-values"))]))
(def
QueryFiltersReply
(xcljb.gen-common/->Reply
[(xcljb.gen-common/->Pad 1)
(xcljb.gen-common/->Field
"num-aliases"
xcljb.gen.xproto-types/CARD32)
(xcljb.gen-common/->Field
"num-filters"
xcljb.gen.xproto-types/CARD32)
(xcljb.gen-common/->Pad 16)
(xcljb.gen-common/->List
"aliases"
xcljb.gen.xproto-types/CARD16
(xcljb.gen-common/->Fieldref "num-aliases"))
(xcljb.gen-common/->List
"filters"
xcljb.gen.xproto-types/STR
(xcljb.gen-common/->Fieldref "num-filters"))]))
(def
PictFormatError
(xcljb.gen-common/->Error' "RENDER" "PictFormat" 0 []))
(def PictureError (xcljb.gen-common/->Error' "RENDER" "Picture" 1 []))
(def PictOpError (xcljb.gen-common/->Error' "RENDER" "PictOp" 2 []))
(def GlyphSetError (xcljb.gen-common/->Error' "RENDER" "GlyphSet" 3 []))
(def GlyphError (xcljb.gen-common/->Error' "RENDER" "Glyph" 4 []))
|
a196ab825ee5f4f49f18d0b373a4af8b167fd5230db272c7150799cd3aec63b8 | morazanm/fsm | stateTransition.rkt | #lang racket
(require "../../fsm-gui/components/stateTransitions.rkt"
"../../fsm-gui/globals.rkt"
"../../fsm-core/private/constants.rkt"
"../test-helpers.rkt")
(module+ test
(require rackunit)
(define getCurrentRule
(test-suite "Tests getCurRule Function"
(test-case "PDA"
(set-machine-type 'pda)
(check-equal? (getCurRule '((F (a a a b b b) ()) (S (a a a b b b) ()))) '((S ε ε) (F ε)))
(check-equal? (getCurRule '((F (a b b b) (c c)) (F (a a b b b) (c)))) '((F a ε) (F (c))))
(check-equal? (getCurRule '((F (b) (c)) (F (b b) (c c)))) '((F b (c)) (F ε)))
(check-equal? (getCurRule '((F () ()) (F (b) (c)))) '((F b (c)) (F ε)))
(check-equal? (getCurRule '((F () ()))) '((empty empty empty) (empty empty)))
(check-equal? (getCurRule '((M (a a b c b a a) ()) (S (a a b c b a a) ()))) '((S ε ε) (M ε)))
(check-equal? (getCurRule '((M (b c b a a) (a a)) (M (a b c b a a) (a)))) '((M a ε) (M (a))))
(check-equal? (getCurRule '((M (c b a a) (b a a)) (M (b c b a a) (a a)))) '((M b ε) (M (b)))))
(test-case "MTTM"
(set-machine-type 'mttm)
(check-equal? (getCurRule '((Q (1 (_ a a b b c c d d)) (1 (_ _)) (1 (_ _)) (1 (_ _)))
(S (0 (_ a a b b c c d d)) (0 (_)) (0 (_)) (0 (_)))))
`((S (,BLANK ,BLANK ,BLANK ,BLANK)) (Q (R R R R)))
"Move Right on tape")
;; Mopve Left
(check-equal? (getCurRule '((E (8 (_ a a b b c c d d _)) (2 (_ b b _)) (2 (_ c c _)) (2 (_ d d _)))
(D (9 (_ a a b b c c d d _)) (3 (_ b b _)) (3 (_ c c _)) (3 (_ d d _)))))
`((D (,BLANK ,BLANK ,BLANK ,BLANK)) (E (L L L L)))
"Move Left on tape")
;; Write a
(check-equal? (getCurRule '((A (1 (_ a a b b c c d d)) (1 (_ _)) (1 (_ _)) (1 (_ _)))
(Q (1 (_ a a b b c c d d)) (1 (_ _)) (1 (_ _)) (1 (_ _)))))
`((Q (a ,BLANK ,BLANK ,BLANK)) (A (a ,BLANK ,BLANK ,BLANK)))
"Write a on tape")
Buggy transition 1
(check-equal? (getCurRule `((E (2 (@ _ a a b b c c d d _)) (1 (_ b b _)) (1 (_ c c _)) (1 (_ d d _)))
(E (3 (@ _ a a b b c c d d _)) (2 (_ b b _)) (2 (_ c c _)) (2 (_ d d _)))))
`((E (a b c d)) (E (L L L L)))
"Was buggy trans 1"))))
(test-all 'verbose
(getCurrentRule))
);; end submodule | null | https://raw.githubusercontent.com/morazanm/fsm/9cbb0928b38c3c9cd94858eed64d3f3d688a4048/fsm-test/fsm-gui/stateTransition.rkt | racket | Mopve Left
Write a
end submodule | #lang racket
(require "../../fsm-gui/components/stateTransitions.rkt"
"../../fsm-gui/globals.rkt"
"../../fsm-core/private/constants.rkt"
"../test-helpers.rkt")
(module+ test
(require rackunit)
(define getCurrentRule
(test-suite "Tests getCurRule Function"
(test-case "PDA"
(set-machine-type 'pda)
(check-equal? (getCurRule '((F (a a a b b b) ()) (S (a a a b b b) ()))) '((S ε ε) (F ε)))
(check-equal? (getCurRule '((F (a b b b) (c c)) (F (a a b b b) (c)))) '((F a ε) (F (c))))
(check-equal? (getCurRule '((F (b) (c)) (F (b b) (c c)))) '((F b (c)) (F ε)))
(check-equal? (getCurRule '((F () ()) (F (b) (c)))) '((F b (c)) (F ε)))
(check-equal? (getCurRule '((F () ()))) '((empty empty empty) (empty empty)))
(check-equal? (getCurRule '((M (a a b c b a a) ()) (S (a a b c b a a) ()))) '((S ε ε) (M ε)))
(check-equal? (getCurRule '((M (b c b a a) (a a)) (M (a b c b a a) (a)))) '((M a ε) (M (a))))
(check-equal? (getCurRule '((M (c b a a) (b a a)) (M (b c b a a) (a a)))) '((M b ε) (M (b)))))
(test-case "MTTM"
(set-machine-type 'mttm)
(check-equal? (getCurRule '((Q (1 (_ a a b b c c d d)) (1 (_ _)) (1 (_ _)) (1 (_ _)))
(S (0 (_ a a b b c c d d)) (0 (_)) (0 (_)) (0 (_)))))
`((S (,BLANK ,BLANK ,BLANK ,BLANK)) (Q (R R R R)))
"Move Right on tape")
(check-equal? (getCurRule '((E (8 (_ a a b b c c d d _)) (2 (_ b b _)) (2 (_ c c _)) (2 (_ d d _)))
(D (9 (_ a a b b c c d d _)) (3 (_ b b _)) (3 (_ c c _)) (3 (_ d d _)))))
`((D (,BLANK ,BLANK ,BLANK ,BLANK)) (E (L L L L)))
"Move Left on tape")
(check-equal? (getCurRule '((A (1 (_ a a b b c c d d)) (1 (_ _)) (1 (_ _)) (1 (_ _)))
(Q (1 (_ a a b b c c d d)) (1 (_ _)) (1 (_ _)) (1 (_ _)))))
`((Q (a ,BLANK ,BLANK ,BLANK)) (A (a ,BLANK ,BLANK ,BLANK)))
"Write a on tape")
Buggy transition 1
(check-equal? (getCurRule `((E (2 (@ _ a a b b c c d d _)) (1 (_ b b _)) (1 (_ c c _)) (1 (_ d d _)))
(E (3 (@ _ a a b b c c d d _)) (2 (_ b b _)) (2 (_ c c _)) (2 (_ d d _)))))
`((E (a b c d)) (E (L L L L)))
"Was buggy trans 1"))))
(test-all 'verbose
(getCurrentRule))
|
f2fae5b0a0de6f8a4eaef4c060e7bc197340a1fca69a48bfa37b463ca6ec81a5 | layerware/hugsql | unbound_fn.clj | (ns hugsql.unbound-fn
(:require [clojure.test :as t]
[hugsql.core :as hugsql]))
(hugsql/def-sqlvec-fns "hugsql/sql/test.sql")
(t/deftest unbound-fn
(let [es (java.util.concurrent.Executors/newFixedThreadPool 20)]
(try
(dotimes [i 1000]
(doseq [[s v] (ns-publics 'hugsql.expr-run)]
(ns-unmap 'hugsql.expr-run s))
(->> (.invokeAll es (for [j (range 10)]
(fn [] (clj-expr-generic-update-sqlvec {:table "test"
:updates {:name "X"}
:id i}))))
(mapv deref)))
(catch Exception e
(throw e))
(finally (.shutdown es)))))
| null | https://raw.githubusercontent.com/layerware/hugsql/052c04a2a6dc99c3c35810ddf83416c2fd93c5e5/hugsql-core/test/hugsql/unbound_fn.clj | clojure | (ns hugsql.unbound-fn
(:require [clojure.test :as t]
[hugsql.core :as hugsql]))
(hugsql/def-sqlvec-fns "hugsql/sql/test.sql")
(t/deftest unbound-fn
(let [es (java.util.concurrent.Executors/newFixedThreadPool 20)]
(try
(dotimes [i 1000]
(doseq [[s v] (ns-publics 'hugsql.expr-run)]
(ns-unmap 'hugsql.expr-run s))
(->> (.invokeAll es (for [j (range 10)]
(fn [] (clj-expr-generic-update-sqlvec {:table "test"
:updates {:name "X"}
:id i}))))
(mapv deref)))
(catch Exception e
(throw e))
(finally (.shutdown es)))))
| |
123a569343d63f5b04293a455c1b8b74200d8d7f84a0a2ed61b72c17f3dcf924 | Opetushallitus/ataru | form_role.clj | (ns ataru.hakija.form-role
(:require [schema.core :as s]))
(s/defschema FormRole (s/enum :hakija :virkailija :with-henkilo))
(s/defn ^:always-validate virkailija? :- s/Bool
[roles :- [FormRole]]
(boolean (some #(= :virkailija %) roles)))
(s/defn ^:always-validate with-henkilo? :- s/Bool
[roles :- [FormRole]]
(boolean (some #(= :with-henkilo %) roles)))
| null | https://raw.githubusercontent.com/Opetushallitus/ataru/2d8ef1d3f972621e301a3818567d4e11219d2e82/src/clj/ataru/hakija/form_role.clj | clojure | (ns ataru.hakija.form-role
(:require [schema.core :as s]))
(s/defschema FormRole (s/enum :hakija :virkailija :with-henkilo))
(s/defn ^:always-validate virkailija? :- s/Bool
[roles :- [FormRole]]
(boolean (some #(= :virkailija %) roles)))
(s/defn ^:always-validate with-henkilo? :- s/Bool
[roles :- [FormRole]]
(boolean (some #(= :with-henkilo %) roles)))
| |
b865114116702bf1ed769004abff9757a9a8052422d4bdd90a5dabbbd21fdfb3 | xldenis/ill | Builtins.hs | {-# LANGUAGE OverloadedStrings #-}
module Thrill.Syntax.Builtins where
import Thrill.Syntax.Type
import Thrill.Syntax.Kind
import Thrill.Syntax.Name
import Thrill.Prelude
import Data.String (IsString)
builtinTypes :: [(QualifiedName, Kind)]
builtinTypes =
[ (Qualified "Prelude" "Int", Star)
, (Qualified "Prelude" "String", Star)
, (Qualified "Prelude" "Char", Star)
]
builtins :: [(QualifiedName, Type QualifiedName)]
builtins = primitives ++ map (\(nm, ty) -> (Qualified "Prelude" nm, ty))
[ ("==", generalize $ constrain [(prelude "Eq", tVarA)] $ tVarA `tFn` tVarA `tFn` tBool)
, ("<=", generalize $ constrain [(prelude "Ord", tVarA)] $ tVarA `tFn` tVarA `tFn` tBool)
, (">=", generalize $ constrain [(prelude "Ord", tVarA)] $ tVarA `tFn` tVarA `tFn` tBool)
, ("<", generalize $ constrain [(prelude "Ord", tVarA)] $ tVarA `tFn` tVarA `tFn` tBool)
, (">", generalize $ constrain [(prelude "Ord", tVarA)] $ tVarA `tFn` tVarA `tFn` tBool)
, ("+", generalize $ constrain [(prelude "Semigroup", tVarA)] $ tVarA `tFn` tVarA `tFn` tVarA)
, ("-", generalize $ constrain [(prelude "Group", tVarA)] $ tVarA `tFn` tVarA `tFn` tVarA)
, ("*", generalize $ constrain [(prelude "MultSemigroup", tVarA)] $ tVarA `tFn` tVarA `tFn` tVarA)
, ("/", generalize $ constrain [(prelude "MultGroup", tVarA)] $ tVarA `tFn` tVarA `tFn` tVarA)
, ("&&", generalize $ tBool `tFn` tBool `tFn` tBool)
, ("||", generalize $ tBool `tFn` tBool `tFn` tBool)
, ("failedPattern", generalize $ tVarA)
]
where
prelude nm = Qualified "Prelude" nm
tVarA = TVar $ Internal "a"
primitives :: [(QualifiedName, Type QualifiedName)]
primitives = map (\(nm, ty) -> (Qualified "Prelude" nm, ty))
[ ("plusInt", tInteger `tFn` tInteger `tFn` tInteger)
, ("minusInt", tInteger `tFn` tInteger `tFn` tInteger)
, ("multInt", tInteger `tFn` tInteger `tFn` tInteger)
, ("divInt", tInteger `tFn` tInteger `tFn` tInteger)
, ("modInt", tInteger `tFn` tInteger `tFn` tInteger)
, ("eqInt", tInteger `tFn` tInteger `tFn` tBool)
, ("ltInt", tInteger `tFn` tInteger `tFn` tBool)
, ("gtInt", tInteger `tFn` tInteger `tFn` tBool)
, ("leqInt", tInteger `tFn` tInteger `tFn` tBool)
, ("geqInt", tInteger `tFn` tInteger `tFn` tBool)
, ("plusDouble", tDouble `tFn` tDouble `tFn` tDouble)
, ("minusDouble", tDouble `tFn` tDouble `tFn` tDouble)
, ("multDouble", tDouble `tFn` tDouble `tFn` tDouble)
, ("divDouble", tDouble `tFn` tDouble `tFn` tDouble)
, ("modDouble", tDouble `tFn` tDouble `tFn` tDouble)
, ("eqDouble", tDouble `tFn` tDouble `tFn` tBool)
, ("ltDouble", tDouble `tFn` tDouble `tFn` tBool)
, ("gtDouble", tDouble `tFn` tDouble `tFn` tBool)
, ("leqDouble", tDouble `tFn` tDouble `tFn` tBool)
, ("geqDouble", tDouble `tFn` tDouble `tFn` tBool)
, ("plusStr", tString `tFn` tString `tFn` tString)
, ("eqStr", tString `tFn` tString `tFn` tBool)
, ("cloneStr", tString `tFn` tInteger `tFn` tInteger `tFn` tString)
, ("lenStr", tString `tFn` tInteger)
, ("eqChar", tChar `tFn` tChar `tFn` tBool)
, ("showChar", tChar `tFn` tString)
, ("ordChar", tChar `tFn` tInteger)
, ("showInt", tInteger `tFn` tString)
, ("omgDebug", tString `tFn` tString)
]
| null | https://raw.githubusercontent.com/xldenis/ill/46bb41bf5c82cd6fc4ad6d0d8d33cda9e87a671c/src/Thrill/Syntax/Builtins.hs | haskell | # LANGUAGE OverloadedStrings # | module Thrill.Syntax.Builtins where
import Thrill.Syntax.Type
import Thrill.Syntax.Kind
import Thrill.Syntax.Name
import Thrill.Prelude
import Data.String (IsString)
builtinTypes :: [(QualifiedName, Kind)]
builtinTypes =
[ (Qualified "Prelude" "Int", Star)
, (Qualified "Prelude" "String", Star)
, (Qualified "Prelude" "Char", Star)
]
builtins :: [(QualifiedName, Type QualifiedName)]
builtins = primitives ++ map (\(nm, ty) -> (Qualified "Prelude" nm, ty))
[ ("==", generalize $ constrain [(prelude "Eq", tVarA)] $ tVarA `tFn` tVarA `tFn` tBool)
, ("<=", generalize $ constrain [(prelude "Ord", tVarA)] $ tVarA `tFn` tVarA `tFn` tBool)
, (">=", generalize $ constrain [(prelude "Ord", tVarA)] $ tVarA `tFn` tVarA `tFn` tBool)
, ("<", generalize $ constrain [(prelude "Ord", tVarA)] $ tVarA `tFn` tVarA `tFn` tBool)
, (">", generalize $ constrain [(prelude "Ord", tVarA)] $ tVarA `tFn` tVarA `tFn` tBool)
, ("+", generalize $ constrain [(prelude "Semigroup", tVarA)] $ tVarA `tFn` tVarA `tFn` tVarA)
, ("-", generalize $ constrain [(prelude "Group", tVarA)] $ tVarA `tFn` tVarA `tFn` tVarA)
, ("*", generalize $ constrain [(prelude "MultSemigroup", tVarA)] $ tVarA `tFn` tVarA `tFn` tVarA)
, ("/", generalize $ constrain [(prelude "MultGroup", tVarA)] $ tVarA `tFn` tVarA `tFn` tVarA)
, ("&&", generalize $ tBool `tFn` tBool `tFn` tBool)
, ("||", generalize $ tBool `tFn` tBool `tFn` tBool)
, ("failedPattern", generalize $ tVarA)
]
where
prelude nm = Qualified "Prelude" nm
tVarA = TVar $ Internal "a"
primitives :: [(QualifiedName, Type QualifiedName)]
primitives = map (\(nm, ty) -> (Qualified "Prelude" nm, ty))
[ ("plusInt", tInteger `tFn` tInteger `tFn` tInteger)
, ("minusInt", tInteger `tFn` tInteger `tFn` tInteger)
, ("multInt", tInteger `tFn` tInteger `tFn` tInteger)
, ("divInt", tInteger `tFn` tInteger `tFn` tInteger)
, ("modInt", tInteger `tFn` tInteger `tFn` tInteger)
, ("eqInt", tInteger `tFn` tInteger `tFn` tBool)
, ("ltInt", tInteger `tFn` tInteger `tFn` tBool)
, ("gtInt", tInteger `tFn` tInteger `tFn` tBool)
, ("leqInt", tInteger `tFn` tInteger `tFn` tBool)
, ("geqInt", tInteger `tFn` tInteger `tFn` tBool)
, ("plusDouble", tDouble `tFn` tDouble `tFn` tDouble)
, ("minusDouble", tDouble `tFn` tDouble `tFn` tDouble)
, ("multDouble", tDouble `tFn` tDouble `tFn` tDouble)
, ("divDouble", tDouble `tFn` tDouble `tFn` tDouble)
, ("modDouble", tDouble `tFn` tDouble `tFn` tDouble)
, ("eqDouble", tDouble `tFn` tDouble `tFn` tBool)
, ("ltDouble", tDouble `tFn` tDouble `tFn` tBool)
, ("gtDouble", tDouble `tFn` tDouble `tFn` tBool)
, ("leqDouble", tDouble `tFn` tDouble `tFn` tBool)
, ("geqDouble", tDouble `tFn` tDouble `tFn` tBool)
, ("plusStr", tString `tFn` tString `tFn` tString)
, ("eqStr", tString `tFn` tString `tFn` tBool)
, ("cloneStr", tString `tFn` tInteger `tFn` tInteger `tFn` tString)
, ("lenStr", tString `tFn` tInteger)
, ("eqChar", tChar `tFn` tChar `tFn` tBool)
, ("showChar", tChar `tFn` tString)
, ("ordChar", tChar `tFn` tInteger)
, ("showInt", tInteger `tFn` tString)
, ("omgDebug", tString `tFn` tString)
]
|
51156b1724c9cdc6e82305eea0469b4e0176da003138e0dc1b35088bbdd6179b | janestreet/core | source_code_position.mli | * This module extends { { ! Base . . Source_code_position ] } .
* @inline
include module type of struct
include Base.Source_code_position
end
type t = Base.Source_code_position.t =
{ pos_fname : string
; pos_lnum : int
; pos_bol : int
; pos_cnum : int
}
[@@deriving fields]
include Comparable.S with type t := t and type comparator_witness := comparator_witness
include Hashable.S with type t := t
module Stable : sig
module V1 : Stable_module_types.With_stable_witness.S0 with type t = t
end
| null | https://raw.githubusercontent.com/janestreet/core/4b6635d206f7adcfac8324820d246299d6f572fe/core/src/source_code_position.mli | ocaml | * This module extends { { ! Base . . Source_code_position ] } .
* @inline
include module type of struct
include Base.Source_code_position
end
type t = Base.Source_code_position.t =
{ pos_fname : string
; pos_lnum : int
; pos_bol : int
; pos_cnum : int
}
[@@deriving fields]
include Comparable.S with type t := t and type comparator_witness := comparator_witness
include Hashable.S with type t := t
module Stable : sig
module V1 : Stable_module_types.With_stable_witness.S0 with type t = t
end
| |
cfdc8d191d00964e1af865b84990a89e14bba7b0ba2e8677898286d4f9570ed3 | namin/propagators | depends.scm | ;;; ----------------------------------------------------------------------
Copyright 2009 Massachusetts Institute of Technology .
;;; ----------------------------------------------------------------------
This file is part of Propagator Network Prototype .
;;;
Propagator Network Prototype 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.
;;;
Propagator Network Prototype 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 Propagator Network Prototype . If not , see
;;; </>.
;;; ----------------------------------------------------------------------
(declare (usual-integrations make-cell cell?))
(define (depends-printer state object)
(with-current-unparser-state state
(lambda (port)
(display "#(depends-on " port)
(write (v&d-value object) port)
(display " " port)
(write (v&d-needs object) port)
(display " " port)
(write (v&d-reason object) port)
(display ")" port))))
(define-structure
(v&d (named 'depends) (type vector)
(constructor %make-depends)
(print-procedure depends-printer)
(safe-accessors #t))
value needs reason)
(define (make-depends value needs #!optional reason)
(%make-depends value needs
(if (default-object? reason) #f reason)))
(define depends-info v&d-value)
(define depends-premises v&d-needs)
(define depends-premises v&d-reason)
(define depends? v&d?)
(declare-coercion-target depends
(lambda (thing)
(make-depends thing '() #f)))
(declare-coercion <symbol> ->depends)
(declare-coercion <number> ->depends)
(declare-coercion <boolean> ->depends)
(declare-coercion rtd:%interval ->depends)
(declare-coercion propagator-constructor? ->depends)
(declare-coercion closure? ->depends)
(declare-coercion pair? ->depends)
(define (more-informative-needs? v&d1 v&d2)
(and (not (lset= eq? (v&d-needs v&d1) (v&d-needs v&d2)))
(lset<= eq? (v&d-needs v&d1) (v&d-needs v&d2))))
(define (merge-needs . v&ds)
(apply lset-union eq? (map v&d-needs v&ds)))
(define (v&d-merge v&d1 v&d2)
(let* ((v&d1-value (v&d-value v&d1))
(v&d2-value (v&d-value v&d2))
(value-merge+effects
(->effectful (merge v&d1-value v&d2-value))))
(let ((value-merge
(effectful-info value-merge+effects))
(value-effects
(effectful-effects value-merge+effects)))
(effectful->
(make-effectful
(cond ((eq? value-merge v&d1-value)
(if (implies? v&d2-value value-merge)
Confirmation of existing information
(if (more-informative-needs? v&d2 v&d1)
v&d2
v&d1)
;; New information is not interesting
v&d1))
((eq? value-merge v&d2-value)
;; New information overrides old information
v&d2)
(else
;; Interesting merge, need both provenances
(make-depends value-merge
(merge-needs v&d1 v&d2)
????)))
(map (attach-needs-to-effect (merge-needs v&d1 v&d2))
value-effects))))))
(define ((attach-needs-to-effect needs) effect)
((generic-attach-premises effect) needs))
(define generic-attach-premises
(make-generic-operator 1 'attach-needs))
(defhandler generic-attach-premises
(lambda (effect)
(lambda (needs)
(make-cell-join-effect
(cell-join-effect-cell1 effect)
(cell-join-effect-cell2 effect)
(generic-flatten ;; TODO Do I need to do this by flattening?
TODO Get rid of this forward reference
(make-depends
(cell-join-effect-control effect)
needs
????))))))
cell-join-effect?)
(defhandler-coercing merge v&d-merge ->depends)
(define (v&d-equivalent? v&d1 v&d2)
(and (lset= eq? (v&d-needs v&d1) (v&d-needs v&d2))
(equivalent? (v&d-value v&d1) (v&d-value v&d2))))
(defhandler equivalent? v&d-equivalent? v&d? v&d?)
(defhandler contradictory?
(lambda (v&d) (contradictory? (v&d-value v&d)))
v&d?)
(define (v&d-> v&d)
(if (nothing? (v&d-value v&d))
nothing
v&d))
(define (v&d-binary-map v&d1 v&d2)
(lambda (f)
(v&d->
(make-depends
(f (v&d-value v&d1) (v&d-value v&d2))
(merge-needs v&d1 v&d2)
????))))
(defhandler-coercing binary-map v&d-binary-map ->depends)
(defhandler generic-unpack
(lambda (v&d function)
(make-depends
(generic-bind (v&d-value v&d) function)
(v&d-needs v&d)
????))
v&d? any?)
;;; This particular predicate dispatch system doesn't actually do
;;; predicate specificity computations. However, defining the most
general handler first has the desired effect .
(defhandler generic-flatten
(lambda (v&d) v&d)
v&d?)
(defhandler generic-flatten
(lambda (v&d) nothing)
(lambda (thing)
(and (v&d? thing)
(nothing? (v&d-value thing)))))
(defhandler generic-flatten
(lambda (v&d)
(generic-flatten
(make-depends
(v&d-value (v&d-value v&d))
(merge-needs v&d (v&d-value v&d))
????)))
(lambda (thing)
(and (v&d? thing)
(v&d? (v&d-value thing)))))
| null | https://raw.githubusercontent.com/namin/propagators/ae694dfe680125e53a3d49e5e91c378f2d333937/experiment/depends.scm | scheme | ----------------------------------------------------------------------
----------------------------------------------------------------------
you can
redistribute it and/or modify it under the terms of the GNU
any later version.
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.
</>.
----------------------------------------------------------------------
New information is not interesting
New information overrides old information
Interesting merge, need both provenances
TODO Do I need to do this by flattening?
This particular predicate dispatch system doesn't actually do
predicate specificity computations. However, defining the most | Copyright 2009 Massachusetts Institute of Technology .
This file is part of Propagator Network Prototype .
General Public License as published by the Free Software
Foundation , either version 3 of the License , or ( at your option )
Propagator Network Prototype is distributed in the hope that it
You should have received a copy of the GNU General Public License
along with Propagator Network Prototype . If not , see
(declare (usual-integrations make-cell cell?))
(define (depends-printer state object)
(with-current-unparser-state state
(lambda (port)
(display "#(depends-on " port)
(write (v&d-value object) port)
(display " " port)
(write (v&d-needs object) port)
(display " " port)
(write (v&d-reason object) port)
(display ")" port))))
(define-structure
(v&d (named 'depends) (type vector)
(constructor %make-depends)
(print-procedure depends-printer)
(safe-accessors #t))
value needs reason)
(define (make-depends value needs #!optional reason)
(%make-depends value needs
(if (default-object? reason) #f reason)))
(define depends-info v&d-value)
(define depends-premises v&d-needs)
(define depends-premises v&d-reason)
(define depends? v&d?)
(declare-coercion-target depends
(lambda (thing)
(make-depends thing '() #f)))
(declare-coercion <symbol> ->depends)
(declare-coercion <number> ->depends)
(declare-coercion <boolean> ->depends)
(declare-coercion rtd:%interval ->depends)
(declare-coercion propagator-constructor? ->depends)
(declare-coercion closure? ->depends)
(declare-coercion pair? ->depends)
(define (more-informative-needs? v&d1 v&d2)
(and (not (lset= eq? (v&d-needs v&d1) (v&d-needs v&d2)))
(lset<= eq? (v&d-needs v&d1) (v&d-needs v&d2))))
(define (merge-needs . v&ds)
(apply lset-union eq? (map v&d-needs v&ds)))
(define (v&d-merge v&d1 v&d2)
(let* ((v&d1-value (v&d-value v&d1))
(v&d2-value (v&d-value v&d2))
(value-merge+effects
(->effectful (merge v&d1-value v&d2-value))))
(let ((value-merge
(effectful-info value-merge+effects))
(value-effects
(effectful-effects value-merge+effects)))
(effectful->
(make-effectful
(cond ((eq? value-merge v&d1-value)
(if (implies? v&d2-value value-merge)
Confirmation of existing information
(if (more-informative-needs? v&d2 v&d1)
v&d2
v&d1)
v&d1))
((eq? value-merge v&d2-value)
v&d2)
(else
(make-depends value-merge
(merge-needs v&d1 v&d2)
????)))
(map (attach-needs-to-effect (merge-needs v&d1 v&d2))
value-effects))))))
(define ((attach-needs-to-effect needs) effect)
((generic-attach-premises effect) needs))
(define generic-attach-premises
(make-generic-operator 1 'attach-needs))
(defhandler generic-attach-premises
(lambda (effect)
(lambda (needs)
(make-cell-join-effect
(cell-join-effect-cell1 effect)
(cell-join-effect-cell2 effect)
TODO Get rid of this forward reference
(make-depends
(cell-join-effect-control effect)
needs
????))))))
cell-join-effect?)
(defhandler-coercing merge v&d-merge ->depends)
(define (v&d-equivalent? v&d1 v&d2)
(and (lset= eq? (v&d-needs v&d1) (v&d-needs v&d2))
(equivalent? (v&d-value v&d1) (v&d-value v&d2))))
(defhandler equivalent? v&d-equivalent? v&d? v&d?)
(defhandler contradictory?
(lambda (v&d) (contradictory? (v&d-value v&d)))
v&d?)
(define (v&d-> v&d)
(if (nothing? (v&d-value v&d))
nothing
v&d))
(define (v&d-binary-map v&d1 v&d2)
(lambda (f)
(v&d->
(make-depends
(f (v&d-value v&d1) (v&d-value v&d2))
(merge-needs v&d1 v&d2)
????))))
(defhandler-coercing binary-map v&d-binary-map ->depends)
(defhandler generic-unpack
(lambda (v&d function)
(make-depends
(generic-bind (v&d-value v&d) function)
(v&d-needs v&d)
????))
v&d? any?)
general handler first has the desired effect .
(defhandler generic-flatten
(lambda (v&d) v&d)
v&d?)
(defhandler generic-flatten
(lambda (v&d) nothing)
(lambda (thing)
(and (v&d? thing)
(nothing? (v&d-value thing)))))
(defhandler generic-flatten
(lambda (v&d)
(generic-flatten
(make-depends
(v&d-value (v&d-value v&d))
(merge-needs v&d (v&d-value v&d))
????)))
(lambda (thing)
(and (v&d? thing)
(v&d? (v&d-value thing)))))
|
23010bc0d1dd780881ef9a3bc9cefbf11ac2d2737301e59069ec12c189e02cc8 | eeng/mercurius | logging.clj | (ns mercurius.core.configuration.logging
(:require [taoensso.timbre :as log]
[clojure.string :as str]))
(defn- truncate [str length]
(subs str (- (count str) length)))
(defn output-fn
"Customize the default output as we don't need the hostname, nor the timestamp on dev (cooper already provides one)"
[data]
(let [{:keys [level ?err #_vargs msg_ ?ns-str ?file timestamp_ ?line]} data]
(str
(str (force timestamp_) " ")
(str/upper-case (first (name level))) " "
"[" (truncate (str (or ?ns-str ?file "?") ":" (or ?line "?")) 15) "] - "
(force msg_)
(when-let [err ?err]
(str "\n" (log/stacktrace err {:stacktrace-fonts {}}))))))
(defn configure-logger [{:keys [log-level]}]
(log/merge-config!
{:level log-level
:output-fn output-fn
:timestamp-opts {:pattern "yy-MM-dd HH:mm:ss.SSS"}}))
| null | https://raw.githubusercontent.com/eeng/mercurius/f83778ddde99aa13692e4fe2e70b2e9dc2fd70e9/src/mercurius/core/configuration/logging.clj | clojure | (ns mercurius.core.configuration.logging
(:require [taoensso.timbre :as log]
[clojure.string :as str]))
(defn- truncate [str length]
(subs str (- (count str) length)))
(defn output-fn
"Customize the default output as we don't need the hostname, nor the timestamp on dev (cooper already provides one)"
[data]
(let [{:keys [level ?err #_vargs msg_ ?ns-str ?file timestamp_ ?line]} data]
(str
(str (force timestamp_) " ")
(str/upper-case (first (name level))) " "
"[" (truncate (str (or ?ns-str ?file "?") ":" (or ?line "?")) 15) "] - "
(force msg_)
(when-let [err ?err]
(str "\n" (log/stacktrace err {:stacktrace-fonts {}}))))))
(defn configure-logger [{:keys [log-level]}]
(log/merge-config!
{:level log-level
:output-fn output-fn
:timestamp-opts {:pattern "yy-MM-dd HH:mm:ss.SSS"}}))
| |
eae4e64c2dd7477a3dcb008986c13b1f222ca4b8edb54303fa3fc772c91226a4 | johnyob/ppx-template | gen_dune_rules.ml | open Core
Code generation for the testing process from :
-05-09-an-introduction-to-ocaml-ppx-ecosystem
*)
let ppx_name = "ppx_template"
module Test = struct
type kind =
| Passing
| Errors
let pp_executable ppf ~kind (name, modules) =
match kind with
| Passing ->
Format.fprintf
ppf
"; The executable under test@,\
@[<v 1>(executable@ (name %s)@ (modules %s)@ (preprocess (pps %s)))@]"
name
modules
ppx_name
| Errors ->
If the PPX errors , then we do n't declare the file as an executable
( since we do n't want to compile it )
(since we don't want to compile it) *)
()
;;
let pp_rule ppf ~kind (name, module_name) =
let pp_action ppf () =
match kind with
| Errors ->
Format.fprintf
ppf
"; expect the process to fail, capturing stderr@,\
@[<v 1>(with-stderr-to@,\
%%{targets}@,\
(bash \"! ./%%{pp} -no-color --impl %%{input}\"))@]"
| Passing ->
Format.fprintf
ppf
"; expect the process to succeed, captured in target@,\
(run ./%%{pp} --impl %%{input} -o %%{targets})"
in
Format.fprintf
ppf
"; Run the PPX on the `.ml` file@,\
@[<v 1>(rule@,\
(targets %s.actual)@,\
@[<v 1>(deps@,\
(:pp pp.exe)@,\
(:input %s.ml))@]@,\
@[<v 1>(action@,\
%a))@]@]"
name
module_name
pp_action
()
;;
let pp_diff_alias_rule ppf name =
Format.fprintf
ppf
"; Compare the post-processed output to the .expected file@,\
@[<v 1>(rule@,\
(alias runtest)@,\
(package %s)@,\
@[<v 1>(action@,\
@[<hov 2>(diff@ %s.expected@ %s.actual)@])@])@]"
ppx_name
name
name
;;
let pp_run_alias_rule ppf ~kind module_name =
match kind with
| Passing ->
If we expect the PPX expansion to succeed , then we should be able to compile the output .
Format.fprintf
ppf
"@,\
; Ensure that the post-processed executable runs correctly@,\
@[<v 1>(rule@,\
(alias runtest)@,\
(package %s)@,\
@[<v 1>(action@,\
@[<hov 2>(run@ ./%s.exe)@])@])@]"
ppx_name
module_name
| Errors -> ()
;;
let pp ppf ~kind filename =
let name = Filename.chop_extension filename in
let module_name = name in
let modules =
(* Each test should only consist of a single file (or module) *)
module_name
in
Format.set_margin 80;
Format.fprintf
ppf
"@[<v 0>; -------- Test: `%s.ml` --------%a@,@,%a@,@,%a%a@,@]@."
module_name
(pp_executable ~kind)
(name, modules)
(pp_rule ~kind)
(name, module_name)
pp_diff_alias_rule
name
(pp_run_alias_rule ~kind)
module_name
;;
module Suite = struct
type t =
{ kind : kind
; files : string list
}
let is_test = function
| "pp.ml" -> false
| "gen_dune_rules.ml" -> false
| filename ->
Filename.check_suffix filename ".ml"
(* Avoid capturing preprocessed files *)
&& not (Filename.check_suffix filename ".pp.ml")
;;
let create ~kind files =
let files = files |> List.sort ~compare:String.compare |> List.filter ~f:is_test in
{ kind; files }
;;
let pp ppf { kind; files } = List.iter files ~f:(pp ppf ~kind)
end
end
let command =
let kind =
Command.Arg_type.create (function
| "passing" -> Test.Passing
| "errors" -> Errors
| kind -> Format.ksprintf failwith "Invalid kind: %s" kind)
in
Command.basic
~summary:(Format.sprintf "Generate dune rules for testing %s" ppx_name)
(let%map_open.Command kind =
flag
"-kind"
(optional_with_default Test.Passing kind)
~doc:"string Test suite kind"
in
fun () ->
let test_suite = Test.Suite.create ~kind (Sys_unix.readdir "." |> Array.to_list) in
Format.printf "%a\n" Test.Suite.pp test_suite)
;;
let () = Command_unix.run ~version:"1.0" command
| null | https://raw.githubusercontent.com/johnyob/ppx-template/eabd72a0d247d5cb4cbf6c738b89f685f095e5bb/test/gen_dune_rules.ml | ocaml | Each test should only consist of a single file (or module)
Avoid capturing preprocessed files | open Core
Code generation for the testing process from :
-05-09-an-introduction-to-ocaml-ppx-ecosystem
*)
let ppx_name = "ppx_template"
module Test = struct
type kind =
| Passing
| Errors
let pp_executable ppf ~kind (name, modules) =
match kind with
| Passing ->
Format.fprintf
ppf
"; The executable under test@,\
@[<v 1>(executable@ (name %s)@ (modules %s)@ (preprocess (pps %s)))@]"
name
modules
ppx_name
| Errors ->
If the PPX errors , then we do n't declare the file as an executable
( since we do n't want to compile it )
(since we don't want to compile it) *)
()
;;
let pp_rule ppf ~kind (name, module_name) =
let pp_action ppf () =
match kind with
| Errors ->
Format.fprintf
ppf
"; expect the process to fail, capturing stderr@,\
@[<v 1>(with-stderr-to@,\
%%{targets}@,\
(bash \"! ./%%{pp} -no-color --impl %%{input}\"))@]"
| Passing ->
Format.fprintf
ppf
"; expect the process to succeed, captured in target@,\
(run ./%%{pp} --impl %%{input} -o %%{targets})"
in
Format.fprintf
ppf
"; Run the PPX on the `.ml` file@,\
@[<v 1>(rule@,\
(targets %s.actual)@,\
@[<v 1>(deps@,\
(:pp pp.exe)@,\
(:input %s.ml))@]@,\
@[<v 1>(action@,\
%a))@]@]"
name
module_name
pp_action
()
;;
let pp_diff_alias_rule ppf name =
Format.fprintf
ppf
"; Compare the post-processed output to the .expected file@,\
@[<v 1>(rule@,\
(alias runtest)@,\
(package %s)@,\
@[<v 1>(action@,\
@[<hov 2>(diff@ %s.expected@ %s.actual)@])@])@]"
ppx_name
name
name
;;
let pp_run_alias_rule ppf ~kind module_name =
match kind with
| Passing ->
If we expect the PPX expansion to succeed , then we should be able to compile the output .
Format.fprintf
ppf
"@,\
; Ensure that the post-processed executable runs correctly@,\
@[<v 1>(rule@,\
(alias runtest)@,\
(package %s)@,\
@[<v 1>(action@,\
@[<hov 2>(run@ ./%s.exe)@])@])@]"
ppx_name
module_name
| Errors -> ()
;;
let pp ppf ~kind filename =
let name = Filename.chop_extension filename in
let module_name = name in
let modules =
module_name
in
Format.set_margin 80;
Format.fprintf
ppf
"@[<v 0>; -------- Test: `%s.ml` --------%a@,@,%a@,@,%a%a@,@]@."
module_name
(pp_executable ~kind)
(name, modules)
(pp_rule ~kind)
(name, module_name)
pp_diff_alias_rule
name
(pp_run_alias_rule ~kind)
module_name
;;
module Suite = struct
type t =
{ kind : kind
; files : string list
}
let is_test = function
| "pp.ml" -> false
| "gen_dune_rules.ml" -> false
| filename ->
Filename.check_suffix filename ".ml"
&& not (Filename.check_suffix filename ".pp.ml")
;;
let create ~kind files =
let files = files |> List.sort ~compare:String.compare |> List.filter ~f:is_test in
{ kind; files }
;;
let pp ppf { kind; files } = List.iter files ~f:(pp ppf ~kind)
end
end
let command =
let kind =
Command.Arg_type.create (function
| "passing" -> Test.Passing
| "errors" -> Errors
| kind -> Format.ksprintf failwith "Invalid kind: %s" kind)
in
Command.basic
~summary:(Format.sprintf "Generate dune rules for testing %s" ppx_name)
(let%map_open.Command kind =
flag
"-kind"
(optional_with_default Test.Passing kind)
~doc:"string Test suite kind"
in
fun () ->
let test_suite = Test.Suite.create ~kind (Sys_unix.readdir "." |> Array.to_list) in
Format.printf "%a\n" Test.Suite.pp test_suite)
;;
let () = Command_unix.run ~version:"1.0" command
|
9c4343fa93990a64100e244cb95a60449f33d052d146e463c568a74381676327 | nibbula/lish | package.lisp | ;;;
package.lisp - Package definition for
;;;
(defpackage :lish
(:documentation
"Lish is both a command shell and a Lisp REPL.
Lish is designed to make typing both operating system commands and Common Lisp
expressions convienient. It combines the features of a traditional operating
system shell with a Lisp REPL. It's designed to hopefully have little annoyance
to people familair with a POSIX shell. But it does not have exact compatibility
with POSIX shells.
The motivation for writing Lish came from the annoyance of having to swtich
between a Lisp REPL and a Unix shell. Lish may be used as a command shell,
without any particular knowledge of it's Lisp programming features.")
(:use :cl :dlib :opsys :dlib-misc :stretchy :char-util :glob
:table :table-print :reader-ext :completion :keymap
:terminal :terminal-ansi :rl :fatchar :fatchar-io :collections
:ostring :ochar :grout :dtime
#+use-regex :regex #-use-regex :cl-ppcre)
# + sbcl (: import - from : sb - ext # : retry )
(:export
;; Main entry point(s)
#:lish
#:shell-toplevel
;; variables
#:*lish-level*
#:*lish-user-package*
#:*shell-name*
#:*shell*
#:*old-pwd*
#:*dir-list*
#:*accepts*
#:*output* #:output #:*o*
#:*input* #:input #:*i*
#:with-output #:with-input
#:*lishrc*
#:*use-bracketed-paste*
#:*version*
#:*major-version* #:*minor-version* #:*build-version*
;; hooks @@@ maybe should be made into options?
#:*pre-command-hook*
#:*post-command-hook*
#:*unknown-command-hook*
#:*enter-shell-hook*
#:*exit-shell-hook*
;; installation
#:make-standalone
#:make-standalone-command
;; shell options
#:option
;; @@@ maybe we don't really need to export all this junk
#:lish-prompt #:set-lish-prompt
#:lish-prompt-function #:set-lish-prompt-function
#:lish-right-prompt #:set-lish-right-prompt
#:lish-sub-prompt #:set-lish-sub-prompt
#:lish-ignore-eof #:set-lish-ignore-eof
#:lish-debug #:set-lish-debug
#:lish-collect-stats #:set-lish-collect-stats
#:lish-autoload-from-asdf #:set-lish-autoload-from-asdf
#:lish-autoload-quietly #:set-lish-autoload-quietly
#:lish-history-expansion #:set-lish-history-expansion
#:lish-expand-braces #:set-lish-expand-braces
#:lish-colorize #:set-lish-colorize
#:lish-auto-cd #:set-lish-auto-cd
#:lish-history-style #:set-lish-history-style
#:lish-history-format #:set-lish-history-format
;; #:lish-history-save-values #:set-lish-history-save-values
#:lish-auto-suggest #:set-lish-auto-suggest
#:lish-partial-line-indicator #:set-lish-partial-line-indicator
#:lish-export-pipe-results #:set-lish-export-pipe-results
#:make-prompt
;; shell object
#:shell
#:shell-interactive-p
#:shell-aliases
#:lish-editor
#:lish-keymap
#:lish-old-pwd
#:lish-dir-list
#:lish-suspended-jobs
#:lish-last-background-job
#:lish-start-time
#:shell-help-table
#:lish-options
;; arguments
#:argument
#:arg-name #:arg-type #:arg-value #:arg-default #:arg-repeating #:arg-rest
#:arg-optional #:arg-hidden #:arg-prompt #:arg-help #:arg-short-arg
#:arg-long-arg
;; argument types
#:arg-boolean #:arg-number #:arg-integer #:arg-float #:arg-character
#:arg-string #:arg-symbol #:arg-keyword #:arg-object
#:arg-case-preserving-object #:arg-sequence #:arg-list #:arg-function
#:arg-package #:arg-date #:arg-pathname #:arg-directory #:arg-choice
#:arg-choices #:arg-choice-labels #:arg-choice-test
#:arg-choice-compare-ignore-case #:arg-choice-compare #:arg-lenient-choice
#:arg-option #:arg-input-stream-or-filename
;; argument types for builtins
#:arg-job-descriptor #:arg-help-subject #:arg-boolean-toggle #:arg-signal
#:arg-pid-or-job #:arg-function #:arg-key-sequence #:arg-command
#:arg-system-designator #:arg-quicklisp-system-designator
#:arg-autoload-place
;; argument generics
#:convert-arg #:argument-choices
#:defargtype
;; commands
#:command #:command-name #:command-function #:command-arglist
#:command-built-in-p #:command-loaded-from #:command-accepts
#:internal-command #:shell-command #:builtin-command #:external-command
#:command-list
#:defcommand #:defexternal
#:!cd #:!pwd #:!pushd #:!popd #:!dirs #:!suspend #:!fg #:!bg #:!jobs
#:!history #:!echo #:!help #:!alias #:!unalias #:!exit #:!quit #:!source
#:!debug #:!export #:!env #:!kill #:!time #:!times #:!umask #:!ulimit
#:!wait #:!exec #:!bind #:!undefcommand #:!hash #:!type #:!opt #:!l #:!load
#:!ldirs #:!ql #:!autoload #:!doc #:!var
#:print-command-help
;; help
#:defhelp #:help-table #:help-function #:help-subjects
#:help-subjects-description #:help-on
;; convenience / scripting
#:alias #:set-alias #:unset-alias #:get-alias
#:command-paths
#:pipe
#:in-bg
#:in-pipe-p
#:out-pipe-p
#:append-file #:append-files
#:run-with-output-to
#:run-with-input-from
#:input-line-words
#:input-line-list
#:map-output-lines
#:command-output-words
#:command-output-list
#:with-streamlike-input
#:with-files-or-input
#:with-shell
#:run-with-env
;; magic punctuation
#:! #:!? #:!! #:!$ #:!$$ #:!@ #:!_ #:!-
#:!= #:!?= #:!!= #:!$= #:!$$= #:!@= #:!_= #:!-=
#:!and #:!or #:!bg
#:!> #:!>> #:!>! #:!>>!
#:!< #:!!<
#:!q #:!h #:!hh #:!v
;; internal-ish things that might want to be used
#:get-command
#:command-to-lisp-args
#:posix-to-lisp-args
#:enable-sharp-dollar-reader
#:disable-sharp-dollar-reader
#:file-enable-sharp-dollar-reader
#:shell-read
#:shell-eval
#:shell-expand
#:shell-expand-to-list
#:fill-middle
#:gradientize
#:format-prompt
#:symbolic-prompt-to-string
#:load-file
#:suspend-job
#:find-job
#:job #:job-id #:job-name #:job-command-line #:job-status
#:job-pid
#:continue-job-in-foreground
#:continue-job-in-background
#:kill-job
#:list-all-jobs
#:accepts
#:get-accepts
#:twiddlify
#:unix-truthy
))
EOF
| null | https://raw.githubusercontent.com/nibbula/lish/1e1eb4e60dca05c005e3641af62efb55c1955e52/package.lisp | lisp |
Main entry point(s)
variables
hooks @@@ maybe should be made into options?
installation
shell options
@@@ maybe we don't really need to export all this junk
#:lish-history-save-values #:set-lish-history-save-values
shell object
arguments
argument types
argument types for builtins
argument generics
commands
help
convenience / scripting
magic punctuation
internal-ish things that might want to be used | package.lisp - Package definition for
(defpackage :lish
(:documentation
"Lish is both a command shell and a Lisp REPL.
Lish is designed to make typing both operating system commands and Common Lisp
expressions convienient. It combines the features of a traditional operating
system shell with a Lisp REPL. It's designed to hopefully have little annoyance
to people familair with a POSIX shell. But it does not have exact compatibility
with POSIX shells.
The motivation for writing Lish came from the annoyance of having to swtich
between a Lisp REPL and a Unix shell. Lish may be used as a command shell,
without any particular knowledge of it's Lisp programming features.")
(:use :cl :dlib :opsys :dlib-misc :stretchy :char-util :glob
:table :table-print :reader-ext :completion :keymap
:terminal :terminal-ansi :rl :fatchar :fatchar-io :collections
:ostring :ochar :grout :dtime
#+use-regex :regex #-use-regex :cl-ppcre)
# + sbcl (: import - from : sb - ext # : retry )
(:export
#:lish
#:shell-toplevel
#:*lish-level*
#:*lish-user-package*
#:*shell-name*
#:*shell*
#:*old-pwd*
#:*dir-list*
#:*accepts*
#:*output* #:output #:*o*
#:*input* #:input #:*i*
#:with-output #:with-input
#:*lishrc*
#:*use-bracketed-paste*
#:*version*
#:*major-version* #:*minor-version* #:*build-version*
#:*pre-command-hook*
#:*post-command-hook*
#:*unknown-command-hook*
#:*enter-shell-hook*
#:*exit-shell-hook*
#:make-standalone
#:make-standalone-command
#:option
#:lish-prompt #:set-lish-prompt
#:lish-prompt-function #:set-lish-prompt-function
#:lish-right-prompt #:set-lish-right-prompt
#:lish-sub-prompt #:set-lish-sub-prompt
#:lish-ignore-eof #:set-lish-ignore-eof
#:lish-debug #:set-lish-debug
#:lish-collect-stats #:set-lish-collect-stats
#:lish-autoload-from-asdf #:set-lish-autoload-from-asdf
#:lish-autoload-quietly #:set-lish-autoload-quietly
#:lish-history-expansion #:set-lish-history-expansion
#:lish-expand-braces #:set-lish-expand-braces
#:lish-colorize #:set-lish-colorize
#:lish-auto-cd #:set-lish-auto-cd
#:lish-history-style #:set-lish-history-style
#:lish-history-format #:set-lish-history-format
#:lish-auto-suggest #:set-lish-auto-suggest
#:lish-partial-line-indicator #:set-lish-partial-line-indicator
#:lish-export-pipe-results #:set-lish-export-pipe-results
#:make-prompt
#:shell
#:shell-interactive-p
#:shell-aliases
#:lish-editor
#:lish-keymap
#:lish-old-pwd
#:lish-dir-list
#:lish-suspended-jobs
#:lish-last-background-job
#:lish-start-time
#:shell-help-table
#:lish-options
#:argument
#:arg-name #:arg-type #:arg-value #:arg-default #:arg-repeating #:arg-rest
#:arg-optional #:arg-hidden #:arg-prompt #:arg-help #:arg-short-arg
#:arg-long-arg
#:arg-boolean #:arg-number #:arg-integer #:arg-float #:arg-character
#:arg-string #:arg-symbol #:arg-keyword #:arg-object
#:arg-case-preserving-object #:arg-sequence #:arg-list #:arg-function
#:arg-package #:arg-date #:arg-pathname #:arg-directory #:arg-choice
#:arg-choices #:arg-choice-labels #:arg-choice-test
#:arg-choice-compare-ignore-case #:arg-choice-compare #:arg-lenient-choice
#:arg-option #:arg-input-stream-or-filename
#:arg-job-descriptor #:arg-help-subject #:arg-boolean-toggle #:arg-signal
#:arg-pid-or-job #:arg-function #:arg-key-sequence #:arg-command
#:arg-system-designator #:arg-quicklisp-system-designator
#:arg-autoload-place
#:convert-arg #:argument-choices
#:defargtype
#:command #:command-name #:command-function #:command-arglist
#:command-built-in-p #:command-loaded-from #:command-accepts
#:internal-command #:shell-command #:builtin-command #:external-command
#:command-list
#:defcommand #:defexternal
#:!cd #:!pwd #:!pushd #:!popd #:!dirs #:!suspend #:!fg #:!bg #:!jobs
#:!history #:!echo #:!help #:!alias #:!unalias #:!exit #:!quit #:!source
#:!debug #:!export #:!env #:!kill #:!time #:!times #:!umask #:!ulimit
#:!wait #:!exec #:!bind #:!undefcommand #:!hash #:!type #:!opt #:!l #:!load
#:!ldirs #:!ql #:!autoload #:!doc #:!var
#:print-command-help
#:defhelp #:help-table #:help-function #:help-subjects
#:help-subjects-description #:help-on
#:alias #:set-alias #:unset-alias #:get-alias
#:command-paths
#:pipe
#:in-bg
#:in-pipe-p
#:out-pipe-p
#:append-file #:append-files
#:run-with-output-to
#:run-with-input-from
#:input-line-words
#:input-line-list
#:map-output-lines
#:command-output-words
#:command-output-list
#:with-streamlike-input
#:with-files-or-input
#:with-shell
#:run-with-env
#:! #:!? #:!! #:!$ #:!$$ #:!@ #:!_ #:!-
#:!= #:!?= #:!!= #:!$= #:!$$= #:!@= #:!_= #:!-=
#:!and #:!or #:!bg
#:!> #:!>> #:!>! #:!>>!
#:!< #:!!<
#:!q #:!h #:!hh #:!v
#:get-command
#:command-to-lisp-args
#:posix-to-lisp-args
#:enable-sharp-dollar-reader
#:disable-sharp-dollar-reader
#:file-enable-sharp-dollar-reader
#:shell-read
#:shell-eval
#:shell-expand
#:shell-expand-to-list
#:fill-middle
#:gradientize
#:format-prompt
#:symbolic-prompt-to-string
#:load-file
#:suspend-job
#:find-job
#:job #:job-id #:job-name #:job-command-line #:job-status
#:job-pid
#:continue-job-in-foreground
#:continue-job-in-background
#:kill-job
#:list-all-jobs
#:accepts
#:get-accepts
#:twiddlify
#:unix-truthy
))
EOF
|
a6c8226934338d08980db84d9cb3a9d4c4affa89f2f65d1bcd5793aca06a6d59 | batebobo/fp1819 | 7-pow.rkt | #lang racket
(require rackunit)
(require rackunit/text-ui)
(require "5-accumulate.rkt")
Искаме да повдигнем , accumulate
(define (pow x k)
(accumulate * 1 1 k (lambda (n) x) (lambda (x) (+ x 1)))
)
(define tests (test-suite
"Pow tests"
(test-case "" (check-equal? (pow 3 3) 27))
(test-case "" (check-equal? (pow 2 10) 1024))
))
(run-tests tests 'verbose)
| null | https://raw.githubusercontent.com/batebobo/fp1819/2061b7e62a1a9ade3a5fff9753f9fe0da5684275/scheme/3/solutions/7-pow.rkt | racket | #lang racket
(require rackunit)
(require rackunit/text-ui)
(require "5-accumulate.rkt")
Искаме да повдигнем , accumulate
(define (pow x k)
(accumulate * 1 1 k (lambda (n) x) (lambda (x) (+ x 1)))
)
(define tests (test-suite
"Pow tests"
(test-case "" (check-equal? (pow 3 3) 27))
(test-case "" (check-equal? (pow 2 10) 1024))
))
(run-tests tests 'verbose)
| |
df6b11b5733664a740dd6144d25d73b569db234f6f5965d4297ad6ddd5a33f50 | ghcjs/ghcjs-dom | WebGPURenderPipelineColorAttachmentDescriptor.hs | # LANGUAGE PatternSynonyms #
# LANGUAGE ForeignFunctionInterface #
# LANGUAGE JavaScriptFFI #
-- For HasCallStack compatibility
{-# LANGUAGE ImplicitParams, ConstraintKinds, KindSignatures #-}
module GHCJS.DOM.JSFFI.Generated.WebGPURenderPipelineColorAttachmentDescriptor
(js_setPixelFormat, setPixelFormat, js_getPixelFormat,
getPixelFormat, WebGPURenderPipelineColorAttachmentDescriptor(..),
gTypeWebGPURenderPipelineColorAttachmentDescriptor)
where
import Prelude ((.), (==), (>>=), return, IO, Int, Float, Double, Bool(..), Maybe, maybe, fromIntegral, round, fmap, Show, Read, Eq, Ord)
import qualified Prelude (error)
import Data.Typeable (Typeable)
import GHCJS.Types (JSVal(..), JSString)
import GHCJS.Foreign (jsNull, jsUndefined)
import GHCJS.Foreign.Callback (syncCallback, asyncCallback, syncCallback1, asyncCallback1, syncCallback2, asyncCallback2, OnBlocked(..))
import GHCJS.Marshal (ToJSVal(..), FromJSVal(..))
import GHCJS.Marshal.Pure (PToJSVal(..), PFromJSVal(..))
import Control.Monad (void)
import Control.Monad.IO.Class (MonadIO(..))
import Data.Int (Int64)
import Data.Word (Word, Word64)
import Data.Maybe (fromJust)
import Data.Traversable (mapM)
import GHCJS.DOM.Types
import Control.Applicative ((<$>))
import GHCJS.DOM.EventTargetClosures (EventName, unsafeEventName, unsafeEventNameAsync)
import GHCJS.DOM.JSFFI.Generated.Enums
foreign import javascript unsafe "$1[\"pixelFormat\"] = $2;"
js_setPixelFormat ::
WebGPURenderPipelineColorAttachmentDescriptor -> Word -> IO ()
| < -US/docs/Web/API/WebGPURenderPipelineColorAttachmentDescriptor.pixelFormat Mozilla WebGPURenderPipelineColorAttachmentDescriptor.pixelFormat documentation >
setPixelFormat ::
(MonadIO m) =>
WebGPURenderPipelineColorAttachmentDescriptor -> Word -> m ()
setPixelFormat self val = liftIO (js_setPixelFormat self val)
foreign import javascript unsafe "$1[\"pixelFormat\"]"
js_getPixelFormat ::
WebGPURenderPipelineColorAttachmentDescriptor -> IO Word
| < -US/docs/Web/API/WebGPURenderPipelineColorAttachmentDescriptor.pixelFormat Mozilla WebGPURenderPipelineColorAttachmentDescriptor.pixelFormat documentation >
getPixelFormat ::
(MonadIO m) =>
WebGPURenderPipelineColorAttachmentDescriptor -> m Word
getPixelFormat self = liftIO (js_getPixelFormat self) | null | https://raw.githubusercontent.com/ghcjs/ghcjs-dom/749963557d878d866be2d0184079836f367dd0ea/ghcjs-dom-jsffi/src/GHCJS/DOM/JSFFI/Generated/WebGPURenderPipelineColorAttachmentDescriptor.hs | haskell | For HasCallStack compatibility
# LANGUAGE ImplicitParams, ConstraintKinds, KindSignatures # | # LANGUAGE PatternSynonyms #
# LANGUAGE ForeignFunctionInterface #
# LANGUAGE JavaScriptFFI #
module GHCJS.DOM.JSFFI.Generated.WebGPURenderPipelineColorAttachmentDescriptor
(js_setPixelFormat, setPixelFormat, js_getPixelFormat,
getPixelFormat, WebGPURenderPipelineColorAttachmentDescriptor(..),
gTypeWebGPURenderPipelineColorAttachmentDescriptor)
where
import Prelude ((.), (==), (>>=), return, IO, Int, Float, Double, Bool(..), Maybe, maybe, fromIntegral, round, fmap, Show, Read, Eq, Ord)
import qualified Prelude (error)
import Data.Typeable (Typeable)
import GHCJS.Types (JSVal(..), JSString)
import GHCJS.Foreign (jsNull, jsUndefined)
import GHCJS.Foreign.Callback (syncCallback, asyncCallback, syncCallback1, asyncCallback1, syncCallback2, asyncCallback2, OnBlocked(..))
import GHCJS.Marshal (ToJSVal(..), FromJSVal(..))
import GHCJS.Marshal.Pure (PToJSVal(..), PFromJSVal(..))
import Control.Monad (void)
import Control.Monad.IO.Class (MonadIO(..))
import Data.Int (Int64)
import Data.Word (Word, Word64)
import Data.Maybe (fromJust)
import Data.Traversable (mapM)
import GHCJS.DOM.Types
import Control.Applicative ((<$>))
import GHCJS.DOM.EventTargetClosures (EventName, unsafeEventName, unsafeEventNameAsync)
import GHCJS.DOM.JSFFI.Generated.Enums
foreign import javascript unsafe "$1[\"pixelFormat\"] = $2;"
js_setPixelFormat ::
WebGPURenderPipelineColorAttachmentDescriptor -> Word -> IO ()
| < -US/docs/Web/API/WebGPURenderPipelineColorAttachmentDescriptor.pixelFormat Mozilla WebGPURenderPipelineColorAttachmentDescriptor.pixelFormat documentation >
setPixelFormat ::
(MonadIO m) =>
WebGPURenderPipelineColorAttachmentDescriptor -> Word -> m ()
setPixelFormat self val = liftIO (js_setPixelFormat self val)
foreign import javascript unsafe "$1[\"pixelFormat\"]"
js_getPixelFormat ::
WebGPURenderPipelineColorAttachmentDescriptor -> IO Word
| < -US/docs/Web/API/WebGPURenderPipelineColorAttachmentDescriptor.pixelFormat Mozilla WebGPURenderPipelineColorAttachmentDescriptor.pixelFormat documentation >
getPixelFormat ::
(MonadIO m) =>
WebGPURenderPipelineColorAttachmentDescriptor -> m Word
getPixelFormat self = liftIO (js_getPixelFormat self) |
1e245a4f2a775b0967f44f85203b4c8dc52e998ecb7e1079f98ed093d7e0fe40 | csabahruska/jhc-components | GenUtil.hs | $ I d : GenUtil.hs , v 1.53 2009/06/04 04:39:15
arch - tag : 835e46b7 - 8ffd-40a0 - aaf9 - 326b7e347760
Copyright ( c ) 2002 ( )
--
-- 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.
----------------------------------------
-- | This is a collection of random useful utility functions written in pure
-- Haskell 98. In general, it trys to conform to the naming scheme put forth
-- the haskell prelude and fill in the obvious omissions, as well as provide
-- useful routines in general. To ensure maximum portability, no instances are
-- exported so it may be added to any project without conflicts.
----------------------------------------
module GenUtil(
-- * Functions
-- ** Error reporting
putErr,putErrLn,putErrDie,
-- ** Simple deconstruction
fromLeft,fromRight,fsts,snds,splitEither,rights,lefts,
isLeft,isRight,
fst3,snd3,thd3,
-- ** System routines
exitSuccess, System.exitFailure, epoch, lookupEnv,endOfTime,
-- ** Random routines
repMaybe,
liftT2, liftT3, liftT4,
snub, snubFst, snubUnder, smerge, sortFst, groupFst, foldl',
fmapLeft,fmapRight,isDisjoint,isConjoint,
groupUnder,
sortUnder,
minimumUnder,
maximumUnder,
sortGroupUnder,
sortGroupUnderF,
sortGroupUnderFG,
sameLength,
naturals,
* * Monad routines
perhapsM,
repeatM, repeatM_, replicateM, replicateM_, maybeToMonad,
toMonadM, ioM, ioMp, foldlM, foldlM_, foldl1M, foldl1M_,
maybeM,
-- ** Text Routines
-- *** Quoting
shellQuote, simpleQuote, simpleUnquote,
-- *** Layout
indentLines,
buildTableLL,
buildTableRL,
buildTable,
trimBlankLines,
paragraph,
paragraphBreak,
expandTabs,
chunkText,
-- *** Scrambling
rot13,
-- ** Random
--intercalate,
powerSet,
randomPermute,
randomPermuteIO,
chunk,
rtup,
triple,
fromEither,
mapFst,
mapSnd,
mapFsts,
mapSnds,
tr,
readHex,
overlaps,
showDuration,
readM,
readsM,
split,
tokens,
count,
hasRepeatUnder,
-- ** Option handling
getArgContents,
parseOpt,
getOptContents,
doTime,
getPrefix,
rspan,
rbreak,
rdropWhile,
rtakeWhile,
rbdropWhile,
concatMapM,
on,
mapMsnd,
mapMfst,
iocatch,
-- * Classes
UniqueProducer(..)
) where
import CPUTime
import Char(isAlphaNum, isSpace, toLower, ord, chr)
import Control.Exception
import Data.List
import Monad
import Prelude hiding (catch)
import Random(StdGen, newStdGen, Random(randomR))
import System.IO.Error (isDoesNotExistError)
import Time
import qualified System
import qualified System.IO as IO
{-# SPECIALIZE snub :: [String] -> [String] #-}
{-# SPECIALIZE snub :: [Int] -> [Int] #-}
# RULES " snub / snub " forall x . ( snub x ) = snub x #
# RULES " snub / nub " forall x . ( nub x ) = snub x #
# RULES " nub / snub " forall x . ( snub x ) = snub x #
{-# RULES "snub/sort" forall x . snub (sort x) = snub x #-}
{-# RULES "sort/snub" forall x . sort (snub x) = snub x #-}
{-# RULES "snub/[]" snub [] = [] #-}
{-# RULES "snub/[x]" forall x . snub [x] = [x] #-}
-- | catch function only for IOException
iocatch :: IO a -> (IOException -> IO a) -> IO a
iocatch = catch
-- | sorted nub of list, much more efficient than nub, but doesnt preserve ordering.
snub :: Ord a => [a] -> [a]
snub = map head . group . sort
| sorted nub of list of tuples , based solely on the first element of each tuple .
snubFst :: Ord a => [(a,b)] -> [(a,b)]
snubFst = map head . groupBy (\(x,_) (y,_) -> x == y) . sortBy (\(x,_) (y,_) -> compare x y)
-- | sorted nub of list based on function of values
snubUnder :: Ord b => (a -> b) -> [a] -> [a]
snubUnder f = map head . groupUnder f . sortUnder f
| sort list of tuples , based on first element of each tuple .
sortFst :: Ord a => [(a,b)] -> [(a,b)]
sortFst = sortBy (\(x,_) (y,_) -> compare x y)
| group list of tuples , based only on equality of the first element of each tuple .
groupFst :: Eq a => [(a,b)] -> [[(a,b)]]
groupFst = groupBy (\(x,_) (y,_) -> x == y)
concatMapM :: Monad m => (a -> m [b]) -> [a] -> m [b]
concatMapM f xs = do
res <- mapM f xs
return $ concat res
on :: (a -> a -> b) -> (c -> a) -> c -> c -> b
(*) `on` f = \x y -> f x * f y
mapMsnd :: Monad m => (b -> m c) -> [(a,b)] -> m [(a,c)]
mapMsnd f xs = do
let g (a,b) = do
c <- f b
return (a,c)
mapM g xs
mapMfst :: Monad m => (b -> m c) -> [(b,a)] -> m [(c,a)]
mapMfst f xs = do
let g (a,b) = do
c <- f a
return (c,b)
mapM g xs
rspan :: (a -> Bool) -> [a] -> ([a], [a])
rspan fn xs = f xs [] where
f [] rs = ([],reverse rs)
f (x:xs) rs
| fn x = f xs (x:rs)
| otherwise = (reverse rs ++ x:za,zb) where
(za,zb) = f xs []
rbreak :: (a -> Bool) -> [a] -> ([a], [a])
rbreak fn xs = rspan (not . fn) xs
rdropWhile :: (a -> Bool) -> [a] -> [a]
rdropWhile fn xs = f xs [] where
f [] _ = []
f (x:xs) rs
| fn x = f xs (x:rs)
| otherwise = reverse rs ++ x:(f xs [])
rtakeWhile :: (a -> Bool) -> [a] -> [a]
rtakeWhile fn xs = f xs [] where
f [] rs = reverse rs
f (x:xs) rs
| fn x = f xs (x:rs)
| otherwise = f xs []
rbdropWhile :: (a -> Bool) -> [a] -> [a]
rbdropWhile fn xs = rdropWhile fn (dropWhile fn xs)
-- | group a list based on a function of the values.
groupUnder :: Eq b => (a -> b) -> [a] -> [[a]]
groupUnder f = groupBy (\x y -> f x == f y)
-- | sort a list based on a function of the values.
sortUnder :: Ord b => (a -> b) -> [a] -> [a]
sortUnder f = sortBy (\x y -> f x `compare` f y)
-- | merge sorted lists in linear time
smerge :: Ord a => [a] -> [a] -> [a]
smerge (x:xs) (y:ys)
| x == y = x:smerge xs ys
| x < y = x:smerge xs (y:ys)
| otherwise = y:smerge (x:xs) ys
smerge [] ys = ys
smerge xs [] = xs
sortGroupUnder :: Ord a => (b -> a) -> [b] -> [[b]]
sortGroupUnder f = groupUnder f . sortUnder f
sortGroupUnderF :: Ord a => (b -> a) -> [b] -> [(a,[b])]
sortGroupUnderF f xs = [ (f x, xs) | xs@(x:_) <- sortGroupUnder f xs]
sortGroupUnderFG :: Ord b => (a -> b) -> (a -> c) -> [a] -> [(b,[c])]
sortGroupUnderFG f g xs = [ (f x, map g xs) | xs@(x:_) <- sortGroupUnder f xs]
minimumUnder :: Ord b => (a -> b) -> [a] -> a
minimumUnder _ [] = error "minimumUnder: empty list"
minimumUnder _ [x] = x
minimumUnder f (x:xs) = g (f x) x xs where
g _ x [] = x
g fb b (x:xs)
| fx < fb = g fx x xs
| otherwise = g fb b xs where
fx = f x
maximumUnder :: Ord b => (a -> b) -> [a] -> a
maximumUnder _ [] = error "maximumUnder: empty list"
maximumUnder _ [x] = x
maximumUnder f (x:xs) = g (f x) x xs where
g _ x [] = x
g fb b (x:xs)
| fx > fb = g fx x xs
| otherwise = g fb b xs where
fx = f x
-- | Flushes stdout and writes string to standard error
putErr :: String -> IO ()
putErr s = IO.hFlush IO.stdout >> IO.hPutStr IO.stderr s
-- | Flush stdout and write string and newline to standard error
putErrLn :: String -> IO ()
putErrLn s = IO.hFlush IO.stdout >> IO.hPutStrLn IO.stderr s
-- | Flush stdout, write string and newline to standard error,
-- then exit program with failure.
putErrDie :: String -> IO a
putErrDie s = putErrLn s >> System.exitFailure
-- | exit program successfully. 'exitFailure' is
also exported from System .
exitSuccess :: IO a
exitSuccess = System.exitWith System.ExitSuccess
# INLINE fromRight #
fromRight :: Either a b -> b
fromRight (Right x) = x
fromRight _ = error "fromRight"
# INLINE fromLeft #
fromLeft :: Either a b -> a
fromLeft (Left x) = x
fromLeft _ = error "fromLeft"
-- | recursivly apply function to value until it returns Nothing
repMaybe :: (a -> Maybe a) -> a -> a
repMaybe f e = case f e of
Just e' -> repMaybe f e'
Nothing -> e
# INLINE liftT2 #
# INLINE liftT3 #
# INLINE liftT4 #
liftT4 (f1,f2,f3,f4) (v1,v2,v3,v4) = (f1 v1, f2 v2, f3 v3, f4 v4)
liftT3 (f,g,h) (x,y,z) = (f x, g y, h z)
| apply functions to values inside a tupele . ' liftT3 ' and ' liftT4 ' also exist .
liftT2 :: (a -> b, c -> d) -> (a,c) -> (b,d)
liftT2 (f,g) (x,y) = (f x, g y)
-- | class for monads which can generate
-- unique values.
class Monad m => UniqueProducer m where
-- | produce a new unique value
newUniq :: m Int
rtup a b = (b,a)
triple a b c = (a,b,c)
fst3 (a,_,_) = a
snd3 (_,b,_) = b
thd3 (_,_,c) = c
| the standard unix epoch
epoch :: ClockTime
epoch = toClockTime $ CalendarTime { ctYear = 1970, ctMonth = January, ctDay = 0, ctHour = 0, ctMin = 0, ctSec = 0, ctTZ = 0, ctPicosec = 0, ctWDay = undefined, ctYDay = undefined, ctTZName = undefined, ctIsDST = undefined}
-- | an arbitrary time in the future
endOfTime :: ClockTime
endOfTime = toClockTime $ CalendarTime { ctYear = 2020, ctMonth = January, ctDay = 0, ctHour = 0, ctMin = 0, ctSec = 0, ctTZ = 0, ctPicosec = 0, ctWDay = undefined, ctYDay = undefined, ctTZName = undefined, ctIsDST = undefined}
# INLINE fsts #
-- | take the fst of every element of a list
fsts :: [(a,b)] -> [a]
fsts = map fst
# INLINE snds #
-- | take the snd of every element of a list
snds :: [(a,b)] -> [b]
snds = map snd
# INLINE repeatM #
{- SPECIALIZE repeatM :: IO a -> IO [a] #-}
repeatM :: Monad m => m a -> m [a]
repeatM x = sequence $ repeat x
# INLINE repeatM _ #
{- SPECIALIZE repeatM_ :: IO a -> IO () #-}
repeatM_ :: Monad m => m a -> m ()
repeatM_ x = sequence_ $ repeat x
{-# RULES "replicateM/0" replicateM 0 = const (return []) #-}
{-# RULES "replicateM_/0" replicateM_ 0 = const (return ()) #-}
# INLINE replicateM #
{- SPECIALIZE replicateM :: Int -> IO a -> IO [a] #-}
replicateM :: Monad m => Int -> m a -> m [a]
replicateM n x = sequence $ replicate n x
# INLINE replicateM _ #
{- SPECIALIZE replicateM_ :: Int -> IO a -> IO () #-}
replicateM_ :: Monad m => Int -> m a -> m ()
replicateM_ n x = sequence_ $ replicate n x
-- | convert a maybe to an arbitrary failable monad
maybeToMonad :: Monad m => Maybe a -> m a
maybeToMonad (Just x) = return x
maybeToMonad Nothing = fail "Nothing"
-- | convert a maybe to an arbitrary failable monad
maybeM :: Monad m => String -> Maybe a -> m a
maybeM _ (Just x) = return x
maybeM s Nothing = fail s
toMonadM :: Monad m => m (Maybe a) -> m a
toMonadM action = join $ liftM maybeToMonad action
foldlM :: Monad m => (a -> b -> m a) -> a -> [b] -> m a
foldlM f v (x:xs) = (f v x) >>= \a -> foldlM f a xs
foldlM _ v [] = return v
foldl1M :: Monad m => (a -> a -> m a) -> [a] -> m a
foldl1M f (x:xs) = foldlM f x xs
foldl1M _ _ = error "foldl1M"
foldlM_ :: Monad m => (a -> b -> m a) -> a -> [b] -> m ()
foldlM_ f v xs = foldlM f v xs >> return ()
foldl1M_ ::Monad m => (a -> a -> m a) -> [a] -> m ()
foldl1M_ f xs = foldl1M f xs >> return ()
-- | partition a list of eithers.
splitEither :: [Either a b] -> ([a],[b])
splitEither (r:rs) = case splitEither rs of
(xs,ys) -> case r of
Left x -> (x:xs,ys)
Right y -> (xs,y:ys)
splitEither [] = ([],[])
isLeft Left {} = True
isLeft _ = False
isRight Right {} = True
isRight _ = False
perhapsM :: Monad m => Bool -> a -> m a
perhapsM True a = return a
perhapsM False _ = fail "perhapsM"
sameLength (_:xs) (_:ys) = sameLength xs ys
sameLength [] [] = True
sameLength _ _ = False
fromEither :: Either a a -> a
fromEither (Left x) = x
fromEither (Right x) = x
# INLINE mapFst #
# INLINE mapSnd #
mapFst :: (a -> b) -> (a,c) -> (b,c)
mapFst f (x,y) = (f x, y)
mapSnd :: (a -> b) -> (c,a) -> (c,b)
mapSnd g (x,y) = ( x,g y)
# INLINE mapFsts #
# INLINE mapSnds #
mapFsts :: (a -> b) -> [(a,c)] -> [(b,c)]
mapFsts f xs = [(f x, y) | (x,y) <- xs]
mapSnds :: (a -> b) -> [(c,a)] -> [(c,b)]
mapSnds g xs = [(x, g y) | (x,y) <- xs]
# INLINE rights #
-- | take just the rights
rights :: [Either a b] -> [b]
rights xs = [x | Right x <- xs]
# INLINE lefts #
-- | take just the lefts
lefts :: [Either a b] -> [a]
lefts xs = [x | Left x <- xs]
| errors into the failing of an arbitrary monad .
ioM :: Monad m => IO a -> IO (m a)
ioM action = iocatch (fmap return action) (\e -> return (fail (show e)))
| errors into the mzero of an arbitrary member of MonadPlus .
ioMp :: MonadPlus m => IO a -> IO (m a)
ioMp action = iocatch (fmap return action) (\_ -> return mzero)
-- | reformat a string to not be wider than a given width, breaking it up
-- between words.
paragraph :: Int -> String -> String
paragraph maxn xs = drop 1 (f maxn (words xs)) where
f n (x:xs) | lx < n = (' ':x) ++ f (n - lx) xs where
lx = length x + 1
f _ (x:xs) = '\n': (x ++ f (maxn - length x) xs)
f _ [] = "\n"
chunk :: Int -> [a] -> [[a]]
chunk 0 _ = repeat []
chunk _ [] = []
chunk mw s = case splitAt mw s of
(a,[]) -> [a]
(a,b) -> a : chunk mw b
chunkText :: Int -> String -> String
chunkText mw s = concatMap (unlines . chunk mw) $ lines s
rot13Char :: Char -> Char
rot13Char c
| c >= 'a' && c <= 'm' || c >= 'A' && c <= 'M' = chr $ ord c + 13
| c >= 'n' && c <= 'z' || c >= 'N' && c <= 'Z' = chr $ ord c - 13
| otherwise = c
rot13 :: String -> String
rot13 = map rot13Char
paragraphBreak : : Int - > String - > String
paragraphBreak maxn xs = unlines ( map ( unlines . map ( unlines . ) . lines . f ) $ lines xs ) where
f _ " " = " "
f n xs | length ss > 0 = if length ss + r rs > n then ' ss where
( ss , rs ) = span isSpace xs
f n xs = ns + + f ( n - length ns ) rs where
( ns , rs ) = span ( not . isSpace ) xs
r xs = length $ fst $ span ( not . isSpace ) xs
paragraphBreak :: Int -> String -> String
paragraphBreak maxn xs = unlines (map ( unlines . map (unlines . chunk maxn) . lines . f maxn ) $ lines xs) where
f _ "" = ""
f n xs | length ss > 0 = if length ss + r rs > n then '\n':f maxn rs else ss where
(ss,rs) = span isSpace xs
f n xs = ns ++ f (n - length ns) rs where
(ns,rs) = span (not . isSpace) xs
r xs = length $ fst $ span (not . isSpace) xs
-}
paragraphBreak :: Int -> String -> String
paragraphBreak maxn xs = unlines $ (map f) $ lines xs where
f s | length s <= maxn = s
f s | isSpace (head b) = a ++ "\n" ++ f (dropWhile isSpace b)
| all (not . isSpace) a = a ++ "\n" ++ f b
| otherwise = reverse (dropWhile isSpace sa) ++ "\n" ++ f (reverse ea ++ b) where
(ea, sa) = span (not . isSpace) $ reverse a
(a,b) = splitAt maxn s
expandTabs' :: Int -> Int -> String -> String
expandTabs' 0 _ s = filter (/= '\t') s
expandTabs' sz off ('\t':s) = replicate len ' ' ++ expandTabs' sz (off + len) s where
len = (sz - (off `mod` sz))
expandTabs' sz _ ('\n':s) = '\n': expandTabs' sz 0 s
expandTabs' sz off (c:cs) = c: expandTabs' sz (off + 1) cs
expandTabs' _ _ "" = ""
| expand tabs into spaces in a string assuming tabs are every 8 spaces and we are starting at column 0 .
expandTabs :: String -> String
expandTabs s = expandTabs' 8 0 s
| Translate characters to other characters in a string , if the second argument is empty ,
delete the characters in the first argument , else map each character to the
cooresponding one in the second argument , cycling the second argument if
-- necessary.
tr :: String -> String -> String -> String
tr as "" s = filter (`notElem` as) s
tr as bs s = map (f as bs) s where
f (a:_) (b:_) c | a == c = b
f (_:as) (_:bs) c = f as bs c
f [] _ c = c
f as' [] c = f as' bs c
--f _ _ _ = error "invalid tr"
-- | quote strings rc style. single quotes protect any characters between
them , to get an actual single quote double it up . Inverse of ' '
simpleQuote :: [String] -> String
simpleQuote ss = unwords (map f ss) where
f s | any isBad s || null s = "'" ++ dquote s ++ "'"
f s = s
dquote s = concatMap (\c -> if c == '\'' then "''" else [c]) s
isBad c = isSpace c || c == '\''
-- | inverse of 'simpleQuote'
simpleUnquote :: String -> [String]
simpleUnquote s = f (dropWhile isSpace s) where
f [] = []
f ('\'':xs) = case quote' "" xs of (x,y) -> x:f (dropWhile isSpace y)
f xs = case span (not . isSpace) xs of (x,y) -> x:f (dropWhile isSpace y)
quote' a ('\'':'\'':xs) = quote' ('\'':a) xs
quote' a ('\'':xs) = (reverse a, xs)
quote' a (x:xs) = quote' (x:a) xs
quote' a [] = (reverse a, "")
-- | quote a set of strings as would be appropriate to pass them as
-- arguments to a sh style shell
shellQuote :: [String] -> String
shellQuote ss = unwords (map f ss) where
f s | any (not . isGood) s || null s = "'" ++ dquote s ++ "'"
f s = s
dquote s = concatMap (\c -> if c == '\'' then "'\\''" else [c]) s
isGood c = isAlphaNum c || c `elem` "@/.-_"
| looks up an enviornment variable and returns it in an arbitrary Monad rather
-- than raising an exception if the variable is not set.
lookupEnv :: Monad m => String -> IO (m String)
lookupEnv s = catch (fmap return $ System.getEnv s) (\e -> if isDoesNotExistError e then return (fail (show e)) else ioError e)
{-# SPECIALIZE fmapLeft :: (a -> c) -> [(Either a b)] -> [(Either c b)] #-}
fmapLeft :: Functor f => (a -> c) -> f (Either a b) -> f (Either c b)
fmapLeft fn = fmap f where
f (Left x) = Left (fn x)
f (Right x) = Right x
{-# SPECIALIZE fmapRight :: (b -> c) -> [(Either a b)] -> [(Either a c)] #-}
fmapRight :: Functor f => (b -> c) -> f (Either a b) -> f (Either a c)
fmapRight fn = fmap f where
f (Left x) = Left x
f (Right x) = Right (fn x)
{-# SPECIALIZE isDisjoint :: [String] -> [String] -> Bool #-}
{-# SPECIALIZE isConjoint :: [String] -> [String] -> Bool #-}
{-# SPECIALIZE isDisjoint :: [Int] -> [Int] -> Bool #-}
{-# SPECIALIZE isConjoint :: [Int] -> [Int] -> Bool #-}
-- | set operations on lists. (slow!)
isDisjoint, isConjoint :: Eq a => [a] -> [a] -> Bool
isConjoint xs ys = or [x == y | x <- xs, y <- ys]
isDisjoint xs ys = not (isConjoint xs ys)
-- | 'concat' composed with 'List.intersperse'. Can be used similarly to join in perl.
--intercalate :: [a] -> [[a]] -> [a]
--intercalate x xss = concat (intersperse x xss)
-- | place spaces before each line in string.
indentLines :: Int -> String -> String
indentLines n s = unlines $ map (replicate n ' ' ++)$ lines s
-- | trim blank lines at beginning and end of string
trimBlankLines :: String -> String
trimBlankLines cs = unlines $ rbdropWhile (all isSpace) (lines cs)
buildTableRL :: [(String,String)] -> [String]
buildTableRL ps = map f ps where
f (x,"") = x
f (x,y) = replicate (bs - length x) ' ' ++ x ++ replicate 4 ' ' ++ y
bs = maximum (map (length . fst) [ p | p@(_,_:_) <- ps ])
buildTableLL :: [(String,String)] -> [String]
buildTableLL ps = map f ps where
f (x,y) = x ++ replicate (bs - length x) ' ' ++ replicate 4 ' ' ++ y
bs = maximum (map (length . fst) ps)
{ - INLINE foldl ' # - }
-- | strict version of 'foldl'
--foldl' :: (a -> b -> a) -> a -> [b] -> a
--foldl' _ a [] = a
--foldl' f a (x:xs) = (foldl' f $! f a x) xs
-- | count elements of list that have a given property
count :: (a -> Bool) -> [a] -> Int
count f xs = g 0 xs where
g n [] = n
g n (x:xs)
| f x = let x = n + 1 in x `seq` g x xs
| otherwise = g n xs
-- | randomly permute a list, using the standard random number generator.
randomPermuteIO :: [a] -> IO [a]
randomPermuteIO xs = newStdGen >>= \g -> return (randomPermute g xs)
| randomly permute a list given a RNG
randomPermute :: StdGen -> [a] -> [a]
randomPermute _ [] = []
randomPermute gen xs = (head tl) : randomPermute gen' (hd ++ tail tl)
where (idx, gen') = randomR (0,length xs - 1) gen
(hd, tl) = splitAt idx xs
hasRepeatUnder f xs = any (not . null . tail) $ sortGroupUnder f xs
-- | compute the power set of a list
powerSet :: [a] -> [[a]]
powerSet [] = [[]]
powerSet (x:xs) = xss /\/ map (x:) xss
where xss = powerSet xs
| interleave two lists lazily , alternating elements from them . This can also be
-- used instead of concatination to avoid space leaks in certain situations.
(/\/) :: [a] -> [a] -> [a]
[] /\/ ys = ys
(x:xs) /\/ ys = x : (ys /\/ xs)
readHexChar a | a >= '0' && a <= '9' = return $ ord a - ord '0'
readHexChar a | z >= 'a' && z <= 'f' = return $ 10 + ord z - ord 'a' where z = toLower a
readHexChar x = fail $ "not hex char: " ++ [x]
readHex :: Monad m => String -> m Int
readHex [] = fail "empty string"
readHex cs = mapM readHexChar cs >>= \cs' -> return (rh $ reverse cs') where
rh (c:cs) = c + 16 * (rh cs)
rh [] = 0
{- SPECIALIZE overlaps :: (Int,Int) -> (Int,Int) -> Bool #-}
| determine if two closed intervals overlap at all .
overlaps :: Ord a => (a,a) -> (a,a) -> Bool
(a,_) `overlaps` (_,y) | y < a = False
(_,b) `overlaps` (x,_) | b < x = False
_ `overlaps` _ = True
-- | translate a number of seconds to a string representing the duration expressed.
showDuration :: (Show a,Integral a) => a -> String
showDuration x = st "d" dayI ++ st "h" hourI ++ st "m" minI ++ show secI ++ "s" where
(dayI, hourI) = divMod hourI' 24
(hourI', minI) = divMod minI' 60
(minI',secI) = divMod x 60
st _ 0 = ""
st c n = show n ++ c
-- | behave like while(<>) in perl, go through the argument list, reading the
concation of each file name mentioned or stdin if ' - ' is on it . If no
arguments are given , read stdin .
getArgContents :: IO String
getArgContents = do
as <- System.getArgs
let f "-" = getContents
f fn = readFile fn
cs <- mapM f as
if null as then getContents else return $ concat cs
| Combination of parseOpt and getArgContents .
getOptContents :: String -> IO (String,[Char],[(Char,String)])
getOptContents args = do
as <- System.getArgs
(as,o1,o2) <- parseOpt args as
let f "-" = getContents
f fn = readFile fn
cs <- mapM f as
s <- if null as then getContents else return $ concat cs
return (s,o1,o2)
| Process options with an option string like the standard C getopt function call .
parseOpt :: Monad m =>
String -- ^ Argument string, list of valid options with : after ones which accept an argument
-> [String] -- ^ Arguments
-> m ([String],[Char],[(Char,String)]) -- ^ (non-options,flags,options with arguments)
parseOpt ps as = f ([],[],[]) as where
(args,oargs) = g ps [] [] where
g (':':_) _ _ = error "getOpt: Invalid option string"
g (c:':':ps) x y = g ps x (c:y)
g (c:ps) x y = g ps (c:x) y
g [] x y = (x,y)
f cs [] = return cs
f (xs,ys,zs) ("--":rs) = return (xs ++ rs, ys, zs)
f cs (('-':as@(_:_)):rs) = z cs as where
z (xs,ys,zs) (c:cs)
| c `elem` args = z (xs,c:ys,zs) cs
| c `elem` oargs = case cs of
[] -> case rs of
(x:rs) -> f (xs,ys,(c,x):zs) rs
[] -> fail $ "Option requires argument: " ++ [c]
x -> f (xs,ys,(c,x):zs) rs
| otherwise = fail $ "Invalid option: " ++ [c]
z cs [] = f cs rs
f (xs,ys,zs) (r:rs) = f (xs ++ [r], ys, zs) rs
readM :: (Monad m, Read a) => String -> m a
readM cs = case [x | (x,t) <- reads cs, ("","") <- lex t] of
[x] -> return x
[] -> fail "readM: no parse"
_ -> fail "readM: ambiguous parse"
readsM :: (Monad m, Read a) => String -> m (a,String)
readsM cs = case readsPrec 0 cs of
[(x,s)] -> return (x,s)
_ -> fail "cannot readsM"
-- | Splits a list into components delimited by separators, where the
-- predicate returns True for a separator element. The resulting
components do not contain the separators . Two adjacent separators
-- result in an empty component in the output. eg.
--
-- > split (=='a') "aabbaca"
-- > ["", "", "bb", "c", ""]
--
split :: (a -> Bool) -> [a] -> [[a]]
split p s = case rest of
[] -> [chunk]
_:rest -> chunk : split p rest
where (chunk, rest) = break p s
-- | Like 'split', except that sequences of adjacent separators are
-- treated as a single separator. eg.
--
-- > tokens (=='a') "aabbaca"
-- > ["bb","c"]
tokens :: (a -> Bool) -> [a] -> [[a]]
tokens p = filter (not.null) . split p
buildTable :: [String] -> [(String,[String])] -> String
buildTable ts rs = bt [ x:xs | (x,xs) <- ("",ts):rs ] where
bt ts = unlines (map f ts) where
f xs = intercalate " " (zipWith es cw xs)
cw = [ maximum (map length xs) | xs <- transpose ts]
es n s = replicate (n - length s) ' ' ++ s
-- | time task
doTime :: String -> IO a -> IO a
doTime str action = do
start <- getCPUTime
x <- action
end <- getCPUTime
putStrLn $ "Timing: " ++ str ++ " " ++ show ((end - start) `div` cpuTimePrecision)
return x
getPrefix :: Monad m => String -> String -> m String
getPrefix a b = f a b where
f [] ss = return ss
f _ [] = fail "getPrefix: value too short"
f (p:ps) (s:ss)
| p == s = f ps ss
| otherwise = fail $ "getPrefix: " ++ a ++ " " ++ b
# INLINE naturals #
naturals :: [Int]
naturals = [0..]
| null | https://raw.githubusercontent.com/csabahruska/jhc-components/a7dace481d017f5a83fbfc062bdd2d099133adf1/jhc-common/src/GenUtil.hs | haskell |
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the
without limitation the rights to use, copy, modify, merge, publish,
the following conditions:
The above copyright notice and this permission notice shall be included
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
--------------------------------------
| This is a collection of random useful utility functions written in pure
Haskell 98. In general, it trys to conform to the naming scheme put forth
the haskell prelude and fill in the obvious omissions, as well as provide
useful routines in general. To ensure maximum portability, no instances are
exported so it may be added to any project without conflicts.
--------------------------------------
* Functions
** Error reporting
** Simple deconstruction
** System routines
** Random routines
** Text Routines
*** Quoting
*** Layout
*** Scrambling
** Random
intercalate,
** Option handling
* Classes
# SPECIALIZE snub :: [String] -> [String] #
# SPECIALIZE snub :: [Int] -> [Int] #
# RULES "snub/sort" forall x . snub (sort x) = snub x #
# RULES "sort/snub" forall x . sort (snub x) = snub x #
# RULES "snub/[]" snub [] = [] #
# RULES "snub/[x]" forall x . snub [x] = [x] #
| catch function only for IOException
| sorted nub of list, much more efficient than nub, but doesnt preserve ordering.
| sorted nub of list based on function of values
| group a list based on a function of the values.
| sort a list based on a function of the values.
| merge sorted lists in linear time
| Flushes stdout and writes string to standard error
| Flush stdout and write string and newline to standard error
| Flush stdout, write string and newline to standard error,
then exit program with failure.
| exit program successfully. 'exitFailure' is
| recursivly apply function to value until it returns Nothing
| class for monads which can generate
unique values.
| produce a new unique value
| an arbitrary time in the future
| take the fst of every element of a list
| take the snd of every element of a list
SPECIALIZE repeatM :: IO a -> IO [a] #
SPECIALIZE repeatM_ :: IO a -> IO () #
# RULES "replicateM/0" replicateM 0 = const (return []) #
# RULES "replicateM_/0" replicateM_ 0 = const (return ()) #
SPECIALIZE replicateM :: Int -> IO a -> IO [a] #
SPECIALIZE replicateM_ :: Int -> IO a -> IO () #
| convert a maybe to an arbitrary failable monad
| convert a maybe to an arbitrary failable monad
| partition a list of eithers.
| take just the rights
| take just the lefts
| reformat a string to not be wider than a given width, breaking it up
between words.
necessary.
f _ _ _ = error "invalid tr"
| quote strings rc style. single quotes protect any characters between
| inverse of 'simpleQuote'
| quote a set of strings as would be appropriate to pass them as
arguments to a sh style shell
than raising an exception if the variable is not set.
# SPECIALIZE fmapLeft :: (a -> c) -> [(Either a b)] -> [(Either c b)] #
# SPECIALIZE fmapRight :: (b -> c) -> [(Either a b)] -> [(Either a c)] #
# SPECIALIZE isDisjoint :: [String] -> [String] -> Bool #
# SPECIALIZE isConjoint :: [String] -> [String] -> Bool #
# SPECIALIZE isDisjoint :: [Int] -> [Int] -> Bool #
# SPECIALIZE isConjoint :: [Int] -> [Int] -> Bool #
| set operations on lists. (slow!)
| 'concat' composed with 'List.intersperse'. Can be used similarly to join in perl.
intercalate :: [a] -> [[a]] -> [a]
intercalate x xss = concat (intersperse x xss)
| place spaces before each line in string.
| trim blank lines at beginning and end of string
| strict version of 'foldl'
foldl' :: (a -> b -> a) -> a -> [b] -> a
foldl' _ a [] = a
foldl' f a (x:xs) = (foldl' f $! f a x) xs
| count elements of list that have a given property
| randomly permute a list, using the standard random number generator.
| compute the power set of a list
used instead of concatination to avoid space leaks in certain situations.
SPECIALIZE overlaps :: (Int,Int) -> (Int,Int) -> Bool #
| translate a number of seconds to a string representing the duration expressed.
| behave like while(<>) in perl, go through the argument list, reading the
^ Argument string, list of valid options with : after ones which accept an argument
^ Arguments
^ (non-options,flags,options with arguments)
| Splits a list into components delimited by separators, where the
predicate returns True for a separator element. The resulting
result in an empty component in the output. eg.
> split (=='a') "aabbaca"
> ["", "", "bb", "c", ""]
| Like 'split', except that sequences of adjacent separators are
treated as a single separator. eg.
> tokens (=='a') "aabbaca"
> ["bb","c"]
| time task | $ I d : GenUtil.hs , v 1.53 2009/06/04 04:39:15
arch - tag : 835e46b7 - 8ffd-40a0 - aaf9 - 326b7e347760
Copyright ( c ) 2002 ( )
" Software " ) , to deal in the Software without restriction , including
distribute , sublicense , and/or sell copies of the Software , and to
permit persons to whom the Software is furnished to do so , subject to
in all copies or substantial portions of the Software .
THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND , EXPRESS
MERCHANTABILITY , FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT .
CLAIM , DAMAGES OR OTHER LIABILITY , WHETHER IN AN ACTION OF CONTRACT ,
module GenUtil(
putErr,putErrLn,putErrDie,
fromLeft,fromRight,fsts,snds,splitEither,rights,lefts,
isLeft,isRight,
fst3,snd3,thd3,
exitSuccess, System.exitFailure, epoch, lookupEnv,endOfTime,
repMaybe,
liftT2, liftT3, liftT4,
snub, snubFst, snubUnder, smerge, sortFst, groupFst, foldl',
fmapLeft,fmapRight,isDisjoint,isConjoint,
groupUnder,
sortUnder,
minimumUnder,
maximumUnder,
sortGroupUnder,
sortGroupUnderF,
sortGroupUnderFG,
sameLength,
naturals,
* * Monad routines
perhapsM,
repeatM, repeatM_, replicateM, replicateM_, maybeToMonad,
toMonadM, ioM, ioMp, foldlM, foldlM_, foldl1M, foldl1M_,
maybeM,
shellQuote, simpleQuote, simpleUnquote,
indentLines,
buildTableLL,
buildTableRL,
buildTable,
trimBlankLines,
paragraph,
paragraphBreak,
expandTabs,
chunkText,
rot13,
powerSet,
randomPermute,
randomPermuteIO,
chunk,
rtup,
triple,
fromEither,
mapFst,
mapSnd,
mapFsts,
mapSnds,
tr,
readHex,
overlaps,
showDuration,
readM,
readsM,
split,
tokens,
count,
hasRepeatUnder,
getArgContents,
parseOpt,
getOptContents,
doTime,
getPrefix,
rspan,
rbreak,
rdropWhile,
rtakeWhile,
rbdropWhile,
concatMapM,
on,
mapMsnd,
mapMfst,
iocatch,
UniqueProducer(..)
) where
import CPUTime
import Char(isAlphaNum, isSpace, toLower, ord, chr)
import Control.Exception
import Data.List
import Monad
import Prelude hiding (catch)
import Random(StdGen, newStdGen, Random(randomR))
import System.IO.Error (isDoesNotExistError)
import Time
import qualified System
import qualified System.IO as IO
# RULES " snub / snub " forall x . ( snub x ) = snub x #
# RULES " snub / nub " forall x . ( nub x ) = snub x #
# RULES " nub / snub " forall x . ( snub x ) = snub x #
iocatch :: IO a -> (IOException -> IO a) -> IO a
iocatch = catch
snub :: Ord a => [a] -> [a]
snub = map head . group . sort
| sorted nub of list of tuples , based solely on the first element of each tuple .
snubFst :: Ord a => [(a,b)] -> [(a,b)]
snubFst = map head . groupBy (\(x,_) (y,_) -> x == y) . sortBy (\(x,_) (y,_) -> compare x y)
snubUnder :: Ord b => (a -> b) -> [a] -> [a]
snubUnder f = map head . groupUnder f . sortUnder f
| sort list of tuples , based on first element of each tuple .
sortFst :: Ord a => [(a,b)] -> [(a,b)]
sortFst = sortBy (\(x,_) (y,_) -> compare x y)
| group list of tuples , based only on equality of the first element of each tuple .
groupFst :: Eq a => [(a,b)] -> [[(a,b)]]
groupFst = groupBy (\(x,_) (y,_) -> x == y)
concatMapM :: Monad m => (a -> m [b]) -> [a] -> m [b]
concatMapM f xs = do
res <- mapM f xs
return $ concat res
on :: (a -> a -> b) -> (c -> a) -> c -> c -> b
(*) `on` f = \x y -> f x * f y
mapMsnd :: Monad m => (b -> m c) -> [(a,b)] -> m [(a,c)]
mapMsnd f xs = do
let g (a,b) = do
c <- f b
return (a,c)
mapM g xs
mapMfst :: Monad m => (b -> m c) -> [(b,a)] -> m [(c,a)]
mapMfst f xs = do
let g (a,b) = do
c <- f a
return (c,b)
mapM g xs
rspan :: (a -> Bool) -> [a] -> ([a], [a])
rspan fn xs = f xs [] where
f [] rs = ([],reverse rs)
f (x:xs) rs
| fn x = f xs (x:rs)
| otherwise = (reverse rs ++ x:za,zb) where
(za,zb) = f xs []
rbreak :: (a -> Bool) -> [a] -> ([a], [a])
rbreak fn xs = rspan (not . fn) xs
rdropWhile :: (a -> Bool) -> [a] -> [a]
rdropWhile fn xs = f xs [] where
f [] _ = []
f (x:xs) rs
| fn x = f xs (x:rs)
| otherwise = reverse rs ++ x:(f xs [])
rtakeWhile :: (a -> Bool) -> [a] -> [a]
rtakeWhile fn xs = f xs [] where
f [] rs = reverse rs
f (x:xs) rs
| fn x = f xs (x:rs)
| otherwise = f xs []
rbdropWhile :: (a -> Bool) -> [a] -> [a]
rbdropWhile fn xs = rdropWhile fn (dropWhile fn xs)
groupUnder :: Eq b => (a -> b) -> [a] -> [[a]]
groupUnder f = groupBy (\x y -> f x == f y)
sortUnder :: Ord b => (a -> b) -> [a] -> [a]
sortUnder f = sortBy (\x y -> f x `compare` f y)
smerge :: Ord a => [a] -> [a] -> [a]
smerge (x:xs) (y:ys)
| x == y = x:smerge xs ys
| x < y = x:smerge xs (y:ys)
| otherwise = y:smerge (x:xs) ys
smerge [] ys = ys
smerge xs [] = xs
sortGroupUnder :: Ord a => (b -> a) -> [b] -> [[b]]
sortGroupUnder f = groupUnder f . sortUnder f
sortGroupUnderF :: Ord a => (b -> a) -> [b] -> [(a,[b])]
sortGroupUnderF f xs = [ (f x, xs) | xs@(x:_) <- sortGroupUnder f xs]
sortGroupUnderFG :: Ord b => (a -> b) -> (a -> c) -> [a] -> [(b,[c])]
sortGroupUnderFG f g xs = [ (f x, map g xs) | xs@(x:_) <- sortGroupUnder f xs]
minimumUnder :: Ord b => (a -> b) -> [a] -> a
minimumUnder _ [] = error "minimumUnder: empty list"
minimumUnder _ [x] = x
minimumUnder f (x:xs) = g (f x) x xs where
g _ x [] = x
g fb b (x:xs)
| fx < fb = g fx x xs
| otherwise = g fb b xs where
fx = f x
maximumUnder :: Ord b => (a -> b) -> [a] -> a
maximumUnder _ [] = error "maximumUnder: empty list"
maximumUnder _ [x] = x
maximumUnder f (x:xs) = g (f x) x xs where
g _ x [] = x
g fb b (x:xs)
| fx > fb = g fx x xs
| otherwise = g fb b xs where
fx = f x
putErr :: String -> IO ()
putErr s = IO.hFlush IO.stdout >> IO.hPutStr IO.stderr s
putErrLn :: String -> IO ()
putErrLn s = IO.hFlush IO.stdout >> IO.hPutStrLn IO.stderr s
putErrDie :: String -> IO a
putErrDie s = putErrLn s >> System.exitFailure
also exported from System .
exitSuccess :: IO a
exitSuccess = System.exitWith System.ExitSuccess
# INLINE fromRight #
fromRight :: Either a b -> b
fromRight (Right x) = x
fromRight _ = error "fromRight"
# INLINE fromLeft #
fromLeft :: Either a b -> a
fromLeft (Left x) = x
fromLeft _ = error "fromLeft"
repMaybe :: (a -> Maybe a) -> a -> a
repMaybe f e = case f e of
Just e' -> repMaybe f e'
Nothing -> e
# INLINE liftT2 #
# INLINE liftT3 #
# INLINE liftT4 #
liftT4 (f1,f2,f3,f4) (v1,v2,v3,v4) = (f1 v1, f2 v2, f3 v3, f4 v4)
liftT3 (f,g,h) (x,y,z) = (f x, g y, h z)
| apply functions to values inside a tupele . ' liftT3 ' and ' liftT4 ' also exist .
liftT2 :: (a -> b, c -> d) -> (a,c) -> (b,d)
liftT2 (f,g) (x,y) = (f x, g y)
class Monad m => UniqueProducer m where
newUniq :: m Int
rtup a b = (b,a)
triple a b c = (a,b,c)
fst3 (a,_,_) = a
snd3 (_,b,_) = b
thd3 (_,_,c) = c
| the standard unix epoch
epoch :: ClockTime
epoch = toClockTime $ CalendarTime { ctYear = 1970, ctMonth = January, ctDay = 0, ctHour = 0, ctMin = 0, ctSec = 0, ctTZ = 0, ctPicosec = 0, ctWDay = undefined, ctYDay = undefined, ctTZName = undefined, ctIsDST = undefined}
endOfTime :: ClockTime
endOfTime = toClockTime $ CalendarTime { ctYear = 2020, ctMonth = January, ctDay = 0, ctHour = 0, ctMin = 0, ctSec = 0, ctTZ = 0, ctPicosec = 0, ctWDay = undefined, ctYDay = undefined, ctTZName = undefined, ctIsDST = undefined}
# INLINE fsts #
fsts :: [(a,b)] -> [a]
fsts = map fst
# INLINE snds #
snds :: [(a,b)] -> [b]
snds = map snd
# INLINE repeatM #
repeatM :: Monad m => m a -> m [a]
repeatM x = sequence $ repeat x
# INLINE repeatM _ #
repeatM_ :: Monad m => m a -> m ()
repeatM_ x = sequence_ $ repeat x
# INLINE replicateM #
replicateM :: Monad m => Int -> m a -> m [a]
replicateM n x = sequence $ replicate n x
# INLINE replicateM _ #
replicateM_ :: Monad m => Int -> m a -> m ()
replicateM_ n x = sequence_ $ replicate n x
maybeToMonad :: Monad m => Maybe a -> m a
maybeToMonad (Just x) = return x
maybeToMonad Nothing = fail "Nothing"
maybeM :: Monad m => String -> Maybe a -> m a
maybeM _ (Just x) = return x
maybeM s Nothing = fail s
toMonadM :: Monad m => m (Maybe a) -> m a
toMonadM action = join $ liftM maybeToMonad action
foldlM :: Monad m => (a -> b -> m a) -> a -> [b] -> m a
foldlM f v (x:xs) = (f v x) >>= \a -> foldlM f a xs
foldlM _ v [] = return v
foldl1M :: Monad m => (a -> a -> m a) -> [a] -> m a
foldl1M f (x:xs) = foldlM f x xs
foldl1M _ _ = error "foldl1M"
foldlM_ :: Monad m => (a -> b -> m a) -> a -> [b] -> m ()
foldlM_ f v xs = foldlM f v xs >> return ()
foldl1M_ ::Monad m => (a -> a -> m a) -> [a] -> m ()
foldl1M_ f xs = foldl1M f xs >> return ()
splitEither :: [Either a b] -> ([a],[b])
splitEither (r:rs) = case splitEither rs of
(xs,ys) -> case r of
Left x -> (x:xs,ys)
Right y -> (xs,y:ys)
splitEither [] = ([],[])
isLeft Left {} = True
isLeft _ = False
isRight Right {} = True
isRight _ = False
perhapsM :: Monad m => Bool -> a -> m a
perhapsM True a = return a
perhapsM False _ = fail "perhapsM"
sameLength (_:xs) (_:ys) = sameLength xs ys
sameLength [] [] = True
sameLength _ _ = False
fromEither :: Either a a -> a
fromEither (Left x) = x
fromEither (Right x) = x
# INLINE mapFst #
# INLINE mapSnd #
mapFst :: (a -> b) -> (a,c) -> (b,c)
mapFst f (x,y) = (f x, y)
mapSnd :: (a -> b) -> (c,a) -> (c,b)
mapSnd g (x,y) = ( x,g y)
# INLINE mapFsts #
# INLINE mapSnds #
mapFsts :: (a -> b) -> [(a,c)] -> [(b,c)]
mapFsts f xs = [(f x, y) | (x,y) <- xs]
mapSnds :: (a -> b) -> [(c,a)] -> [(c,b)]
mapSnds g xs = [(x, g y) | (x,y) <- xs]
# INLINE rights #
rights :: [Either a b] -> [b]
rights xs = [x | Right x <- xs]
# INLINE lefts #
lefts :: [Either a b] -> [a]
lefts xs = [x | Left x <- xs]
| errors into the failing of an arbitrary monad .
ioM :: Monad m => IO a -> IO (m a)
ioM action = iocatch (fmap return action) (\e -> return (fail (show e)))
| errors into the mzero of an arbitrary member of MonadPlus .
ioMp :: MonadPlus m => IO a -> IO (m a)
ioMp action = iocatch (fmap return action) (\_ -> return mzero)
paragraph :: Int -> String -> String
paragraph maxn xs = drop 1 (f maxn (words xs)) where
f n (x:xs) | lx < n = (' ':x) ++ f (n - lx) xs where
lx = length x + 1
f _ (x:xs) = '\n': (x ++ f (maxn - length x) xs)
f _ [] = "\n"
chunk :: Int -> [a] -> [[a]]
chunk 0 _ = repeat []
chunk _ [] = []
chunk mw s = case splitAt mw s of
(a,[]) -> [a]
(a,b) -> a : chunk mw b
chunkText :: Int -> String -> String
chunkText mw s = concatMap (unlines . chunk mw) $ lines s
rot13Char :: Char -> Char
rot13Char c
| c >= 'a' && c <= 'm' || c >= 'A' && c <= 'M' = chr $ ord c + 13
| c >= 'n' && c <= 'z' || c >= 'N' && c <= 'Z' = chr $ ord c - 13
| otherwise = c
rot13 :: String -> String
rot13 = map rot13Char
paragraphBreak : : Int - > String - > String
paragraphBreak maxn xs = unlines ( map ( unlines . map ( unlines . ) . lines . f ) $ lines xs ) where
f _ " " = " "
f n xs | length ss > 0 = if length ss + r rs > n then ' ss where
( ss , rs ) = span isSpace xs
f n xs = ns + + f ( n - length ns ) rs where
( ns , rs ) = span ( not . isSpace ) xs
r xs = length $ fst $ span ( not . isSpace ) xs
paragraphBreak :: Int -> String -> String
paragraphBreak maxn xs = unlines (map ( unlines . map (unlines . chunk maxn) . lines . f maxn ) $ lines xs) where
f _ "" = ""
f n xs | length ss > 0 = if length ss + r rs > n then '\n':f maxn rs else ss where
(ss,rs) = span isSpace xs
f n xs = ns ++ f (n - length ns) rs where
(ns,rs) = span (not . isSpace) xs
r xs = length $ fst $ span (not . isSpace) xs
-}
paragraphBreak :: Int -> String -> String
paragraphBreak maxn xs = unlines $ (map f) $ lines xs where
f s | length s <= maxn = s
f s | isSpace (head b) = a ++ "\n" ++ f (dropWhile isSpace b)
| all (not . isSpace) a = a ++ "\n" ++ f b
| otherwise = reverse (dropWhile isSpace sa) ++ "\n" ++ f (reverse ea ++ b) where
(ea, sa) = span (not . isSpace) $ reverse a
(a,b) = splitAt maxn s
expandTabs' :: Int -> Int -> String -> String
expandTabs' 0 _ s = filter (/= '\t') s
expandTabs' sz off ('\t':s) = replicate len ' ' ++ expandTabs' sz (off + len) s where
len = (sz - (off `mod` sz))
expandTabs' sz _ ('\n':s) = '\n': expandTabs' sz 0 s
expandTabs' sz off (c:cs) = c: expandTabs' sz (off + 1) cs
expandTabs' _ _ "" = ""
| expand tabs into spaces in a string assuming tabs are every 8 spaces and we are starting at column 0 .
expandTabs :: String -> String
expandTabs s = expandTabs' 8 0 s
| Translate characters to other characters in a string , if the second argument is empty ,
delete the characters in the first argument , else map each character to the
cooresponding one in the second argument , cycling the second argument if
tr :: String -> String -> String -> String
tr as "" s = filter (`notElem` as) s
tr as bs s = map (f as bs) s where
f (a:_) (b:_) c | a == c = b
f (_:as) (_:bs) c = f as bs c
f [] _ c = c
f as' [] c = f as' bs c
them , to get an actual single quote double it up . Inverse of ' '
simpleQuote :: [String] -> String
simpleQuote ss = unwords (map f ss) where
f s | any isBad s || null s = "'" ++ dquote s ++ "'"
f s = s
dquote s = concatMap (\c -> if c == '\'' then "''" else [c]) s
isBad c = isSpace c || c == '\''
simpleUnquote :: String -> [String]
simpleUnquote s = f (dropWhile isSpace s) where
f [] = []
f ('\'':xs) = case quote' "" xs of (x,y) -> x:f (dropWhile isSpace y)
f xs = case span (not . isSpace) xs of (x,y) -> x:f (dropWhile isSpace y)
quote' a ('\'':'\'':xs) = quote' ('\'':a) xs
quote' a ('\'':xs) = (reverse a, xs)
quote' a (x:xs) = quote' (x:a) xs
quote' a [] = (reverse a, "")
shellQuote :: [String] -> String
shellQuote ss = unwords (map f ss) where
f s | any (not . isGood) s || null s = "'" ++ dquote s ++ "'"
f s = s
dquote s = concatMap (\c -> if c == '\'' then "'\\''" else [c]) s
isGood c = isAlphaNum c || c `elem` "@/.-_"
| looks up an enviornment variable and returns it in an arbitrary Monad rather
lookupEnv :: Monad m => String -> IO (m String)
lookupEnv s = catch (fmap return $ System.getEnv s) (\e -> if isDoesNotExistError e then return (fail (show e)) else ioError e)
fmapLeft :: Functor f => (a -> c) -> f (Either a b) -> f (Either c b)
fmapLeft fn = fmap f where
f (Left x) = Left (fn x)
f (Right x) = Right x
fmapRight :: Functor f => (b -> c) -> f (Either a b) -> f (Either a c)
fmapRight fn = fmap f where
f (Left x) = Left x
f (Right x) = Right (fn x)
isDisjoint, isConjoint :: Eq a => [a] -> [a] -> Bool
isConjoint xs ys = or [x == y | x <- xs, y <- ys]
isDisjoint xs ys = not (isConjoint xs ys)
indentLines :: Int -> String -> String
indentLines n s = unlines $ map (replicate n ' ' ++)$ lines s
trimBlankLines :: String -> String
trimBlankLines cs = unlines $ rbdropWhile (all isSpace) (lines cs)
buildTableRL :: [(String,String)] -> [String]
buildTableRL ps = map f ps where
f (x,"") = x
f (x,y) = replicate (bs - length x) ' ' ++ x ++ replicate 4 ' ' ++ y
bs = maximum (map (length . fst) [ p | p@(_,_:_) <- ps ])
buildTableLL :: [(String,String)] -> [String]
buildTableLL ps = map f ps where
f (x,y) = x ++ replicate (bs - length x) ' ' ++ replicate 4 ' ' ++ y
bs = maximum (map (length . fst) ps)
{ - INLINE foldl ' # - }
count :: (a -> Bool) -> [a] -> Int
count f xs = g 0 xs where
g n [] = n
g n (x:xs)
| f x = let x = n + 1 in x `seq` g x xs
| otherwise = g n xs
randomPermuteIO :: [a] -> IO [a]
randomPermuteIO xs = newStdGen >>= \g -> return (randomPermute g xs)
| randomly permute a list given a RNG
randomPermute :: StdGen -> [a] -> [a]
randomPermute _ [] = []
randomPermute gen xs = (head tl) : randomPermute gen' (hd ++ tail tl)
where (idx, gen') = randomR (0,length xs - 1) gen
(hd, tl) = splitAt idx xs
hasRepeatUnder f xs = any (not . null . tail) $ sortGroupUnder f xs
powerSet :: [a] -> [[a]]
powerSet [] = [[]]
powerSet (x:xs) = xss /\/ map (x:) xss
where xss = powerSet xs
| interleave two lists lazily , alternating elements from them . This can also be
(/\/) :: [a] -> [a] -> [a]
[] /\/ ys = ys
(x:xs) /\/ ys = x : (ys /\/ xs)
readHexChar a | a >= '0' && a <= '9' = return $ ord a - ord '0'
readHexChar a | z >= 'a' && z <= 'f' = return $ 10 + ord z - ord 'a' where z = toLower a
readHexChar x = fail $ "not hex char: " ++ [x]
readHex :: Monad m => String -> m Int
readHex [] = fail "empty string"
readHex cs = mapM readHexChar cs >>= \cs' -> return (rh $ reverse cs') where
rh (c:cs) = c + 16 * (rh cs)
rh [] = 0
| determine if two closed intervals overlap at all .
overlaps :: Ord a => (a,a) -> (a,a) -> Bool
(a,_) `overlaps` (_,y) | y < a = False
(_,b) `overlaps` (x,_) | b < x = False
_ `overlaps` _ = True
showDuration :: (Show a,Integral a) => a -> String
showDuration x = st "d" dayI ++ st "h" hourI ++ st "m" minI ++ show secI ++ "s" where
(dayI, hourI) = divMod hourI' 24
(hourI', minI) = divMod minI' 60
(minI',secI) = divMod x 60
st _ 0 = ""
st c n = show n ++ c
concation of each file name mentioned or stdin if ' - ' is on it . If no
arguments are given , read stdin .
getArgContents :: IO String
getArgContents = do
as <- System.getArgs
let f "-" = getContents
f fn = readFile fn
cs <- mapM f as
if null as then getContents else return $ concat cs
| Combination of parseOpt and getArgContents .
getOptContents :: String -> IO (String,[Char],[(Char,String)])
getOptContents args = do
as <- System.getArgs
(as,o1,o2) <- parseOpt args as
let f "-" = getContents
f fn = readFile fn
cs <- mapM f as
s <- if null as then getContents else return $ concat cs
return (s,o1,o2)
| Process options with an option string like the standard C getopt function call .
parseOpt :: Monad m =>
parseOpt ps as = f ([],[],[]) as where
(args,oargs) = g ps [] [] where
g (':':_) _ _ = error "getOpt: Invalid option string"
g (c:':':ps) x y = g ps x (c:y)
g (c:ps) x y = g ps (c:x) y
g [] x y = (x,y)
f cs [] = return cs
f (xs,ys,zs) ("--":rs) = return (xs ++ rs, ys, zs)
f cs (('-':as@(_:_)):rs) = z cs as where
z (xs,ys,zs) (c:cs)
| c `elem` args = z (xs,c:ys,zs) cs
| c `elem` oargs = case cs of
[] -> case rs of
(x:rs) -> f (xs,ys,(c,x):zs) rs
[] -> fail $ "Option requires argument: " ++ [c]
x -> f (xs,ys,(c,x):zs) rs
| otherwise = fail $ "Invalid option: " ++ [c]
z cs [] = f cs rs
f (xs,ys,zs) (r:rs) = f (xs ++ [r], ys, zs) rs
readM :: (Monad m, Read a) => String -> m a
readM cs = case [x | (x,t) <- reads cs, ("","") <- lex t] of
[x] -> return x
[] -> fail "readM: no parse"
_ -> fail "readM: ambiguous parse"
readsM :: (Monad m, Read a) => String -> m (a,String)
readsM cs = case readsPrec 0 cs of
[(x,s)] -> return (x,s)
_ -> fail "cannot readsM"
components do not contain the separators . Two adjacent separators
split :: (a -> Bool) -> [a] -> [[a]]
split p s = case rest of
[] -> [chunk]
_:rest -> chunk : split p rest
where (chunk, rest) = break p s
tokens :: (a -> Bool) -> [a] -> [[a]]
tokens p = filter (not.null) . split p
buildTable :: [String] -> [(String,[String])] -> String
buildTable ts rs = bt [ x:xs | (x,xs) <- ("",ts):rs ] where
bt ts = unlines (map f ts) where
f xs = intercalate " " (zipWith es cw xs)
cw = [ maximum (map length xs) | xs <- transpose ts]
es n s = replicate (n - length s) ' ' ++ s
doTime :: String -> IO a -> IO a
doTime str action = do
start <- getCPUTime
x <- action
end <- getCPUTime
putStrLn $ "Timing: " ++ str ++ " " ++ show ((end - start) `div` cpuTimePrecision)
return x
getPrefix :: Monad m => String -> String -> m String
getPrefix a b = f a b where
f [] ss = return ss
f _ [] = fail "getPrefix: value too short"
f (p:ps) (s:ss)
| p == s = f ps ss
| otherwise = fail $ "getPrefix: " ++ a ++ " " ++ b
# INLINE naturals #
naturals :: [Int]
naturals = [0..]
|
8997fbb7cbf540d8ab75020da1385aee5325f2128965b003602ad70c80a804ca | ostinelli/bisbino | bisbino_app.erl | % ==========================================================================================================
BISBINO
%
Copyright ( C ) 2010 , < >
% All rights reserved.
%
% BSD License
%
% Redistribution and use in source and binary forms, with or without modification, are permitted provided
% that the following conditions are met:
%
% * Redistributions of source code must retain the above copyright notice, this list of conditions and the
% following disclaimer.
% * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and
% the following disclaimer in the documentation and/or other materials provided with the distribution.
% * Neither the name of the authors nor the names of its contributors may be used to endorse or promote
% products derived from this software without specific prior written permission.
%
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS " AS IS " AND ANY EXPRESS OR
% WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
PARTICULAR PURPOSE ARE DISCLAIMED . IN NO EVENT SHALL THE COPYRIGHT HOLDER OR FOR
ANY DIRECT , INDIRECT , INCIDENTAL , SPECIAL , EXEMPLARY , OR CONSEQUENTIAL DAMAGES ( INCLUDING , BUT NOT LIMITED
TO , PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES ; LOSS OF USE , DATA , OR PROFITS ; OR BUSINESS INTERRUPTION )
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY , WHETHER IN CONTRACT , STRICT LIABILITY , OR TORT ( INCLUDING
% NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
% POSSIBILITY OF SUCH DAMAGE.
% ==========================================================================================================
-module(bisbino_app).
-behaviour(application).
-vsn("0.1-dev").
% application callbacks
-export([start/2, stop/1]).
% macros
-define(SERVER, ?MODULE).
% includes
-include("../include/misultin.hrl").
= = = = = = = = = = = = = = = = = = = = = = = = = = = = \/ API = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =
% ============================ /\ API ======================================================================
= = = = = = = = = = = = = = = = = = = = = = = = = = = = \/ APPLICATION CALLBACKS = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =
% ----------------------------------------------------------------------------------------------------------
Function : - > { ok , Pid } | { ok , Pid , State } | { error , Reason }
% Description: Starts the application
% ----------------------------------------------------------------------------------------------------------
start(_Type, _StartArgs) ->
?LOG_DEBUG("starting supervisor", []),
bisbino_sup:start_link().
% ----------------------------------------------------------------------------------------------------------
% Function: stop(State) -> void()
% Description: Stops the application
% ----------------------------------------------------------------------------------------------------------
stop(_State) ->
ok.
% ============================ /\ APPLICATION CALLBACKS ====================================================
= = = = = = = = = = = = = = = = = = = = = = = = = = = = \/ INTERNAL FUNCTIONS = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =
% ============================ /\ INTERNAL FUNCTIONS =======================================================
| null | https://raw.githubusercontent.com/ostinelli/bisbino/eb722fbf174edbe4aac0acb48ab3be076f241860/src/bisbino_app.erl | erlang | ==========================================================================================================
All rights reserved.
BSD License
Redistribution and use in source and binary forms, with or without modification, are permitted provided
that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this list of conditions and the
following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice, this list of conditions and
the following disclaimer in the documentation and/or other materials provided with the distribution.
* Neither the name of the authors nor the names of its contributors may be used to endorse or promote
products derived from this software without specific prior written permission.
WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
==========================================================================================================
application callbacks
macros
includes
============================ /\ API ======================================================================
----------------------------------------------------------------------------------------------------------
Description: Starts the application
----------------------------------------------------------------------------------------------------------
----------------------------------------------------------------------------------------------------------
Function: stop(State) -> void()
Description: Stops the application
----------------------------------------------------------------------------------------------------------
============================ /\ APPLICATION CALLBACKS ====================================================
============================ /\ INTERNAL FUNCTIONS ======================================================= | BISBINO
Copyright ( C ) 2010 , < >
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS " AS IS " AND ANY EXPRESS OR
PARTICULAR PURPOSE ARE DISCLAIMED . IN NO EVENT SHALL THE COPYRIGHT HOLDER OR FOR
ANY DIRECT , INDIRECT , INCIDENTAL , SPECIAL , EXEMPLARY , OR CONSEQUENTIAL DAMAGES ( INCLUDING , BUT NOT LIMITED
TO , PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES ; LOSS OF USE , DATA , OR PROFITS ; OR BUSINESS INTERRUPTION )
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY , WHETHER IN CONTRACT , STRICT LIABILITY , OR TORT ( INCLUDING
-module(bisbino_app).
-behaviour(application).
-vsn("0.1-dev").
-export([start/2, stop/1]).
-define(SERVER, ?MODULE).
-include("../include/misultin.hrl").
= = = = = = = = = = = = = = = = = = = = = = = = = = = = \/ API = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =
= = = = = = = = = = = = = = = = = = = = = = = = = = = = \/ APPLICATION CALLBACKS = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =
Function : - > { ok , Pid } | { ok , Pid , State } | { error , Reason }
start(_Type, _StartArgs) ->
?LOG_DEBUG("starting supervisor", []),
bisbino_sup:start_link().
stop(_State) ->
ok.
= = = = = = = = = = = = = = = = = = = = = = = = = = = = \/ INTERNAL FUNCTIONS = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =
|
4de91b86efcc90402197aa420b95313cfbc9efde43030f8207066cd7c2685164 | uswitch/transducers-workshop | lab04.clj | (ns transducers-workshop.solutions.lab04
(:require
[clojure.core.reducers :as r]
[transducers-workshop.solutions.lab01 :as lab01]
[transducers-workshop.xf :as xf]
[clojure.core.async :as async]))
(defn load-data
"load the usual test data but repeat them to create a much
larger dataset"
[n]
(into [] (apply concat (repeat n (lab01/load-data)))))
; (require '[transducers-workshop.solutions.lab04 :as lab04] :reload)
; (require '[transducers-workshop.solutions.lab01 :as lab01] :reload)
(defn parallel-reducers [params feed]
(r/fold
(r/monoid into (constantly []))
((lab01/xform params) conj)
feed))
(defn call-parallel-reducers []
(parallel-reducers
{:repayment-method :payment-method-repayment
:loan-amount 1500000}
(load-data 1000)))
; (time (def cs (call-parallel-reducers)))
(def max-parallel
(inc (.availableProcessors (Runtime/getRuntime))))
(defn parallel-async [params feed]
(let [out (async/chan (async/buffer 100))]
(async/pipeline
max-parallel
out
(lab01/xform params)
(async/to-chan feed))
(->> out (async/reduce conj []) async/<!!)))
(defn call-parallel-async []
(parallel-async
{:repayment-method :payment-method-repayment
:loan-amount 1500000}
(load-data 1000)))
; (time (def cs (call-parallel-async)))
(defn parallel-async-multiple [params feed]
(let [io (async/chan (async/buffer 100))
out (async/chan (async/buffer 50))
prepare-pipeline (async/pipeline
max-parallel
io
lab01/prepare-data
(async/to-chan feed))
filter-pipeline (async/pipeline
(quot max-parallel 2)
out
(lab01/filter-data params)
io)]
(->> out (async/reduce conj []) async/<!!)))
(defn call-parallel-async-multiple []
(parallel-async-multiple
{:repayment-method :payment-method-repayment
:loan-amount 1500000}
(load-data 1000)))
; (time (def cs (call-parallel-async-multiple)))
| null | https://raw.githubusercontent.com/uswitch/transducers-workshop/8779a70f55db58b2c40d98b1cb055f75f3442bf2/src/transducers_workshop/solutions/lab04.clj | clojure | (require '[transducers-workshop.solutions.lab04 :as lab04] :reload)
(require '[transducers-workshop.solutions.lab01 :as lab01] :reload)
(time (def cs (call-parallel-reducers)))
(time (def cs (call-parallel-async)))
(time (def cs (call-parallel-async-multiple))) | (ns transducers-workshop.solutions.lab04
(:require
[clojure.core.reducers :as r]
[transducers-workshop.solutions.lab01 :as lab01]
[transducers-workshop.xf :as xf]
[clojure.core.async :as async]))
(defn load-data
"load the usual test data but repeat them to create a much
larger dataset"
[n]
(into [] (apply concat (repeat n (lab01/load-data)))))
(defn parallel-reducers [params feed]
(r/fold
(r/monoid into (constantly []))
((lab01/xform params) conj)
feed))
(defn call-parallel-reducers []
(parallel-reducers
{:repayment-method :payment-method-repayment
:loan-amount 1500000}
(load-data 1000)))
(def max-parallel
(inc (.availableProcessors (Runtime/getRuntime))))
(defn parallel-async [params feed]
(let [out (async/chan (async/buffer 100))]
(async/pipeline
max-parallel
out
(lab01/xform params)
(async/to-chan feed))
(->> out (async/reduce conj []) async/<!!)))
(defn call-parallel-async []
(parallel-async
{:repayment-method :payment-method-repayment
:loan-amount 1500000}
(load-data 1000)))
(defn parallel-async-multiple [params feed]
(let [io (async/chan (async/buffer 100))
out (async/chan (async/buffer 50))
prepare-pipeline (async/pipeline
max-parallel
io
lab01/prepare-data
(async/to-chan feed))
filter-pipeline (async/pipeline
(quot max-parallel 2)
out
(lab01/filter-data params)
io)]
(->> out (async/reduce conj []) async/<!!)))
(defn call-parallel-async-multiple []
(parallel-async-multiple
{:repayment-method :payment-method-repayment
:loan-amount 1500000}
(load-data 1000)))
|
6e699f53b7df440407877ce46ebc98a8764a846cb9b02ac3293a2a11999499d8 | paypal/seazme-sources | analytics_jira_fields.clj | (ns seazme.scripts.analytics-jira-fields
(:require [seazme.sources.jira-api :as jira-api]
[clojure.data.json :as json] [clojure.edn :as edn] [clojure.java.io :as io] [clojure.data.csv :as csv]
[clj-time.format :as tf] [clj-time.coerce :as tr] [clj-time.core :as tc]
[clojure.core.match :refer [match]])
(:use seazme.scripts.common seazme.common.common))
;;
;; parameters
;;
(def work-dir (str (System/getProperty "user.home") "/seazme-tmpdir"))
(def conf-file (str work-dir "/config.edn"))
(def cfmap-file (str work-dir "/cfmap.csv"))
;;
;; STEPS
;;
1 extract data from SeazMe cache ( assuming it has been produced ) or DataHub itself ( WIP )
(comment
1 update cache
)
2 extract project / customfield data
(comment
(def path "...")
(def f1 (->> path clojure.java.io/file file-seq (filter #(.isFile %)) sort))
(count f1)
;;real
;; on source machine
(a1 f1 "agg1")
(u2v "agg1" "agg2cf" anacf)
(u2v "agg1" "agg2p" anap)
(v2csv "agg2cf" csvcf)
(v2csv "agg2p" csvp)
;;test
(comment
(with-open [in (-> "agg1.edn.gz" io/input-stream java.util.zip.GZIPInputStream. io/reader java.io.PushbackReader.)]
(let[edn-seq (repeatedly (partial edn/read {:eof nil} in))]
(def aaa (->> edn-seq (take-while (partial not= nil)) (remove empty?) (take 100) doall))))
(->> aaa (map anap) pprint)
(->> aaa (map anacf) (reduce (partial merge-with +)) pprint)
(->> aaa (map anap) (reduce (partial merge-with +)) pprint))
)
3 exctract field use
(comment
o
(def path "...")
(def f1 (->> path clojure.java.io/file file-seq (filter #(.isFile %)) #_(filter (comp neg? #(compare "2019-01-01" %) #(.getName %))) sort))
(->> f1 (map (partial scan-file proct)) dorun)
(->> @cf-files vals (map #(.close %)) dorun)(reset! cf-files {})
timetracking.edns.gz votes.edns.gz watches.edns.gz worklog.edns.gz issuelinks.edns.gz subtasks.edns.gz
(def path2 "o")
(def f2 (->> path2 clojure.java.io/file file-seq (filter #(.isFile %))))
(def stats (->> f2 (pmap f2p)))
(s-to-csv "cfuse.csv" stats)
)
4 copy files to a laptop
(comment
scp / cp and ungzip " * " to " work - dir "
)
5 prepare mapping file , on laptop
(comment
(produce-cf-file conf-file cfmap-file)
)
;;
;; common code
;;
(defn s-to-csv [f d] (with-open [out-file (io/writer f)] (csv/write-csv out-file d)))
(defn subs* [s b e] (subs s b (min e (count s))))
;;
;; field use
;;
(defn newfile1 [cfk] (-> (str "o/" (name cfk) ".edns.gz") clojure.java.io/output-stream java.util.zip.GZIPOutputStream. clojure.java.io/writer))
(def cf-files (atom {}))
(defn newfile2 [[cfk cfv]]
(swap! cf-files new-if-not-exists cfk #(newfile1 cfk))
(let [f (@cf-files cfk)]
(.write f (prn-str cfv))
(.newLine f)))
(defn proct[t]
(prn "processing:" (:key t))
(->> t :fields (filter (comp not nil? second)) (pmap newfile2) doall))
(defn dispatch[fn e]
(let [S java.lang.String I java.lang.Long D java.lang.Double]
(match [e (class e)]
[v S] (subs* v 0 42)
[v I] v
[v D] v
[{:progress _, :total _} _] e
[{:value v} _] v
[{:name v} _] v
[[ & r ] _] (clojure.string/join "," (sort (map (partial dispatch fn) r)))
:else (throw (Exception. (str fn ":" (pr-str e)))))))
TODO convert to scan file !
(with-open [in (-> fs clojure.java.io/input-stream java.util.zip.GZIPInputStream. clojure.java.io/reader java.io.PushbackReader.)]
(let[edn-seq (repeatedly (partial edn/read {:eof nil} in))
fn (.getName fs)
pieces (->> edn-seq
(take-while (partial not= nil))
#_(take 10)
(map (partial dispatch fn)))
frq (frequencies pieces)
va (vals frq)
ma (apply max va)
su (reduce + va)]
[fn ma su (double (/ ma su))])))
;;
;; mapping file
;;
(defn produce-cf-file[conf-file cfmap-file]
(let [config (-> conf-file slurp read-string)
credentials (-> config :credentials)
url (-> config :url)
pja (jira-api/mk-pja-api :get jira-api/pja-rea-400 url credentials false)
cfs (-> (pja "api/2/field") :body (json/read-str :key-fn keyword))]
(->> cfs (map #(map % [:id :name])) (s-to-csv cfmap-file))))
;;
;; extracting data from JIRA
;;
(def jira-ts-formatter (tf/formatters :date-time))
(defn since2007[d] (tc/in-weeks (tc/interval (tc/date-time 2007) (tf/parse jira-ts-formatter d))))
(defn ese3[e] [(-> e :fields :updated since2007) (-> e :fields :project :key) (->> e :fields (filter val) keys)])
(defn ese2[e] [(-> e :fields :updated since2007) (->> e :fields (filter val) keys)])
(defn write-to-stream-1[w s] (.write w (pr-str s)) (.newLine w))
(defn write-to-stream[w s] (locking w #_(prn (count s)) (.write w (pr-str s)) (.newLine w)))
;;(defn- write-to-stream[w s] (prn (count s))(.write w (pr-str s)) (.newLine w))
;;TODO copy docs from paper
(defn anacf [s] (frequencies (mapcat (fn[[k1 k2 vv]] (map #(vector k1 k2 %) vv)) s)))
(defn anap [s] (frequencies (map (fn[[k1 k2 vv]] (vector k1 k2)) s)))
(defn csvcf [out [[k1 k2 v] c]] (.write out (str k1","k2","(name v)","c)) (.newLine out))
(defn csvp [out [[k1 k2] c]] (.write out (str k1","k2","c)) (.newLine out))
(defn u2v[u v f]
(with-open [in (-> (str u ".edn.gz") io/input-stream java.util.zip.GZIPInputStream. io/reader java.io.PushbackReader.)
out (-> (str v ".edn.gz") io/output-stream java.util.zip.GZIPOutputStream. io/writer)]
(let[edn-seq (repeatedly (partial edn/read {:eof nil} in))]
(->> edn-seq
(take-while (partial not= nil))
(remove empty?)
(map f)
(map (partial write-to-stream-1 out))
dorun))))
(defn v2csv[v f]
(with-open [in (-> (str v ".edn.gz") io/input-stream java.util.zip.GZIPInputStream. io/reader java.io.PushbackReader.)
out (-> (str v ".csv.gz") io/output-stream java.util.zip.GZIPOutputStream. io/writer)]
(let[edn-seq (repeatedly (partial edn/read {:eof nil} in))
pieces (->> edn-seq
(take-while (partial not= nil))
(reduce (partial merge-with +)))]
(->> pieces (map (partial f out)) dorun))))
(defn a1[f1 v]
(with-open [w (-> (str v ".edn.gz") clojure.java.io/output-stream java.util.zip.GZIPOutputStream. clojure.java.io/writer)]
(->> f1 (pmap (partial scan-file ese3)) (map (partial write-to-stream w)) dorun)))
| null | https://raw.githubusercontent.com/paypal/seazme-sources/57e5b7579f5e475a908b2318a00549dd131f7745/src/main/clojure/seazme/scripts/analytics_jira_fields.clj | clojure |
parameters
STEPS
real
on source machine
test
common code
field use
mapping file
extracting data from JIRA
(defn- write-to-stream[w s] (prn (count s))(.write w (pr-str s)) (.newLine w))
TODO copy docs from paper | (ns seazme.scripts.analytics-jira-fields
(:require [seazme.sources.jira-api :as jira-api]
[clojure.data.json :as json] [clojure.edn :as edn] [clojure.java.io :as io] [clojure.data.csv :as csv]
[clj-time.format :as tf] [clj-time.coerce :as tr] [clj-time.core :as tc]
[clojure.core.match :refer [match]])
(:use seazme.scripts.common seazme.common.common))
(def work-dir (str (System/getProperty "user.home") "/seazme-tmpdir"))
(def conf-file (str work-dir "/config.edn"))
(def cfmap-file (str work-dir "/cfmap.csv"))
1 extract data from SeazMe cache ( assuming it has been produced ) or DataHub itself ( WIP )
(comment
1 update cache
)
2 extract project / customfield data
(comment
(def path "...")
(def f1 (->> path clojure.java.io/file file-seq (filter #(.isFile %)) sort))
(count f1)
(a1 f1 "agg1")
(u2v "agg1" "agg2cf" anacf)
(u2v "agg1" "agg2p" anap)
(v2csv "agg2cf" csvcf)
(v2csv "agg2p" csvp)
(comment
(with-open [in (-> "agg1.edn.gz" io/input-stream java.util.zip.GZIPInputStream. io/reader java.io.PushbackReader.)]
(let[edn-seq (repeatedly (partial edn/read {:eof nil} in))]
(def aaa (->> edn-seq (take-while (partial not= nil)) (remove empty?) (take 100) doall))))
(->> aaa (map anap) pprint)
(->> aaa (map anacf) (reduce (partial merge-with +)) pprint)
(->> aaa (map anap) (reduce (partial merge-with +)) pprint))
)
3 exctract field use
(comment
o
(def path "...")
(def f1 (->> path clojure.java.io/file file-seq (filter #(.isFile %)) #_(filter (comp neg? #(compare "2019-01-01" %) #(.getName %))) sort))
(->> f1 (map (partial scan-file proct)) dorun)
(->> @cf-files vals (map #(.close %)) dorun)(reset! cf-files {})
timetracking.edns.gz votes.edns.gz watches.edns.gz worklog.edns.gz issuelinks.edns.gz subtasks.edns.gz
(def path2 "o")
(def f2 (->> path2 clojure.java.io/file file-seq (filter #(.isFile %))))
(def stats (->> f2 (pmap f2p)))
(s-to-csv "cfuse.csv" stats)
)
4 copy files to a laptop
(comment
scp / cp and ungzip " * " to " work - dir "
)
5 prepare mapping file , on laptop
(comment
(produce-cf-file conf-file cfmap-file)
)
(defn s-to-csv [f d] (with-open [out-file (io/writer f)] (csv/write-csv out-file d)))
(defn subs* [s b e] (subs s b (min e (count s))))
(defn newfile1 [cfk] (-> (str "o/" (name cfk) ".edns.gz") clojure.java.io/output-stream java.util.zip.GZIPOutputStream. clojure.java.io/writer))
(def cf-files (atom {}))
(defn newfile2 [[cfk cfv]]
(swap! cf-files new-if-not-exists cfk #(newfile1 cfk))
(let [f (@cf-files cfk)]
(.write f (prn-str cfv))
(.newLine f)))
(defn proct[t]
(prn "processing:" (:key t))
(->> t :fields (filter (comp not nil? second)) (pmap newfile2) doall))
(defn dispatch[fn e]
(let [S java.lang.String I java.lang.Long D java.lang.Double]
(match [e (class e)]
[v S] (subs* v 0 42)
[v I] v
[v D] v
[{:progress _, :total _} _] e
[{:value v} _] v
[{:name v} _] v
[[ & r ] _] (clojure.string/join "," (sort (map (partial dispatch fn) r)))
:else (throw (Exception. (str fn ":" (pr-str e)))))))
TODO convert to scan file !
(with-open [in (-> fs clojure.java.io/input-stream java.util.zip.GZIPInputStream. clojure.java.io/reader java.io.PushbackReader.)]
(let[edn-seq (repeatedly (partial edn/read {:eof nil} in))
fn (.getName fs)
pieces (->> edn-seq
(take-while (partial not= nil))
#_(take 10)
(map (partial dispatch fn)))
frq (frequencies pieces)
va (vals frq)
ma (apply max va)
su (reduce + va)]
[fn ma su (double (/ ma su))])))
(defn produce-cf-file[conf-file cfmap-file]
(let [config (-> conf-file slurp read-string)
credentials (-> config :credentials)
url (-> config :url)
pja (jira-api/mk-pja-api :get jira-api/pja-rea-400 url credentials false)
cfs (-> (pja "api/2/field") :body (json/read-str :key-fn keyword))]
(->> cfs (map #(map % [:id :name])) (s-to-csv cfmap-file))))
(def jira-ts-formatter (tf/formatters :date-time))
(defn since2007[d] (tc/in-weeks (tc/interval (tc/date-time 2007) (tf/parse jira-ts-formatter d))))
(defn ese3[e] [(-> e :fields :updated since2007) (-> e :fields :project :key) (->> e :fields (filter val) keys)])
(defn ese2[e] [(-> e :fields :updated since2007) (->> e :fields (filter val) keys)])
(defn write-to-stream-1[w s] (.write w (pr-str s)) (.newLine w))
(defn write-to-stream[w s] (locking w #_(prn (count s)) (.write w (pr-str s)) (.newLine w)))
(defn anacf [s] (frequencies (mapcat (fn[[k1 k2 vv]] (map #(vector k1 k2 %) vv)) s)))
(defn anap [s] (frequencies (map (fn[[k1 k2 vv]] (vector k1 k2)) s)))
(defn csvcf [out [[k1 k2 v] c]] (.write out (str k1","k2","(name v)","c)) (.newLine out))
(defn csvp [out [[k1 k2] c]] (.write out (str k1","k2","c)) (.newLine out))
(defn u2v[u v f]
(with-open [in (-> (str u ".edn.gz") io/input-stream java.util.zip.GZIPInputStream. io/reader java.io.PushbackReader.)
out (-> (str v ".edn.gz") io/output-stream java.util.zip.GZIPOutputStream. io/writer)]
(let[edn-seq (repeatedly (partial edn/read {:eof nil} in))]
(->> edn-seq
(take-while (partial not= nil))
(remove empty?)
(map f)
(map (partial write-to-stream-1 out))
dorun))))
(defn v2csv[v f]
(with-open [in (-> (str v ".edn.gz") io/input-stream java.util.zip.GZIPInputStream. io/reader java.io.PushbackReader.)
out (-> (str v ".csv.gz") io/output-stream java.util.zip.GZIPOutputStream. io/writer)]
(let[edn-seq (repeatedly (partial edn/read {:eof nil} in))
pieces (->> edn-seq
(take-while (partial not= nil))
(reduce (partial merge-with +)))]
(->> pieces (map (partial f out)) dorun))))
(defn a1[f1 v]
(with-open [w (-> (str v ".edn.gz") clojure.java.io/output-stream java.util.zip.GZIPOutputStream. clojure.java.io/writer)]
(->> f1 (pmap (partial scan-file ese3)) (map (partial write-to-stream w)) dorun)))
|
39d7b219f8e4486bd4429d15ac48f956631e4920a75d551386978b388de035ff | informatimago/lisp | asdf-file.lisp | -*- mode : lisp;coding : utf-8 -*-
;;;;**************************************************************************
FILE : asdf-file.lisp
;;;;LANGUAGE: Common-Lisp
;;;;SYSTEM: Common-Lisp
USER - INTERFACE :
;;;;DESCRIPTION
;;;;
;;;; Reads ASDF files.
;;;;
< PJB > < >
MODIFICATIONS
2014 - 09 - 02 < PJB > Added generate - dot .
2013 - 09 - 06 < PJB > Updated for publication .
2012 - 04 - 09 < PJB > Created .
;;;;LEGAL
AGPL3
;;;;
Copyright 2012 - 2016
;;;;
;;;; This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation , either version 3 of the License , or
;;;; (at your option) any later version.
;;;;
;;;; This program is distributed in the hope that it will be useful,
;;;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details .
;;;;
You should have received a copy of the GNU Affero General Public License
;;;; along with this program. If not, see </>.
;;;;**************************************************************************
(eval-when (:compile-toplevel :load-toplevel :execute)
(setf *readtable* (copy-readtable nil)))
(defpackage "COM.INFORMATIMAGO.TOOLS.ASDF-FILE"
(:use "COMMON-LISP"
"SPLIT-SEQUENCE"
"COM.INFORMATIMAGO.COMMON-LISP.CESARUM.UTILITY"
"COM.INFORMATIMAGO.COMMON-LISP.CESARUM.LIST"
"COM.INFORMATIMAGO.COMMON-LISP.CESARUM.STRING"
"COM.INFORMATIMAGO.TOOLS.DEPENDENCY-CYCLES"
"COM.INFORMATIMAGO.TOOLS.SOURCE")
(:shadow "DEPENDENCIES")
(:export
;; Generating simple ASD files:
"MAKE-COMPONENTS"
"GENERATE-ASD"
;; Reading and writing asd files:
"FIND-ASD-FILES"
"ASD-SYSTEMS-IN-ASD-FILE"
"READ-ASDF-SYSTEM-DEFINITIONS"
"WRITE-ASDF-SYSTEM-DEFINITION"
"SAVE-ASDF-SYSTEM-FILE"
"DEFAULT-HEADERS-FOR-SYSTEM"
;; Generating test systems:
"TEST-SYSTEM-FOR-SYSTEM"
"TEST-SYSTEM-P"
"TEST-SYSTEM-FOR-SYSTEM"
"GENERATE-TEST-SYSTEM-FOR-SYSTEM-AT-PATH")
(:documentation "
Reads simple .asd files, without instanciating ASDF objects.
============================================================
(LOAD-SIMPLE-ASD-FILE path-to-asd-file)
--> hashtable mapping file names to ASDF-FILE structures.
NOTE: The current implementation expects the defsystem form to be the
first and only form in the asd file.
Generate simple .asd files:
============================================================
(GENERATE-ASD :system-name (list \"source-1\" \"source-2\") \"lisp\"
:description \"Short description\"
:version \"1.0.0\"
:author \"Name <email@address>\"
:license \"AGPL3\"
:predefined-packages '(\"COMMON-LISP\"))
:implicit-dependencies '())
:depends-on '(:other-system))
:load-paths (list (make-pathname :directory '(:relative))))
:vanillap t)
License:
AGPL3
Copyright Pascal J. Bourguignon 2012 - 2014
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see </>.
"))
(in-package "COM.INFORMATIMAGO.TOOLS.ASDF-FILE")
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; GENERATE-ASD
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defun make-components (paths &key (predefined-packages '("COMMON-LISP"))
(component-class :file)
(implicit-dependencies '())
(load-paths (list (make-pathname
:directory '(:relative)))))
(mapcar
(lambda (depend)
(let* ((depend (mapcar (lambda (path) (pathname-name path)) depend))
(target (first depend))
(depends (delete (first depend)
(append implicit-dependencies (rest depend))
:test (function string=))))
(list* component-class target (when depends (list :depends-on depends)))))
(get-depends paths predefined-packages load-paths)))
(defun gen-defsystem-form (name paths &key description (version "0.0.0")
author maintainer licence license
(component-class :file)
(predefined-packages '("COMMON-LISP"))
(implicit-dependencies '())
(depends-on '())
(load-paths (list (make-pathname
:directory '(:relative)))))
"
DO: Generate an ASD file for ASDF.
NAME: Name of the generated ASDF system.
PATHS: List of pathnames to the source files of this ASDF system.
DESCRIPTION: A description string for the ASDF system.
VERSION: A version string for the ASDF system.
AUTHOR: An author string for the ASDF system.
LICENSE: A licence string for the ASDF system.
PREDEFINED-PACKAGES: A list of packages that are removed from the dependencies.
IMPLICIT-DEPENDENCIES: A list of dependencies added to all targets.
LOAD:-PATHS A list of directory paths where the sources are searched in.
"
(flet ((enumerate (list) (format nil "~{~A, ~}~:[none~;~1@*~{~A~^ and ~A~}~]"
(butlast list 2) (last list 2))))
(let* ((headers (mapcar (lambda (path) (list* :path path
(with-open-file (stream path)
(read-source-header stream))))
paths))
(authors (or author
(enumerate (delete-duplicates
(apply (function append)
(mapcar (function header-authors)
headers))
:test (function string-equal)))))
(licence (or licence license
(enumerate (delete-duplicates
(mapcar (function header-licence) headers)
:test (function string-equal)))))
(description
(unsplit-string
(or (ensure-list description)
(mapcan
(lambda (header)
(append (list (format nil "~2%PACKAGE: ~A~2%"
(second
(get-package (header-slot header :path)))))
(mapcar (lambda (line) (format nil "~A~%" line))
(header-description header))
(list (format nil "~%"))))
headers))
" "))
(components (make-components
paths
:component-class component-class
:predefined-packages (append depends-on
predefined-packages)
:implicit-dependencies implicit-dependencies
:load-paths load-paths)))
`(asdf:defsystem ,name
:description ,description
:version ,version
:author ,authors
:maintainer ,maintainer
:licence ,licence
:depends-on ,depends-on
:components ,components))))
(defun generate-asd (system-name sources source-type
&key description (version "0.0.0")
author licence license
(predefined-packages '("COMMON-LISP"))
(implicit-dependencies '())
(depends-on '())
(load-paths (list (make-pathname :directory '(:relative))))
(vanillap t))
"
VANILLAP: if true, then generate a simple, vanilla system.
Otherwise, decorate it with PJB output-files.
"
(let ((*package* (find-package :com.informatimago.tools.make-depends.make-depends)))
(with-open-file (out (make-pathname :directory '(:relative)
:name "system"
;;(string-downcase system-name)
:type "asd" :version nil)
:direction :output
:if-exists :supersede
:if-does-not-exist :create)
#+(or)(push (truename (merge-pathnames
(make-pathname :directory '(:relative)
:name nil :type nil :version nil)
out)) asdf::*central-registry*)
(format out ";; -*- mode:lisp -*-~%")
(mapc
(lambda (sexp) (print sexp out) (terpri out))
;; Out to the asd file:
(append
(unless vanillap
`((defpackage "COM.INFORMATIMAGO.ASDF" (:use "COMMON-LISP"))
(in-package "COM.INFORMATIMAGO.ASDF")
;; ASDF imposes the file type classes to be
;; in the same package as the defsystem.
(unless (handler-case (find-class 'pjb-cl-source-file) (t () nil))
(defclass pjb-cl-source-file (asdf::cl-source-file) ())
(flet ((output-files (c)
(flet ((implementation-id ()
(flet ((first-word (text)
(let ((pos (position (character " ")
text)))
(remove (character ".")
(if pos
(subseq text 0 pos)
text)))))
(format
nil "~A-~A-~A"
(cond
((string-equal
"International Allegro CL Enterprise Edition"
(lisp-implementation-type))
"ACL")
(t (first-word (lisp-implementation-type))))
(first-word (lisp-implementation-version))
(first-word (machine-type))))))
(let* ((object (compile-file-pathname
(asdf::component-pathname c)))
(path (merge-pathnames
(make-pathname
:directory
(list :relative
(format nil "OBJ-~:@(~A~)"
(implementation-id)))
:name (pathname-name object)
:type (pathname-type object))
object)))
(ensure-directories-exist path)
(list path)))))
(defmethod asdf::output-files ((operation asdf::compile-op)
(c pjb-cl-source-file))
(output-files c))
(defmethod asdf::output-files ((operation asdf::load-op)
(c pjb-cl-source-file))
(output-files c))))))
`(,(gen-defsystem-form
system-name
(mapcar
(lambda (source) (make-pathname :name (string-downcase (string source))
:type source-type))
sources)
:description (or description
(format nil
"This ASDF system gathers all the ~A packages."
(string-upcase system-name)))
:version version
:author author
:maintainer author
:licence (or licence license)
:component-class (if vanillap :cl-source-file :pjb-cl-source-file)
:predefined-packages predefined-packages
:implicit-dependencies implicit-dependencies
:depends-on depends-on
:load-paths load-paths)))))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Reading and writing ASD files as sexps.
;;;
(defun read-asdf-system-definitions (stream)
"
Reads an ASD file stream and return a list of asdf:defsystem forms
found.
DEFPACKAGE and IN-PACKAGE forms are evaluated, but IN-PACKAGE forms
are neutralized with a local dynamic binding of *PACKAGE*.
"
(let ((*package* *package*)
(forms (read-source-code stream
:test (lambda (sexp)
(and (consp sexp)
(eql (first sexp) 'asdf:defsystem))))))
(cdr (assoc :test forms))))
(defun find-asd-files (root-directory)
"Returns a list of pathnames to asd files found recursively in the ROOT-DIRECTORY."
(directory (merge-pathnames (make-pathname :directory '(:relative :wild-inferiors)
:name :wild
:type "asd"
:case :local
:defaults root-directory)
root-directory nil)))
(defun asd-systems-in-asd-file (asd-file-pathname)
"
Returns a list of system names found in the asd file ASD-FILE-PATHNAME.
DEFPACKAGE and IN-PACKAGE forms are evaluated, but IN-PACKAGE forms
are neutralized with a local dynamic binding of *PACKAGE*.
"
(with-open-file (stream asd-file-pathname)
(mapcan (lambda (defsystem-form)
(ignore-errors
(destructuring-bind (defsystem name &rest ignored) defsystem-form
(declare (ignore defsystem ignored))
(list (string-downcase name)))))
(read-asdf-system-definitions stream))))
(defun write-asdf-system-definition (stream defsystem-form)
"Writes the defsystem-form to the STREAM."
(pop defsystem-form)
(with-standard-io-syntax
(let ((name (pop defsystem-form))
(description (getf defsystem-form :description))
(author (getf defsystem-form :author))
(maintainer (getf defsystem-form :maintainer))
(licence (or (getf defsystem-form :license) (getf defsystem-form :licence)))
(version (or (getf defsystem-form :version) "1.0.0"))
(properties (getf defsystem-form :properties))
(encoding (getf defsystem-form :encoding))
(depends-on (getf defsystem-form :depends-on))
(perform (getf defsystem-form :perform))
(in-order-to (getf defsystem-form :in-order-to))
(components (getf defsystem-form :components))
(*print-pretty* t)
(*print-case* :downcase))
(format stream "~&(asdf:defsystem ~S" name)
(format stream "~& ;; system attributes:")
(format stream "~& ~15S ~S" :description description)
(format stream "~& ~15S ~S" :author author)
(format stream "~& ~15S ~S" :maintainer (or author maintainer))
(format stream "~& ~15S ~S" :licence licence)
(format stream "~& ;; component attributes:")
(format stream "~& ~15S ~S" :version version)
(format stream "~& ~15S ~S" :properties properties)
(when encoding
(format stream "~& #+asdf-unicode ~S #+asdf-unicode ~S" :encoding encoding))
(format stream "~& ~15S (~{~S~^~%~19<~>~})" :depends-on depends-on)
(format stream "~& ~15S (~{~S~^~%~19<~>~})" :components components)
(when perform
(format stream "~& ~15S (~{~S~^~%~19<~>~})" :perform perform))
(when in-order-to
(format stream "~& ~15S (~{~S~^~%~19<~>~})" :in-order-to in-order-to))
(format stream ")~%")))
defsystem-form)
(defun initials (name)
(coerce (loop
:for word :in (split-sequence #\space name :remove-empty-subseqs t)
:while (alpha-char-p (aref word 0))
:collect (aref word 0)) 'string))
(defun default-headers-for-system (pathname defsystem-form
&key
(default-author "Pascal J. Bourguignon")
(default-email "")
(default-initials "PJB"))
"
RETURN: A p-list containing a default source file header for the
file at PATHNAME containing the DEFSYSTEM-FORM.
"
(flet ((ref (key)
(case key
(:name (second defsystem-form))
(otherwise (getf (cddr defsystem-form) key)))))
(multiple-value-bind (se mi ho da mo ye)
(decode-universal-time (get-universal-time))
(declare (ignore se mi ho))
(list
:file (file-namestring pathname)
:language "Common-Lisp"
:system "None"
:user-interface "None"
:description (append
(list (format nil "This file defines the ~A system." (ref :name)))
(ensure-list (ref :description))
(and (ref :long-description)
(split-sequence #\Newline (ref :long-description))))
:usage '()
:authors (flet ((add-initials (name)
(format nil "<~A> ~A" (initials name) name)))
(if (ref :author)
(mapcar (function add-initials)
(if (ref :maintainer)
(if (string-equal (ref :author) (ref :maintainer))
(ensure-list (ref :author))
(list (ref :author) (ref :maintainer)))
(ensure-list (ref :author))))
(if (ref :maintainer)
(mapcar (function add-initials)
(ensure-list (ref :maintainer)))
(list (format nil "<~A> ~A <~A>"
default-initials
default-author
default-email)))))
:modifications (list
(format nil "~4,'0D-~2,'0D-~2,'0D <~A> Created."
ye mo da default-initials))
:bugs '()
:legal (list
"AGPL3"
""
(format nil "Copyright ~A ~A - ~:*~A" default-author ye)
""
"This program is free software: you can redistribute it and/or modify"
"it under the terms of the GNU Affero General Public License as published by"
"the Free Software Foundation, either version 3 of the License, or"
"(at your option) any later version."
""
"This program is distributed in the hope that it will be useful,"
"but WITHOUT ANY WARRANTY; without even the implied warranty of"
"MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the"
"GNU Affero General Public License for more details."
""
"You should have received a copy of the GNU Affero General Public License"
"along with this program. If not, see </>")))))
(defun save-asdf-system-file (pathname defsystem-form
&key
(external-format :utf-8)
(emacs-head-variables '((:|mode| "lisp") (:|coding| "utf-8")))
(headers '()))
"Saves the DEFSYSTEM-FORM into the ASD file at PATHNAME (superseded)."
(with-open-file (stream pathname
:direction :output
:if-does-not-exist :create
:if-exists :supersede
:external-format external-format)
(write-emacs-head-variables emacs-head-variables stream)
(write-source-header (or headers
(default-headers-for-system pathname defsystem-form))
stream)
(terpri stream)
(write-asdf-system-definition stream defsystem-form)
(format stream "~%;;;; THE END ;;;;~%")))
;; (defun test-system-asd-file-header (pathname def-tested-system)
;; "Returns: headers for"
;; (default-headers-for-system
;; (file-namestring pathname)
( list * ' asdf : ( second tested - system )
;; :description (list "This file defines a system to test the system"
;; (string tested-system))
( tested - system ) ) ) )
(defun test-system-p (defsystem-form)
"Predicate whether DEFSYSTEM-FORM defines a test system
ie. whether the system name ends in \".test\"."
(let ((name (string (second defsystem-form))))
(suffixp ".test" name :test (function char-equal))))
(defun test-system-for-system (defsystem-form)
"
RETURN: A defsystem form for a test system for the system defined by
DEFSYSTEM-FORM.
"
(flet ((ref (key)
(case key
(:name (string-downcase (second defsystem-form)))
(otherwise (getf (cddr defsystem-form) key)))))
(multiple-value-bind (se mi ho da mo ye)
(decode-universal-time (get-universal-time))
(declare (ignore se mi ho da))
(let* ((author-email "")
(date (format nil "~[Winter~;Spring~;Summer~;Automn~] ~D"
(truncate mo 3) ye))
(tested-system-name (ref :name))
(test-system-name (format nil "~A.test" tested-system-name))
(output-directory (format nil "/tmp/documentation/~A/" test-system-name)))
`(asdf:defsystem ,test-system-name
;; system attributes:
:description ,(format nil "Tests the ~A system." tested-system-name)
:long-description ,(or (ref :long-decription) (ref :decription))
:author ,(ref :author)
:maintainer ,(ref :maintainer)
:licence ,(or (ref :licence) (ref :license))
;; component attributes:
:version "1.0.0" ; ,(ref :version)
:properties ((#:author-email . ,author-email)
(#:date . ,date)
((#:albert #:output-dir) . ,output-directory)
((#:albert #:formats) . ("docbook"))
((#:albert #:docbook #:template) . "book")
((#:albert #:docbook #:bgcolor) . "white")
((#:albert #:docbook #:textcolor) . "black"))
:depends-on (,(ref :name)
"com.informatimago.common-lisp.cesarum") ; simple-test
:components ((:file "source-test" :depends-on ()))
#+asdf-unicode :encoding #+asdf-unicode :utf-8
#+asdf3 :perform #+asdf3 (asdf:test-op (cl-user::operation cl-user::system)
(declare (ignore cl-user::operation cl-user::system))
;; template:
(let ((*package* (find-package "TESTED-PACKAGE")))
(uiop:symbol-call "TESTED-PACKAGE" "TEST/ALL"))))))))
(defun generate-test-system-for-system-at-path (asdf-system-pathname
&key (verbose t))
"
Writes asd files defining test systems for each system found in the
asdf file at ASDF-SYSTEM-PATHNAME, unless such a file already exists.
"
(with-open-file (stream asdf-system-pathname)
(when verbose
(format *trace-output* "~&;; Reading system asd file ~A~%" asdf-system-pathname))
(dolist (defsys (read-asdf-system-definitions stream))
(if (test-system-p defsys)
(when verbose
(format *trace-output* "~&;; Already a test system.~%"))
(let* ((test-defsys (test-system-for-system defsys))
(test-pathname (merge-pathnames
(make-pathname :name (string-downcase (second test-defsys))
:type "asd"
:version nil
:case :local)
asdf-system-pathname
nil)))
(if (probe-file test-pathname)
(when verbose
(format *trace-output* "~&;; Test system file ~A already exists.~%" test-pathname))
(progn
(when verbose
(format *trace-output* "~&;; Generating test system asd file ~A~%" test-pathname))
(save-asdf-system-file test-pathname test-defsys
:headers (default-headers-for-system test-pathname test-defsys)))))))))
#-(and) (progn
(default-headers-for-system
"/tmp/a.lisp"
'(asdf:defsystem "com.informatimago.common-lisp.cesarum.test"
;; system attributes:
:description "Tests the cesarum library."
:author "Pascal J. Bourguignon <>"
:maintainer "Pascal J. Bourguignon <>"
:licence "AGPL3"
;; component attributes:
:version "1.3.3"
:properties ((#:author-email . "")
(#:date . "Winter 2015")
((#:albert #:output-dir) . "/tmp/documentation/com.informatimago.common-lisp.cesarum-test/")
((#:albert #:formats) . ("docbook"))
((#:albert #:docbook #:template) . "book")
((#:albert #:docbook #:bgcolor) . "white")
((#:albert #:docbook #:textcolor) . "black"))
:depends-on ("com.informatimago.common-lisp.cesarum")
:components ((:file "set-test" :depends-on ())
(:file "index-set-test" :depends-on ("set-test")))
#+asdf-unicode :encoding #+asdf-unicode :utf-8
#+asdf3 :perform #+asdf3 (asdf:test-op (cl-user::o cl-user::s)
(let ((*package* (find-package "COM.INFORMATIMAGO.COMMON-LISP.CESARUM.SET")))
(uiop:symbol-call "COM.INFORMATIMAGO.COMMON-LISP.CESARUM.SET" "TEST/ALL"))
(let ((*package* (find-package "COM.INFORMATIMAGO.COMMON-LISP.CESARUM.INDEX-SET")))
(uiop:symbol-call "COM.INFORMATIMAGO.COMMON-LISP.CESARUM.INDEX-SET" "TEST/ALL")))))
(map nil (function generate-test-system-for-system-at-path)
(directory #P "~/src/public/lisp/**/*.asd"))
progn
;;;; THE END ;;;;
| null | https://raw.githubusercontent.com/informatimago/lisp/571af24c06ba466e01b4c9483f8bb7690bc46d03/tools/asdf-file.lisp | lisp | coding : utf-8 -*-
**************************************************************************
LANGUAGE: Common-Lisp
SYSTEM: Common-Lisp
DESCRIPTION
Reads ASDF files.
LEGAL
This program is free software: you can redistribute it and/or modify
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
along with this program. If not, see </>.
**************************************************************************
Generating simple ASD files:
Reading and writing asd files:
Generating test systems:
without even the implied warranty of
GENERATE-ASD
(string-downcase system-name)
Out to the asd file:
ASDF imposes the file type classes to be
in the same package as the defsystem.
Reading and writing ASD files as sexps.
(defun test-system-asd-file-header (pathname def-tested-system)
"Returns: headers for"
(default-headers-for-system
(file-namestring pathname)
:description (list "This file defines a system to test the system"
(string tested-system))
system attributes:
component attributes:
,(ref :version)
simple-test
template:
system attributes:
component attributes:
THE END ;;;; | FILE : asdf-file.lisp
USER - INTERFACE :
< PJB > < >
MODIFICATIONS
2014 - 09 - 02 < PJB > Added generate - dot .
2013 - 09 - 06 < PJB > Updated for publication .
2012 - 04 - 09 < PJB > Created .
AGPL3
Copyright 2012 - 2016
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation , either version 3 of the License , or
GNU Affero General Public License for more details .
You should have received a copy of the GNU Affero General Public License
(eval-when (:compile-toplevel :load-toplevel :execute)
(setf *readtable* (copy-readtable nil)))
(defpackage "COM.INFORMATIMAGO.TOOLS.ASDF-FILE"
(:use "COMMON-LISP"
"SPLIT-SEQUENCE"
"COM.INFORMATIMAGO.COMMON-LISP.CESARUM.UTILITY"
"COM.INFORMATIMAGO.COMMON-LISP.CESARUM.LIST"
"COM.INFORMATIMAGO.COMMON-LISP.CESARUM.STRING"
"COM.INFORMATIMAGO.TOOLS.DEPENDENCY-CYCLES"
"COM.INFORMATIMAGO.TOOLS.SOURCE")
(:shadow "DEPENDENCIES")
(:export
"MAKE-COMPONENTS"
"GENERATE-ASD"
"FIND-ASD-FILES"
"ASD-SYSTEMS-IN-ASD-FILE"
"READ-ASDF-SYSTEM-DEFINITIONS"
"WRITE-ASDF-SYSTEM-DEFINITION"
"SAVE-ASDF-SYSTEM-FILE"
"DEFAULT-HEADERS-FOR-SYSTEM"
"TEST-SYSTEM-FOR-SYSTEM"
"TEST-SYSTEM-P"
"TEST-SYSTEM-FOR-SYSTEM"
"GENERATE-TEST-SYSTEM-FOR-SYSTEM-AT-PATH")
(:documentation "
Reads simple .asd files, without instanciating ASDF objects.
============================================================
(LOAD-SIMPLE-ASD-FILE path-to-asd-file)
--> hashtable mapping file names to ASDF-FILE structures.
NOTE: The current implementation expects the defsystem form to be the
first and only form in the asd file.
Generate simple .asd files:
============================================================
(GENERATE-ASD :system-name (list \"source-1\" \"source-2\") \"lisp\"
:description \"Short description\"
:version \"1.0.0\"
:author \"Name <email@address>\"
:license \"AGPL3\"
:predefined-packages '(\"COMMON-LISP\"))
:implicit-dependencies '())
:depends-on '(:other-system))
:load-paths (list (make-pathname :directory '(:relative))))
:vanillap t)
License:
AGPL3
Copyright Pascal J. Bourguignon 2012 - 2014
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see </>.
"))
(in-package "COM.INFORMATIMAGO.TOOLS.ASDF-FILE")
(defun make-components (paths &key (predefined-packages '("COMMON-LISP"))
(component-class :file)
(implicit-dependencies '())
(load-paths (list (make-pathname
:directory '(:relative)))))
(mapcar
(lambda (depend)
(let* ((depend (mapcar (lambda (path) (pathname-name path)) depend))
(target (first depend))
(depends (delete (first depend)
(append implicit-dependencies (rest depend))
:test (function string=))))
(list* component-class target (when depends (list :depends-on depends)))))
(get-depends paths predefined-packages load-paths)))
(defun gen-defsystem-form (name paths &key description (version "0.0.0")
author maintainer licence license
(component-class :file)
(predefined-packages '("COMMON-LISP"))
(implicit-dependencies '())
(depends-on '())
(load-paths (list (make-pathname
:directory '(:relative)))))
"
DO: Generate an ASD file for ASDF.
NAME: Name of the generated ASDF system.
PATHS: List of pathnames to the source files of this ASDF system.
DESCRIPTION: A description string for the ASDF system.
VERSION: A version string for the ASDF system.
AUTHOR: An author string for the ASDF system.
LICENSE: A licence string for the ASDF system.
PREDEFINED-PACKAGES: A list of packages that are removed from the dependencies.
IMPLICIT-DEPENDENCIES: A list of dependencies added to all targets.
LOAD:-PATHS A list of directory paths where the sources are searched in.
"
(flet ((enumerate (list) (format nil "~{~A, ~}~:[none~;~1@*~{~A~^ and ~A~}~]"
(butlast list 2) (last list 2))))
(let* ((headers (mapcar (lambda (path) (list* :path path
(with-open-file (stream path)
(read-source-header stream))))
paths))
(authors (or author
(enumerate (delete-duplicates
(apply (function append)
(mapcar (function header-authors)
headers))
:test (function string-equal)))))
(licence (or licence license
(enumerate (delete-duplicates
(mapcar (function header-licence) headers)
:test (function string-equal)))))
(description
(unsplit-string
(or (ensure-list description)
(mapcan
(lambda (header)
(append (list (format nil "~2%PACKAGE: ~A~2%"
(second
(get-package (header-slot header :path)))))
(mapcar (lambda (line) (format nil "~A~%" line))
(header-description header))
(list (format nil "~%"))))
headers))
" "))
(components (make-components
paths
:component-class component-class
:predefined-packages (append depends-on
predefined-packages)
:implicit-dependencies implicit-dependencies
:load-paths load-paths)))
`(asdf:defsystem ,name
:description ,description
:version ,version
:author ,authors
:maintainer ,maintainer
:licence ,licence
:depends-on ,depends-on
:components ,components))))
(defun generate-asd (system-name sources source-type
&key description (version "0.0.0")
author licence license
(predefined-packages '("COMMON-LISP"))
(implicit-dependencies '())
(depends-on '())
(load-paths (list (make-pathname :directory '(:relative))))
(vanillap t))
"
VANILLAP: if true, then generate a simple, vanilla system.
Otherwise, decorate it with PJB output-files.
"
(let ((*package* (find-package :com.informatimago.tools.make-depends.make-depends)))
(with-open-file (out (make-pathname :directory '(:relative)
:name "system"
:type "asd" :version nil)
:direction :output
:if-exists :supersede
:if-does-not-exist :create)
#+(or)(push (truename (merge-pathnames
(make-pathname :directory '(:relative)
:name nil :type nil :version nil)
out)) asdf::*central-registry*)
(format out ";; -*- mode:lisp -*-~%")
(mapc
(lambda (sexp) (print sexp out) (terpri out))
(append
(unless vanillap
`((defpackage "COM.INFORMATIMAGO.ASDF" (:use "COMMON-LISP"))
(in-package "COM.INFORMATIMAGO.ASDF")
(unless (handler-case (find-class 'pjb-cl-source-file) (t () nil))
(defclass pjb-cl-source-file (asdf::cl-source-file) ())
(flet ((output-files (c)
(flet ((implementation-id ()
(flet ((first-word (text)
(let ((pos (position (character " ")
text)))
(remove (character ".")
(if pos
(subseq text 0 pos)
text)))))
(format
nil "~A-~A-~A"
(cond
((string-equal
"International Allegro CL Enterprise Edition"
(lisp-implementation-type))
"ACL")
(t (first-word (lisp-implementation-type))))
(first-word (lisp-implementation-version))
(first-word (machine-type))))))
(let* ((object (compile-file-pathname
(asdf::component-pathname c)))
(path (merge-pathnames
(make-pathname
:directory
(list :relative
(format nil "OBJ-~:@(~A~)"
(implementation-id)))
:name (pathname-name object)
:type (pathname-type object))
object)))
(ensure-directories-exist path)
(list path)))))
(defmethod asdf::output-files ((operation asdf::compile-op)
(c pjb-cl-source-file))
(output-files c))
(defmethod asdf::output-files ((operation asdf::load-op)
(c pjb-cl-source-file))
(output-files c))))))
`(,(gen-defsystem-form
system-name
(mapcar
(lambda (source) (make-pathname :name (string-downcase (string source))
:type source-type))
sources)
:description (or description
(format nil
"This ASDF system gathers all the ~A packages."
(string-upcase system-name)))
:version version
:author author
:maintainer author
:licence (or licence license)
:component-class (if vanillap :cl-source-file :pjb-cl-source-file)
:predefined-packages predefined-packages
:implicit-dependencies implicit-dependencies
:depends-on depends-on
:load-paths load-paths)))))))
(defun read-asdf-system-definitions (stream)
"
Reads an ASD file stream and return a list of asdf:defsystem forms
found.
DEFPACKAGE and IN-PACKAGE forms are evaluated, but IN-PACKAGE forms
are neutralized with a local dynamic binding of *PACKAGE*.
"
(let ((*package* *package*)
(forms (read-source-code stream
:test (lambda (sexp)
(and (consp sexp)
(eql (first sexp) 'asdf:defsystem))))))
(cdr (assoc :test forms))))
(defun find-asd-files (root-directory)
"Returns a list of pathnames to asd files found recursively in the ROOT-DIRECTORY."
(directory (merge-pathnames (make-pathname :directory '(:relative :wild-inferiors)
:name :wild
:type "asd"
:case :local
:defaults root-directory)
root-directory nil)))
(defun asd-systems-in-asd-file (asd-file-pathname)
"
Returns a list of system names found in the asd file ASD-FILE-PATHNAME.
DEFPACKAGE and IN-PACKAGE forms are evaluated, but IN-PACKAGE forms
are neutralized with a local dynamic binding of *PACKAGE*.
"
(with-open-file (stream asd-file-pathname)
(mapcan (lambda (defsystem-form)
(ignore-errors
(destructuring-bind (defsystem name &rest ignored) defsystem-form
(declare (ignore defsystem ignored))
(list (string-downcase name)))))
(read-asdf-system-definitions stream))))
(defun write-asdf-system-definition (stream defsystem-form)
"Writes the defsystem-form to the STREAM."
(pop defsystem-form)
(with-standard-io-syntax
(let ((name (pop defsystem-form))
(description (getf defsystem-form :description))
(author (getf defsystem-form :author))
(maintainer (getf defsystem-form :maintainer))
(licence (or (getf defsystem-form :license) (getf defsystem-form :licence)))
(version (or (getf defsystem-form :version) "1.0.0"))
(properties (getf defsystem-form :properties))
(encoding (getf defsystem-form :encoding))
(depends-on (getf defsystem-form :depends-on))
(perform (getf defsystem-form :perform))
(in-order-to (getf defsystem-form :in-order-to))
(components (getf defsystem-form :components))
(*print-pretty* t)
(*print-case* :downcase))
(format stream "~&(asdf:defsystem ~S" name)
(format stream "~& ;; system attributes:")
(format stream "~& ~15S ~S" :description description)
(format stream "~& ~15S ~S" :author author)
(format stream "~& ~15S ~S" :maintainer (or author maintainer))
(format stream "~& ~15S ~S" :licence licence)
(format stream "~& ;; component attributes:")
(format stream "~& ~15S ~S" :version version)
(format stream "~& ~15S ~S" :properties properties)
(when encoding
(format stream "~& #+asdf-unicode ~S #+asdf-unicode ~S" :encoding encoding))
(format stream "~& ~15S (~{~S~^~%~19<~>~})" :depends-on depends-on)
(format stream "~& ~15S (~{~S~^~%~19<~>~})" :components components)
(when perform
(format stream "~& ~15S (~{~S~^~%~19<~>~})" :perform perform))
(when in-order-to
(format stream "~& ~15S (~{~S~^~%~19<~>~})" :in-order-to in-order-to))
(format stream ")~%")))
defsystem-form)
(defun initials (name)
(coerce (loop
:for word :in (split-sequence #\space name :remove-empty-subseqs t)
:while (alpha-char-p (aref word 0))
:collect (aref word 0)) 'string))
(defun default-headers-for-system (pathname defsystem-form
&key
(default-author "Pascal J. Bourguignon")
(default-email "")
(default-initials "PJB"))
"
RETURN: A p-list containing a default source file header for the
file at PATHNAME containing the DEFSYSTEM-FORM.
"
(flet ((ref (key)
(case key
(:name (second defsystem-form))
(otherwise (getf (cddr defsystem-form) key)))))
(multiple-value-bind (se mi ho da mo ye)
(decode-universal-time (get-universal-time))
(declare (ignore se mi ho))
(list
:file (file-namestring pathname)
:language "Common-Lisp"
:system "None"
:user-interface "None"
:description (append
(list (format nil "This file defines the ~A system." (ref :name)))
(ensure-list (ref :description))
(and (ref :long-description)
(split-sequence #\Newline (ref :long-description))))
:usage '()
:authors (flet ((add-initials (name)
(format nil "<~A> ~A" (initials name) name)))
(if (ref :author)
(mapcar (function add-initials)
(if (ref :maintainer)
(if (string-equal (ref :author) (ref :maintainer))
(ensure-list (ref :author))
(list (ref :author) (ref :maintainer)))
(ensure-list (ref :author))))
(if (ref :maintainer)
(mapcar (function add-initials)
(ensure-list (ref :maintainer)))
(list (format nil "<~A> ~A <~A>"
default-initials
default-author
default-email)))))
:modifications (list
(format nil "~4,'0D-~2,'0D-~2,'0D <~A> Created."
ye mo da default-initials))
:bugs '()
:legal (list
"AGPL3"
""
(format nil "Copyright ~A ~A - ~:*~A" default-author ye)
""
"This program is free software: you can redistribute it and/or modify"
"it under the terms of the GNU Affero General Public License as published by"
"the Free Software Foundation, either version 3 of the License, or"
"(at your option) any later version."
""
"This program is distributed in the hope that it will be useful,"
"but WITHOUT ANY WARRANTY; without even the implied warranty of"
"MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the"
"GNU Affero General Public License for more details."
""
"You should have received a copy of the GNU Affero General Public License"
"along with this program. If not, see </>")))))
(defun save-asdf-system-file (pathname defsystem-form
&key
(external-format :utf-8)
(emacs-head-variables '((:|mode| "lisp") (:|coding| "utf-8")))
(headers '()))
"Saves the DEFSYSTEM-FORM into the ASD file at PATHNAME (superseded)."
(with-open-file (stream pathname
:direction :output
:if-does-not-exist :create
:if-exists :supersede
:external-format external-format)
(write-emacs-head-variables emacs-head-variables stream)
(write-source-header (or headers
(default-headers-for-system pathname defsystem-form))
stream)
(terpri stream)
(write-asdf-system-definition stream defsystem-form)
(format stream "~%;;;; THE END ;;;;~%")))
( list * ' asdf : ( second tested - system )
( tested - system ) ) ) )
(defun test-system-p (defsystem-form)
"Predicate whether DEFSYSTEM-FORM defines a test system
ie. whether the system name ends in \".test\"."
(let ((name (string (second defsystem-form))))
(suffixp ".test" name :test (function char-equal))))
(defun test-system-for-system (defsystem-form)
"
RETURN: A defsystem form for a test system for the system defined by
DEFSYSTEM-FORM.
"
(flet ((ref (key)
(case key
(:name (string-downcase (second defsystem-form)))
(otherwise (getf (cddr defsystem-form) key)))))
(multiple-value-bind (se mi ho da mo ye)
(decode-universal-time (get-universal-time))
(declare (ignore se mi ho da))
(let* ((author-email "")
(date (format nil "~[Winter~;Spring~;Summer~;Automn~] ~D"
(truncate mo 3) ye))
(tested-system-name (ref :name))
(test-system-name (format nil "~A.test" tested-system-name))
(output-directory (format nil "/tmp/documentation/~A/" test-system-name)))
`(asdf:defsystem ,test-system-name
:description ,(format nil "Tests the ~A system." tested-system-name)
:long-description ,(or (ref :long-decription) (ref :decription))
:author ,(ref :author)
:maintainer ,(ref :maintainer)
:licence ,(or (ref :licence) (ref :license))
:properties ((#:author-email . ,author-email)
(#:date . ,date)
((#:albert #:output-dir) . ,output-directory)
((#:albert #:formats) . ("docbook"))
((#:albert #:docbook #:template) . "book")
((#:albert #:docbook #:bgcolor) . "white")
((#:albert #:docbook #:textcolor) . "black"))
:depends-on (,(ref :name)
:components ((:file "source-test" :depends-on ()))
#+asdf-unicode :encoding #+asdf-unicode :utf-8
#+asdf3 :perform #+asdf3 (asdf:test-op (cl-user::operation cl-user::system)
(declare (ignore cl-user::operation cl-user::system))
(let ((*package* (find-package "TESTED-PACKAGE")))
(uiop:symbol-call "TESTED-PACKAGE" "TEST/ALL"))))))))
(defun generate-test-system-for-system-at-path (asdf-system-pathname
&key (verbose t))
"
Writes asd files defining test systems for each system found in the
asdf file at ASDF-SYSTEM-PATHNAME, unless such a file already exists.
"
(with-open-file (stream asdf-system-pathname)
(when verbose
(format *trace-output* "~&;; Reading system asd file ~A~%" asdf-system-pathname))
(dolist (defsys (read-asdf-system-definitions stream))
(if (test-system-p defsys)
(when verbose
(format *trace-output* "~&;; Already a test system.~%"))
(let* ((test-defsys (test-system-for-system defsys))
(test-pathname (merge-pathnames
(make-pathname :name (string-downcase (second test-defsys))
:type "asd"
:version nil
:case :local)
asdf-system-pathname
nil)))
(if (probe-file test-pathname)
(when verbose
(format *trace-output* "~&;; Test system file ~A already exists.~%" test-pathname))
(progn
(when verbose
(format *trace-output* "~&;; Generating test system asd file ~A~%" test-pathname))
(save-asdf-system-file test-pathname test-defsys
:headers (default-headers-for-system test-pathname test-defsys)))))))))
#-(and) (progn
(default-headers-for-system
"/tmp/a.lisp"
'(asdf:defsystem "com.informatimago.common-lisp.cesarum.test"
:description "Tests the cesarum library."
:author "Pascal J. Bourguignon <>"
:maintainer "Pascal J. Bourguignon <>"
:licence "AGPL3"
:version "1.3.3"
:properties ((#:author-email . "")
(#:date . "Winter 2015")
((#:albert #:output-dir) . "/tmp/documentation/com.informatimago.common-lisp.cesarum-test/")
((#:albert #:formats) . ("docbook"))
((#:albert #:docbook #:template) . "book")
((#:albert #:docbook #:bgcolor) . "white")
((#:albert #:docbook #:textcolor) . "black"))
:depends-on ("com.informatimago.common-lisp.cesarum")
:components ((:file "set-test" :depends-on ())
(:file "index-set-test" :depends-on ("set-test")))
#+asdf-unicode :encoding #+asdf-unicode :utf-8
#+asdf3 :perform #+asdf3 (asdf:test-op (cl-user::o cl-user::s)
(let ((*package* (find-package "COM.INFORMATIMAGO.COMMON-LISP.CESARUM.SET")))
(uiop:symbol-call "COM.INFORMATIMAGO.COMMON-LISP.CESARUM.SET" "TEST/ALL"))
(let ((*package* (find-package "COM.INFORMATIMAGO.COMMON-LISP.CESARUM.INDEX-SET")))
(uiop:symbol-call "COM.INFORMATIMAGO.COMMON-LISP.CESARUM.INDEX-SET" "TEST/ALL")))))
(map nil (function generate-test-system-for-system-at-path)
(directory #P "~/src/public/lisp/**/*.asd"))
progn
|
275c76e7525fc2a9dbea8f9d494f86c912fa2c402d0e97ee6dfd33ab5ba90963 | dongcarl/guix | selinux.scm | ;;; GNU Guix --- Functional package management for GNU
Copyright © 2016 , 2017 , 2018 < >
Copyright © 2018 < >
Copyright © 2019 , 2020 < >
;;;
;;; 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 selinux)
#:use-module ((guix licenses) #:prefix license:)
#:use-module (guix packages)
#:use-module (guix download)
#:use-module (guix git-download)
#:use-module (guix utils)
#:use-module (guix build-system gnu)
#:use-module (guix build-system python)
#:use-module (gnu packages)
#:use-module (gnu packages admin)
#:use-module (gnu packages bison)
#:use-module (gnu packages docbook)
#:use-module (gnu packages flex)
#:use-module (gnu packages gettext)
#:use-module (gnu packages glib)
#:use-module (gnu packages linux)
#:use-module (gnu packages networking)
#:use-module (gnu packages pcre)
#:use-module (gnu packages pkg-config)
#:use-module (gnu packages python)
#:use-module (gnu packages python-xyz)
#:use-module (gnu packages swig)
#:use-module (gnu packages xml))
;; Update the SELinux packages together!
(define-public libsepol
(package
(name "libsepol")
(version "3.0")
(source (let ((release "20191204"))
(origin
(method git-fetch)
(uri (git-reference
(url "")
(commit release)))
(file-name (string-append "selinux-" release "-checkout"))
(sha256
(base32
"05rpzm72cgprd0ccr6lvx9hm8j8b5nkqi4avshlsyg7s3sdlcxjs")))))
(build-system gnu-build-system)
(arguments
tests require , which requires libsepol
#:test-target "test"
#:make-flags
(let ((out (assoc-ref %outputs "out"))
(target ,(%current-target-system)))
(list (string-append "PREFIX=" out)
(string-append "SHLIBDIR=" out "/lib")
(string-append "MAN3DIR=" out "/share/man/man3")
(string-append "MAN5DIR=" out "/share/man/man5")
(string-append "MAN8DIR=" out "/share/man/man8")
(string-append "LDFLAGS=-Wl,-rpath=" out "/lib")
(string-append "CC="
(if target
(string-append (assoc-ref %build-inputs "cross-gcc")
"/bin/" target "-gcc")
"gcc"))))
#:phases
(modify-phases %standard-phases
(delete 'configure)
(add-after 'unpack 'enter-dir
(lambda _ (chdir ,name) #t))
(add-after 'enter-dir 'portability
(lambda _
(substitute* "src/ibpkeys.c"
(("#include \"ibpkey_internal.h\"" line)
(string-append line "\n#include <inttypes.h>\n"))
(("%#lx") "%#\" PRIx64 \""))
#t)))))
(native-inputs
`(("flex" ,flex)))
(home-page "/")
(synopsis "Library for manipulating SELinux policies")
(description
"The libsepol library provides an API for the manipulation of SELinux
binary policies. It is used by @code{checkpolicy} (the policy compiler) and
similar tools, and programs such as @code{load_policy}, which must perform
specific transformations on binary policies (for example, customizing policy
boolean settings).")
(license license:lgpl2.1+)))
(define-public checkpolicy
(package/inherit libsepol
(name "checkpolicy")
(arguments
`(#:tests? #f ; there is no check target
#:make-flags
(let ((out (assoc-ref %outputs "out"))
(target ,(%current-target-system)))
(list (string-append "PREFIX=" out)
(string-append "LIBSEPOLA="
(assoc-ref %build-inputs "libsepol")
"/lib/libsepol.a")
(string-append "CC="
(if target
(string-append (assoc-ref %build-inputs "cross-gcc")
"/bin/" target "-gcc")
"gcc"))))
#:phases
(modify-phases %standard-phases
(delete 'configure)
(delete 'portability)
(add-after 'unpack 'enter-dir
(lambda _ (chdir ,name) #t)))))
(inputs
`(("libsepol" ,libsepol)))
(native-inputs
`(("bison" ,bison)
("flex" ,flex)))
(synopsis "Check SELinux security policy configurations and modules")
(description
"This package provides the tools \"checkpolicy\" and \"checkmodule\".
Checkpolicy is a program that checks and compiles a SELinux security policy
configuration into a binary representation that can be loaded into the kernel.
Checkmodule is a program that checks and compiles a SELinux security policy
module into a binary representation.")
;; GPLv2 only
(license license:gpl2)))
(define-public libselinux
(package/inherit libsepol
(name "libselinux")
(outputs '("out" "python"))
(arguments
(substitute-keyword-arguments (package-arguments libsepol)
((#:make-flags flags)
`(cons* "PYTHON=python3"
(string-append "LIBSEPOLA="
(assoc-ref %build-inputs "libsepol")
"/lib/libsepol.a")
(string-append "PYTHONLIBDIR="
(assoc-ref %outputs "python")
"/lib/python"
,(version-major+minor (package-version python))
"/site-packages/")
,flags))
((#:phases phases)
`(modify-phases ,phases
(delete 'portability)
(replace 'enter-dir
(lambda _ (chdir ,name) #t))
(add-after 'build 'pywrap
(lambda* (#:key make-flags #:allow-other-keys)
(apply invoke "make" "pywrap" make-flags)))
(add-after 'install 'install-pywrap
(lambda* (#:key make-flags outputs #:allow-other-keys)
;; The build system uses "python setup.py install" to install
;; Python bindings. Instruct it to use the correct output.
(substitute* "src/Makefile"
(("--prefix=\\$\\(PREFIX\\)")
(string-append "--prefix=" (assoc-ref outputs "python"))))
(apply invoke "make" "install-pywrap" make-flags)))))))
These libraries are in " Requires.private " in libselinux.pc .
(propagated-inputs
`(("libsepol" ,libsepol)
("pcre" ,pcre)))
For pywrap phase
(inputs
`(("python" ,python-wrapper)))
These inputs are only needed for the pywrap phase .
(native-inputs
`(("swig" ,swig)
("pkg-config" ,pkg-config)))
(synopsis "SELinux core libraries and utilities")
(description
"The libselinux library provides an API for SELinux applications to get
and set process and file security contexts, and to obtain security policy
decisions. It is required for any applications that use the SELinux API, and
used by all applications that are SELinux-aware. This package also includes
the core SELinux management utilities.")
(license license:public-domain)))
(define-public libsemanage
(package/inherit libsepol
(name "libsemanage")
(arguments
(substitute-keyword-arguments (package-arguments libsepol)
((#:make-flags flags)
`(cons* "PYTHON=python3"
(string-append "PYTHONLIBDIR="
(assoc-ref %outputs "out")
"/lib/python"
,(version-major+minor (package-version python))
"/site-packages/")
,flags))
((#:phases phases)
`(modify-phases ,phases
(delete 'portability)
(replace 'enter-dir
(lambda _ (chdir ,name) #t))
(add-before 'install 'adjust-semanage-conf-location
(lambda _
(substitute* "src/Makefile"
(("DEFAULT_SEMANAGE_CONF_LOCATION=/etc")
"DEFAULT_SEMANAGE_CONF_LOCATION=$(PREFIX)/etc"))
#t))
(add-after 'build 'pywrap
(lambda* (#:key make-flags #:allow-other-keys)
(apply invoke "make" "pywrap" make-flags)))
(add-after 'install 'install-pywrap
(lambda* (#:key make-flags #:allow-other-keys)
(apply invoke "make" "install-pywrap" make-flags)))))))
(inputs
`(("libsepol" ,libsepol)
("libselinux" ,libselinux)
("audit" ,audit)
For pywrap phase
("python" ,python-wrapper)))
(native-inputs
`(("bison" ,bison)
("flex" ,flex)
For pywrap phase
("swig" ,swig)
("pkg-config" ,pkg-config)))
(synopsis "SELinux policy management libraries")
(description
"The libsemanage library provides an API for the manipulation of SELinux
binary policies.")
(license license:lgpl2.1+)))
(define-public secilc
(package/inherit libsepol
(name "secilc")
(arguments
(substitute-keyword-arguments (package-arguments libsepol)
((#:make-flags flags)
`(let ((docbook (assoc-ref %build-inputs "docbook-xsl")))
(cons (string-append "XMLTO=xmlto --skip-validation -x "
docbook "/xml/xsl/docbook-xsl-"
,(package-version docbook-xsl)
"/manpages/docbook.xsl")
,flags)))
((#:phases phases)
`(modify-phases ,phases
(delete 'portability)
(replace 'enter-dir
(lambda _ (chdir ,name) #t))))))
(inputs
`(("libsepol" ,libsepol)))
(native-inputs
`(("xmlto" ,xmlto)
("docbook-xsl" ,docbook-xsl)))
(synopsis "SELinux common intermediate language (CIL) compiler")
(description "The SELinux CIL compiler is a compiler that converts the
@dfn{common intermediate language} (CIL) into a kernel binary policy file.")
(license license:bsd-2)))
(define-public python-sepolgen
(package/inherit libsepol
(name "python-sepolgen")
(arguments
`(#:modules ((srfi srfi-1)
(guix build gnu-build-system)
(guix build utils))
,@(substitute-keyword-arguments (package-arguments libsepol)
((#:phases phases)
`(modify-phases ,phases
(delete 'portability)
(replace 'enter-dir
(lambda _ (chdir "python/sepolgen") #t))
;; By default all Python files would be installed to
;; $out/gnu/store/...-python-.../, so we override the
;; PACKAGEDIR to fix this.
(add-after 'enter-dir 'fix-target-path
(lambda* (#:key inputs outputs #:allow-other-keys)
(let ((get-python-version
FIXME : copied from python - build - system
(lambda (python)
(let* ((version (last (string-split python #\-)))
(components (string-split version #\.))
(major+minor (take components 2)))
(string-join major+minor ".")))))
(substitute* "src/sepolgen/Makefile"
(("^PACKAGEDIR.*")
(string-append "PACKAGEDIR="
(assoc-ref outputs "out")
"/lib/python"
(get-python-version
(assoc-ref inputs "python"))
"/site-packages/sepolgen")))
(substitute* "src/share/Makefile"
(("\\$\\(DESTDIR\\)") (assoc-ref outputs "out"))))
#t)))))))
(inputs
`(("python" ,python-wrapper)))
(native-inputs '())
(synopsis "Python module for generating SELinux policies")
(description
"This package contains a Python module that forms the core of
@code{audit2allow}, a part of the package @code{policycoreutils}. The
sepolgen library contains: Reference Policy Representation, which are Objects
for representing policies and the reference policy interfaces. It has objects
and algorithms for representing access and sets of access in an abstract way
and searching that access. It also has a parser for reference policy
\"headers\". It contains infrastructure for parsing SELinux related messages
as produced by the audit system. It has facilities for generating policy
based on required access.")
;; GPLv2 only
(license license:gpl2)))
(define-public python-setools
(package
(name "python-setools")
(version "4.1.1")
(source (origin
(method git-fetch)
(uri (git-reference
(url "")
(commit version)))
(file-name (string-append name "-" version "-checkout"))
(sha256
(base32
"0459xxly6zzqc5azcwk3rbbcxvj60dq08f8z6xr05y7dsbb16cg6"))))
(build-system python-build-system)
(arguments
`(#:tests? #f ; the test target causes a rebuild
#:phases
(modify-phases %standard-phases
(delete 'portability)
(add-after 'unpack 'set-SEPOL-variable
(lambda* (#:key inputs #:allow-other-keys)
(setenv "SEPOL"
(string-append (assoc-ref inputs "libsepol")
"/lib/libsepol.a"))))
(add-after 'unpack 'remove-Werror
(lambda _
(substitute* "setup.py"
(("'-Werror',") ""))
#t))
(add-after 'unpack 'fix-target-paths
(lambda* (#:key outputs #:allow-other-keys)
(substitute* "setup.py"
(("join\\(sys.prefix")
(string-append "join(\"" (assoc-ref outputs "out") "/\"")))
#t)))))
(propagated-inputs
`(("python-networkx" ,python-networkx)))
(inputs
`(("libsepol" ,libsepol)
("libselinux" ,libselinux)))
(native-inputs
`(("bison" ,bison)
("flex" ,flex)
("swig" ,swig)))
(home-page "")
(synopsis "Tools for SELinux policy analysis")
(description "SETools is a collection of graphical tools, command-line
tools, and libraries designed to facilitate SELinux policy analysis.")
;; Some programs are under GPL, all libraries under LGPL.
(license (list license:lgpl2.1+
license:gpl2+))))
(define-public policycoreutils
(package/inherit libsepol
(name "policycoreutils")
(arguments
`(#:test-target "test"
#:make-flags
(let ((out (assoc-ref %outputs "out")))
(list "CC=gcc"
(string-append "PREFIX=" out)
(string-append "LOCALEDIR=" out "/share/locale")
(string-append "BASHCOMPLETIONDIR=" out
"/share/bash-completion/completions")
"INSTALL=install -c -p"
"INSTALL_DIR=install -d"
;; These ones are needed because some Makefiles define the
;; directories relative to DESTDIR, not relative to PREFIX.
(string-append "SBINDIR=" out "/sbin")
(string-append "ETCDIR=" out "/etc")
(string-append "SYSCONFDIR=" out "/etc/sysconfig")
(string-append "MAN5DIR=" out "/share/man/man5")
(string-append "INSTALL_NLS_DIR=" out "/share/locale")
(string-append "AUTOSTARTDIR=" out "/etc/xdg/autostart")
(string-append "DBUSSERVICEDIR=" out "/share/dbus-1/services")
(string-append "SYSTEMDDIR=" out "/lib/systemd")
(string-append "INITDIR=" out "/etc/rc.d/init.d")
(string-append "SELINUXDIR=" out "/etc/selinux")))
#:phases
(modify-phases %standard-phases
(delete 'configure)
(delete 'portability)
(add-after 'unpack 'enter-dir
(lambda _ (chdir ,name) #t))
(add-after 'enter-dir 'ignore-/usr-tests
(lambda* (#:key inputs #:allow-other-keys)
;; Rewrite lookup paths for header files.
(substitute* '("newrole/Makefile"
"setfiles/Makefile"
"run_init/Makefile")
(("/usr(/include/security/pam_appl.h)" _ file)
(string-append (assoc-ref inputs "pam") file))
(("/usr(/include/libaudit.h)" _ file)
(string-append (assoc-ref inputs "audit") file)))
#t)))))
(inputs
`(("audit" ,audit)
("pam" ,linux-pam)
("libsepol" ,libsepol)
("libselinux" ,libselinux)
("libsemanage" ,libsemanage)))
(native-inputs
`(("gettext" ,gettext-minimal)))
(synopsis "SELinux core utilities")
(description "The policycoreutils package contains the core utilities that
are required for the basic operation of an SELinux-enabled GNU system and its
policies. These utilities include @code{load_policy} to load policies,
@code{setfiles} to label file systems, @code{newrole} to switch roles, and
@code{run_init} to run service scripts in their proper context.")
(license license:gpl2+)))
| null | https://raw.githubusercontent.com/dongcarl/guix/82543e9649da2da9a5285ede4ec4f718fd740fcb/gnu/packages/selinux.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.
Update the SELinux packages together!
there is no check target
GPLv2 only
The build system uses "python setup.py install" to install
Python bindings. Instruct it to use the correct output.
By default all Python files would be installed to
$out/gnu/store/...-python-.../, so we override the
PACKAGEDIR to fix this.
GPLv2 only
the test target causes a rebuild
Some programs are under GPL, all libraries under LGPL.
These ones are needed because some Makefiles define the
directories relative to DESTDIR, not relative to PREFIX.
Rewrite lookup paths for header files. | Copyright © 2016 , 2017 , 2018 < >
Copyright © 2018 < >
Copyright © 2019 , 2020 < >
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 selinux)
#:use-module ((guix licenses) #:prefix license:)
#:use-module (guix packages)
#:use-module (guix download)
#:use-module (guix git-download)
#:use-module (guix utils)
#:use-module (guix build-system gnu)
#:use-module (guix build-system python)
#:use-module (gnu packages)
#:use-module (gnu packages admin)
#:use-module (gnu packages bison)
#:use-module (gnu packages docbook)
#:use-module (gnu packages flex)
#:use-module (gnu packages gettext)
#:use-module (gnu packages glib)
#:use-module (gnu packages linux)
#:use-module (gnu packages networking)
#:use-module (gnu packages pcre)
#:use-module (gnu packages pkg-config)
#:use-module (gnu packages python)
#:use-module (gnu packages python-xyz)
#:use-module (gnu packages swig)
#:use-module (gnu packages xml))
(define-public libsepol
(package
(name "libsepol")
(version "3.0")
(source (let ((release "20191204"))
(origin
(method git-fetch)
(uri (git-reference
(url "")
(commit release)))
(file-name (string-append "selinux-" release "-checkout"))
(sha256
(base32
"05rpzm72cgprd0ccr6lvx9hm8j8b5nkqi4avshlsyg7s3sdlcxjs")))))
(build-system gnu-build-system)
(arguments
tests require , which requires libsepol
#:test-target "test"
#:make-flags
(let ((out (assoc-ref %outputs "out"))
(target ,(%current-target-system)))
(list (string-append "PREFIX=" out)
(string-append "SHLIBDIR=" out "/lib")
(string-append "MAN3DIR=" out "/share/man/man3")
(string-append "MAN5DIR=" out "/share/man/man5")
(string-append "MAN8DIR=" out "/share/man/man8")
(string-append "LDFLAGS=-Wl,-rpath=" out "/lib")
(string-append "CC="
(if target
(string-append (assoc-ref %build-inputs "cross-gcc")
"/bin/" target "-gcc")
"gcc"))))
#:phases
(modify-phases %standard-phases
(delete 'configure)
(add-after 'unpack 'enter-dir
(lambda _ (chdir ,name) #t))
(add-after 'enter-dir 'portability
(lambda _
(substitute* "src/ibpkeys.c"
(("#include \"ibpkey_internal.h\"" line)
(string-append line "\n#include <inttypes.h>\n"))
(("%#lx") "%#\" PRIx64 \""))
#t)))))
(native-inputs
`(("flex" ,flex)))
(home-page "/")
(synopsis "Library for manipulating SELinux policies")
(description
"The libsepol library provides an API for the manipulation of SELinux
binary policies. It is used by @code{checkpolicy} (the policy compiler) and
similar tools, and programs such as @code{load_policy}, which must perform
specific transformations on binary policies (for example, customizing policy
boolean settings).")
(license license:lgpl2.1+)))
(define-public checkpolicy
(package/inherit libsepol
(name "checkpolicy")
(arguments
#:make-flags
(let ((out (assoc-ref %outputs "out"))
(target ,(%current-target-system)))
(list (string-append "PREFIX=" out)
(string-append "LIBSEPOLA="
(assoc-ref %build-inputs "libsepol")
"/lib/libsepol.a")
(string-append "CC="
(if target
(string-append (assoc-ref %build-inputs "cross-gcc")
"/bin/" target "-gcc")
"gcc"))))
#:phases
(modify-phases %standard-phases
(delete 'configure)
(delete 'portability)
(add-after 'unpack 'enter-dir
(lambda _ (chdir ,name) #t)))))
(inputs
`(("libsepol" ,libsepol)))
(native-inputs
`(("bison" ,bison)
("flex" ,flex)))
(synopsis "Check SELinux security policy configurations and modules")
(description
"This package provides the tools \"checkpolicy\" and \"checkmodule\".
Checkpolicy is a program that checks and compiles a SELinux security policy
configuration into a binary representation that can be loaded into the kernel.
Checkmodule is a program that checks and compiles a SELinux security policy
module into a binary representation.")
(license license:gpl2)))
(define-public libselinux
(package/inherit libsepol
(name "libselinux")
(outputs '("out" "python"))
(arguments
(substitute-keyword-arguments (package-arguments libsepol)
((#:make-flags flags)
`(cons* "PYTHON=python3"
(string-append "LIBSEPOLA="
(assoc-ref %build-inputs "libsepol")
"/lib/libsepol.a")
(string-append "PYTHONLIBDIR="
(assoc-ref %outputs "python")
"/lib/python"
,(version-major+minor (package-version python))
"/site-packages/")
,flags))
((#:phases phases)
`(modify-phases ,phases
(delete 'portability)
(replace 'enter-dir
(lambda _ (chdir ,name) #t))
(add-after 'build 'pywrap
(lambda* (#:key make-flags #:allow-other-keys)
(apply invoke "make" "pywrap" make-flags)))
(add-after 'install 'install-pywrap
(lambda* (#:key make-flags outputs #:allow-other-keys)
(substitute* "src/Makefile"
(("--prefix=\\$\\(PREFIX\\)")
(string-append "--prefix=" (assoc-ref outputs "python"))))
(apply invoke "make" "install-pywrap" make-flags)))))))
These libraries are in " Requires.private " in libselinux.pc .
(propagated-inputs
`(("libsepol" ,libsepol)
("pcre" ,pcre)))
For pywrap phase
(inputs
`(("python" ,python-wrapper)))
These inputs are only needed for the pywrap phase .
(native-inputs
`(("swig" ,swig)
("pkg-config" ,pkg-config)))
(synopsis "SELinux core libraries and utilities")
(description
"The libselinux library provides an API for SELinux applications to get
and set process and file security contexts, and to obtain security policy
decisions. It is required for any applications that use the SELinux API, and
used by all applications that are SELinux-aware. This package also includes
the core SELinux management utilities.")
(license license:public-domain)))
(define-public libsemanage
(package/inherit libsepol
(name "libsemanage")
(arguments
(substitute-keyword-arguments (package-arguments libsepol)
((#:make-flags flags)
`(cons* "PYTHON=python3"
(string-append "PYTHONLIBDIR="
(assoc-ref %outputs "out")
"/lib/python"
,(version-major+minor (package-version python))
"/site-packages/")
,flags))
((#:phases phases)
`(modify-phases ,phases
(delete 'portability)
(replace 'enter-dir
(lambda _ (chdir ,name) #t))
(add-before 'install 'adjust-semanage-conf-location
(lambda _
(substitute* "src/Makefile"
(("DEFAULT_SEMANAGE_CONF_LOCATION=/etc")
"DEFAULT_SEMANAGE_CONF_LOCATION=$(PREFIX)/etc"))
#t))
(add-after 'build 'pywrap
(lambda* (#:key make-flags #:allow-other-keys)
(apply invoke "make" "pywrap" make-flags)))
(add-after 'install 'install-pywrap
(lambda* (#:key make-flags #:allow-other-keys)
(apply invoke "make" "install-pywrap" make-flags)))))))
(inputs
`(("libsepol" ,libsepol)
("libselinux" ,libselinux)
("audit" ,audit)
For pywrap phase
("python" ,python-wrapper)))
(native-inputs
`(("bison" ,bison)
("flex" ,flex)
For pywrap phase
("swig" ,swig)
("pkg-config" ,pkg-config)))
(synopsis "SELinux policy management libraries")
(description
"The libsemanage library provides an API for the manipulation of SELinux
binary policies.")
(license license:lgpl2.1+)))
(define-public secilc
(package/inherit libsepol
(name "secilc")
(arguments
(substitute-keyword-arguments (package-arguments libsepol)
((#:make-flags flags)
`(let ((docbook (assoc-ref %build-inputs "docbook-xsl")))
(cons (string-append "XMLTO=xmlto --skip-validation -x "
docbook "/xml/xsl/docbook-xsl-"
,(package-version docbook-xsl)
"/manpages/docbook.xsl")
,flags)))
((#:phases phases)
`(modify-phases ,phases
(delete 'portability)
(replace 'enter-dir
(lambda _ (chdir ,name) #t))))))
(inputs
`(("libsepol" ,libsepol)))
(native-inputs
`(("xmlto" ,xmlto)
("docbook-xsl" ,docbook-xsl)))
(synopsis "SELinux common intermediate language (CIL) compiler")
(description "The SELinux CIL compiler is a compiler that converts the
@dfn{common intermediate language} (CIL) into a kernel binary policy file.")
(license license:bsd-2)))
(define-public python-sepolgen
(package/inherit libsepol
(name "python-sepolgen")
(arguments
`(#:modules ((srfi srfi-1)
(guix build gnu-build-system)
(guix build utils))
,@(substitute-keyword-arguments (package-arguments libsepol)
((#:phases phases)
`(modify-phases ,phases
(delete 'portability)
(replace 'enter-dir
(lambda _ (chdir "python/sepolgen") #t))
(add-after 'enter-dir 'fix-target-path
(lambda* (#:key inputs outputs #:allow-other-keys)
(let ((get-python-version
FIXME : copied from python - build - system
(lambda (python)
(let* ((version (last (string-split python #\-)))
(components (string-split version #\.))
(major+minor (take components 2)))
(string-join major+minor ".")))))
(substitute* "src/sepolgen/Makefile"
(("^PACKAGEDIR.*")
(string-append "PACKAGEDIR="
(assoc-ref outputs "out")
"/lib/python"
(get-python-version
(assoc-ref inputs "python"))
"/site-packages/sepolgen")))
(substitute* "src/share/Makefile"
(("\\$\\(DESTDIR\\)") (assoc-ref outputs "out"))))
#t)))))))
(inputs
`(("python" ,python-wrapper)))
(native-inputs '())
(synopsis "Python module for generating SELinux policies")
(description
"This package contains a Python module that forms the core of
@code{audit2allow}, a part of the package @code{policycoreutils}. The
sepolgen library contains: Reference Policy Representation, which are Objects
for representing policies and the reference policy interfaces. It has objects
and algorithms for representing access and sets of access in an abstract way
and searching that access. It also has a parser for reference policy
\"headers\". It contains infrastructure for parsing SELinux related messages
as produced by the audit system. It has facilities for generating policy
based on required access.")
(license license:gpl2)))
(define-public python-setools
(package
(name "python-setools")
(version "4.1.1")
(source (origin
(method git-fetch)
(uri (git-reference
(url "")
(commit version)))
(file-name (string-append name "-" version "-checkout"))
(sha256
(base32
"0459xxly6zzqc5azcwk3rbbcxvj60dq08f8z6xr05y7dsbb16cg6"))))
(build-system python-build-system)
(arguments
#:phases
(modify-phases %standard-phases
(delete 'portability)
(add-after 'unpack 'set-SEPOL-variable
(lambda* (#:key inputs #:allow-other-keys)
(setenv "SEPOL"
(string-append (assoc-ref inputs "libsepol")
"/lib/libsepol.a"))))
(add-after 'unpack 'remove-Werror
(lambda _
(substitute* "setup.py"
(("'-Werror',") ""))
#t))
(add-after 'unpack 'fix-target-paths
(lambda* (#:key outputs #:allow-other-keys)
(substitute* "setup.py"
(("join\\(sys.prefix")
(string-append "join(\"" (assoc-ref outputs "out") "/\"")))
#t)))))
(propagated-inputs
`(("python-networkx" ,python-networkx)))
(inputs
`(("libsepol" ,libsepol)
("libselinux" ,libselinux)))
(native-inputs
`(("bison" ,bison)
("flex" ,flex)
("swig" ,swig)))
(home-page "")
(synopsis "Tools for SELinux policy analysis")
(description "SETools is a collection of graphical tools, command-line
tools, and libraries designed to facilitate SELinux policy analysis.")
(license (list license:lgpl2.1+
license:gpl2+))))
(define-public policycoreutils
(package/inherit libsepol
(name "policycoreutils")
(arguments
`(#:test-target "test"
#:make-flags
(let ((out (assoc-ref %outputs "out")))
(list "CC=gcc"
(string-append "PREFIX=" out)
(string-append "LOCALEDIR=" out "/share/locale")
(string-append "BASHCOMPLETIONDIR=" out
"/share/bash-completion/completions")
"INSTALL=install -c -p"
"INSTALL_DIR=install -d"
(string-append "SBINDIR=" out "/sbin")
(string-append "ETCDIR=" out "/etc")
(string-append "SYSCONFDIR=" out "/etc/sysconfig")
(string-append "MAN5DIR=" out "/share/man/man5")
(string-append "INSTALL_NLS_DIR=" out "/share/locale")
(string-append "AUTOSTARTDIR=" out "/etc/xdg/autostart")
(string-append "DBUSSERVICEDIR=" out "/share/dbus-1/services")
(string-append "SYSTEMDDIR=" out "/lib/systemd")
(string-append "INITDIR=" out "/etc/rc.d/init.d")
(string-append "SELINUXDIR=" out "/etc/selinux")))
#:phases
(modify-phases %standard-phases
(delete 'configure)
(delete 'portability)
(add-after 'unpack 'enter-dir
(lambda _ (chdir ,name) #t))
(add-after 'enter-dir 'ignore-/usr-tests
(lambda* (#:key inputs #:allow-other-keys)
(substitute* '("newrole/Makefile"
"setfiles/Makefile"
"run_init/Makefile")
(("/usr(/include/security/pam_appl.h)" _ file)
(string-append (assoc-ref inputs "pam") file))
(("/usr(/include/libaudit.h)" _ file)
(string-append (assoc-ref inputs "audit") file)))
#t)))))
(inputs
`(("audit" ,audit)
("pam" ,linux-pam)
("libsepol" ,libsepol)
("libselinux" ,libselinux)
("libsemanage" ,libsemanage)))
(native-inputs
`(("gettext" ,gettext-minimal)))
(synopsis "SELinux core utilities")
(description "The policycoreutils package contains the core utilities that
are required for the basic operation of an SELinux-enabled GNU system and its
policies. These utilities include @code{load_policy} to load policies,
@code{setfiles} to label file systems, @code{newrole} to switch roles, and
@code{run_init} to run service scripts in their proper context.")
(license license:gpl2+)))
|
9f0ac21dc0d0a62fc0f8ab7ae5ec68e2a7898228d0fba20aa8d19bcba76867b7 | kuberlog/holon | change.lisp | (in-package :holon)
this idea was stolen from
;; and encoded into lisp
cc *
(defun wait-for-user () (read-line))
(defun get-leverage (change-to-be-made)
(change-pleasure-link change-to-be-made)
(change-pain-link change-to-be-made))
(defun change-pain-link (change-to-be-made)
(format t "Think of the worst thing that could result from not ~a" change-to-be-made)
(wait-for-user)
(format t "Feel what it would be like to experience the worst thing")
(wait-for-user))
(defun change-pleasure-link (change-to-be-made)
(format t "Think of the best thing that could result from ~a" change-to-be-made)
(wait-for-user)
(format t "Feel what it would be like to obtain that best thing")
(wait-for-user))
(defun apply-leverage (change-to-be-made)
(format t "Now do one action that commits me to ~a" change-to-be-made))
(defun change (change-to-be-made)
(get-leverage change-to-be-made)
(apply-leverage change-to-be-made))
; *cc -> creative commons
| null | https://raw.githubusercontent.com/kuberlog/holon/27236b6947ff3e7472d844142fc3c2882589db11/lisp/change/change.lisp | lisp | and encoded into lisp
*cc -> creative commons | (in-package :holon)
this idea was stolen from
cc *
(defun wait-for-user () (read-line))
(defun get-leverage (change-to-be-made)
(change-pleasure-link change-to-be-made)
(change-pain-link change-to-be-made))
(defun change-pain-link (change-to-be-made)
(format t "Think of the worst thing that could result from not ~a" change-to-be-made)
(wait-for-user)
(format t "Feel what it would be like to experience the worst thing")
(wait-for-user))
(defun change-pleasure-link (change-to-be-made)
(format t "Think of the best thing that could result from ~a" change-to-be-made)
(wait-for-user)
(format t "Feel what it would be like to obtain that best thing")
(wait-for-user))
(defun apply-leverage (change-to-be-made)
(format t "Now do one action that commits me to ~a" change-to-be-made))
(defun change (change-to-be-made)
(get-leverage change-to-be-made)
(apply-leverage change-to-be-made))
|
235a74fb9601bb6d09d640910b4a0ced480c18cea61f05f4fa52dd1efedb0ddf | ferd/calcalc | calcalc_icelandic.erl | -module(calcalc_icelandic).
-compile(export_all).
-export([epoch/0, date/1, is_valid/1,
to_fixed/1, from_fixed/1]).
-import(calcalc_math, [sum/3,
lcm/2, gcd/2, mod/2, amod/2, signum/1,
floor/1, ceil/1,
deg/1]).
-include("calcalc.hrl").
sunnudagur() -> calcalc_day_of_week:sunday().
mánudagur() -> calcalc_day_of_week:monday().
'Þriðjudagur'() -> calcalac_day_of_week:tuesday().
miðvikudagur() -> calcalc_day_of_week:wednesday().
fimmtudagur() -> calcalc_day_of_week:thursday().
föstudagur() -> calcalc_day_of_week:friday().
laugardagur() -> calcalc_day_of_week:saturday().
-spec epoch() -> integer().
epoch() -> calcalc_gregorian:epoch(). % fixed(1)
-spec date(map()) -> calcalc:date().
date(#{year := Y, season := S, week := W, weekday := D}) ->
#{cal => ?CAL, year => Y, season => S, week => W, weekday => D}.
-spec is_valid(calcalc:date()) -> boolean().
is_valid(Date = #{}) ->
Date == from_fixed(to_fixed(Date)).
-spec to_fixed(calcalc:date()) -> calcalc:fixed().
to_fixed(#{cal := ?CAL, year := Y, season := S, week := W, weekday := D}) ->
{Start, Shift} = case S of
summer -> {summer(Y), calcalc_day_of_week:thursday()};
winter -> {winter(Y), calcalc_day_of_week:saturday()}
end,
Start + 7 * (W-1) + mod(D - Shift, 7).
-spec from_fixed(calcalc:fixed()) -> calcalc:date().
from_fixed(Date) ->
GregorianYear = calcalc_gregorian:year_from_fixed(Date),
Year = case Date >= summer(GregorianYear) of
true -> GregorianYear;
false -> GregorianYear-1
end,
Season = case Date < winter(Year) of
true -> summer;
false -> winter
end,
SeasonStart = case Season of
summer -> summer(Year);
winter -> winter(Year)
end,
Week = 1 + floor((Date - SeasonStart)/7),
Day = calcalc_day_of_week:from_fixed(Date),
#{cal => ?CAL, year => Year, season => Season, week => Week, weekday => Day}.
summer(Year) ->
calcalc_day_of_week:kday_on_or_after(
calcalc_day_of_week:thursday(),
calcalc_gregorian:to_fixed(calcalc_gregorian:date(
#{year => Year, month => calcalc_gregorian:april(), day => 19}
))
).
winter(Year) ->
summer(Year+1)-180.
| null | https://raw.githubusercontent.com/ferd/calcalc/d16eec3512d7b4402b1ddde82128f2483e955e98/src/calcalc_icelandic.erl | erlang | fixed(1) | -module(calcalc_icelandic).
-compile(export_all).
-export([epoch/0, date/1, is_valid/1,
to_fixed/1, from_fixed/1]).
-import(calcalc_math, [sum/3,
lcm/2, gcd/2, mod/2, amod/2, signum/1,
floor/1, ceil/1,
deg/1]).
-include("calcalc.hrl").
sunnudagur() -> calcalc_day_of_week:sunday().
mánudagur() -> calcalc_day_of_week:monday().
'Þriðjudagur'() -> calcalac_day_of_week:tuesday().
miðvikudagur() -> calcalc_day_of_week:wednesday().
fimmtudagur() -> calcalc_day_of_week:thursday().
föstudagur() -> calcalc_day_of_week:friday().
laugardagur() -> calcalc_day_of_week:saturday().
-spec epoch() -> integer().
-spec date(map()) -> calcalc:date().
date(#{year := Y, season := S, week := W, weekday := D}) ->
#{cal => ?CAL, year => Y, season => S, week => W, weekday => D}.
-spec is_valid(calcalc:date()) -> boolean().
is_valid(Date = #{}) ->
Date == from_fixed(to_fixed(Date)).
-spec to_fixed(calcalc:date()) -> calcalc:fixed().
to_fixed(#{cal := ?CAL, year := Y, season := S, week := W, weekday := D}) ->
{Start, Shift} = case S of
summer -> {summer(Y), calcalc_day_of_week:thursday()};
winter -> {winter(Y), calcalc_day_of_week:saturday()}
end,
Start + 7 * (W-1) + mod(D - Shift, 7).
-spec from_fixed(calcalc:fixed()) -> calcalc:date().
from_fixed(Date) ->
GregorianYear = calcalc_gregorian:year_from_fixed(Date),
Year = case Date >= summer(GregorianYear) of
true -> GregorianYear;
false -> GregorianYear-1
end,
Season = case Date < winter(Year) of
true -> summer;
false -> winter
end,
SeasonStart = case Season of
summer -> summer(Year);
winter -> winter(Year)
end,
Week = 1 + floor((Date - SeasonStart)/7),
Day = calcalc_day_of_week:from_fixed(Date),
#{cal => ?CAL, year => Year, season => Season, week => Week, weekday => Day}.
summer(Year) ->
calcalc_day_of_week:kday_on_or_after(
calcalc_day_of_week:thursday(),
calcalc_gregorian:to_fixed(calcalc_gregorian:date(
#{year => Year, month => calcalc_gregorian:april(), day => 19}
))
).
winter(Year) ->
summer(Year+1)-180.
|
9bb1be9a953fb72345e5ec7cf4366acf2804a3894ee3d23a02a70031f6ccb067 | orthecreedence/cl-rethinkdb | run.lisp | (in-package :cl-rethinkdb-test)
(defun run-tests ()
(run! 'cl-rethinkdb-test))
| null | https://raw.githubusercontent.com/orthecreedence/cl-rethinkdb/f435e72dce7f900f599ade193859a202fd1ac33e/test/run.lisp | lisp | (in-package :cl-rethinkdb-test)
(defun run-tests ()
(run! 'cl-rethinkdb-test))
| |
ee110a7cbdac7dc605d98a227e356ebd81f07816fb4031c406b86178200141f3 | racket/games | utils.rkt | (module utils racket
(require sgl/gl-vectors
sgl
racket/math
racket/gui
racket/class
"doors.rkt")
(provide door-bm
magic-door-bm
locked-door-bm
door-drawer
locked-door-drawer
magic-door-drawer
open-door-drawer
make-i-player-icon
make-key-thing-icon)
(define light-black (gl-float-vector 0.0 0.0 0.0 0.25))
(define green (gl-float-vector 0.0 1.0 0.0 1.0))
(define yellow (gl-float-vector 1.0 1.0 0.0 1.0))
(define black (gl-float-vector 0.0 0.0 0.0 1.0))
(define dark-gray (gl-float-vector 0.2 0.2 0.2 1.0))
(define door-bm
(make-object bitmap%
(build-path (collection-path "games" "checkers") "light.jpg")))
(define (door-drawer game)
(bitmap->drawer door-bm game))
(define (open-door-drawer game)
void)
(define (add-to-door draw)
(let* ([w (send door-bm get-width)]
[h (send door-bm get-height)]
[bm (make-object bitmap% w h)]
[dc (make-object bitmap-dc% bm)])
(send dc draw-bitmap door-bm 0 0)
(draw dc w h)
(send dc set-bitmap #f)
bm))
(define magic-door-bm
(add-to-door
(lambda (dc w h)
(send dc set-font (send the-font-list find-or-create-font 32 'default))
(send dc set-text-foreground (make-object color% "yellow"))
(let-values ([(sw sh sd sa) (send dc get-text-extent "\u2605")])
(send dc draw-text "\u2605" (/ (- w sw) 2) (/ (- h sh) 2))))))
(define (magic-door-drawer game)
(bitmap->drawer magic-door-bm game))
(define locked-door-bm
(add-to-door
(lambda (dc w h)
(send dc set-brush (send the-brush-list find-or-create-brush "black" 'solid))
(send dc set-pen (send the-pen-list find-or-create-pen "black" 1 'solid))
(send dc draw-ellipse (/ (- w (* 0.2 h)) 2) (* 0.2 h)
(* 0.2 h) (* 0.2 h))
(send dc draw-rectangle (* w 0.45) (* 0.3 h)
(* 0.1 w) (* 0.3 h)))))
(define (locked-door-drawer game)
(bitmap->drawer locked-door-bm game))
(define (q game)
(send game with-gl-context
(lambda ()
(let ([q (gl-new-quadric)])
(gl-quadric-draw-style q 'fill)
(gl-quadric-normals q 'smooth)
q))))
(define (sphere-dl game color)
(send game with-gl-context
(let ([q (q game)])
(lambda ()
(let ((list-id (gl-gen-lists 1)))
(gl-new-list list-id 'compile)
(gl-material-v 'front-and-back 'ambient-and-diffuse color)
(gl-sphere q 0.5 20 20)
(gl-end-list)
list-id)))))
(define (make-cylinder-dl game color disk?)
(send game with-gl-context
(lambda ()
(let ((list-id (gl-gen-lists 1))
(q (q game)))
(gl-new-list list-id 'compile)
(gl-material-v 'front-and-back 'ambient-and-diffuse color)
(gl-cylinder q 0.5 0.5 1.0 20 1)
(when disk?
(gl-push-matrix)
(gl-translate 0 0 1.0)
(gl-disk q 0.0 0.5 25 1)
(gl-pop-matrix))
(gl-end-list)
list-id))))
(define (make-i-player-icon game
#:optional
[data #f]
#:key
[color green] )
(let ([shadow-cylinder-dl (make-cylinder-dl game dark-gray #t)]
[cylinder-dl (make-cylinder-dl game color #f)]
[sphere-dl (sphere-dl game color)])
(send game make-player-icon
(lambda (just-shadow?)
(with-light
just-shadow?
(lambda ()
(unless just-shadow?
(gl-push-matrix)
(gl-translate 0.0 0.0 0.30)
(gl-scale 0.25 0.25 0.25)
(gl-scale 0.5 0.5 0.5)
(gl-call-list sphere-dl)
(gl-pop-matrix))
(gl-push-matrix)
(gl-scale 0.25 0.25 0.5)
(gl-scale 0.5 0.5 0.5)
(gl-call-list (if just-shadow?
shadow-cylinder-dl
cylinder-dl))
(gl-pop-matrix))))
data)))
(define (make-key-dl game color)
(send game with-gl-context
(lambda ()
(let ((list-id (gl-gen-lists 1))
(q (q game)))
(gl-new-list list-id 'compile)
(gl-material-v 'front-and-back 'ambient-and-diffuse color)
(gl-push-matrix)
(gl-translate -0.25 0 0)
(gl-cylinder q 0.25 0.25 0.2 20 1)
(gl-cylinder q 0.1 0.1 0.2 20 1)
(gl-disk q 0.1 0.25 20 2)
(gl-translate 0 0 0.2)
(gl-disk q 0.1 0.25 20 2)
(gl-pop-matrix)
(gl-push-matrix)
(gl-translate -0.05 0 0.1)
(gl-rotate 90 0 1 0)
(gl-cylinder q 0.1 0.1 0.5 16 1)
(gl-push-matrix)
(gl-translate 0 0 0.5)
(gl-disk q 0 0.1 16 1)
(gl-pop-matrix)
(let ([tooth
(lambda ()
(gl-push-matrix)
(gl-rotate 90 1 0 0)
(gl-cylinder q 0.05 0.05 0.25 16 1)
(gl-translate 0 0 0.25)
(gl-disk q 0 0.05 16 1)
(gl-pop-matrix))])
(gl-translate 0 0 0.2)
(tooth)
(gl-translate 0 0 0.2)
(tooth))
(gl-pop-matrix)
(gl-end-list)
list-id))))
(define (with-light just-shadow? thunk)
(unless just-shadow?
(gl-enable 'light0)
(gl-light-model-v 'light-model-ambient (gl-float-vector 0.5 0.5 0.5 0.0)))
(thunk)
(unless just-shadow?
(gl-light-model-v 'light-model-ambient (gl-float-vector 1.0 1.0 1.0 0.0))
(gl-disable 'light0)))
(define (make-key-thing-icon game
#:optional
[data #f]
#:key
[color yellow])
(let ([dl (make-key-dl game color)])
(send game make-thing-icon
(lambda (#:optional [just-shadow? #f])
(with-light just-shadow? (lambda ()
(gl-scale 0.5 0.5 0.5)
(gl-call-list dl))))
data))))
| null | https://raw.githubusercontent.com/racket/games/e57376f067be51257ed12cdf3e4509a00ffd533d/doors/utils.rkt | racket | (module utils racket
(require sgl/gl-vectors
sgl
racket/math
racket/gui
racket/class
"doors.rkt")
(provide door-bm
magic-door-bm
locked-door-bm
door-drawer
locked-door-drawer
magic-door-drawer
open-door-drawer
make-i-player-icon
make-key-thing-icon)
(define light-black (gl-float-vector 0.0 0.0 0.0 0.25))
(define green (gl-float-vector 0.0 1.0 0.0 1.0))
(define yellow (gl-float-vector 1.0 1.0 0.0 1.0))
(define black (gl-float-vector 0.0 0.0 0.0 1.0))
(define dark-gray (gl-float-vector 0.2 0.2 0.2 1.0))
(define door-bm
(make-object bitmap%
(build-path (collection-path "games" "checkers") "light.jpg")))
(define (door-drawer game)
(bitmap->drawer door-bm game))
(define (open-door-drawer game)
void)
(define (add-to-door draw)
(let* ([w (send door-bm get-width)]
[h (send door-bm get-height)]
[bm (make-object bitmap% w h)]
[dc (make-object bitmap-dc% bm)])
(send dc draw-bitmap door-bm 0 0)
(draw dc w h)
(send dc set-bitmap #f)
bm))
(define magic-door-bm
(add-to-door
(lambda (dc w h)
(send dc set-font (send the-font-list find-or-create-font 32 'default))
(send dc set-text-foreground (make-object color% "yellow"))
(let-values ([(sw sh sd sa) (send dc get-text-extent "\u2605")])
(send dc draw-text "\u2605" (/ (- w sw) 2) (/ (- h sh) 2))))))
(define (magic-door-drawer game)
(bitmap->drawer magic-door-bm game))
(define locked-door-bm
(add-to-door
(lambda (dc w h)
(send dc set-brush (send the-brush-list find-or-create-brush "black" 'solid))
(send dc set-pen (send the-pen-list find-or-create-pen "black" 1 'solid))
(send dc draw-ellipse (/ (- w (* 0.2 h)) 2) (* 0.2 h)
(* 0.2 h) (* 0.2 h))
(send dc draw-rectangle (* w 0.45) (* 0.3 h)
(* 0.1 w) (* 0.3 h)))))
(define (locked-door-drawer game)
(bitmap->drawer locked-door-bm game))
(define (q game)
(send game with-gl-context
(lambda ()
(let ([q (gl-new-quadric)])
(gl-quadric-draw-style q 'fill)
(gl-quadric-normals q 'smooth)
q))))
(define (sphere-dl game color)
(send game with-gl-context
(let ([q (q game)])
(lambda ()
(let ((list-id (gl-gen-lists 1)))
(gl-new-list list-id 'compile)
(gl-material-v 'front-and-back 'ambient-and-diffuse color)
(gl-sphere q 0.5 20 20)
(gl-end-list)
list-id)))))
(define (make-cylinder-dl game color disk?)
(send game with-gl-context
(lambda ()
(let ((list-id (gl-gen-lists 1))
(q (q game)))
(gl-new-list list-id 'compile)
(gl-material-v 'front-and-back 'ambient-and-diffuse color)
(gl-cylinder q 0.5 0.5 1.0 20 1)
(when disk?
(gl-push-matrix)
(gl-translate 0 0 1.0)
(gl-disk q 0.0 0.5 25 1)
(gl-pop-matrix))
(gl-end-list)
list-id))))
(define (make-i-player-icon game
#:optional
[data #f]
#:key
[color green] )
(let ([shadow-cylinder-dl (make-cylinder-dl game dark-gray #t)]
[cylinder-dl (make-cylinder-dl game color #f)]
[sphere-dl (sphere-dl game color)])
(send game make-player-icon
(lambda (just-shadow?)
(with-light
just-shadow?
(lambda ()
(unless just-shadow?
(gl-push-matrix)
(gl-translate 0.0 0.0 0.30)
(gl-scale 0.25 0.25 0.25)
(gl-scale 0.5 0.5 0.5)
(gl-call-list sphere-dl)
(gl-pop-matrix))
(gl-push-matrix)
(gl-scale 0.25 0.25 0.5)
(gl-scale 0.5 0.5 0.5)
(gl-call-list (if just-shadow?
shadow-cylinder-dl
cylinder-dl))
(gl-pop-matrix))))
data)))
(define (make-key-dl game color)
(send game with-gl-context
(lambda ()
(let ((list-id (gl-gen-lists 1))
(q (q game)))
(gl-new-list list-id 'compile)
(gl-material-v 'front-and-back 'ambient-and-diffuse color)
(gl-push-matrix)
(gl-translate -0.25 0 0)
(gl-cylinder q 0.25 0.25 0.2 20 1)
(gl-cylinder q 0.1 0.1 0.2 20 1)
(gl-disk q 0.1 0.25 20 2)
(gl-translate 0 0 0.2)
(gl-disk q 0.1 0.25 20 2)
(gl-pop-matrix)
(gl-push-matrix)
(gl-translate -0.05 0 0.1)
(gl-rotate 90 0 1 0)
(gl-cylinder q 0.1 0.1 0.5 16 1)
(gl-push-matrix)
(gl-translate 0 0 0.5)
(gl-disk q 0 0.1 16 1)
(gl-pop-matrix)
(let ([tooth
(lambda ()
(gl-push-matrix)
(gl-rotate 90 1 0 0)
(gl-cylinder q 0.05 0.05 0.25 16 1)
(gl-translate 0 0 0.25)
(gl-disk q 0 0.05 16 1)
(gl-pop-matrix))])
(gl-translate 0 0 0.2)
(tooth)
(gl-translate 0 0 0.2)
(tooth))
(gl-pop-matrix)
(gl-end-list)
list-id))))
(define (with-light just-shadow? thunk)
(unless just-shadow?
(gl-enable 'light0)
(gl-light-model-v 'light-model-ambient (gl-float-vector 0.5 0.5 0.5 0.0)))
(thunk)
(unless just-shadow?
(gl-light-model-v 'light-model-ambient (gl-float-vector 1.0 1.0 1.0 0.0))
(gl-disable 'light0)))
(define (make-key-thing-icon game
#:optional
[data #f]
#:key
[color yellow])
(let ([dl (make-key-dl game color)])
(send game make-thing-icon
(lambda (#:optional [just-shadow? #f])
(with-light just-shadow? (lambda ()
(gl-scale 0.5 0.5 0.5)
(gl-call-list dl))))
data))))
| |
3d96c25ab524db1c1797f6125fc991df327893cdb8586657477439c8d5e9ab28 | carl-eastlund/dracula | prover.rkt | #lang racket
(require (prefix-in acl2- "conditionals.rkt")
"../teachpacks/testing.rkt")
(define-syntax (assert-event stx)
(syntax-case stx ()
[(_ e)
(syntax/loc stx (check-expect (acl2-if e 't '()) 't))]))
(define-syntax (thm stx)
(syntax-case stx ()
[(_ e) #'(begin)]))
(define-syntax (progn stx)
(syntax-case stx ()
[(_ . ds) #'(begin . ds)]))
(define-syntax (disable stx)
(syntax-case stx ()
[(_ . stuff) #'(begin)]))
(define-syntax (enable stx)
(syntax-case stx ()
[(_ . stuff) #'(begin)]))
(define-syntax (in-theory stx)
(syntax-case stx ()
[(_ spec)
#'(begin)]))
(define-syntax-rule (set-ruler-extenders e)
(define-values [] (begin e (values))))
(define-syntax (theory-invariant stx)
#'(begin))
(define-syntax (defpkg stx) #'(begin))
(define-syntax (deflabel stx) #'(begin))
(define-syntax (assert$ stx)
(syntax-case stx ()
[(_ test form)
#'(acl2-if test
form
(error 'assert$ "Assertion failed!~n~a" 'test))]))
(define-syntax (mv stx)
(syntax-case stx ()
[(_ expr1 expr2 . exprs)
#'(list expr1 expr2 . exprs)]))
(define-syntax (mv-let stx)
(syntax-case stx ()
[(_ ids expr body)
#'(match-let ([(list . ids) expr]) body)]))
(define-syntax (deftheory stx)
(syntax-case stx (:doc)
[(_ name expr :doc doc-string) #'(define name '(theory: expr))]
[(_ name expr) #'(deftheory name expr :doc "")]))
(define-syntax (defequiv stx)
(syntax-case stx ()
[(_ name)
(identifier? #'name)
(syntax/loc stx (begin))]))
(provide (all-defined-out)
(rename-out [time time$]))
| null | https://raw.githubusercontent.com/carl-eastlund/dracula/a937f4b40463779246e3544e4021c53744a33847/lang/prover.rkt | racket | #lang racket
(require (prefix-in acl2- "conditionals.rkt")
"../teachpacks/testing.rkt")
(define-syntax (assert-event stx)
(syntax-case stx ()
[(_ e)
(syntax/loc stx (check-expect (acl2-if e 't '()) 't))]))
(define-syntax (thm stx)
(syntax-case stx ()
[(_ e) #'(begin)]))
(define-syntax (progn stx)
(syntax-case stx ()
[(_ . ds) #'(begin . ds)]))
(define-syntax (disable stx)
(syntax-case stx ()
[(_ . stuff) #'(begin)]))
(define-syntax (enable stx)
(syntax-case stx ()
[(_ . stuff) #'(begin)]))
(define-syntax (in-theory stx)
(syntax-case stx ()
[(_ spec)
#'(begin)]))
(define-syntax-rule (set-ruler-extenders e)
(define-values [] (begin e (values))))
(define-syntax (theory-invariant stx)
#'(begin))
(define-syntax (defpkg stx) #'(begin))
(define-syntax (deflabel stx) #'(begin))
(define-syntax (assert$ stx)
(syntax-case stx ()
[(_ test form)
#'(acl2-if test
form
(error 'assert$ "Assertion failed!~n~a" 'test))]))
(define-syntax (mv stx)
(syntax-case stx ()
[(_ expr1 expr2 . exprs)
#'(list expr1 expr2 . exprs)]))
(define-syntax (mv-let stx)
(syntax-case stx ()
[(_ ids expr body)
#'(match-let ([(list . ids) expr]) body)]))
(define-syntax (deftheory stx)
(syntax-case stx (:doc)
[(_ name expr :doc doc-string) #'(define name '(theory: expr))]
[(_ name expr) #'(deftheory name expr :doc "")]))
(define-syntax (defequiv stx)
(syntax-case stx ()
[(_ name)
(identifier? #'name)
(syntax/loc stx (begin))]))
(provide (all-defined-out)
(rename-out [time time$]))
| |
ff990b606d3632df8c23bec8f4c03b83c06fa79f198106fc320cc1a7458baf25 | jepsen-io/jepsen | rethinkdb.clj | (ns jepsen.rethinkdb
(:refer-clojure :exclude [run!])
(:require [clojure [pprint :refer :all]
[string :as str]
[set :as set]]
[clojure.java.io :as io]
[clojure.tools.logging :refer [debug info warn]]
[jepsen [core :as jepsen]
[db :as db]
[util :as util :refer [meh timeout retry with-retry]]
[control :as c :refer [|]]
[client :as client]
[checker :as checker]
[generator :as gen]
[nemesis :as nemesis]
[net :as net]
[store :as store]
[report :as report]
[tests :as tests]]
[jepsen.control [util :as cu]]
[jepsen.os.debian :as debian]
[jepsen.checker.timeline :as timeline]
[rethinkdb.core :refer [connect close]]
[rethinkdb.query :as r]
[rethinkdb.query-builder :refer [term]]
[knossos.core :as knossos]
[knossos.model :as model]
[cheshire.core :as json])
(:import (clojure.lang ExceptionInfo)))
(def log-file "/var/log/rethinkdb")
(defn faketime-script
"A sh script which invokes cmd with a faketime wrapper."
[cmd]
(str "#!/bin/bash\n"
"faketime -m -f \"+$((RANDOM%100))s x1.${RANDOM}\" "
cmd
" \"$@\""))
(defn faketime-wrapper!
"Replaces an executable with a faketime wrapper. Idempotent."
[cmd]
(let [cmd' (str cmd ".no-faketime")
wrapper (faketime-script cmd')]
(when-not (cu/exists? cmd')
(info "Installing faketime wrapper.")
(c/exec :mv cmd cmd')
(c/exec :echo wrapper :> cmd)
(c/exec :chmod "a+x" cmd))))
(defn install!
"Install RethinkDB on a node"
[node version]
; Install package
(debian/add-repo! "rethinkdb"
"deb jessie main")
(c/su (c/exec :wget :-qO :- "" |
:apt-key :add :-))
(debian/install {"rethinkdb" version})
(faketime-wrapper! "/usr/bin/rethinkdb")
; Set up logfile
(c/exec :touch log-file)
(c/exec :chown "rethinkdb:rethinkdb" log-file))
(defn join-lines
"A string of config file lines for nodes to join the cluster"
[test]
(->> test
:nodes
(map (fn [node] (str "join=" (name node) :29015)))
(clojure.string/join "\n")))
(defn configure!
"Set up configuration files"
[test node]
(info "Configuring" node)
(c/su
(c/exec :echo (-> "jepsen.conf"
io/resource
slurp
(str "\n\n"
(join-lines test) "\n\n"
"server-name=" (name node) "\n"
"server-tag=" (name node) "\n"))
:> "/etc/rethinkdb/instances.d/jepsen.conf")))
(defn start!
"Starts the rethinkdb service"
[node]
(c/su
(info node "Starting rethinkdb")
(c/exec :service :rethinkdb :start)
(info node "Started rethinkdb")))
(defn conn
"Open a connection to the given node."
[node]
(connect :host (name node) :port 28015))
(defn wait-for-conn
"Wait until a connection can be opened to the given node."
[node]
(info "Waiting for connection to" node)
(retry 5 (close (conn node)))
(info node "ready"))
(defn run!
"Like rethinkdb.query/run, but asserts that there were no errors."
[query conn]
(let [result (r/run query conn)]
(when (contains? result :errors)
(assert (zero? (:errors result)) (:first_error result)))
result))
(defn wait-table
"Wait for all replicas for a table to be ready"
[conn db tbl]
(run! (term :WAIT [(r/table (r/db db) tbl)] {}) conn))
(defn db
"Set up and tear down RethinkDB"
[version]
(reify db/DB
(setup! [_ test node]
(install! node version)
(configure! test node)
(start! node)
(wait-for-conn node))
(teardown! [_ test node]
(info node "Nuking" node "RethinkDB")
(cu/grepkill! "rethinkdb")
(c/su
(c/exec :rm :-rf "/var/lib/rethinkdb/jepsen")
(c/exec :truncate :-c :--size 0 log-file))
(info node "RethinkDB dead"))
db/LogFiles
(log-files [_ test node] [log-file])))
(defmacro with-errors
"Takes an invocation operation, a set of idempotent operation
functions which can be safely assumed to fail without altering the
model state, and a body to evaluate. Catches RethinkDB errors and
maps them to failure ops matching the invocation.
Also includes an automatic timeout of 5000 ms."
[op idempotent-ops & body]
`(let [error-type# (if (~idempotent-ops (:f ~op))
:fail
:info)]
(timeout 5000 (assoc ~op :type error-type# :error :timeout)
(try
~@body
(catch clojure.lang.ExceptionInfo e#
(let [code# (-> e# ex-data :response :e)]
(assert (integer? code#))
(case code#
4100000 (assoc ~op :type :fail, :error (:cause (ex-data e#)))
(assoc ~op :type error-type#, :error (str e#)))))))))
(defn primaries
"All nodes that think they're primaries for the given db and table"
[nodes db table]
(->> nodes
(pmap (fn [node]
(-> (r/db db)
(r/table table)
(r/status)
(run! (conn node))
:shards
(->> (mapcat :primary_replicas)
(some #{(name node)}))
(when node))))
(remove nil?)))
(defn reconfigure!
"Reconfigures replicas for a table."
[conn db table primary replicas]
(let [res (-> (r/db db)
(r/table table)
(r/reconfigure {:shards 1
:replicas (->> replicas
(map name)
(map #(vector % 1))
(into {}))
:primary_replica_tag (name primary)})
(run! conn))]
(assert (= 1 (:reconfigured res)))
(info "reconfigured" {:replicas replicas, :primary primary})
res))
(defn reconfigure-nemesis
"A nemesis which randomly reconfigures the cluster topology for the given db
and table names."
[db table]
(reify client/Client
(setup! [this _ _] this)
(invoke! [_ test op]
(assert (= :reconfigure (:f op)))
(timeout 5000 (assoc op :value :timeout)
(with-retry [i 10]
(let [size (inc (rand-int (count (:nodes test))))
replicas (->> (:nodes test)
shuffle
(take size))
primary (rand-nth replicas)
conn (conn primary)]
(try
(info "will reconfigure to" replicas "(" primary ")")
(reconfigure! conn db table primary replicas)
(assoc op :value {:replicas replicas :primary primary})
(finally (close conn))))
(catch clojure.lang.ExceptionInfo e
(if (zero? i)
(throw e)
(condp re-find (.getMessage e)
#"Could not find any servers with server tag"
(do (warn "reconfigure caught; retrying:" (.getMessage e))
(retry (dec i)))
#"The server\(s\) hosting table .+? are currently unreachable."
(do (warn "reconfigure failed: servers unreachable. retrying")
(retry (dec i)))
(throw e)))))))
(teardown! [_ test])))
(defn reconfigure-grudge
"Computes a network partition grudge likely to mess up the given primary and
replicas."
[nodes primary replicas primary' replicas']
Construct a grudge which splits the cluster in half , each
; primary in a different side.
component1 (->> (disj nodes primary')
shuffle
(take (/ (count nodes) 2))
set)
component2 (set/difference nodes component1)]
(nemesis/complete-grudge [component1 component2])
; Disregard that, pick randomly
(if (< (rand) 0.5)
{}
(nemesis/complete-grudge (nemesis/bisect (shuffle nodes))))))
(defn aggressive-reconfigure-nemesis
"A nemesis which reconfigures the cluster topology for the given db
and table names, introducing partitions selected particularly to break
guarantees."
([db table]
(aggressive-reconfigure-nemesis db table (atom {})))
([db table state]
(reify client/Client
(setup! [this _ _] this)
(invoke! [_ test op]
(assert (= :reconfigure (:f op)))
(locking state
(timeout 10000 (assoc op :value :timeout)
(with-retry [i 10]
(let [{:keys [replicas primary grudge]
:or {primary (first (:nodes test))
replicas [(first (:nodes test))]
grudge {}}} @state
nodes (set (:nodes test))
; Pick a new primary and replicas at random.
size' (inc (rand-int (count nodes)))
replicas' (->> nodes
shuffle
(take size'))
primary' (rand-nth replicas')
; Pick a new primary visible to the current one.
;primary' (-> nodes
; (disj primary)
; (set/difference (set (grudge primary)))
)
; Pick a new set of replicas including the primary, visible
; to the new primary.
;size' (rand-int (count nodes))
;replicas' (->> (-> nodes
; (disj primary')
; (set/difference (set (grudge primary'))))
; shuffle
; (take size')
; (cons primary'))
grudge' (reconfigure-grudge nodes primary replicas
primary' replicas')
conn (conn primary')]
(try
Reconfigure
(info "will reconfigure" primary replicas "->" primary' replicas' " under grudge" grudge)
(reconfigure! conn db table primary' replicas')
; Set up new network topology
(net/heal! (:net test) test)
(info "network healed")
(nemesis/partition! test grudge')
(info "network partitioned:" grudge')
; Save state for next time
(reset! state {:primary primary'
:replicas replicas'
:grudge grudge'})
; Return
(assoc op :value @state)
(finally (close conn))))
(catch clojure.lang.ExceptionInfo e
(if (zero? i)
(throw e)
(condp re-find (.getMessage e)
#"Could not find any servers with server tag"
(do (warn "reconfigure caught; retrying:" (.getMessage e))
(retry (dec i)))
#"The server\(s\) hosting table .+? are currently unreachable."
(do (warn "reconfigure failed: servers unreachable. Healing net and retrying")
(net/heal! (:net test) test)
(retry (dec i)))
(throw e))))))))
(teardown! [_ test]))))
(defn test-
"Constructs a test with the given name prefixed by 'rethinkdb ', merging any
given options."
[name opts]
(merge
(assoc tests/noop-test
:name (str "rethinkdb " name)
:os debian/os
:db (db (:version opts))
:model (model/cas-register)
:checker (checker/perf))
(dissoc opts :version)))
| null | https://raw.githubusercontent.com/jepsen-io/jepsen/a75d5a50dd5fa8d639a622c124bf61253460b754/rethinkdb/src/jepsen/rethinkdb.clj | clojure | Install package
Set up logfile
primary in a different side.
Disregard that, pick randomly
Pick a new primary and replicas at random.
Pick a new primary visible to the current one.
primary' (-> nodes
(disj primary)
(set/difference (set (grudge primary)))
Pick a new set of replicas including the primary, visible
to the new primary.
size' (rand-int (count nodes))
replicas' (->> (-> nodes
(disj primary')
(set/difference (set (grudge primary'))))
shuffle
(take size')
(cons primary'))
Set up new network topology
Save state for next time
Return | (ns jepsen.rethinkdb
(:refer-clojure :exclude [run!])
(:require [clojure [pprint :refer :all]
[string :as str]
[set :as set]]
[clojure.java.io :as io]
[clojure.tools.logging :refer [debug info warn]]
[jepsen [core :as jepsen]
[db :as db]
[util :as util :refer [meh timeout retry with-retry]]
[control :as c :refer [|]]
[client :as client]
[checker :as checker]
[generator :as gen]
[nemesis :as nemesis]
[net :as net]
[store :as store]
[report :as report]
[tests :as tests]]
[jepsen.control [util :as cu]]
[jepsen.os.debian :as debian]
[jepsen.checker.timeline :as timeline]
[rethinkdb.core :refer [connect close]]
[rethinkdb.query :as r]
[rethinkdb.query-builder :refer [term]]
[knossos.core :as knossos]
[knossos.model :as model]
[cheshire.core :as json])
(:import (clojure.lang ExceptionInfo)))
(def log-file "/var/log/rethinkdb")
(defn faketime-script
"A sh script which invokes cmd with a faketime wrapper."
[cmd]
(str "#!/bin/bash\n"
"faketime -m -f \"+$((RANDOM%100))s x1.${RANDOM}\" "
cmd
" \"$@\""))
(defn faketime-wrapper!
"Replaces an executable with a faketime wrapper. Idempotent."
[cmd]
(let [cmd' (str cmd ".no-faketime")
wrapper (faketime-script cmd')]
(when-not (cu/exists? cmd')
(info "Installing faketime wrapper.")
(c/exec :mv cmd cmd')
(c/exec :echo wrapper :> cmd)
(c/exec :chmod "a+x" cmd))))
(defn install!
"Install RethinkDB on a node"
[node version]
(debian/add-repo! "rethinkdb"
"deb jessie main")
(c/su (c/exec :wget :-qO :- "" |
:apt-key :add :-))
(debian/install {"rethinkdb" version})
(faketime-wrapper! "/usr/bin/rethinkdb")
(c/exec :touch log-file)
(c/exec :chown "rethinkdb:rethinkdb" log-file))
(defn join-lines
"A string of config file lines for nodes to join the cluster"
[test]
(->> test
:nodes
(map (fn [node] (str "join=" (name node) :29015)))
(clojure.string/join "\n")))
(defn configure!
"Set up configuration files"
[test node]
(info "Configuring" node)
(c/su
(c/exec :echo (-> "jepsen.conf"
io/resource
slurp
(str "\n\n"
(join-lines test) "\n\n"
"server-name=" (name node) "\n"
"server-tag=" (name node) "\n"))
:> "/etc/rethinkdb/instances.d/jepsen.conf")))
(defn start!
"Starts the rethinkdb service"
[node]
(c/su
(info node "Starting rethinkdb")
(c/exec :service :rethinkdb :start)
(info node "Started rethinkdb")))
(defn conn
"Open a connection to the given node."
[node]
(connect :host (name node) :port 28015))
(defn wait-for-conn
"Wait until a connection can be opened to the given node."
[node]
(info "Waiting for connection to" node)
(retry 5 (close (conn node)))
(info node "ready"))
(defn run!
"Like rethinkdb.query/run, but asserts that there were no errors."
[query conn]
(let [result (r/run query conn)]
(when (contains? result :errors)
(assert (zero? (:errors result)) (:first_error result)))
result))
(defn wait-table
"Wait for all replicas for a table to be ready"
[conn db tbl]
(run! (term :WAIT [(r/table (r/db db) tbl)] {}) conn))
(defn db
"Set up and tear down RethinkDB"
[version]
(reify db/DB
(setup! [_ test node]
(install! node version)
(configure! test node)
(start! node)
(wait-for-conn node))
(teardown! [_ test node]
(info node "Nuking" node "RethinkDB")
(cu/grepkill! "rethinkdb")
(c/su
(c/exec :rm :-rf "/var/lib/rethinkdb/jepsen")
(c/exec :truncate :-c :--size 0 log-file))
(info node "RethinkDB dead"))
db/LogFiles
(log-files [_ test node] [log-file])))
(defmacro with-errors
"Takes an invocation operation, a set of idempotent operation
functions which can be safely assumed to fail without altering the
model state, and a body to evaluate. Catches RethinkDB errors and
maps them to failure ops matching the invocation.
Also includes an automatic timeout of 5000 ms."
[op idempotent-ops & body]
`(let [error-type# (if (~idempotent-ops (:f ~op))
:fail
:info)]
(timeout 5000 (assoc ~op :type error-type# :error :timeout)
(try
~@body
(catch clojure.lang.ExceptionInfo e#
(let [code# (-> e# ex-data :response :e)]
(assert (integer? code#))
(case code#
4100000 (assoc ~op :type :fail, :error (:cause (ex-data e#)))
(assoc ~op :type error-type#, :error (str e#)))))))))
(defn primaries
"All nodes that think they're primaries for the given db and table"
[nodes db table]
(->> nodes
(pmap (fn [node]
(-> (r/db db)
(r/table table)
(r/status)
(run! (conn node))
:shards
(->> (mapcat :primary_replicas)
(some #{(name node)}))
(when node))))
(remove nil?)))
(defn reconfigure!
"Reconfigures replicas for a table."
[conn db table primary replicas]
(let [res (-> (r/db db)
(r/table table)
(r/reconfigure {:shards 1
:replicas (->> replicas
(map name)
(map #(vector % 1))
(into {}))
:primary_replica_tag (name primary)})
(run! conn))]
(assert (= 1 (:reconfigured res)))
(info "reconfigured" {:replicas replicas, :primary primary})
res))
(defn reconfigure-nemesis
"A nemesis which randomly reconfigures the cluster topology for the given db
and table names."
[db table]
(reify client/Client
(setup! [this _ _] this)
(invoke! [_ test op]
(assert (= :reconfigure (:f op)))
(timeout 5000 (assoc op :value :timeout)
(with-retry [i 10]
(let [size (inc (rand-int (count (:nodes test))))
replicas (->> (:nodes test)
shuffle
(take size))
primary (rand-nth replicas)
conn (conn primary)]
(try
(info "will reconfigure to" replicas "(" primary ")")
(reconfigure! conn db table primary replicas)
(assoc op :value {:replicas replicas :primary primary})
(finally (close conn))))
(catch clojure.lang.ExceptionInfo e
(if (zero? i)
(throw e)
(condp re-find (.getMessage e)
#"Could not find any servers with server tag"
(do (warn "reconfigure caught; retrying:" (.getMessage e))
(retry (dec i)))
#"The server\(s\) hosting table .+? are currently unreachable."
(do (warn "reconfigure failed: servers unreachable. retrying")
(retry (dec i)))
(throw e)))))))
(teardown! [_ test])))
(defn reconfigure-grudge
"Computes a network partition grudge likely to mess up the given primary and
replicas."
[nodes primary replicas primary' replicas']
Construct a grudge which splits the cluster in half , each
component1 (->> (disj nodes primary')
shuffle
(take (/ (count nodes) 2))
set)
component2 (set/difference nodes component1)]
(nemesis/complete-grudge [component1 component2])
(if (< (rand) 0.5)
{}
(nemesis/complete-grudge (nemesis/bisect (shuffle nodes))))))
(defn aggressive-reconfigure-nemesis
"A nemesis which reconfigures the cluster topology for the given db
and table names, introducing partitions selected particularly to break
guarantees."
([db table]
(aggressive-reconfigure-nemesis db table (atom {})))
([db table state]
(reify client/Client
(setup! [this _ _] this)
(invoke! [_ test op]
(assert (= :reconfigure (:f op)))
(locking state
(timeout 10000 (assoc op :value :timeout)
(with-retry [i 10]
(let [{:keys [replicas primary grudge]
:or {primary (first (:nodes test))
replicas [(first (:nodes test))]
grudge {}}} @state
nodes (set (:nodes test))
size' (inc (rand-int (count nodes)))
replicas' (->> nodes
shuffle
(take size'))
primary' (rand-nth replicas')
)
grudge' (reconfigure-grudge nodes primary replicas
primary' replicas')
conn (conn primary')]
(try
Reconfigure
(info "will reconfigure" primary replicas "->" primary' replicas' " under grudge" grudge)
(reconfigure! conn db table primary' replicas')
(net/heal! (:net test) test)
(info "network healed")
(nemesis/partition! test grudge')
(info "network partitioned:" grudge')
(reset! state {:primary primary'
:replicas replicas'
:grudge grudge'})
(assoc op :value @state)
(finally (close conn))))
(catch clojure.lang.ExceptionInfo e
(if (zero? i)
(throw e)
(condp re-find (.getMessage e)
#"Could not find any servers with server tag"
(do (warn "reconfigure caught; retrying:" (.getMessage e))
(retry (dec i)))
#"The server\(s\) hosting table .+? are currently unreachable."
(do (warn "reconfigure failed: servers unreachable. Healing net and retrying")
(net/heal! (:net test) test)
(retry (dec i)))
(throw e))))))))
(teardown! [_ test]))))
(defn test-
"Constructs a test with the given name prefixed by 'rethinkdb ', merging any
given options."
[name opts]
(merge
(assoc tests/noop-test
:name (str "rethinkdb " name)
:os debian/os
:db (db (:version opts))
:model (model/cas-register)
:checker (checker/perf))
(dissoc opts :version)))
|
ccc8740a97bcd562c2df0d2257aaaf2c5d6d4a7e42eecf0af5d9d292dd10e655 | haskell-lisp/yale-haskell | core-symbols.scm | ;;; This defines all core symbols.
Core symbols are stored in global variables . The core - symbol
;;; macro just turns a string into a variable name.
(define-syntax (core-symbol str)
(make-core-symbol-name str))
(define (make-core-symbol-name str)
(string->symbol (string-append "*core-" str "*")))
(define (symbol->core-var name)
(make-core-symbol-name (symbol->string name)))
(define (get-core-var-names vars type)
(let ((res (assq type vars)))
(if (eq? res '#f)
'()
(map (function string->symbol) (tuple-2-2 res)))))
;;; This is just used to create a define for each var without a
;;; value.
(define-syntax (define-core-variables)
`(begin
,@(define-core-variables-1 *haskell-prelude-vars*)
,@(define-core-variables-1 *haskell-noncore-vars*)))
(define (define-core-variables-1 vars)
(concat (map (lambda (ty)
(map (function init-core-symbol)
(get-core-var-names vars ty)))
'(classes methods types constructors synonyms values))))
(define (init-core-symbol sym)
`(define ,(symbol->core-var sym) '()))
(define-syntax (create-core-globals)
`(begin
(begin ,@(create-core-defs *haskell-prelude-vars* '#t))
(begin ,@(create-core-defs *haskell-noncore-vars* '#f))))
(define (create-core-defs defs prelude-core?)
`(,@(map (lambda (x) (define-core-value x prelude-core?))
(get-core-var-names defs 'values))
,@(map (lambda (x) (define-core-method x prelude-core?))
(get-core-var-names defs 'methods))
,@(map (lambda (x) (define-core-synonym x prelude-core?))
(get-core-var-names defs 'synonyms))
,@(map (lambda (x) (define-core-class x prelude-core?))
(get-core-var-names defs 'classes))
,@(map (lambda (x) (define-core-type x prelude-core?))
(get-core-var-names defs 'types))
,@(map (lambda (x) (define-core-constr x prelude-core?))
(get-core-var-names defs 'constructors))))
(define (define-core-value name pc?)
`(setf ,(symbol->core-var name)
(make-core-value-definition ',name ',pc?)))
(define (make-core-value-definition name pc?)
(install-core-sym
(make var (name name) (module '|*Core|) (unit '|*Core|))
name
pc?))
(define (define-core-method name pc?)
`(setf ,(symbol->core-var name)
(make-core-method-definition ',name ',pc?)))
(define (make-core-method-definition name pc?)
(install-core-sym
(make method-var (name name) (module '|*Core|) (unit '|*Core|))
name
pc?))
(define (define-core-class name pc?)
`(setf ,(symbol->core-var name)
(make-core-class-definition ',name ',pc?)))
(define (make-core-class-definition name pc?)
(install-core-sym
(make class (name name) (module '|*Core|) (unit '|*Core|))
name
pc?))
(define (define-core-synonym name pc?)
`(setf ,(symbol->core-var name)
(make-core-synonym-definition ',name ',pc?)))
(define (make-core-synonym-definition name pc?)
(install-core-sym
(make synonym (name name) (module '|*Core|) (unit '|*Core|))
name
pc?))
(define (define-core-type name pc?)
`(setf ,(symbol->core-var name)
(make-core-type-definition ',name ',pc?)))
(define (make-core-type-definition name pc?)
(install-core-sym
(make algdata (name name) (module '|*Core|) (unit '|*Core|))
name
pc?))
(define (define-core-constr name pc?)
`(setf ,(symbol->core-var name)
(make-core-constr-definition ',name ',pc?)))
(define (make-core-constr-definition name pc?)
(setf name (add-con-prefix/symbol name))
(install-core-sym
(make con (name name) (module '|*Core|) (unit '|*Core|))
name
pc?))
(define (install-core-sym def name preludecore?)
(setf (def-core? def) '#t)
(when preludecore?
(setf (def-prelude? def) '#t))
(setf (table-entry (dynamic *core-symbols*) name) def)
(when preludecore?
(setf (table-entry (dynamic *prelude-core-symbols*) name) def))
def)
| null | https://raw.githubusercontent.com/haskell-lisp/yale-haskell/4e987026148fe65c323afbc93cd560c07bf06b3f/top/core-symbols.scm | scheme | This defines all core symbols.
macro just turns a string into a variable name.
This is just used to create a define for each var without a
value. |
Core symbols are stored in global variables . The core - symbol
(define-syntax (core-symbol str)
(make-core-symbol-name str))
(define (make-core-symbol-name str)
(string->symbol (string-append "*core-" str "*")))
(define (symbol->core-var name)
(make-core-symbol-name (symbol->string name)))
(define (get-core-var-names vars type)
(let ((res (assq type vars)))
(if (eq? res '#f)
'()
(map (function string->symbol) (tuple-2-2 res)))))
(define-syntax (define-core-variables)
`(begin
,@(define-core-variables-1 *haskell-prelude-vars*)
,@(define-core-variables-1 *haskell-noncore-vars*)))
(define (define-core-variables-1 vars)
(concat (map (lambda (ty)
(map (function init-core-symbol)
(get-core-var-names vars ty)))
'(classes methods types constructors synonyms values))))
(define (init-core-symbol sym)
`(define ,(symbol->core-var sym) '()))
(define-syntax (create-core-globals)
`(begin
(begin ,@(create-core-defs *haskell-prelude-vars* '#t))
(begin ,@(create-core-defs *haskell-noncore-vars* '#f))))
(define (create-core-defs defs prelude-core?)
`(,@(map (lambda (x) (define-core-value x prelude-core?))
(get-core-var-names defs 'values))
,@(map (lambda (x) (define-core-method x prelude-core?))
(get-core-var-names defs 'methods))
,@(map (lambda (x) (define-core-synonym x prelude-core?))
(get-core-var-names defs 'synonyms))
,@(map (lambda (x) (define-core-class x prelude-core?))
(get-core-var-names defs 'classes))
,@(map (lambda (x) (define-core-type x prelude-core?))
(get-core-var-names defs 'types))
,@(map (lambda (x) (define-core-constr x prelude-core?))
(get-core-var-names defs 'constructors))))
(define (define-core-value name pc?)
`(setf ,(symbol->core-var name)
(make-core-value-definition ',name ',pc?)))
(define (make-core-value-definition name pc?)
(install-core-sym
(make var (name name) (module '|*Core|) (unit '|*Core|))
name
pc?))
(define (define-core-method name pc?)
`(setf ,(symbol->core-var name)
(make-core-method-definition ',name ',pc?)))
(define (make-core-method-definition name pc?)
(install-core-sym
(make method-var (name name) (module '|*Core|) (unit '|*Core|))
name
pc?))
(define (define-core-class name pc?)
`(setf ,(symbol->core-var name)
(make-core-class-definition ',name ',pc?)))
(define (make-core-class-definition name pc?)
(install-core-sym
(make class (name name) (module '|*Core|) (unit '|*Core|))
name
pc?))
(define (define-core-synonym name pc?)
`(setf ,(symbol->core-var name)
(make-core-synonym-definition ',name ',pc?)))
(define (make-core-synonym-definition name pc?)
(install-core-sym
(make synonym (name name) (module '|*Core|) (unit '|*Core|))
name
pc?))
(define (define-core-type name pc?)
`(setf ,(symbol->core-var name)
(make-core-type-definition ',name ',pc?)))
(define (make-core-type-definition name pc?)
(install-core-sym
(make algdata (name name) (module '|*Core|) (unit '|*Core|))
name
pc?))
(define (define-core-constr name pc?)
`(setf ,(symbol->core-var name)
(make-core-constr-definition ',name ',pc?)))
(define (make-core-constr-definition name pc?)
(setf name (add-con-prefix/symbol name))
(install-core-sym
(make con (name name) (module '|*Core|) (unit '|*Core|))
name
pc?))
(define (install-core-sym def name preludecore?)
(setf (def-core? def) '#t)
(when preludecore?
(setf (def-prelude? def) '#t))
(setf (table-entry (dynamic *core-symbols*) name) def)
(when preludecore?
(setf (table-entry (dynamic *prelude-core-symbols*) name) def))
def)
|
22d019ca8e765c572f2901509f831140a842dcad0f8d92518ed2f9f6c49068a8 | softwarelanguageslab/maf | R5RS_gambit_primes-2.scm | ; Changes:
* removed : 0
* added : 0
* swaps : 0
* negated predicates : 1
; * swapped branches: 0
* calls to i d fun : 2
(letrec ((interval-list (lambda (m n)
(<change>
(if (> m n)
()
(cons m (interval-list (+ 1 m) n)))
((lambda (x) x) (if (> m n) () (cons m (interval-list (+ 1 m) n)))))))
(sieve (lambda (l)
(letrec ((remove-multiples (lambda (n l)
(if (null? l)
()
(if (= (modulo (car l) n) 0)
(remove-multiples n (cdr l))
(cons (car l) (remove-multiples n (cdr l))))))))
(<change>
(if (null? l)
()
(cons (car l) (sieve (remove-multiples (car l) (cdr l)))))
((lambda (x) x)
(if (<change> (null? l) (not (null? l)))
()
(cons (car l) (sieve (remove-multiples (car l) (cdr l))))))))))
(primes<= (lambda (n)
(sieve (interval-list 2 n)))))
(equal?
(primes<= 100)
(__toplevel_cons
2
(__toplevel_cons
3
(__toplevel_cons
5
(__toplevel_cons
7
(__toplevel_cons
11
(__toplevel_cons
13
(__toplevel_cons
17
(__toplevel_cons
19
(__toplevel_cons
23
(__toplevel_cons
29
(__toplevel_cons
31
(__toplevel_cons
37
(__toplevel_cons
41
(__toplevel_cons
43
(__toplevel_cons
47
(__toplevel_cons
53
(__toplevel_cons
59
(__toplevel_cons
61
(__toplevel_cons
67
(__toplevel_cons
71
(__toplevel_cons
73
(__toplevel_cons 79 (__toplevel_cons 83 (__toplevel_cons 89 (__toplevel_cons 97 ()))))))))))))))))))))))))))) | null | https://raw.githubusercontent.com/softwarelanguageslab/maf/11acedf56b9bf0c8e55ddb6aea754b6766d8bb40/test/changes/scheme/generated/R5RS_gambit_primes-2.scm | scheme | Changes:
* swapped branches: 0 | * removed : 0
* added : 0
* swaps : 0
* negated predicates : 1
* calls to i d fun : 2
(letrec ((interval-list (lambda (m n)
(<change>
(if (> m n)
()
(cons m (interval-list (+ 1 m) n)))
((lambda (x) x) (if (> m n) () (cons m (interval-list (+ 1 m) n)))))))
(sieve (lambda (l)
(letrec ((remove-multiples (lambda (n l)
(if (null? l)
()
(if (= (modulo (car l) n) 0)
(remove-multiples n (cdr l))
(cons (car l) (remove-multiples n (cdr l))))))))
(<change>
(if (null? l)
()
(cons (car l) (sieve (remove-multiples (car l) (cdr l)))))
((lambda (x) x)
(if (<change> (null? l) (not (null? l)))
()
(cons (car l) (sieve (remove-multiples (car l) (cdr l))))))))))
(primes<= (lambda (n)
(sieve (interval-list 2 n)))))
(equal?
(primes<= 100)
(__toplevel_cons
2
(__toplevel_cons
3
(__toplevel_cons
5
(__toplevel_cons
7
(__toplevel_cons
11
(__toplevel_cons
13
(__toplevel_cons
17
(__toplevel_cons
19
(__toplevel_cons
23
(__toplevel_cons
29
(__toplevel_cons
31
(__toplevel_cons
37
(__toplevel_cons
41
(__toplevel_cons
43
(__toplevel_cons
47
(__toplevel_cons
53
(__toplevel_cons
59
(__toplevel_cons
61
(__toplevel_cons
67
(__toplevel_cons
71
(__toplevel_cons
73
(__toplevel_cons 79 (__toplevel_cons 83 (__toplevel_cons 89 (__toplevel_cons 97 ()))))))))))))))))))))))))))) |
e3392cb4b02227c6009f54ebe65856d0b2dba8073d9bc07839a0ed71af5e5a50 | kind2-mc/kind2 | subSystem.ml | This file is part of the Kind 2 model checker .
Copyright ( c ) 2014 by the Board of Trustees of the University of Iowa
Licensed under the Apache License , Version 2.0 ( the " License " ) ; you
may not use this file except in compliance with the License . You
may obtain a copy of the License at
-2.0
Unless required by applicable law or agreed to in writing , software
distributed under the License is distributed on an " AS IS " BASIS ,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND , either express or
implied . See the License for the specific language governing
permissions and limitations under the License .
Copyright (c) 2014 by the Board of Trustees of the University of Iowa
Licensed under the Apache License, Version 2.0 (the "License"); you
may not use this file except in compliance with the License. You
may obtain a copy of the License at
-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied. See the License for the specific language governing
permissions and limitations under the License.
*)
type 'a t = {
(* Name of the system as a scope. *)
scope: Scope.t ;
(* Original input. *)
source : 'a ;
(* System can be abstracted to its contract. *)
has_contract : bool ;
(* System has modes. *)
has_modes : bool ;
(* System can be refined to its implementation. *)
has_impl : bool ;
(* Direct sub-systems. *)
subsystems : 'a t list ;
}
(* Strategy info of a subsystem. *)
let strategy_info_of {
has_contract ; has_modes ; has_impl
} = {
Strategy.can_refine = has_impl ;
Strategy.has_contract ;
Strategy.has_modes ;
}
Add all subsystems of the systems in the second argument to the accumulator
in topological order with the top system at the head of the list .
in topological order with the top system at the head of the list. *)
let rec all_subsystems' accum = function
(* All subsystems added, return. *)
| [] -> accum
First system on the stack is already in the accumulator .
| { scope } :: tl when accum |> List.exists (
fun { scope = s } -> scope = s
) ->
(* Skip altogether, subsystems have already been added. *)
all_subsystems' accum tl
First system on the stack .
| { subsystems } as h :: tl ->
(* Subsystems that are not in the accumulator. *)
let tl' =
subsystems |> List.fold_left (fun tl' ({ scope } as subsystem) ->
if
(* System of the same name is in the accumulator? *)
List.exists
(fun { scope = s } -> scope = s)
accum
then (* Do not add twice. *)
tl'
First get subsystems of this system .
subsystem :: tl'
) []
in
(* Are all subsystems in the accumulator? *)
match tl' with
(* Now add this system. *)
| [] -> all_subsystems' (h :: accum) tl
First add all subsystems .
| _ -> all_subsystems' accum (tl' @ h :: tl)
(* Return all subsystems in topological order with the top system at the head
of the list. *)
let all_subsystems s = all_subsystems' [] [s]
let all_subsystems_of_list l = all_subsystems' [] l
(* Search depth-first for the subsystem in the list of subsystems, skip over
systems already visited. *)
let rec find_subsystem' scope visited = function
Stack is empty , scope not found .
| [] -> raise Not_found
Take first element from stack .
| ({ scope = scope'; subsystems } as subsystem) :: tl ->
(* Return subsystem if scope matches. *)
if scope = scope' then subsystem else
(* System already seen? *)
if List.mem scope' visited then
(* Continue with rest of stack. *)
find_subsystem' scope visited tl
else
(* Push subsystems of this system to stack. *)
find_subsystem' scope (scope' :: visited) (subsystems @ tl)
(* Return the subsystem of the given scope.
Raise [Not_found] if there is no subsystem of that scope. *)
let find_subsystem subsystem scope = find_subsystem' scope [] [subsystem]
let find_subsystem_of_list subsystems scope = find_subsystem' scope [] subsystems
(*
Local Variables:
compile-command: "make -C .. -k"
indent-tabs-mode: nil
End:
*)
| null | https://raw.githubusercontent.com/kind2-mc/kind2/639c5f2773b4c23048ebd3710b1d2e4a24b61558/src/subSystem.ml | ocaml | Name of the system as a scope.
Original input.
System can be abstracted to its contract.
System has modes.
System can be refined to its implementation.
Direct sub-systems.
Strategy info of a subsystem.
All subsystems added, return.
Skip altogether, subsystems have already been added.
Subsystems that are not in the accumulator.
System of the same name is in the accumulator?
Do not add twice.
Are all subsystems in the accumulator?
Now add this system.
Return all subsystems in topological order with the top system at the head
of the list.
Search depth-first for the subsystem in the list of subsystems, skip over
systems already visited.
Return subsystem if scope matches.
System already seen?
Continue with rest of stack.
Push subsystems of this system to stack.
Return the subsystem of the given scope.
Raise [Not_found] if there is no subsystem of that scope.
Local Variables:
compile-command: "make -C .. -k"
indent-tabs-mode: nil
End:
| This file is part of the Kind 2 model checker .
Copyright ( c ) 2014 by the Board of Trustees of the University of Iowa
Licensed under the Apache License , Version 2.0 ( the " License " ) ; you
may not use this file except in compliance with the License . You
may obtain a copy of the License at
-2.0
Unless required by applicable law or agreed to in writing , software
distributed under the License is distributed on an " AS IS " BASIS ,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND , either express or
implied . See the License for the specific language governing
permissions and limitations under the License .
Copyright (c) 2014 by the Board of Trustees of the University of Iowa
Licensed under the Apache License, Version 2.0 (the "License"); you
may not use this file except in compliance with the License. You
may obtain a copy of the License at
-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied. See the License for the specific language governing
permissions and limitations under the License.
*)
type 'a t = {
scope: Scope.t ;
source : 'a ;
has_contract : bool ;
has_modes : bool ;
has_impl : bool ;
subsystems : 'a t list ;
}
let strategy_info_of {
has_contract ; has_modes ; has_impl
} = {
Strategy.can_refine = has_impl ;
Strategy.has_contract ;
Strategy.has_modes ;
}
Add all subsystems of the systems in the second argument to the accumulator
in topological order with the top system at the head of the list .
in topological order with the top system at the head of the list. *)
let rec all_subsystems' accum = function
| [] -> accum
First system on the stack is already in the accumulator .
| { scope } :: tl when accum |> List.exists (
fun { scope = s } -> scope = s
) ->
all_subsystems' accum tl
First system on the stack .
| { subsystems } as h :: tl ->
let tl' =
subsystems |> List.fold_left (fun tl' ({ scope } as subsystem) ->
if
List.exists
(fun { scope = s } -> scope = s)
accum
tl'
First get subsystems of this system .
subsystem :: tl'
) []
in
match tl' with
| [] -> all_subsystems' (h :: accum) tl
First add all subsystems .
| _ -> all_subsystems' accum (tl' @ h :: tl)
let all_subsystems s = all_subsystems' [] [s]
let all_subsystems_of_list l = all_subsystems' [] l
let rec find_subsystem' scope visited = function
Stack is empty , scope not found .
| [] -> raise Not_found
Take first element from stack .
| ({ scope = scope'; subsystems } as subsystem) :: tl ->
if scope = scope' then subsystem else
if List.mem scope' visited then
find_subsystem' scope visited tl
else
find_subsystem' scope (scope' :: visited) (subsystems @ tl)
let find_subsystem subsystem scope = find_subsystem' scope [] [subsystem]
let find_subsystem_of_list subsystems scope = find_subsystem' scope [] subsystems
|
00ed8f146d0e5af5b967eb54de7b16d038521f78801d8ac2544f07d6a5d703d6 | tonyfloatersu/solution-haskell-craft-of-FP | TreeADT.hs | module TreeADT ( Tree
, nil
, isNil
, isNode
, leftSub
, rightSub
, treeVal
, insTree
, delete
, minTree
, elemT
, showTree ) where
data Tree a = Nil | Node a (Tree a) (Tree a)
nil :: Tree a
nil = Nil
isNil :: Tree a -> Bool
isNil Nil = True
isNil _ = False
isNode :: Tree a -> Bool
isNode Node {} = True
isNode _ = False
leftSub :: Tree a -> Tree a
leftSub Nil = Nil
leftSub (Node _ lft _) = lft
rightSub :: Tree a -> Tree a
rightSub Nil = Nil
rightSub (Node _ _ rht) = rht
treeVal :: Tree a -> a
treeVal Nil = error "tree is nil"
treeVal (Node v _ _) = v
insTree :: Ord a => a -> Tree a -> Tree a
insTree val Nil = Node val Nil Nil
insTree val (Node v t1 t2)
| val == v = Node v t1 t2
| val < v = Node v (insTree val t1) t2
| otherwise = Node v t1 (insTree val t2)
delete :: Ord a => a -> Tree a -> Tree a
delete _ Nil = Nil
delete val (Node v tl tr)
| val < v = Node v (delete val tl) tr
| val > v = Node v tl (delete val tr)
| isNil tl = tr
| isNil tr = tl
| otherwise = Node modif tl (delete modif tr)
where (Just modif) = minTree tr
minTree :: Ord a => Tree a -> Maybe a
minTree tree
| isNil tree = Nothing
| isNil (leftSub tree) = Just (treeVal tree)
| otherwise = minTree (leftSub tree)
elemT :: Ord a => a -> Tree a -> Bool
elemT _ Nil = False
elemT val (Node wh tl tr)
| val < wh = elemT val tl
| val > wh = elemT val tr
| otherwise = True
showTree :: (Show a) => Tree a -> String
showTree Nil = "empty root."
showTree (Node what tl tr) = unlines (showTreeSub (Node what tl tr))
showTreeSub :: (Show a) => Tree a -> [String]
showTreeSub Nil = []
showTreeSub (Node ele tl_ tr_) = show ele : showSubs tl_ tr_
where pad :: String -> String -> [String] -> [String]
pad s1 s2 = zipWith (++) (s1 : repeat s2)
showSubs :: (Show a) => Tree a -> Tree a -> [String]
showSubs _tl _tr = pad "+- " "| " (showTreeSub _tl)
++ pad "`- " " " (showTreeSub _tr)
| null | https://raw.githubusercontent.com/tonyfloatersu/solution-haskell-craft-of-FP/0d4090ef28417c82a7b01e4a764f657641cb83f3/TreeADT.hs | haskell | module TreeADT ( Tree
, nil
, isNil
, isNode
, leftSub
, rightSub
, treeVal
, insTree
, delete
, minTree
, elemT
, showTree ) where
data Tree a = Nil | Node a (Tree a) (Tree a)
nil :: Tree a
nil = Nil
isNil :: Tree a -> Bool
isNil Nil = True
isNil _ = False
isNode :: Tree a -> Bool
isNode Node {} = True
isNode _ = False
leftSub :: Tree a -> Tree a
leftSub Nil = Nil
leftSub (Node _ lft _) = lft
rightSub :: Tree a -> Tree a
rightSub Nil = Nil
rightSub (Node _ _ rht) = rht
treeVal :: Tree a -> a
treeVal Nil = error "tree is nil"
treeVal (Node v _ _) = v
insTree :: Ord a => a -> Tree a -> Tree a
insTree val Nil = Node val Nil Nil
insTree val (Node v t1 t2)
| val == v = Node v t1 t2
| val < v = Node v (insTree val t1) t2
| otherwise = Node v t1 (insTree val t2)
delete :: Ord a => a -> Tree a -> Tree a
delete _ Nil = Nil
delete val (Node v tl tr)
| val < v = Node v (delete val tl) tr
| val > v = Node v tl (delete val tr)
| isNil tl = tr
| isNil tr = tl
| otherwise = Node modif tl (delete modif tr)
where (Just modif) = minTree tr
minTree :: Ord a => Tree a -> Maybe a
minTree tree
| isNil tree = Nothing
| isNil (leftSub tree) = Just (treeVal tree)
| otherwise = minTree (leftSub tree)
elemT :: Ord a => a -> Tree a -> Bool
elemT _ Nil = False
elemT val (Node wh tl tr)
| val < wh = elemT val tl
| val > wh = elemT val tr
| otherwise = True
showTree :: (Show a) => Tree a -> String
showTree Nil = "empty root."
showTree (Node what tl tr) = unlines (showTreeSub (Node what tl tr))
showTreeSub :: (Show a) => Tree a -> [String]
showTreeSub Nil = []
showTreeSub (Node ele tl_ tr_) = show ele : showSubs tl_ tr_
where pad :: String -> String -> [String] -> [String]
pad s1 s2 = zipWith (++) (s1 : repeat s2)
showSubs :: (Show a) => Tree a -> Tree a -> [String]
showSubs _tl _tr = pad "+- " "| " (showTreeSub _tl)
++ pad "`- " " " (showTreeSub _tr)
| |
c7d799d6202ab518568d44817188fedaaf4ed87983ba873540d993dff135e8bb | ont-app/igraph | core.cljc | (ns ^{:author "Eric D. Scott",
:doc "Abstractions over a graph object, intended to sit alongside the
other basic clojure data structures such as maps, vectors and sets.
"}
ont-app.igraph.core
(:require [clojure.pprint :as pp]
[clojure.set :as set]
[clojure.spec.alpha :as spec]
[clojure.string :as str]
#?(:clj [clojure.java.io :as io])
))
;; FUN WITH READER MACROS
#?(:cljs
(enable-console-print!)
)
#?(:cljs
(defn on-js-reload [] )
)
(declare normal-form)
#?(:clj
(defn write-to-file
"Side-effect: writes normal form of `g` to `path` as edn.
Returns: `path`
Where
- `path` is the output of `path-fn`
- `g` implements IGraph
- `path-fn` a function [g] -> `path`.
NOTE: Anything that would choke the reader on slurp should be removed
from `g` before saving.
"
[path g]
(let [output-path (str/replace path #"^file://" "")
]
(io/make-parents output-path)
(spit output-path
(with-out-str
(pp/pprint
(normal-form g))))
output-path
)))
(declare add)
#?(:clj
(defn read-from-file
"returns `g` with the contents of `path` added
Where
- `g` implements IGraph
- `path` is an edn file containing a normal-form representation of some graph,
typically the output of save-to-file."
[g path]
(add g (read-string (slurp (io/as-file path))))
))
;; No reader macros below this point
(defprotocol IGraph
"An abstraction for S-P-O graphs"
;;;;;;;;;;;;;;;;;;;;
;; ACCESS FUNCTIONS
;;;;;;;;;;;;;;;;;;;;
(normal-form [g] "Returns {`s` {`p` #{`o`...}...}...}
Where
- `s` is the subject of a triple := [`s` `p` `o`] in `g`
- `p` is predicate of same
- `o` is the object of same
")
(subjects [g]
"Returns (`s`...) for `g`
Where
- `s` is a subject in one or more triples in `g`
- `g` is a graph.
"
)
(get-p-o [g s]
"Returns {`p` #{`o` ...}} associated with `s` in `g`, or nil.
Where
- `g` is a graph
- `s` is subject
- `p` and `o` are in triples := [`s` `p` `o`] in `g`
"
)
(get-o [g s p]
"Returns {`o` ...} for `s` and `p` in `g`, or nil.
Where
- `g` is a graph
- `s` is subject of some triples in `g`
- `p` is predicate of some triples in `g`
- `o` appears in triple [`s` `p` `o`] in `g`
"
)
(ask [g s p o]
"Returns truthy value iff [`s` `p` `o`] appears in `g`
Where
- `g` is a graph
- `s` is subject of some triples in `g`
- `p` is predicate of some triples in `g`
- `o` appears in triple [`s` `p` `o`] in `g`
"
)
(query [g q]
"Returns #{`binding` ...} for query spec `q` applied to `g`
Where
- `binding` := {`var` `value`, ...}
- `q` is a query specification suitable for the native format of `g`
- `g` is a graph
- `var` is a variable specified in `q`
- `value` is a value found in `g` bounded to `var` per `q`
"
)
;; for IFn
(invoke [g] [g s] [g s p] [g s p o]
"Applies `g` as a function to the rest of its arguments, representing
triples [`s` `p` `o`] in `g` respectively. `p` may optionally be
a traversal function (See `traverse` docs)
- (g) -> {`s` {`p` #{`o`...}...}...} ;; = (normal-form `g`)
- (g s) -> {`p` #{`o`...}, ...} ;; = (get-p-o `g`)
= ( match - or - traverse g s p )
- (g s p o) -> `o` iff [`s` `p` `o`] is in `g` ;; = (match-or-traverse g s p o)
")
;; mutability
(mutability [g]
"Returns one of ::read-only ::immutable ::mutable ::accumulate-only"
)
)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; CONTENT MANIPULATION
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defprotocol IGraphImmutable
(add [g to-add]
"Returns `g`', with `to-add` added to its contents.
Throws a ::ReadOnly exception if (read-only? `g`)
Where
- `g` is a graph
- `to-add` is in triples-format
"
)
(subtract [g to-subtract]
"Returns `g`' with `to-subtract` removed from its contents.
Throws an exception if (mutability g) != ::immutable
Where
- `g` is an immutablegraph
- `to-subtract` is in triples-removal-format
"
))
(defprotocol IGraphMutable
(add! [g to-add]
"Returns `g`, with `to-add` added to its contents.
Throws an exception if (mutability g) != ::mutable
Where
- `g` is a mutable graph
- `to-add` is in triples-format
"
)
(subtract! [g to-subtract]
"Returns `g` with `to-subtract` removed from its contents.
Throws a ::ReadOnly exception if (read-only? `g`)
Where
- `g` is a graph
- `to-subtract` is in triples-removal-format
"
))
(defprotocol IGraphAccumulateOnly
(claim [g to-add]
"Returns `g`, with `to-add` added to `g`'s associated transactor.
Throws an exception if (mutability g) != ::accumulate-only
Where
- `g` is a mutable graph
- `to-add` is in triples-format
NOTE: see Datomic documentation for the 'add' operation for details
"
)
(retract [g to-retract]
"Returns `g` with `comm` reset to head
Side-effect: `to-retract` retracted from `comm`
Throws an exception if (mutability g) != ::accumulate-only.
Where
- `g` is a graph
- `comm` is a datomic-style transactor
`to-retract` is in triples-removal-format
NOTE: see Datomic documentation for details
"
))
(defprotocol IGraphSet
"Basic set operations between graphs."
(union [g1 g2]
"Returns an IGraph whose normal form contains all triples from g1 and g2"
)
(intersection [g1 g2]
"Returns an IGraph whose normal form contains all and only statements shared by both g1 and g2"
)
(difference [g1 g2]
"Returns an IGraph whose normal form contains all statements in g1 not present in g2."
)
)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; MULTI-METHODS FOR ALTERING GRAPHS
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn normal-form?
"Returns true iff `m` is in normal form for IGraph."
TODO : port to clojure.spec
[m]
(and (map? m)
(or (empty? m)
(let [p (m (first (keys m)))
o (p (first (keys p)))
]
(set? o)))))
(spec/def ::normal-form #(normal-form? %))
(spec/def ::vector (spec/and vector? #(> (count %) 1) #(odd? (count %))))
(spec/def ::vector-of-vectors (spec/and vector? (spec/every ::vector)))
(spec/def ::triples-format (spec/or :vector-of-vectors ::vector-of-vectors
:vector ::vector
:normal-form ::normal-form))
(defn triples-format
"Returns the value of (:triples-format (meta `triples-spec`)) or one of #{:vector :vector-of-vectors :normal-form `type`} inferred from the shape of `triples-spec`
Where
- `args` := [`g` `triples-spec`], arguments to a method add or remove from graph
- `g` is a graph
- `triples-spec` is a specification of triples typically to add to or remove
from `g`
- `:normal-form` indicates (normal-form? `triples-spec`) = true
- `:triple` indicates `triples-spec` := [`s` `p` `o`]
- `:vector-of-vectors` indicates `triples-spec` := [`triple`...]
- `type` = (type `triples-spec`)
"
[triples-spec]
(or (::triples-format (meta triples-spec))
(let [conform (spec/conform ::triples-format triples-spec)]
(if (= conform ::spec/invalid)
(throw (ex-info "Invalid triples format"
(spec/explain-data ::triples-format triples-spec)))
;; else we're good
(let [[format _value_] conform]
format)))))
(spec/fdef triples-format
:ret #{:vector-of-vectors
:vector
:normal-form
})
(defmulti add-to-graph
"Returns `g`, with `to-add` added
Where
- `g` is a Graph
- `to-add` is interpetable as a set of triples
Dispatched according to `triples-format`
"
(fn [g to-add] [(type g) (triples-format to-add)]))
;; To subtract from a graph, we can use normal form or
;; leave out p and o ...
(spec/def ::underspecified-triple (spec/and vector?
#(> (count %) 0)
#(< (count %) 3)
#(not (vector? (% 0)))))
(spec/def ::vector-of-underspecified (spec/and vector?
#(> (count %) 0)
#(vector? (% 0))))
(spec/def ::removal-format (spec/or
:triples-format ::triples-format
:underspecified-triple ::underspecified-triple
:vector-of-vectors ::vector-of-underspecified))
(defn triples-removal-format
"Returns a keyword describing the format of `triples-spec` for removing a
set of triples from a graph.
"
[triples-spec]
(or (::triples-format (meta triples-spec))
(let [conform (spec/conform ::removal-format triples-spec)]
(if (= conform ::spec/invalid)
(throw (ex-info "Invalid triples format"
(spec/explain-data ::removal-format triples-spec)))
;; else we're good
(let [[format value] conform]
(if (= format :triples-format)
;; value is the kind of triples format
(let [[triples-format _] value]
triples-format)
;;else :underspecifed
format))))))
(spec/fdef triples-removal-format
:ret #{:vector-of-vectors
:vector
:normal-form
:underspecified-triple})
(defmulti remove-from-graph
"Returns `g`, with `to-remove` removed
Where
- `g` is a Graph
- `to-remove` is interpetable as a set of triples
Dispatched according to `triples-removal-format`
"
(fn [g to-remove] [(type g) (triples-removal-format to-remove)]))
;;;;;;;;;;;;;;;
;;; Traversal
;;;;;;;;;;;;;;;;
(defn traverse
"Returns `acc` acquired by applying `traversal` to `g` starting with `queue`, informed by `context`
Where
- `acc` is an arbitrary clojure 'accumulator' object (similar to a
reduce function). Default is `[]`.
- `traversal` := (fn [g context acc queue]...)
-> [`context'` `acc'` `queue'`]
- `g` is a graph
- `context` := {`context-key` `context-value`....}, expressing important
aspects of the traversal state
- `queue` := [`node` ...], nodes to visit
- `context-key` := #{:history ... maybe :skip? ... :seek ... or other
keys specific to `traversal`, which `traversal` may use to communicate
with future iterations of itself.
- `history` := #{`visited-node` ...}, this is conj'd with each visited node on
each call to avoid cycles.
- `skip?` (optional) := (fn [`node`] -> true if we should skip). This may also
be a set of nodes to skip. This allows for overriding the default skipping
behavior which simply skips `history`
- `seek` (optional) := (fn [context acc] -> `acc'`, a function to be called
at the start of each traversal, a truthy, non-empty response to which will
be the immediate return value of the traverse function. This would save you
the time and trouble of processing the whole queue, or making each traversal
function smart enough to stop early. Must return the same type as `acc`.
- `node` is typically an element in `g`, but can be any value the traversal
function knows how to handle
- `visited-node` is a node visited upstream. We filter these out to
avoid cycles. This can also be specified in advance by the user.
- `target` is a node we may be searching for.
Note: it is good practice to assign a :transition-fn metadata tag to
transition functions, though such data is not referenced anywhere
at this point.
"
([g traversal queue]
(traverse g traversal {:history #{}} [] queue))
([g traversal acc queue]
(traverse g traversal {:history #{}} acc queue))
([g traversal context acc queue]
{:pre [(satisfies? IGraph g)
(fn? traversal)
(map? context)
(or (set? (:history context))
(nil? (:history context)))
(or (nil? (:seek context))
(fn? (:seek context)))
(or (nil? (:skip? context))
(fn? (:skip? context))
(set? (:skip? context)))
(sequential? queue)
]
;; :post (= (type acc) (type %)) doesn't like recur
}
(let [seek (and (:seek context) ((:seek context) context acc))
must be same type as acc
(assert (= (type result) (type acc)))
result)
]
(if (and seek (seq seek))
(check-result seek)
;; else no seek
(if (or (nil? queue)
(empty? queue))
;; nothing more to visit...
(if (:seek context)
(check-result ((:seek context) context acc))
acc)
;; else the queue is not empty...
(let [skip? (or (:skip? context)
(:history context)
#{}
)]
(if (skip? (first queue))
(recur g traversal context acc (rest queue))
;;else we don't skip the head of the queue...
(let [[context acc queue-next] (traversal g context acc queue)]
(recur g
traversal
(update context :history
(fn [history]
(conj (or history #{})
(first queue))))
acc
queue-next
)))))))))
(defn transitive-closure
"Returns `traversal` for chains of `p`.
Where
`traversal` := (fn [g acc queue]...) -> [`context` `acc'` `queue'`],
s.t. `queue'` conj's all `o` s.t. (g `s` `p` `o`).
A traversal function argument for the `traverse` function .
`p` is a predicate, typcially an element of `g`
`g` is a graph.
NOTE:
cf the '*' operator in SPARQL property paths
"
[p]
#_{:pre [(not (fn? p))] ;; direct matches only, no traversals
;; I think that can be relaxed now
}
(fn transistive-closure-traversal [g context acc queue]
[context,
(conj acc (first queue)),
(reduce conj (rest queue) (g (first queue) p))]))
(defn traverse-link
"Returns traversal function (fn [g context, acc queue]...)
-> [context, acc', queue'], following one `p` in `g`
Where
- `acc` is a set
- `queue` := [`node` ...], nodes to visit in traversal
- `p` is a predicate in `g`
- `g` is a graph
NOTE: typically used as one component in a traversal path
"
[p]
{:pre [(not (fn? p)) ;; direct matches only. No traversals
]
}
(fn link-traversal [g context acc queue]
(let [s (first queue)]
[context,
(reduce conj
acc
(g s p)),
(rest queue)])))
(defn maybe-traverse-link
"Returns traversal function (fn [g context, acc queue]...)
-> [context, acc', queue'],
Where
- `acc'` includes `node` and and as many `o`s as are linked from `node`
by `p` in `g`
- `queue` := [`node` ...], nodes to visit in traversal
- `p` is a predicate in `g`
- `g` is a graph
NOTE: typically used as one component in a traversal path.
cf the '?' operator in SPARQL property paths
"
[p]
(fn optional-link-traversal [g context acc queue]
(let [s (first queue)]
[context,
(reduce conj
(conj acc s)
(g s p)),
(rest queue)])))
(defn traverse-or
"Returns traversal function (fn [g context, acc queue]...)
-> [context, acc', queue'], for `ps`
Where
- `acc'` includes `node` and and as many `o`s as are linked from `node`
by `p1` | `p2` | ... in `g`
- `queue` := [`node` ...], nodes to visit in traversal
- `ps` := [`p1`, `p2`, ...]
- `p1`, `p2`, ... are all predicates in `g`, or traversal functions
- `g` is a graph
cf the '|' operator in SPARQL property paths
"
[& ps]
(fn traversal-disjunction [g context acc queue]
(letfn [(collect-traversals
[s sacc p]
(reduce conj sacc (g s p)))
]
[context,
(reduce conj acc (reduce (partial collect-traversals (first queue))
#{}
ps)),
(rest queue)
]) ))
(defn t-comp
"Returns a traversal function composed of elements specified in `comp-spec`
Where
- `comp-spec` := {:path [`spec-element`, ...]
`spec-element` {:fn `traversal-fn`
:doc `docstring`
:into `initial-acc` (default [])
:local-context-fn `local-fn` (default nil)
:update-global-context `global-fn` ( default nil)
}
}
Or Alternatively, [`traversal-fn-or-property-name`, ...] for the short
form.
- `spec-element` is typically a keyword naming a stage in the traversal, though
it can also be a direct reference to a traversal function, in which case
it will be equivalent to {:fn `spec-element`}
- `traversal-fn-generator` := (fn [spec-element]...) -> `traversal-fn`, to be
invoked in cases where there is no `spec-element` in `comp-spec`,
traverse-link is the typical choice here.
- `traversal-fn` := (fn [g context acc queue]...) -> [context' acc' queue']
- `context` is a traversal context conforming to the traverse function (see docs)
- `update-fn` := (fn [global-context local-context] ...) -> global-context'
This is provided in case there is some coordination that needs to be provided
between stages in a composed traversal.
- `initial-acc` is the (usually empty) container used to initial the acc
of the traversal stage being specified
- `local-context-fn` := [global-context] -> `local-context`
- `update-global-context` := [global-context local-context] -> `global-context`'
- `local-context` is the context for a given stage of the traversal
- `global-context` carries over between traversal stages.
Examples
(def comp-spec {
:isa? {:fn (maybe-traverse-link :isa)
:doc `traverses an isa link, if it exists`
:local-context {:doc `traversing an isa link`}
:update-global-context
(fn [gc lc] (assoc gc
:status :followed-isa-link))
}
:subClassOf* {:fn (transitive-closure :subClassOf)
:doc 'traverses 0 or more subClassof links'
:local-context-fn (fn [c] {:doc 'traversing subClassOf*'})
:into #{}
:update-global-context
(fn [gc lc] (assoc gc
:status :followed-subclassof))
}
}})
(traversal-comp (merge comp-spec
{:path [:isa? :subClassOf*]
:doc 'Traverses the chain of subsumption links for an instance or class'
}))
(t-comp (merge comp-spec {:path [:isa :label] :doc 'gets class labels')))
Short form example:
(t-comp [:family/parent :family/brother])
... Equal to (t-comp [(traverse-link :family/parent)
(traverse-link :family/brother)]
An inferred 'uncle' relation.
"
;; TODO: consider moving examples above into the README
[comp-spec]
{:pre [(or (not (:path comp-spec)) (vector? (:path comp-spec)))
TODO use clojure.spec
}
(let [comp-spec (if (vector? comp-spec) ;; short form, convert to long form
{:path comp-spec}
comp-spec) ;; else already in long form
]
(fn composed-traversal [g context acc queue]
{:pre [(satisfies? IGraph g)
(map? context)
(sequential? queue)
]
}
(loop [c context
path (:path comp-spec) ;; [<p>, ...]
q queue]
(if (empty? path)
;; q is the final result...
[(if-let [update-context (:update-global-context c)]
(update-context context c)
context)
(into acc q)
[]]
;; else there's more path
(let [p (first path)
p-spec (or (comp-spec p) {})
c (if-let [lcfn (:local-context-fn p-spec)]
(lcfn c)
{})
f (cond
(fn? p) p
:else
(or (:fn p-spec)
(traverse-link p)
))
_ (assert f)
a (or (:into (comp-spec p)) []) ;; breadth-first by default
]
(recur c
(rest path)
(traverse g f c a q))))))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; MATCH-OR-TRAVERSE INVOCATION
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn- match-or-traverse-tag
"Returns :traverse if `p` is a function, else :match
Informs p-dispatcher
"
[p]
(if (fn? p)
:traverse
;;else it's a straight match
:match))
(defn p-dispatcher
"Returns :traverse or :match, as a basis for dispatching standard `invoke` methods involving a `p` argument, which may be either a value to match or a traversal function.
"
([_g_ _s_ p]
(match-or-traverse-tag p))
([_g_ _s_ p _o_]
(match-or-traverse-tag p)))
(defmulti match-or-traverse
"Returns values appropriate for (g s p) or (g s p o) invocations
Where
- `o` is an object in `g`
- `s` is a subject in `g`
- `p` is either a predicate in `g` or a traversal function accumulating
a set, starting with an empty accumulator and queue of [`s`]
(see docs for `traverse`)
NOTE: Implementers of IGraph will typically use this
method for IFn `invoke` members involving a `p` argument.
"
p-dispatcher)
(defmethod match-or-traverse :traverse
([g s p]
{:doc "`p` is a traversal function. Aggregate a set."
:pre [(fn? p)]
}
(traverse g p #{} [s]))
;;;;;;;;;;
([g s p o]
{:doc "`p` is a traversal function. Stop when you find `o`."
:pre [(fn? p)]
}
(declare unique)
(let [seek-o (fn seek-o [_context_ acc]
(clojure.set/intersection acc #{o}))
]
(unique (traverse g p {:seek seek-o} #{} [s])))))
(defmethod match-or-traverse :match
([g s p]
{:doc "`p` is a graph property to be matched"}
(get-o g s p))
;;;;;;;;;;;;
([g s p o]
(ask g s p o)))
;;;;;;;;;;;;;;;;;;;;
;; Utility functions
;;;;;;;;;;;;;;;;;;;;
Stuff to deal with cardinality one ....
(defn unique
"Returns the single member of `coll`, or nil if `coll` is empty. Calls `on-ambiguity` if there is more than one member (default is to throw an Exception).
Where
- `coll` is a collection
- `on-ambiguity` := (fn [coll] ...) -> `value`, default raises an error.
Note: this can be used when you've called (G s p) and you're sure there is
only one object.
"
([coll on-ambiguity]
(if (seq coll)
(if (> (count coll) 1)
(on-ambiguity coll)
(first coll))))
([coll]
(unique coll (fn [coll]
(throw (ex-info "Unique called on non-unique collection"
{:type ::NonUnique
:coll coll
}))))))
;; Inverse of normalize-flat-description
(defn flatten-description
"Returns `p-o` description with singletons broken out into scalars
Where
- `p-o` := {`p` #{`o`}, ...}, normal form at 'description' level of a graph.
"
[p-o]
(let [maybe-flatten (fn [acc k v]
(assoc acc
k
(if (and (set? v) (= (count v) 1))
(unique v)
v)))
]
(reduce-kv maybe-flatten {} p-o)))
^{:inverse-of flatten-description}
(defn normalize-flat-description
"Returns a normalized p-o description of `m`
Where
- `m` is a plain clojure map"
[m]
(let [maybe-setify (fn [acc k v]
(assoc acc
k
(if (not (set? v))
#{v}
v)))
]
(reduce-kv maybe-setify {} m)))
(defn assert-unique-fn
"Returns `g`', replacing any existing [s p *] with [s p o] per `context`
Where
- `g` is a graph
- `context` := m s.t. (keys m) = #{:add-fn :subtrct-fn}
- `add-fn` is one of #{add, add! claim} appropriate to `g`'s modification protocol
- `subtract-fn` is one of #{subtract, subtract! retract} appropriate to `g`'s
modification protocol
"
([context g s p o]
(let [{:keys [add-fn subtract-fn]} context
]
(add-fn (subtract-fn g [s p])
[s p o]))))
(def assert-unique
"fn [g s p o] -> g', asserting a unique triple in immutable graph.
- Wrapper around `assert-unique-fn`"
(partial assert-unique-fn {:add-fn add :subtract-fn subtract}))
(def assert-unique!
"fn [g s p o] -> g', asserting a unique triple in mutable graph.
- Wrapper around `assert-unique-fn`"
(partial assert-unique-fn {:add-fn add! :subtract-fn subtract!}))
(def claim-unique
"fn [g s p o] -> g', asserting a unique triple in an accumulate-only graph .
- Wrapper around `assert-unique-fn`"
(partial assert-unique-fn {:add-fn claim :subtract-fn retract}))
(defn reduce-spo
"Returns `acc'` s.t. (f acc s p o) -> `acc'` for every triple in `g`
Where
- `f` := (fn [acc s p o] -> `acc'`
- `acc` is any value, a reduction accumlator
- `s` `p` `o` constitute a triple in `g`
- `g` implements IGraph
NOTE: C.f. reduce-kv
"
;;TODO f should conform to some spec
[f acc g]
(letfn [(collect-o [s p acc o]
(f acc s p o)
)
(collect-p-o [s acc p]
(reduce (partial collect-o s p)
acc
(g s p)))
(collect-s-p-o [acc s]
(reduce (partial collect-p-o s)
acc
(keys (g s))))
]
(reduce collect-s-p-o
acc
(subjects g))))
| null | https://raw.githubusercontent.com/ont-app/igraph/449ebc6eeef139118fe5a700e953dd167353f7ce/src/ont_app/igraph/core.cljc | clojure | FUN WITH READER MACROS
No reader macros below this point
ACCESS FUNCTIONS
for IFn
= (normal-form `g`)
= (get-p-o `g`)
= (match-or-traverse g s p o)
mutability
CONTENT MANIPULATION
MULTI-METHODS FOR ALTERING GRAPHS
else we're good
To subtract from a graph, we can use normal form or
leave out p and o ...
else we're good
value is the kind of triples format
else :underspecifed
Traversal
:post (= (type acc) (type %)) doesn't like recur
else no seek
nothing more to visit...
else the queue is not empty...
else we don't skip the head of the queue...
direct matches only, no traversals
I think that can be relaxed now
direct matches only. No traversals
TODO: consider moving examples above into the README
short form, convert to long form
else already in long form
[<p>, ...]
q is the final result...
else there's more path
breadth-first by default
MATCH-OR-TRAVERSE INVOCATION
else it's a straight match
Utility functions
Inverse of normalize-flat-description
TODO f should conform to some spec | (ns ^{:author "Eric D. Scott",
:doc "Abstractions over a graph object, intended to sit alongside the
other basic clojure data structures such as maps, vectors and sets.
"}
ont-app.igraph.core
(:require [clojure.pprint :as pp]
[clojure.set :as set]
[clojure.spec.alpha :as spec]
[clojure.string :as str]
#?(:clj [clojure.java.io :as io])
))
#?(:cljs
(enable-console-print!)
)
#?(:cljs
(defn on-js-reload [] )
)
(declare normal-form)
#?(:clj
(defn write-to-file
"Side-effect: writes normal form of `g` to `path` as edn.
Returns: `path`
Where
- `path` is the output of `path-fn`
- `g` implements IGraph
- `path-fn` a function [g] -> `path`.
NOTE: Anything that would choke the reader on slurp should be removed
from `g` before saving.
"
[path g]
(let [output-path (str/replace path #"^file://" "")
]
(io/make-parents output-path)
(spit output-path
(with-out-str
(pp/pprint
(normal-form g))))
output-path
)))
(declare add)
#?(:clj
(defn read-from-file
"returns `g` with the contents of `path` added
Where
- `g` implements IGraph
- `path` is an edn file containing a normal-form representation of some graph,
typically the output of save-to-file."
[g path]
(add g (read-string (slurp (io/as-file path))))
))
(defprotocol IGraph
"An abstraction for S-P-O graphs"
(normal-form [g] "Returns {`s` {`p` #{`o`...}...}...}
Where
- `s` is the subject of a triple := [`s` `p` `o`] in `g`
- `p` is predicate of same
- `o` is the object of same
")
(subjects [g]
"Returns (`s`...) for `g`
Where
- `s` is a subject in one or more triples in `g`
- `g` is a graph.
"
)
(get-p-o [g s]
"Returns {`p` #{`o` ...}} associated with `s` in `g`, or nil.
Where
- `g` is a graph
- `s` is subject
- `p` and `o` are in triples := [`s` `p` `o`] in `g`
"
)
(get-o [g s p]
"Returns {`o` ...} for `s` and `p` in `g`, or nil.
Where
- `g` is a graph
- `s` is subject of some triples in `g`
- `p` is predicate of some triples in `g`
- `o` appears in triple [`s` `p` `o`] in `g`
"
)
(ask [g s p o]
"Returns truthy value iff [`s` `p` `o`] appears in `g`
Where
- `g` is a graph
- `s` is subject of some triples in `g`
- `p` is predicate of some triples in `g`
- `o` appears in triple [`s` `p` `o`] in `g`
"
)
(query [g q]
"Returns #{`binding` ...} for query spec `q` applied to `g`
Where
- `binding` := {`var` `value`, ...}
- `q` is a query specification suitable for the native format of `g`
- `g` is a graph
- `var` is a variable specified in `q`
- `value` is a value found in `g` bounded to `var` per `q`
"
)
(invoke [g] [g s] [g s p] [g s p o]
"Applies `g` as a function to the rest of its arguments, representing
triples [`s` `p` `o`] in `g` respectively. `p` may optionally be
a traversal function (See `traverse` docs)
= ( match - or - traverse g s p )
")
(mutability [g]
"Returns one of ::read-only ::immutable ::mutable ::accumulate-only"
)
)
(defprotocol IGraphImmutable
(add [g to-add]
"Returns `g`', with `to-add` added to its contents.
Throws a ::ReadOnly exception if (read-only? `g`)
Where
- `g` is a graph
- `to-add` is in triples-format
"
)
(subtract [g to-subtract]
"Returns `g`' with `to-subtract` removed from its contents.
Throws an exception if (mutability g) != ::immutable
Where
- `g` is an immutablegraph
- `to-subtract` is in triples-removal-format
"
))
(defprotocol IGraphMutable
(add! [g to-add]
"Returns `g`, with `to-add` added to its contents.
Throws an exception if (mutability g) != ::mutable
Where
- `g` is a mutable graph
- `to-add` is in triples-format
"
)
(subtract! [g to-subtract]
"Returns `g` with `to-subtract` removed from its contents.
Throws a ::ReadOnly exception if (read-only? `g`)
Where
- `g` is a graph
- `to-subtract` is in triples-removal-format
"
))
(defprotocol IGraphAccumulateOnly
(claim [g to-add]
"Returns `g`, with `to-add` added to `g`'s associated transactor.
Throws an exception if (mutability g) != ::accumulate-only
Where
- `g` is a mutable graph
- `to-add` is in triples-format
NOTE: see Datomic documentation for the 'add' operation for details
"
)
(retract [g to-retract]
"Returns `g` with `comm` reset to head
Side-effect: `to-retract` retracted from `comm`
Throws an exception if (mutability g) != ::accumulate-only.
Where
- `g` is a graph
- `comm` is a datomic-style transactor
`to-retract` is in triples-removal-format
NOTE: see Datomic documentation for details
"
))
(defprotocol IGraphSet
"Basic set operations between graphs."
(union [g1 g2]
"Returns an IGraph whose normal form contains all triples from g1 and g2"
)
(intersection [g1 g2]
"Returns an IGraph whose normal form contains all and only statements shared by both g1 and g2"
)
(difference [g1 g2]
"Returns an IGraph whose normal form contains all statements in g1 not present in g2."
)
)
(defn normal-form?
"Returns true iff `m` is in normal form for IGraph."
TODO : port to clojure.spec
[m]
(and (map? m)
(or (empty? m)
(let [p (m (first (keys m)))
o (p (first (keys p)))
]
(set? o)))))
(spec/def ::normal-form #(normal-form? %))
(spec/def ::vector (spec/and vector? #(> (count %) 1) #(odd? (count %))))
(spec/def ::vector-of-vectors (spec/and vector? (spec/every ::vector)))
(spec/def ::triples-format (spec/or :vector-of-vectors ::vector-of-vectors
:vector ::vector
:normal-form ::normal-form))
(defn triples-format
"Returns the value of (:triples-format (meta `triples-spec`)) or one of #{:vector :vector-of-vectors :normal-form `type`} inferred from the shape of `triples-spec`
Where
- `args` := [`g` `triples-spec`], arguments to a method add or remove from graph
- `g` is a graph
- `triples-spec` is a specification of triples typically to add to or remove
from `g`
- `:normal-form` indicates (normal-form? `triples-spec`) = true
- `:triple` indicates `triples-spec` := [`s` `p` `o`]
- `:vector-of-vectors` indicates `triples-spec` := [`triple`...]
- `type` = (type `triples-spec`)
"
[triples-spec]
(or (::triples-format (meta triples-spec))
(let [conform (spec/conform ::triples-format triples-spec)]
(if (= conform ::spec/invalid)
(throw (ex-info "Invalid triples format"
(spec/explain-data ::triples-format triples-spec)))
(let [[format _value_] conform]
format)))))
(spec/fdef triples-format
:ret #{:vector-of-vectors
:vector
:normal-form
})
(defmulti add-to-graph
"Returns `g`, with `to-add` added
Where
- `g` is a Graph
- `to-add` is interpetable as a set of triples
Dispatched according to `triples-format`
"
(fn [g to-add] [(type g) (triples-format to-add)]))
(spec/def ::underspecified-triple (spec/and vector?
#(> (count %) 0)
#(< (count %) 3)
#(not (vector? (% 0)))))
(spec/def ::vector-of-underspecified (spec/and vector?
#(> (count %) 0)
#(vector? (% 0))))
(spec/def ::removal-format (spec/or
:triples-format ::triples-format
:underspecified-triple ::underspecified-triple
:vector-of-vectors ::vector-of-underspecified))
(defn triples-removal-format
"Returns a keyword describing the format of `triples-spec` for removing a
set of triples from a graph.
"
[triples-spec]
(or (::triples-format (meta triples-spec))
(let [conform (spec/conform ::removal-format triples-spec)]
(if (= conform ::spec/invalid)
(throw (ex-info "Invalid triples format"
(spec/explain-data ::removal-format triples-spec)))
(let [[format value] conform]
(if (= format :triples-format)
(let [[triples-format _] value]
triples-format)
format))))))
(spec/fdef triples-removal-format
:ret #{:vector-of-vectors
:vector
:normal-form
:underspecified-triple})
(defmulti remove-from-graph
"Returns `g`, with `to-remove` removed
Where
- `g` is a Graph
- `to-remove` is interpetable as a set of triples
Dispatched according to `triples-removal-format`
"
(fn [g to-remove] [(type g) (triples-removal-format to-remove)]))
(defn traverse
"Returns `acc` acquired by applying `traversal` to `g` starting with `queue`, informed by `context`
Where
- `acc` is an arbitrary clojure 'accumulator' object (similar to a
reduce function). Default is `[]`.
- `traversal` := (fn [g context acc queue]...)
-> [`context'` `acc'` `queue'`]
- `g` is a graph
- `context` := {`context-key` `context-value`....}, expressing important
aspects of the traversal state
- `queue` := [`node` ...], nodes to visit
- `context-key` := #{:history ... maybe :skip? ... :seek ... or other
keys specific to `traversal`, which `traversal` may use to communicate
with future iterations of itself.
- `history` := #{`visited-node` ...}, this is conj'd with each visited node on
each call to avoid cycles.
- `skip?` (optional) := (fn [`node`] -> true if we should skip). This may also
be a set of nodes to skip. This allows for overriding the default skipping
behavior which simply skips `history`
- `seek` (optional) := (fn [context acc] -> `acc'`, a function to be called
at the start of each traversal, a truthy, non-empty response to which will
be the immediate return value of the traverse function. This would save you
the time and trouble of processing the whole queue, or making each traversal
function smart enough to stop early. Must return the same type as `acc`.
- `node` is typically an element in `g`, but can be any value the traversal
function knows how to handle
- `visited-node` is a node visited upstream. We filter these out to
avoid cycles. This can also be specified in advance by the user.
- `target` is a node we may be searching for.
Note: it is good practice to assign a :transition-fn metadata tag to
transition functions, though such data is not referenced anywhere
at this point.
"
([g traversal queue]
(traverse g traversal {:history #{}} [] queue))
([g traversal acc queue]
(traverse g traversal {:history #{}} acc queue))
([g traversal context acc queue]
{:pre [(satisfies? IGraph g)
(fn? traversal)
(map? context)
(or (set? (:history context))
(nil? (:history context)))
(or (nil? (:seek context))
(fn? (:seek context)))
(or (nil? (:skip? context))
(fn? (:skip? context))
(set? (:skip? context)))
(sequential? queue)
]
}
(let [seek (and (:seek context) ((:seek context) context acc))
must be same type as acc
(assert (= (type result) (type acc)))
result)
]
(if (and seek (seq seek))
(check-result seek)
(if (or (nil? queue)
(empty? queue))
(if (:seek context)
(check-result ((:seek context) context acc))
acc)
(let [skip? (or (:skip? context)
(:history context)
#{}
)]
(if (skip? (first queue))
(recur g traversal context acc (rest queue))
(let [[context acc queue-next] (traversal g context acc queue)]
(recur g
traversal
(update context :history
(fn [history]
(conj (or history #{})
(first queue))))
acc
queue-next
)))))))))
(defn transitive-closure
"Returns `traversal` for chains of `p`.
Where
`traversal` := (fn [g acc queue]...) -> [`context` `acc'` `queue'`],
s.t. `queue'` conj's all `o` s.t. (g `s` `p` `o`).
A traversal function argument for the `traverse` function .
`p` is a predicate, typcially an element of `g`
`g` is a graph.
NOTE:
cf the '*' operator in SPARQL property paths
"
[p]
}
(fn transistive-closure-traversal [g context acc queue]
[context,
(conj acc (first queue)),
(reduce conj (rest queue) (g (first queue) p))]))
(defn traverse-link
"Returns traversal function (fn [g context, acc queue]...)
-> [context, acc', queue'], following one `p` in `g`
Where
- `acc` is a set
- `queue` := [`node` ...], nodes to visit in traversal
- `p` is a predicate in `g`
- `g` is a graph
NOTE: typically used as one component in a traversal path
"
[p]
]
}
(fn link-traversal [g context acc queue]
(let [s (first queue)]
[context,
(reduce conj
acc
(g s p)),
(rest queue)])))
(defn maybe-traverse-link
"Returns traversal function (fn [g context, acc queue]...)
-> [context, acc', queue'],
Where
- `acc'` includes `node` and and as many `o`s as are linked from `node`
by `p` in `g`
- `queue` := [`node` ...], nodes to visit in traversal
- `p` is a predicate in `g`
- `g` is a graph
NOTE: typically used as one component in a traversal path.
cf the '?' operator in SPARQL property paths
"
[p]
(fn optional-link-traversal [g context acc queue]
(let [s (first queue)]
[context,
(reduce conj
(conj acc s)
(g s p)),
(rest queue)])))
(defn traverse-or
"Returns traversal function (fn [g context, acc queue]...)
-> [context, acc', queue'], for `ps`
Where
- `acc'` includes `node` and and as many `o`s as are linked from `node`
by `p1` | `p2` | ... in `g`
- `queue` := [`node` ...], nodes to visit in traversal
- `ps` := [`p1`, `p2`, ...]
- `p1`, `p2`, ... are all predicates in `g`, or traversal functions
- `g` is a graph
cf the '|' operator in SPARQL property paths
"
[& ps]
(fn traversal-disjunction [g context acc queue]
(letfn [(collect-traversals
[s sacc p]
(reduce conj sacc (g s p)))
]
[context,
(reduce conj acc (reduce (partial collect-traversals (first queue))
#{}
ps)),
(rest queue)
]) ))
(defn t-comp
"Returns a traversal function composed of elements specified in `comp-spec`
Where
- `comp-spec` := {:path [`spec-element`, ...]
`spec-element` {:fn `traversal-fn`
:doc `docstring`
:into `initial-acc` (default [])
:local-context-fn `local-fn` (default nil)
:update-global-context `global-fn` ( default nil)
}
}
Or Alternatively, [`traversal-fn-or-property-name`, ...] for the short
form.
- `spec-element` is typically a keyword naming a stage in the traversal, though
it can also be a direct reference to a traversal function, in which case
it will be equivalent to {:fn `spec-element`}
- `traversal-fn-generator` := (fn [spec-element]...) -> `traversal-fn`, to be
invoked in cases where there is no `spec-element` in `comp-spec`,
traverse-link is the typical choice here.
- `traversal-fn` := (fn [g context acc queue]...) -> [context' acc' queue']
- `context` is a traversal context conforming to the traverse function (see docs)
- `update-fn` := (fn [global-context local-context] ...) -> global-context'
This is provided in case there is some coordination that needs to be provided
between stages in a composed traversal.
- `initial-acc` is the (usually empty) container used to initial the acc
of the traversal stage being specified
- `local-context-fn` := [global-context] -> `local-context`
- `update-global-context` := [global-context local-context] -> `global-context`'
- `local-context` is the context for a given stage of the traversal
- `global-context` carries over between traversal stages.
Examples
(def comp-spec {
:isa? {:fn (maybe-traverse-link :isa)
:doc `traverses an isa link, if it exists`
:local-context {:doc `traversing an isa link`}
:update-global-context
(fn [gc lc] (assoc gc
:status :followed-isa-link))
}
:subClassOf* {:fn (transitive-closure :subClassOf)
:doc 'traverses 0 or more subClassof links'
:local-context-fn (fn [c] {:doc 'traversing subClassOf*'})
:into #{}
:update-global-context
(fn [gc lc] (assoc gc
:status :followed-subclassof))
}
}})
(traversal-comp (merge comp-spec
{:path [:isa? :subClassOf*]
:doc 'Traverses the chain of subsumption links for an instance or class'
}))
(t-comp (merge comp-spec {:path [:isa :label] :doc 'gets class labels')))
Short form example:
(t-comp [:family/parent :family/brother])
... Equal to (t-comp [(traverse-link :family/parent)
(traverse-link :family/brother)]
An inferred 'uncle' relation.
"
[comp-spec]
{:pre [(or (not (:path comp-spec)) (vector? (:path comp-spec)))
TODO use clojure.spec
}
{:path comp-spec}
]
(fn composed-traversal [g context acc queue]
{:pre [(satisfies? IGraph g)
(map? context)
(sequential? queue)
]
}
(loop [c context
q queue]
(if (empty? path)
[(if-let [update-context (:update-global-context c)]
(update-context context c)
context)
(into acc q)
[]]
(let [p (first path)
p-spec (or (comp-spec p) {})
c (if-let [lcfn (:local-context-fn p-spec)]
(lcfn c)
{})
f (cond
(fn? p) p
:else
(or (:fn p-spec)
(traverse-link p)
))
_ (assert f)
]
(recur c
(rest path)
(traverse g f c a q))))))))
(defn- match-or-traverse-tag
"Returns :traverse if `p` is a function, else :match
Informs p-dispatcher
"
[p]
(if (fn? p)
:traverse
:match))
(defn p-dispatcher
"Returns :traverse or :match, as a basis for dispatching standard `invoke` methods involving a `p` argument, which may be either a value to match or a traversal function.
"
([_g_ _s_ p]
(match-or-traverse-tag p))
([_g_ _s_ p _o_]
(match-or-traverse-tag p)))
(defmulti match-or-traverse
"Returns values appropriate for (g s p) or (g s p o) invocations
Where
- `o` is an object in `g`
- `s` is a subject in `g`
- `p` is either a predicate in `g` or a traversal function accumulating
a set, starting with an empty accumulator and queue of [`s`]
(see docs for `traverse`)
NOTE: Implementers of IGraph will typically use this
method for IFn `invoke` members involving a `p` argument.
"
p-dispatcher)
(defmethod match-or-traverse :traverse
([g s p]
{:doc "`p` is a traversal function. Aggregate a set."
:pre [(fn? p)]
}
(traverse g p #{} [s]))
([g s p o]
{:doc "`p` is a traversal function. Stop when you find `o`."
:pre [(fn? p)]
}
(declare unique)
(let [seek-o (fn seek-o [_context_ acc]
(clojure.set/intersection acc #{o}))
]
(unique (traverse g p {:seek seek-o} #{} [s])))))
(defmethod match-or-traverse :match
([g s p]
{:doc "`p` is a graph property to be matched"}
(get-o g s p))
([g s p o]
(ask g s p o)))
Stuff to deal with cardinality one ....
(defn unique
"Returns the single member of `coll`, or nil if `coll` is empty. Calls `on-ambiguity` if there is more than one member (default is to throw an Exception).
Where
- `coll` is a collection
- `on-ambiguity` := (fn [coll] ...) -> `value`, default raises an error.
Note: this can be used when you've called (G s p) and you're sure there is
only one object.
"
([coll on-ambiguity]
(if (seq coll)
(if (> (count coll) 1)
(on-ambiguity coll)
(first coll))))
([coll]
(unique coll (fn [coll]
(throw (ex-info "Unique called on non-unique collection"
{:type ::NonUnique
:coll coll
}))))))
(defn flatten-description
"Returns `p-o` description with singletons broken out into scalars
Where
- `p-o` := {`p` #{`o`}, ...}, normal form at 'description' level of a graph.
"
[p-o]
(let [maybe-flatten (fn [acc k v]
(assoc acc
k
(if (and (set? v) (= (count v) 1))
(unique v)
v)))
]
(reduce-kv maybe-flatten {} p-o)))
^{:inverse-of flatten-description}
(defn normalize-flat-description
"Returns a normalized p-o description of `m`
Where
- `m` is a plain clojure map"
[m]
(let [maybe-setify (fn [acc k v]
(assoc acc
k
(if (not (set? v))
#{v}
v)))
]
(reduce-kv maybe-setify {} m)))
(defn assert-unique-fn
"Returns `g`', replacing any existing [s p *] with [s p o] per `context`
Where
- `g` is a graph
- `context` := m s.t. (keys m) = #{:add-fn :subtrct-fn}
- `add-fn` is one of #{add, add! claim} appropriate to `g`'s modification protocol
- `subtract-fn` is one of #{subtract, subtract! retract} appropriate to `g`'s
modification protocol
"
([context g s p o]
(let [{:keys [add-fn subtract-fn]} context
]
(add-fn (subtract-fn g [s p])
[s p o]))))
(def assert-unique
"fn [g s p o] -> g', asserting a unique triple in immutable graph.
- Wrapper around `assert-unique-fn`"
(partial assert-unique-fn {:add-fn add :subtract-fn subtract}))
(def assert-unique!
"fn [g s p o] -> g', asserting a unique triple in mutable graph.
- Wrapper around `assert-unique-fn`"
(partial assert-unique-fn {:add-fn add! :subtract-fn subtract!}))
(def claim-unique
"fn [g s p o] -> g', asserting a unique triple in an accumulate-only graph .
- Wrapper around `assert-unique-fn`"
(partial assert-unique-fn {:add-fn claim :subtract-fn retract}))
(defn reduce-spo
"Returns `acc'` s.t. (f acc s p o) -> `acc'` for every triple in `g`
Where
- `f` := (fn [acc s p o] -> `acc'`
- `acc` is any value, a reduction accumlator
- `s` `p` `o` constitute a triple in `g`
- `g` implements IGraph
NOTE: C.f. reduce-kv
"
[f acc g]
(letfn [(collect-o [s p acc o]
(f acc s p o)
)
(collect-p-o [s acc p]
(reduce (partial collect-o s p)
acc
(g s p)))
(collect-s-p-o [acc s]
(reduce (partial collect-p-o s)
acc
(keys (g s))))
]
(reduce collect-s-p-o
acc
(subjects g))))
|
4afb980b00e49da967568af6a6bbc90f8f87b3188f57471bf4a7b1e1ab467499 | camllight/camllight | main.ml | (* The lexer generator. Command-line parsing. *)
#open "sys";;
#open "lexing";;
#open "parsing";;
#open "syntax";;
#open "scanner";;
#open "grammar";;
#open "lexgen";;
#open "output";;
let main () =
if vect_length command_line != 2 then begin
prerr_endline "Usage: camllex <input file>";
io__exit 2
end;
let source_name = command_line.(1) in
let dest_name =
if filename__check_suffix source_name ".mll" then
filename__chop_suffix source_name ".mll" ^ ".ml"
else
source_name ^ ".ml" in
ic := open_in_bin source_name;
oc := open_out dest_name;
let lexbuf =
create_lexer_channel !ic in
let (Lexdef(header,_) as def) =
try
lexer_definition main lexbuf
with exn ->
close_out !oc;
sys__remove dest_name;
begin match exn with
Parse_error ->
prerr_string "Syntax error around char ";
prerr_int (get_lexeme_start lexbuf);
prerr_endline "."
| scan_aux__Lexical_error s ->
prerr_string "Lexical error around char ";
prerr_int (get_lexeme_start lexbuf);
prerr_string ": ";
prerr_string s;
prerr_endline "."
| _ -> raise exn
end;
exit 2 in
let ((init, states, acts) as dfa) = make_dfa def in
output_lexdef header dfa;
close_in !ic;
close_out !oc
;;
printexc__f main (); exit 0;;
| null | https://raw.githubusercontent.com/camllight/camllight/0cc537de0846393322058dbb26449427bfc76786/windows/src/lex/main.ml | ocaml | The lexer generator. Command-line parsing. |
#open "sys";;
#open "lexing";;
#open "parsing";;
#open "syntax";;
#open "scanner";;
#open "grammar";;
#open "lexgen";;
#open "output";;
let main () =
if vect_length command_line != 2 then begin
prerr_endline "Usage: camllex <input file>";
io__exit 2
end;
let source_name = command_line.(1) in
let dest_name =
if filename__check_suffix source_name ".mll" then
filename__chop_suffix source_name ".mll" ^ ".ml"
else
source_name ^ ".ml" in
ic := open_in_bin source_name;
oc := open_out dest_name;
let lexbuf =
create_lexer_channel !ic in
let (Lexdef(header,_) as def) =
try
lexer_definition main lexbuf
with exn ->
close_out !oc;
sys__remove dest_name;
begin match exn with
Parse_error ->
prerr_string "Syntax error around char ";
prerr_int (get_lexeme_start lexbuf);
prerr_endline "."
| scan_aux__Lexical_error s ->
prerr_string "Lexical error around char ";
prerr_int (get_lexeme_start lexbuf);
prerr_string ": ";
prerr_string s;
prerr_endline "."
| _ -> raise exn
end;
exit 2 in
let ((init, states, acts) as dfa) = make_dfa def in
output_lexdef header dfa;
close_in !ic;
close_out !oc
;;
printexc__f main (); exit 0;;
|
830ea69ee5cf53aa45ab7ccafccb9b9a414d085ce7ce5dfe02f71b3cca73c570 | imitator-model-checker/imitator | AlgoBCShuffle.mli | * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
*
* IMITATOR
*
* Université Paris 13 , LIPN , CNRS , France
* Université de Lorraine , CNRS , , LORIA , Nancy , France
*
* Module description : Classical Behavioral Cartography with exhaustive coverage of integer points [ AF10 ] . Shuffled version , used for the distributed cartography . [ ACN15 ]
*
* File contributors : * Created : 2016/03/14
*
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
*
* IMITATOR
*
* Université Paris 13, LIPN, CNRS, France
* Université de Lorraine, CNRS, Inria, LORIA, Nancy, France
*
* Module description: Classical Behavioral Cartography with exhaustive coverage of integer points [AF10]. Shuffled version, used for the distributed cartography. [ACN15]
*
* File contributors : Étienne André
* Created : 2016/03/14
*
************************************************************)
(************************************************************)
(* Modules *)
(************************************************************)
open AlgoCartoGeneric
(************************************************************)
(* Class definition *)
(************************************************************)
class algoBCShuffle : HyperRectangle.hyper_rectangle -> NumConst.t -> (PVal.pval -> AlgoStateBased.algoStateBased) -> tiles_storage ->
object inherit algoCartoGeneric
(************************************************************)
(* Class variables *)
(************************************************************)
(************************************************************)
(* Class methods *)
(************************************************************)
method algorithm_name : string
method initialize_variables : unit
( * * Return a new instance of the algorithm to be iteratively called ( typically IM or PRP )
method algorithm_instance : AlgoIMK.algoIMK*)
(* Create the initial point for the analysis *)
method get_initial_point : more_points
(* Find the next point *)
method find_next_point : more_points
method compute_bc_result : Result.imitator_result
end | null | https://raw.githubusercontent.com/imitator-model-checker/imitator/105408ae2bd8c3e3291f286e4d127defd492a58b/src/AlgoBCShuffle.mli | ocaml | **********************************************************
Modules
**********************************************************
**********************************************************
Class definition
**********************************************************
**********************************************************
Class variables
**********************************************************
**********************************************************
Class methods
**********************************************************
Create the initial point for the analysis
Find the next point | * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
*
* IMITATOR
*
* Université Paris 13 , LIPN , CNRS , France
* Université de Lorraine , CNRS , , LORIA , Nancy , France
*
* Module description : Classical Behavioral Cartography with exhaustive coverage of integer points [ AF10 ] . Shuffled version , used for the distributed cartography . [ ACN15 ]
*
* File contributors : * Created : 2016/03/14
*
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
*
* IMITATOR
*
* Université Paris 13, LIPN, CNRS, France
* Université de Lorraine, CNRS, Inria, LORIA, Nancy, France
*
* Module description: Classical Behavioral Cartography with exhaustive coverage of integer points [AF10]. Shuffled version, used for the distributed cartography. [ACN15]
*
* File contributors : Étienne André
* Created : 2016/03/14
*
************************************************************)
open AlgoCartoGeneric
class algoBCShuffle : HyperRectangle.hyper_rectangle -> NumConst.t -> (PVal.pval -> AlgoStateBased.algoStateBased) -> tiles_storage ->
object inherit algoCartoGeneric
method algorithm_name : string
method initialize_variables : unit
( * * Return a new instance of the algorithm to be iteratively called ( typically IM or PRP )
method algorithm_instance : AlgoIMK.algoIMK*)
method get_initial_point : more_points
method find_next_point : more_points
method compute_bc_result : Result.imitator_result
end |
e1a6032591848d8ab4b0e1dfe078da970a454a08103e67fbcd6d6931bac872bb | arttuka/reagent-material-ui | person_2_rounded.cljs | (ns reagent-mui.icons.person-2-rounded
"Imports @mui/icons-material/Person2Rounded as a Reagent component."
(:require-macros [reagent-mui.util :refer [create-svg-icon e]])
(:require [react :as react]
["@mui/material/SvgIcon" :as SvgIcon]
[reagent-mui.util]))
(def person-2-rounded (create-svg-icon (e "path" #js {"d" "M18.39 14.56C16.71 13.7 14.53 13 12 13s-4.71.7-6.39 1.56C4.61 15.07 4 16.1 4 17.22V18c0 1.1.9 2 2 2h12c1.1 0 2-.9 2-2v-.78c0-1.12-.61-2.15-1.61-2.66zM9.78 12h4.44c1.21 0 2.14-1.06 1.98-2.26l-.32-2.45C15.57 5.39 13.92 4 12 4S8.43 5.39 8.12 7.29L7.8 9.74c-.16 1.2.77 2.26 1.98 2.26z"})
"Person2Rounded"))
| null | https://raw.githubusercontent.com/arttuka/reagent-material-ui/14103a696c41c0eb67fc07fc67cd8799efd88cb9/src/icons/reagent_mui/icons/person_2_rounded.cljs | clojure | (ns reagent-mui.icons.person-2-rounded
"Imports @mui/icons-material/Person2Rounded as a Reagent component."
(:require-macros [reagent-mui.util :refer [create-svg-icon e]])
(:require [react :as react]
["@mui/material/SvgIcon" :as SvgIcon]
[reagent-mui.util]))
(def person-2-rounded (create-svg-icon (e "path" #js {"d" "M18.39 14.56C16.71 13.7 14.53 13 12 13s-4.71.7-6.39 1.56C4.61 15.07 4 16.1 4 17.22V18c0 1.1.9 2 2 2h12c1.1 0 2-.9 2-2v-.78c0-1.12-.61-2.15-1.61-2.66zM9.78 12h4.44c1.21 0 2.14-1.06 1.98-2.26l-.32-2.45C15.57 5.39 13.92 4 12 4S8.43 5.39 8.12 7.29L7.8 9.74c-.16 1.2.77 2.26 1.98 2.26z"})
"Person2Rounded"))
| |
59429d43e42ab34ff89a0ad22d4b8ae643efe1f866d2453bce8adc9d45f2cf56 | BillHallahan/G2 | TestUtils.hs | {-# LANGUAGE OverloadedStrings #-}
module TestUtils where
import qualified Data.Map as M
import Data.Monoid
import qualified Data.Text as T
import System.Directory
import G2.Config
import G2.Language
mkConfigTestIO :: IO Config
mkConfigTestIO = do
homedir <- getHomeDirectory
return $
(mkConfigDirect homedir [] M.empty)
{ higherOrderSolver = AllFuncs
, timeLimit = 150
-- , baseInclude = [ "./base-4.9.1.0/Control/Exception/"
, " ./base-4.9.1.0/ " ]
, base = baseSimple homedir
, extraDefaultMods = [] }
mkConfigTestWithSetIO :: IO Config
mkConfigTestWithSetIO = mkConfigTestWithMapIO
mkConfigTestWithMapIO :: IO Config
mkConfigTestWithMapIO = do
config <- mkConfigTestIO
homedir <- getHomeDirectory
return $ config { base = base config }
eqIgT :: Expr -> Expr -> Bool
eqIgT (Var n) (Var n') = eqIgIds n n'
eqIgT (Lit c) (Lit c') = c == c'
eqIgT (Prim p _) (Prim p' _) = p == p'
eqIgT (Lam _ n e) (Lam _ n' e') = eqIgIds n n' && e `eqIgT` e'
eqIgT (App e1 e2) (App e1' e2') = e1 `eqIgT` e1' && e2 `eqIgT` e2'
eqIgT (Data (DataCon n _)) (Data (DataCon n' _)) = eqIgNames n n'
eqIgT (Type _) (Type _)= True
eqIgT _ _ = False
eqIgIds :: Id -> Id -> Bool
eqIgIds (Id n _) (Id n' _) = eqIgNames n n'
eqIgNames :: Name -> Name -> Bool
eqIgNames (Name n m _ _) (Name n' m' _ _) = n == n' && m == m'
typeNameIs :: Type -> T.Text -> Bool
typeNameIs (TyCon n _) s = s == nameOcc n
typeNameIs (TyApp t _) s = typeNameIs t s
typeNameIs _ _ = False
dcHasName :: T.Text -> Expr -> Bool
dcHasName s (Data (DataCon n _)) = s == nameOcc n
dcHasName _ _ = False
isBool :: Expr -> Bool
isBool (Data (DataCon _ (TyCon (Name "Bool" _ _ _) _))) = True
isBool _ = False
dcInAppHasName :: T.Text -> Expr -> Int -> Bool
dcInAppHasName s (Data (DataCon n _)) 0 = s == nameOcc n
dcInAppHasName s (App a _) n = dcInAppHasName s a (n - 1)
dcInAppHasName _ _ _ = False
buriedDCName :: T.Text -> Expr -> Bool
buriedDCName s (App a _) = buriedDCName s a
buriedDCName s (Data (DataCon n _)) = s == nameOcc n
buriedDCName _ _ = False
appNthArgIs :: Expr -> (Expr -> Bool) -> Int -> Bool
appNthArgIs a f i =
let
u = unApp a
in
case length u > i of
True -> f (u !! i)
False -> False
isInt :: Expr -> (Integer -> Bool) -> Bool
isInt (Lit (LitInt x)) f = f x
isInt (App _ (Lit (LitInt x))) f = f x
isInt _ _ = False
appNth :: Expr -> Int -> (Expr -> Bool) -> Bool
appNth e 0 p = p e
appNth (App _ e) i p = appNth e (i - 1) p
appNth _ _ _ = False
isIntT :: Type -> Bool
isIntT (TyCon (Name "Int" _ _ _) _) = True
isIntT _ = False
isDouble :: Expr -> (Rational -> Bool) -> Bool
isDouble (App _ (Lit (LitDouble x))) f = f x
isDouble _ _ = False
isFloat :: Expr -> (Rational -> Bool) -> Bool
isFloat (Lit (LitFloat x)) f = f x
isFloat (App _ (Lit (LitFloat x))) f = f x
isFloat _ _ = False
inCast :: Expr -> (Expr -> Bool) -> (Coercion -> Bool) -> Bool
inCast (Cast e c) p q = p e && q c
inCast _ _ _ = False
notCast :: Expr -> Bool
notCast (Cast _ _) = False
notCast _ = True
getInt :: Expr -> a -> (Integer -> a) -> a
getInt (Lit (LitInt x)) _ f = f x
getInt (App _ (Lit (LitInt x))) _ f = f x
getInt _ x _ = x
getIntB :: Expr -> (Integer -> Bool) -> Bool
getIntB e = getInt e False
getBoolB :: Expr -> (Bool -> Bool) -> Bool
getBoolB (Data (DataCon n _)) f = f (nameOcc n == "True")
getBoolB _ _ = False
isApp :: Expr -> Bool
isApp (App _ _) = True
isApp _ = False
isError :: Expr -> Bool
isError (Prim Error _) = True
isError _ = False
isTyFun :: Type -> Bool
isTyFun (TyFun _ _) = True
isTyFun _ = False
noUndefined :: Expr -> Bool
noUndefined = getAll . evalASTs noUndefined'
noUndefined' :: Expr -> All
noUndefined' (Prim Undefined _) = All False
noUndefined' _ = All True
| null | https://raw.githubusercontent.com/BillHallahan/G2/521ac4f4a6573f15521765cefc3255be33249d2e/tests/TestUtils.hs | haskell | # LANGUAGE OverloadedStrings #
, baseInclude = [ "./base-4.9.1.0/Control/Exception/" |
module TestUtils where
import qualified Data.Map as M
import Data.Monoid
import qualified Data.Text as T
import System.Directory
import G2.Config
import G2.Language
mkConfigTestIO :: IO Config
mkConfigTestIO = do
homedir <- getHomeDirectory
return $
(mkConfigDirect homedir [] M.empty)
{ higherOrderSolver = AllFuncs
, timeLimit = 150
, " ./base-4.9.1.0/ " ]
, base = baseSimple homedir
, extraDefaultMods = [] }
mkConfigTestWithSetIO :: IO Config
mkConfigTestWithSetIO = mkConfigTestWithMapIO
mkConfigTestWithMapIO :: IO Config
mkConfigTestWithMapIO = do
config <- mkConfigTestIO
homedir <- getHomeDirectory
return $ config { base = base config }
eqIgT :: Expr -> Expr -> Bool
eqIgT (Var n) (Var n') = eqIgIds n n'
eqIgT (Lit c) (Lit c') = c == c'
eqIgT (Prim p _) (Prim p' _) = p == p'
eqIgT (Lam _ n e) (Lam _ n' e') = eqIgIds n n' && e `eqIgT` e'
eqIgT (App e1 e2) (App e1' e2') = e1 `eqIgT` e1' && e2 `eqIgT` e2'
eqIgT (Data (DataCon n _)) (Data (DataCon n' _)) = eqIgNames n n'
eqIgT (Type _) (Type _)= True
eqIgT _ _ = False
eqIgIds :: Id -> Id -> Bool
eqIgIds (Id n _) (Id n' _) = eqIgNames n n'
eqIgNames :: Name -> Name -> Bool
eqIgNames (Name n m _ _) (Name n' m' _ _) = n == n' && m == m'
typeNameIs :: Type -> T.Text -> Bool
typeNameIs (TyCon n _) s = s == nameOcc n
typeNameIs (TyApp t _) s = typeNameIs t s
typeNameIs _ _ = False
dcHasName :: T.Text -> Expr -> Bool
dcHasName s (Data (DataCon n _)) = s == nameOcc n
dcHasName _ _ = False
isBool :: Expr -> Bool
isBool (Data (DataCon _ (TyCon (Name "Bool" _ _ _) _))) = True
isBool _ = False
dcInAppHasName :: T.Text -> Expr -> Int -> Bool
dcInAppHasName s (Data (DataCon n _)) 0 = s == nameOcc n
dcInAppHasName s (App a _) n = dcInAppHasName s a (n - 1)
dcInAppHasName _ _ _ = False
buriedDCName :: T.Text -> Expr -> Bool
buriedDCName s (App a _) = buriedDCName s a
buriedDCName s (Data (DataCon n _)) = s == nameOcc n
buriedDCName _ _ = False
appNthArgIs :: Expr -> (Expr -> Bool) -> Int -> Bool
appNthArgIs a f i =
let
u = unApp a
in
case length u > i of
True -> f (u !! i)
False -> False
isInt :: Expr -> (Integer -> Bool) -> Bool
isInt (Lit (LitInt x)) f = f x
isInt (App _ (Lit (LitInt x))) f = f x
isInt _ _ = False
appNth :: Expr -> Int -> (Expr -> Bool) -> Bool
appNth e 0 p = p e
appNth (App _ e) i p = appNth e (i - 1) p
appNth _ _ _ = False
isIntT :: Type -> Bool
isIntT (TyCon (Name "Int" _ _ _) _) = True
isIntT _ = False
isDouble :: Expr -> (Rational -> Bool) -> Bool
isDouble (App _ (Lit (LitDouble x))) f = f x
isDouble _ _ = False
isFloat :: Expr -> (Rational -> Bool) -> Bool
isFloat (Lit (LitFloat x)) f = f x
isFloat (App _ (Lit (LitFloat x))) f = f x
isFloat _ _ = False
inCast :: Expr -> (Expr -> Bool) -> (Coercion -> Bool) -> Bool
inCast (Cast e c) p q = p e && q c
inCast _ _ _ = False
notCast :: Expr -> Bool
notCast (Cast _ _) = False
notCast _ = True
getInt :: Expr -> a -> (Integer -> a) -> a
getInt (Lit (LitInt x)) _ f = f x
getInt (App _ (Lit (LitInt x))) _ f = f x
getInt _ x _ = x
getIntB :: Expr -> (Integer -> Bool) -> Bool
getIntB e = getInt e False
getBoolB :: Expr -> (Bool -> Bool) -> Bool
getBoolB (Data (DataCon n _)) f = f (nameOcc n == "True")
getBoolB _ _ = False
isApp :: Expr -> Bool
isApp (App _ _) = True
isApp _ = False
isError :: Expr -> Bool
isError (Prim Error _) = True
isError _ = False
isTyFun :: Type -> Bool
isTyFun (TyFun _ _) = True
isTyFun _ = False
noUndefined :: Expr -> Bool
noUndefined = getAll . evalASTs noUndefined'
noUndefined' :: Expr -> All
noUndefined' (Prim Undefined _) = All False
noUndefined' _ = All True
|
6e3c2e78dcdc38c3a77c77b860eb8ef35fbf966bc63ec1baa84ff13fc73325b5 | sebashack/servantRestfulAPI | API.hs | {-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleContexts #-}
# LANGUAGE FlexibleInstances #
# LANGUAGE MultiParamTypeClasses #
# LANGUAGE OverloadedStrings #
{-# LANGUAGE ScopedTypeVariables #-}
# LANGUAGE TypeFamilies #
{-# LANGUAGE TypeOperators #-}
# LANGUAGE UndecidableInstances #
# LANGUAGE ScopedTypeVariables #
module Domains.ContentAdminDomain.Article.API
(
ArticleAPI
) where
import Domains.ContentAdminDomain.Article.DataTypes
import Servant.API
import Codec.Picture.Types
import Servant.JuicyPixels
import qualified Data.Time as TM
import qualified Data.Text as T
type ArticleId = T.Text
type ArticleAPI =
1 --
"article" :> Capture "articleId" ArticleId
:> QueryParam "lang" T.Text
:> Get '[JSON] ArticleWithAbstracts
2 --
:<|> "articles" :> QueryParam "lang" T.Text
:> QueryParam "from" Int
:> QueryParam "size" Int
:> Get '[JSON] [Abstract]
3 --
:<|> "articles" :> "search"
:> QueryParam "lang" T.Text
:> QueryParam "words" T.Text
:> QueryParam "from" Int
:> QueryParam "size" Int
:> Get '[JSON] [Abstract]
4 --
:<|> "articles" :> "location"
:> Capture "country" T.Text
:> QueryParam "region" T.Text
:> QueryParam "city" T.Text
:> QueryParam "lang" T.Text
:> QueryParam "from" Int
:> QueryParam "size" Int
:> Get '[JSON] [Abstract]
If no language is specified , the default language will always be english .
| null | https://raw.githubusercontent.com/sebashack/servantRestfulAPI/e625535d196acefaff4f5bf03108816be668fe4d/libs/Domains/ContentAdminDomain/Article/API.hs | haskell | # LANGUAGE DataKinds #
# LANGUAGE DeriveGeneric #
# LANGUAGE FlexibleContexts #
# LANGUAGE ScopedTypeVariables #
# LANGUAGE TypeOperators #
| # LANGUAGE FlexibleInstances #
# LANGUAGE MultiParamTypeClasses #
# LANGUAGE OverloadedStrings #
# LANGUAGE TypeFamilies #
# LANGUAGE UndecidableInstances #
# LANGUAGE ScopedTypeVariables #
module Domains.ContentAdminDomain.Article.API
(
ArticleAPI
) where
import Domains.ContentAdminDomain.Article.DataTypes
import Servant.API
import Codec.Picture.Types
import Servant.JuicyPixels
import qualified Data.Time as TM
import qualified Data.Text as T
type ArticleId = T.Text
type ArticleAPI =
"article" :> Capture "articleId" ArticleId
:> QueryParam "lang" T.Text
:> Get '[JSON] ArticleWithAbstracts
:<|> "articles" :> QueryParam "lang" T.Text
:> QueryParam "from" Int
:> QueryParam "size" Int
:> Get '[JSON] [Abstract]
:<|> "articles" :> "search"
:> QueryParam "lang" T.Text
:> QueryParam "words" T.Text
:> QueryParam "from" Int
:> QueryParam "size" Int
:> Get '[JSON] [Abstract]
:<|> "articles" :> "location"
:> Capture "country" T.Text
:> QueryParam "region" T.Text
:> QueryParam "city" T.Text
:> QueryParam "lang" T.Text
:> QueryParam "from" Int
:> QueryParam "size" Int
:> Get '[JSON] [Abstract]
If no language is specified , the default language will always be english .
|
1fb86b6283c6b1d3555cffa1e75c83c6b3b676428ba5528d4c5b1bbbaca58b11 | skanev/playground | 25.scm | SICP exercise 5.25
;
; Modify the evaluator so that it uses normal-order evaluation, based on the
lazy evaluator of section 4.2 .
; This is tricky.
;
First , in order to do normal - order evaluation , we should not cache thunk
; values. That would beat the purpose of normal-order.
;
Second , we will accomplish this with a more general procedure called
; ev-map-operands, that will apply the procedure in the exp register to each
; argument in unev. It is used by primitive-apply with actual-value and
; compound-apply with delay-it.
;
; We will also modify ev-if to use actual-value.
(define (delay-it exp env) (list 'thunk exp env))
(define (thunk? obj) (tagged-list? obj 'thunk))
(define (thunk-exp thunk) (cadr thunk))
(define (thunk-env thunk) (caddr thunk))
(define extra-operations
(list (list 'delay-it delay-it)
(list 'thunk? thunk?)
(list 'thunk-env thunk-env)
(list 'thunk-exp thunk-exp)))
(define ec-core
'(
(assign continue (label done))
eval-dispatch
(test (op self-evaluating?) (reg exp))
(branch (label ev-self-eval))
(test (op variable?) (reg exp))
(branch (label ev-variable))
(test (op quoted?) (reg exp))
(branch (label ev-quoted))
(test (op assignment?) (reg exp))
(branch (label ev-assignment))
(test (op definition?) (reg exp))
(branch (label ev-definition))
(test (op if?) (reg exp))
(branch (label ev-if))
(test (op lambda?) (reg exp))
(branch (label ev-lambda))
(test (op begin?) (reg exp))
(branch (label ev-begin))
(test (op application?) (reg exp))
(branch (label ev-application))
(goto (label unknown-expression-type))
; Delaying expressions
delay-it
(assign val (op delay-it) (reg exp) (reg env))
(goto (reg continue))
actual-value
(save continue)
(assign continue (label actual-value-after-eval))
(goto (label eval-dispatch))
actual-value-after-eval
(restore continue)
(assign exp (reg val))
(goto (label force-it))
force-it
(test (op thunk?) (reg exp))
(branch (label force-it-thunk))
(goto (reg continue))
force-it-thunk
(assign env (op thunk-env) (reg exp))
(assign exp (op thunk-exp) (reg exp))
(goto (label actual-value))
; Evaluating simple expressions
ev-self-eval
(assign val (reg exp))
(goto (reg continue))
ev-variable
(assign val (op lookup-variable-value) (reg exp) (reg env))
(goto (reg continue))
ev-quoted
(assign val (op text-of-quotation) (reg exp))
(goto (reg continue))
ev-lambda
(assign unev (op lambda-parameters) (reg exp))
(assign exp (op lambda-body) (reg exp))
(assign val (op make-procedure) (reg unev) (reg exp) (reg env))
(goto (reg continue))
; Evaluating procedure applications
ev-application
(save continue)
(save env)
(assign unev (op operands) (reg exp))
(save unev)
(assign exp (op operator) (reg exp))
(assign continue (label ev-appl-did-operator))
(goto (label eval-dispatch))
ev-appl-did-operator
(restore unev)
(restore env)
(assign proc (reg val))
(goto (label apply-dispatch))
; Procedure application
apply-dispatch
(test (op primitive-procedure?) (reg proc))
(branch (label primitive-apply))
(test (op compound-procedure?) (reg proc))
(branch (label compound-apply))
(goto (label unknown-procedure-type))
primitive-apply
(assign exp (label actual-value))
(assign continue (label primitive-apply-after-args))
(goto (label ev-map-operands))
primitive-apply-after-args
(assign val (op apply-primitive-procedure) (reg proc) (reg argl))
(restore continue)
(goto (reg continue))
compound-apply
(save continue)
(assign exp (label delay-it))
(assign continue (label compound-apply-after-args))
(goto (label ev-map-operands))
compound-apply-after-args
(restore continue)
(assign unev (op procedure-parameters) (reg proc))
(assign env (op procedure-environment) (reg proc))
(assign env (op extend-environment) (reg unev) (reg argl) (reg env))
(assign unev (op procedure-body) (reg proc))
(goto (label ev-sequence))
ev-map-operands
(assign argl (op empty-arglist))
(test (op no-operands?) (reg unev))
(branch (label ev-map-no-args))
(save continue)
(save proc)
(assign proc (reg exp))
(save proc)
ev-map-operand-loop
(restore proc)
(assign exp (op first-operand) (reg unev))
(test (op last-operand?) (reg unev))
(branch (label ev-map-last-arg))
(save proc)
(save argl)
(save env)
(save unev)
(assign continue (label ev-map-accumulate-arg))
(goto (reg proc))
ev-map-accumulate-arg
(restore unev)
(restore env)
(restore argl)
(assign argl (op adjoin-arg) (reg val) (reg argl))
(assign unev (op rest-operands) (reg unev))
(goto (label ev-map-operand-loop))
ev-map-last-arg
(save argl)
(assign continue (label ev-map-accumulate-last-arg))
(goto (reg proc))
ev-map-accumulate-last-arg
(restore argl)
(assign argl (op adjoin-arg) (reg val) (reg argl))
(restore proc)
(restore continue)
(goto (reg continue))
ev-map-no-args
(goto (reg continue))
; Sequence evaluation
ev-begin
(assign unev (op begin-actions) (reg exp))
(save continue)
(goto (label ev-sequence))
ev-sequence
(assign exp (op first-exp) (reg unev))
(test (op last-exp?) (reg unev))
(branch (label ev-sequence-last-exp))
(save unev)
(save env)
(assign continue (label ev-sequence-continue))
(goto (label eval-dispatch))
ev-sequence-continue
(restore env)
(restore unev)
(assign unev (op rest-exps) (reg unev))
(goto (label ev-sequence))
ev-sequence-last-exp
(restore continue)
(goto (label eval-dispatch))
; Conditionals
ev-if
(save exp)
(save env)
(save continue)
(assign continue (label ev-if-decide))
(assign exp (op if-predicate) (reg exp))
(goto (label actual-value))
ev-if-decide
(restore continue)
(restore env)
(restore exp)
(test (op true?) (reg val))
(branch (label ev-if-consequent))
ev-if-alternative
(assign exp (op if-alternative) (reg exp))
(goto (label eval-dispatch))
ev-if-consequent
(assign exp (op if-consequent) (reg exp))
(goto (label eval-dispatch))
; Assignments and definitions
ev-assignment
(assign unev (op assignment-variable) (reg exp))
(save unev)
(assign exp (op assignment-value) (reg exp))
(save env)
(save continue)
(assign continue (label ev-assignment-1))
(goto (label eval-dispatch))
ev-assignment-1
(restore continue)
(restore env)
(restore unev)
(perform (op set-variable-value!) (reg unev) (reg val) (reg env))
(assign val (const ok))
(goto (reg continue))
ev-definition
(assign unev (op definition-variable) (reg exp))
(save unev)
(assign exp (op definition-value) (reg exp))
(save env)
(save continue)
(assign continue (label ev-definition-1))
(goto (label eval-dispatch))
ev-definition-1
(restore continue)
(restore env)
(restore unev)
(perform (op define-variable!) (reg unev) (reg val) (reg env))
(assign val (const ok))
(goto (reg continue))
unknown-expression-type
unknown-procedure-type
done))
| null | https://raw.githubusercontent.com/skanev/playground/d88e53a7f277b35041c2f709771a0b96f993b310/scheme/sicp/05/25.scm | scheme |
Modify the evaluator so that it uses normal-order evaluation, based on the
This is tricky.
values. That would beat the purpose of normal-order.
ev-map-operands, that will apply the procedure in the exp register to each
argument in unev. It is used by primitive-apply with actual-value and
compound-apply with delay-it.
We will also modify ev-if to use actual-value.
Delaying expressions
Evaluating simple expressions
Evaluating procedure applications
Procedure application
Sequence evaluation
Conditionals
Assignments and definitions | SICP exercise 5.25
lazy evaluator of section 4.2 .
First , in order to do normal - order evaluation , we should not cache thunk
Second , we will accomplish this with a more general procedure called
(define (delay-it exp env) (list 'thunk exp env))
(define (thunk? obj) (tagged-list? obj 'thunk))
(define (thunk-exp thunk) (cadr thunk))
(define (thunk-env thunk) (caddr thunk))
(define extra-operations
(list (list 'delay-it delay-it)
(list 'thunk? thunk?)
(list 'thunk-env thunk-env)
(list 'thunk-exp thunk-exp)))
(define ec-core
'(
(assign continue (label done))
eval-dispatch
(test (op self-evaluating?) (reg exp))
(branch (label ev-self-eval))
(test (op variable?) (reg exp))
(branch (label ev-variable))
(test (op quoted?) (reg exp))
(branch (label ev-quoted))
(test (op assignment?) (reg exp))
(branch (label ev-assignment))
(test (op definition?) (reg exp))
(branch (label ev-definition))
(test (op if?) (reg exp))
(branch (label ev-if))
(test (op lambda?) (reg exp))
(branch (label ev-lambda))
(test (op begin?) (reg exp))
(branch (label ev-begin))
(test (op application?) (reg exp))
(branch (label ev-application))
(goto (label unknown-expression-type))
delay-it
(assign val (op delay-it) (reg exp) (reg env))
(goto (reg continue))
actual-value
(save continue)
(assign continue (label actual-value-after-eval))
(goto (label eval-dispatch))
actual-value-after-eval
(restore continue)
(assign exp (reg val))
(goto (label force-it))
force-it
(test (op thunk?) (reg exp))
(branch (label force-it-thunk))
(goto (reg continue))
force-it-thunk
(assign env (op thunk-env) (reg exp))
(assign exp (op thunk-exp) (reg exp))
(goto (label actual-value))
ev-self-eval
(assign val (reg exp))
(goto (reg continue))
ev-variable
(assign val (op lookup-variable-value) (reg exp) (reg env))
(goto (reg continue))
ev-quoted
(assign val (op text-of-quotation) (reg exp))
(goto (reg continue))
ev-lambda
(assign unev (op lambda-parameters) (reg exp))
(assign exp (op lambda-body) (reg exp))
(assign val (op make-procedure) (reg unev) (reg exp) (reg env))
(goto (reg continue))
ev-application
(save continue)
(save env)
(assign unev (op operands) (reg exp))
(save unev)
(assign exp (op operator) (reg exp))
(assign continue (label ev-appl-did-operator))
(goto (label eval-dispatch))
ev-appl-did-operator
(restore unev)
(restore env)
(assign proc (reg val))
(goto (label apply-dispatch))
apply-dispatch
(test (op primitive-procedure?) (reg proc))
(branch (label primitive-apply))
(test (op compound-procedure?) (reg proc))
(branch (label compound-apply))
(goto (label unknown-procedure-type))
primitive-apply
(assign exp (label actual-value))
(assign continue (label primitive-apply-after-args))
(goto (label ev-map-operands))
primitive-apply-after-args
(assign val (op apply-primitive-procedure) (reg proc) (reg argl))
(restore continue)
(goto (reg continue))
compound-apply
(save continue)
(assign exp (label delay-it))
(assign continue (label compound-apply-after-args))
(goto (label ev-map-operands))
compound-apply-after-args
(restore continue)
(assign unev (op procedure-parameters) (reg proc))
(assign env (op procedure-environment) (reg proc))
(assign env (op extend-environment) (reg unev) (reg argl) (reg env))
(assign unev (op procedure-body) (reg proc))
(goto (label ev-sequence))
ev-map-operands
(assign argl (op empty-arglist))
(test (op no-operands?) (reg unev))
(branch (label ev-map-no-args))
(save continue)
(save proc)
(assign proc (reg exp))
(save proc)
ev-map-operand-loop
(restore proc)
(assign exp (op first-operand) (reg unev))
(test (op last-operand?) (reg unev))
(branch (label ev-map-last-arg))
(save proc)
(save argl)
(save env)
(save unev)
(assign continue (label ev-map-accumulate-arg))
(goto (reg proc))
ev-map-accumulate-arg
(restore unev)
(restore env)
(restore argl)
(assign argl (op adjoin-arg) (reg val) (reg argl))
(assign unev (op rest-operands) (reg unev))
(goto (label ev-map-operand-loop))
ev-map-last-arg
(save argl)
(assign continue (label ev-map-accumulate-last-arg))
(goto (reg proc))
ev-map-accumulate-last-arg
(restore argl)
(assign argl (op adjoin-arg) (reg val) (reg argl))
(restore proc)
(restore continue)
(goto (reg continue))
ev-map-no-args
(goto (reg continue))
ev-begin
(assign unev (op begin-actions) (reg exp))
(save continue)
(goto (label ev-sequence))
ev-sequence
(assign exp (op first-exp) (reg unev))
(test (op last-exp?) (reg unev))
(branch (label ev-sequence-last-exp))
(save unev)
(save env)
(assign continue (label ev-sequence-continue))
(goto (label eval-dispatch))
ev-sequence-continue
(restore env)
(restore unev)
(assign unev (op rest-exps) (reg unev))
(goto (label ev-sequence))
ev-sequence-last-exp
(restore continue)
(goto (label eval-dispatch))
ev-if
(save exp)
(save env)
(save continue)
(assign continue (label ev-if-decide))
(assign exp (op if-predicate) (reg exp))
(goto (label actual-value))
ev-if-decide
(restore continue)
(restore env)
(restore exp)
(test (op true?) (reg val))
(branch (label ev-if-consequent))
ev-if-alternative
(assign exp (op if-alternative) (reg exp))
(goto (label eval-dispatch))
ev-if-consequent
(assign exp (op if-consequent) (reg exp))
(goto (label eval-dispatch))
ev-assignment
(assign unev (op assignment-variable) (reg exp))
(save unev)
(assign exp (op assignment-value) (reg exp))
(save env)
(save continue)
(assign continue (label ev-assignment-1))
(goto (label eval-dispatch))
ev-assignment-1
(restore continue)
(restore env)
(restore unev)
(perform (op set-variable-value!) (reg unev) (reg val) (reg env))
(assign val (const ok))
(goto (reg continue))
ev-definition
(assign unev (op definition-variable) (reg exp))
(save unev)
(assign exp (op definition-value) (reg exp))
(save env)
(save continue)
(assign continue (label ev-definition-1))
(goto (label eval-dispatch))
ev-definition-1
(restore continue)
(restore env)
(restore unev)
(perform (op define-variable!) (reg unev) (reg val) (reg env))
(assign val (const ok))
(goto (reg continue))
unknown-expression-type
unknown-procedure-type
done))
|
b3c48645e9817d15d8d81f2b585a97de17ad98be0ce5381074030dfc1115c9d6 | huangjs/cl | ratpoi.lisp | -*- Mode : Lisp ; Package : Maxima ; Syntax : Common - Lisp ; Base : 10 -*- ; ; ; ;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; The data in this file contains enhancments. ;;;;;
;;; ;;;;;
Copyright ( c ) 1984,1987 by , University of Texas ; ; ; ; ;
;;; All rights reserved ;;;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
( c ) Copyright 1980 Massachusetts Institute of Technology ; ; ;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
#+:poisson-cre
(progn
(declare-top (special $ratvars genvar))
(defvar poisco1 '(1 . 1))
(defvar poiscom1 '(-1 . 1))
THESE PROGRAMS MAKE POISSON COEFFICIENTS RATIONAL FUNCTIONS ( CRE )
;;; POISCDECODE DECODES A COEFFICIENT
(defun poiscdecode (x)
($ratdisrep (cons (list 'mrat 'simp (cdr $ratvars) genvar) x)))
INTOPOISCO PUTS AN EXPRESSION INTO POISSON COEFFICIENT FORM
(defun intopoisco (x)
(if (and (not (atom x)) (numberp (cdr x)))
x
(cdr (ratrep x (cdr $ratvars)))))
POISCO+ ADDS 2 COEFFICIENTS
POISCO * MULTIPLIES 2 COEFFICIENTS
(defun poisco* (x y)
(rattimes x y t))
(defun poisco+ (x y)
(ratplus x y))
HALVE DIVIDES A COEFFICIENT BY 2
(defun halve (r)
(rattimes '(1 . 2) r t))
POISSUBSTCO SUBSTITUTES AN EXPRESSION FOR A VARIABLE IN A COEFFICIENT .
(defun poissubstco (a b x)
(intopoisco
(maxima-substitute
a b
($ratdisrep (cons (list 'mrat 'simp (cdr $ratvars) genvar) x)))))
(defun poispzero (x)
(equal 0 (car x)))
TEST FOR ZERO
(defun poiscointeg (h var)
(intopoisco ($integrate (poiscdecode h) var)))
)
| null | https://raw.githubusercontent.com/huangjs/cl/96158b3f82f82a6b7d53ef04b3b29c5c8de2dbf7/lib/maxima/src/ratpoi.lisp | lisp | Package : Maxima ; Syntax : Common - Lisp ; Base : 10 -*- ; ; ; ;
The data in this file contains enhancments. ;;;;;
;;;;;
; ; ; ;
All rights reserved ;;;;;
; ;
POISCDECODE DECODES A COEFFICIENT |
#+:poisson-cre
(progn
(declare-top (special $ratvars genvar))
(defvar poisco1 '(1 . 1))
(defvar poiscom1 '(-1 . 1))
THESE PROGRAMS MAKE POISSON COEFFICIENTS RATIONAL FUNCTIONS ( CRE )
(defun poiscdecode (x)
($ratdisrep (cons (list 'mrat 'simp (cdr $ratvars) genvar) x)))
INTOPOISCO PUTS AN EXPRESSION INTO POISSON COEFFICIENT FORM
(defun intopoisco (x)
(if (and (not (atom x)) (numberp (cdr x)))
x
(cdr (ratrep x (cdr $ratvars)))))
POISCO+ ADDS 2 COEFFICIENTS
POISCO * MULTIPLIES 2 COEFFICIENTS
(defun poisco* (x y)
(rattimes x y t))
(defun poisco+ (x y)
(ratplus x y))
HALVE DIVIDES A COEFFICIENT BY 2
(defun halve (r)
(rattimes '(1 . 2) r t))
POISSUBSTCO SUBSTITUTES AN EXPRESSION FOR A VARIABLE IN A COEFFICIENT .
(defun poissubstco (a b x)
(intopoisco
(maxima-substitute
a b
($ratdisrep (cons (list 'mrat 'simp (cdr $ratvars) genvar) x)))))
(defun poispzero (x)
(equal 0 (car x)))
TEST FOR ZERO
(defun poiscointeg (h var)
(intopoisco ($integrate (poiscdecode h) var)))
)
|
31e06562823c63e6eef64a0409271e4df52d53795d727754e9c67b267118f38a | joachimdb/dl4clj | core_test.clj | (ns dl4clj.core-test
(:require [clojure.test :refer :all]
[dl4clj.core :refer :all]))
(deftest a-test
(testing "FIXME, I fail."
(is (= 0 1))))
| null | https://raw.githubusercontent.com/joachimdb/dl4clj/fe9af7c886b80df5e18cd79923fbc6955ddc2694/test/dl4clj/core_test.clj | clojure | (ns dl4clj.core-test
(:require [clojure.test :refer :all]
[dl4clj.core :refer :all]))
(deftest a-test
(testing "FIXME, I fail."
(is (= 0 1))))
| |
0f790c0eecd9f329fd115212c3cbb2a1d2fe6b134f3b46a2f14b827d450aecec | careercup/CtCI-6th-Edition-Clojure | chapter_2_q4_test.clj | (ns ^{:author "Leeor Engel"}
chapter-2.chapter-2-q4-test
(:require [clojure.test :refer :all]
[chapter-2.chapter-2-q4 :refer :all]))
(deftest partition-test
(is (= '(2) (partition-list '(2) 2)))
(is (= '(2) (partition-list '(2) 1)))
(is (= '(2) (partition-list '(2) 3)))
(is (= '(2 4) (partition-list '(4 2) 3)))
(is (= '(2 6 10) (partition-list '(10 6 2) 5)))
(is (= '(1 2 3 10 5 8 5) (partition-list '(3 5 8 5 10 2 1) 5)))
(is (= '(1 2 3 10 5 8 5) (partition-list '(3 5 8 5 10 2 1) 4)))) | null | https://raw.githubusercontent.com/careercup/CtCI-6th-Edition-Clojure/ef151b94978af82fb3e0b1b0cd084d910870c52a/test/chapter_2/chapter_2_q4_test.clj | clojure | (ns ^{:author "Leeor Engel"}
chapter-2.chapter-2-q4-test
(:require [clojure.test :refer :all]
[chapter-2.chapter-2-q4 :refer :all]))
(deftest partition-test
(is (= '(2) (partition-list '(2) 2)))
(is (= '(2) (partition-list '(2) 1)))
(is (= '(2) (partition-list '(2) 3)))
(is (= '(2 4) (partition-list '(4 2) 3)))
(is (= '(2 6 10) (partition-list '(10 6 2) 5)))
(is (= '(1 2 3 10 5 8 5) (partition-list '(3 5 8 5 10 2 1) 5)))
(is (= '(1 2 3 10 5 8 5) (partition-list '(3 5 8 5 10 2 1) 4)))) | |
24ab1b0ee7383c5bd4ece1db3dc2d76fe8dd1f9e1ad6dbaf88c0e6dbac36f76e | acowley/concurrent-machines | Pipeline.hs | import Data.Time.Clock (getCurrentTime, diffUTCTime)
import Control.Concurrent (threadDelay)
import Control.Monad.IO.Class (MonadIO, liftIO)
import Data.Machine.Concurrent
worker :: String -> Double -> ProcessT IO () ()
worker name dt = repeatedly $ do _ <- await
liftIO $ do
putStrLn $ name ++ " working on its input"
threadDelay dt'
yield ()
where dt' = floor $ dt * 1000000
timed :: MonadIO m => m a -> m (a, Double)
timed m = do t1 <- liftIO getCurrentTime
r <- m
t2 <- liftIO getCurrentTime
return (r, realToFrac $ t2 `diffUTCTime` t1)
main :: IO ()
main = do (r,dt) <- timed . runT . supply (repeat ()) $
worker "A" 1 ~> worker "B" 1 ~> worker "C" 1 ~> taking 3
putStrLn $ "Sequentially produced "++show r
putStrLn $ "Sequential processing took "++show dt++"s"
(r',dt') <- timed . runT . supply (repeat ()) $
worker "A" 1 >~> worker "B" 1 >~> worker "C" 1 >~> taking 3
putStrLn $ "Pipeline produced "++show r'
putStrLn $ "Pipeline processing took "++show dt'++"s"
| null | https://raw.githubusercontent.com/acowley/concurrent-machines/70d2a8ae481e6fef503f2609c65b530bd1f96e1b/examples/Pipeline.hs | haskell | import Data.Time.Clock (getCurrentTime, diffUTCTime)
import Control.Concurrent (threadDelay)
import Control.Monad.IO.Class (MonadIO, liftIO)
import Data.Machine.Concurrent
worker :: String -> Double -> ProcessT IO () ()
worker name dt = repeatedly $ do _ <- await
liftIO $ do
putStrLn $ name ++ " working on its input"
threadDelay dt'
yield ()
where dt' = floor $ dt * 1000000
timed :: MonadIO m => m a -> m (a, Double)
timed m = do t1 <- liftIO getCurrentTime
r <- m
t2 <- liftIO getCurrentTime
return (r, realToFrac $ t2 `diffUTCTime` t1)
main :: IO ()
main = do (r,dt) <- timed . runT . supply (repeat ()) $
worker "A" 1 ~> worker "B" 1 ~> worker "C" 1 ~> taking 3
putStrLn $ "Sequentially produced "++show r
putStrLn $ "Sequential processing took "++show dt++"s"
(r',dt') <- timed . runT . supply (repeat ()) $
worker "A" 1 >~> worker "B" 1 >~> worker "C" 1 >~> taking 3
putStrLn $ "Pipeline produced "++show r'
putStrLn $ "Pipeline processing took "++show dt'++"s"
| |
b1a330752dcbffb1d1f4496be384cb24730a70584269acd66deb0866d10b4065 | maximedenes/native-coq | dumpglob.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 *)
(************************************************************************)
val open_glob_file : string -> unit
val close_glob_file : unit -> unit
val start_dump_glob : string -> unit
val end_dump_glob : unit -> unit
val dump : unit -> bool
val noglob : unit -> unit
val dump_to_stdout : unit -> unit
val dump_into_file : string -> unit
val dump_to_dotglob : unit -> unit
val pause : unit -> unit
val continue : unit -> unit
type coqdoc_state = Lexer.location_table
val coqdoc_freeze : unit -> coqdoc_state
val coqdoc_unfreeze : coqdoc_state -> unit
val add_glob : Pp.loc -> Libnames.global_reference -> unit
val add_glob_kn : Pp.loc -> Names.kernel_name -> unit
val dump_definition : Pp.loc * Names.identifier -> bool -> string -> unit
val dump_moddef : Pp.loc -> Names.module_path -> string -> unit
val dump_modref : Pp.loc -> Names.module_path -> string -> unit
val dump_reference : Pp.loc -> string -> string -> string -> unit
val dump_libref : Pp.loc -> Names.dir_path -> string -> unit
val dump_notation_location : (int * int) list -> Topconstr.notation -> (Notation.notation_location * Topconstr.scope_name option) -> unit
val dump_binding : Pp.loc -> Names.Idset.elt -> unit
val dump_notation : Pp.loc * (Topconstr.notation * Notation.notation_location) -> Topconstr.scope_name option -> bool -> unit
val dump_constraint : Topconstr.typeclass_constraint -> bool -> string -> unit
val dump_string : string -> unit
| null | https://raw.githubusercontent.com/maximedenes/native-coq/3623a4d9fe95c165f02f7119c0e6564a83a9f4c9/interp/dumpglob.mli | ocaml | **********************************************************************
// * This file is distributed under the terms of the
* GNU Lesser General Public License Version 2.1
********************************************************************** | v * The Coq Proof Assistant / The Coq Development Team
< O _ _ _ , , * INRIA - CNRS - LIX - LRI - PPS - Copyright 1999 - 2010
\VV/ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
val open_glob_file : string -> unit
val close_glob_file : unit -> unit
val start_dump_glob : string -> unit
val end_dump_glob : unit -> unit
val dump : unit -> bool
val noglob : unit -> unit
val dump_to_stdout : unit -> unit
val dump_into_file : string -> unit
val dump_to_dotglob : unit -> unit
val pause : unit -> unit
val continue : unit -> unit
type coqdoc_state = Lexer.location_table
val coqdoc_freeze : unit -> coqdoc_state
val coqdoc_unfreeze : coqdoc_state -> unit
val add_glob : Pp.loc -> Libnames.global_reference -> unit
val add_glob_kn : Pp.loc -> Names.kernel_name -> unit
val dump_definition : Pp.loc * Names.identifier -> bool -> string -> unit
val dump_moddef : Pp.loc -> Names.module_path -> string -> unit
val dump_modref : Pp.loc -> Names.module_path -> string -> unit
val dump_reference : Pp.loc -> string -> string -> string -> unit
val dump_libref : Pp.loc -> Names.dir_path -> string -> unit
val dump_notation_location : (int * int) list -> Topconstr.notation -> (Notation.notation_location * Topconstr.scope_name option) -> unit
val dump_binding : Pp.loc -> Names.Idset.elt -> unit
val dump_notation : Pp.loc * (Topconstr.notation * Notation.notation_location) -> Topconstr.scope_name option -> bool -> unit
val dump_constraint : Topconstr.typeclass_constraint -> bool -> string -> unit
val dump_string : string -> unit
|
2f7ee291d910005f50dfd35eced7997ed1c6ffc479a239cced8c7e6694ee9c5f | coleslaw-org/coleslaw | heroku.lisp | (eval-when (:compile-toplevel :load-toplevel)
(ql:quickload 'hunchentoot))
(defpackage :coleslaw-heroku
(:use :cl)
(:import-from #:hunchentoot :create-folder-dispatcher-and-handler
:create-static-file-dispatcher-and-handler
:*dispatch-table*)
(:import-from #:coleslaw :deploy)
(:export #:enable))
(in-package :coleslaw-heroku)
(defmethod deploy :after (staging)
(push (create-folder-dispatcher-and-handler "/" "/app/.curr/")
*dispatch-table*)
(push (create-static-file-dispatcher-and-handler "/" "/app/.curr/index.html")
*dispatch-table*))
(defun enable ())
| null | https://raw.githubusercontent.com/coleslaw-org/coleslaw/0b9f027a36ea00ca2e4b6f8d9fd7a135127cc2da/plugins/heroku.lisp | lisp | (eval-when (:compile-toplevel :load-toplevel)
(ql:quickload 'hunchentoot))
(defpackage :coleslaw-heroku
(:use :cl)
(:import-from #:hunchentoot :create-folder-dispatcher-and-handler
:create-static-file-dispatcher-and-handler
:*dispatch-table*)
(:import-from #:coleslaw :deploy)
(:export #:enable))
(in-package :coleslaw-heroku)
(defmethod deploy :after (staging)
(push (create-folder-dispatcher-and-handler "/" "/app/.curr/")
*dispatch-table*)
(push (create-static-file-dispatcher-and-handler "/" "/app/.curr/index.html")
*dispatch-table*))
(defun enable ())
| |
ecddeb49d7f95d638393d871e1ca655325366a0762b02219d1206e9a3548d8fc | apinf/proxy42 | vegur_websockets_backend.erl | Copyright ( c ) 2013 - 2015 , Heroku Inc < > .
%%% All rights reserved.
%%%
%%% Redistribution and use in source and binary forms, with or without
%%% modification, are permitted provided that the following conditions are
%%% met:
%%%
%%% * Redistributions of source code must retain the above copyright
%%% notice, this list of conditions and the following disclaimer.
%%%
%%% * Redistributions in binary form must reproduce the above copyright
%%% notice, this list of conditions and the following disclaimer in the
%%% documentation and/or other materials provided with the distribution.
%%%
%%% * The names of its contributors may not be used to endorse or promote
%%% products derived from this software without specific prior written
%%% permission.
%%%
%%% THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
" AS IS " AND ANY EXPRESS OR IMPLIED WARRANTIES , INCLUDING , BUT NOT
%%% LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
%%% A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR ANY DIRECT , INDIRECT , INCIDENTAL ,
SPECIAL , EXEMPLARY , OR CONSEQUENTIAL DAMAGES ( INCLUDING , BUT NOT
LIMITED TO , PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES ; LOSS OF USE ,
%%% DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY , WHETHER IN CONTRACT , STRICT LIABILITY , OR TORT
%%% (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
%%% OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-module(vegur_websockets_backend).
-behaviour(cowboyku_websocket_handler).
-export([init/3]).
-export([websocket_init/3]).
-export([websocket_handle/3]).
-export([websocket_info/3]).
-export([websocket_terminate/3]).
init({tcp, http}, _Req, _Opts) ->
{upgrade, protocol, cowboyku_websocket}.
websocket_init(_TransportName, Req, _Opts) ->
{ok, Req, undefined_state}.
websocket_handle({text, Msg}, Req, State) ->
{reply, {text, Msg}, Req, State};
websocket_handle(_Data, Req, State) ->
{ok, Req, State}.
websocket_info(_Info, Req, State) ->
{ok, Req, State}.
websocket_terminate(_Reason, _Req, _State) ->
ok.
| null | https://raw.githubusercontent.com/apinf/proxy42/01b483b711881391e8306bf64b83b4df9d0bc832/apps/vegur/test/vegur_websockets_backend.erl | erlang | All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* The names of its contributors may not be used to endorse or promote
products derived from this software without specific prior written
permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. | Copyright ( c ) 2013 - 2015 , Heroku Inc < > .
" AS IS " AND ANY EXPRESS OR IMPLIED WARRANTIES , INCLUDING , BUT NOT
OWNER OR ANY DIRECT , INDIRECT , INCIDENTAL ,
SPECIAL , EXEMPLARY , OR CONSEQUENTIAL DAMAGES ( INCLUDING , BUT NOT
LIMITED TO , PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES ; LOSS OF USE ,
THEORY OF LIABILITY , WHETHER IN CONTRACT , STRICT LIABILITY , OR TORT
-module(vegur_websockets_backend).
-behaviour(cowboyku_websocket_handler).
-export([init/3]).
-export([websocket_init/3]).
-export([websocket_handle/3]).
-export([websocket_info/3]).
-export([websocket_terminate/3]).
init({tcp, http}, _Req, _Opts) ->
{upgrade, protocol, cowboyku_websocket}.
websocket_init(_TransportName, Req, _Opts) ->
{ok, Req, undefined_state}.
websocket_handle({text, Msg}, Req, State) ->
{reply, {text, Msg}, Req, State};
websocket_handle(_Data, Req, State) ->
{ok, Req, State}.
websocket_info(_Info, Req, State) ->
{ok, Req, State}.
websocket_terminate(_Reason, _Req, _State) ->
ok.
|
3d9ae6416034d858029afec2f13613d996fea4972adc8c87b806b6cfa7fa599c | patricoferris/jsoo-mithril | index.ml | open Mithril
open Brr
module Date = struct
type t = Jv.t
let date = Jv.get Jv.global "Date"
let now () =
let d = Jv.new' date [||] in
let date = Jv.call d "toLocaleDateString" [||] |> Jv.to_string in
let time = Jv.call d "toLocaleTimeString" [||] |> Jv.to_string in
date ^ " " ^ time
end
(* A nice, typed OCaml representation of a todo item *)
module Todo = struct
type t = { text : string; mutable completed : bool; created : string }
let v text =
Brr.Console.log [ Date.now () ];
{ text; completed = false; created = Date.now () }
let toggle t = t.completed <- not t.completed
let equal = Stdlib.( = )
end
let choose a b c = if a then b else c
let todos, add_todo, remove_todo =
let t = ref [] in
let add e =
let open Ev in
let event = of_jv e in
let code = Keyboard.key (as_type event) |> Jstr.to_string in
let target = Ev.target event |> Ev.target_to_jv in
match (code, Jv.find target "value") with
| "Enter", Some s when Jv.is_some s ->
(* Update state *)
t := Todo.v (Jv.to_string s) :: !t;
(* Set target's value to none *)
Jv.set target "value" Jv.null
| _ -> ()
in
let remove todo =
t := List.filter (fun todo' -> not (Todo.equal todo todo')) !t
in
(t, add, remove)
let todos =
let key = Attr.(v [| attr "onkeypress" (Jv.repr add_todo) |]) in
let todo t =
let remove =
Attr.(v [| attr "onclick" (Jv.repr (fun () -> remove_todo t)) |])
in
let toggle =
Attr.(v [| attr "onclick" (Jv.repr (fun () -> Todo.toggle t)) |])
in
M.v
("div.todo" ^ choose t.completed ".completed" "")
~children:
(`Vnodes
[
M.v "p" ~children:(`String t.text);
M.v "p" ~children:(`String t.created);
M.v "button.remove" ~attr:remove ~children:(`String "Remove");
M.v "button.complete" ~attr:toggle
~children:(`String (choose t.completed "Uncomplete" "Complete"));
])
in
let input =
M.(
v ~attr:key "input#new-todo[placeholder='What's to be done?'][autofocus]")
in
let view _ =
M.(
v "div.main"
~children:
(`Vnodes
[
v "h1" ~children:(`String "Todo Stack");
input;
v "div.todo-list" ~children:(`Vnodes (List.map todo !todos));
]))
in
Component.v view
let () =
let body = Brr.(Document.body G.document) in
M.(mount body todos)
| null | https://raw.githubusercontent.com/patricoferris/jsoo-mithril/5f2ccebd647f737bac7dbd1981b78a4d5bd0f5ea/examples/1-section/todo-stack/example/index.ml | ocaml | A nice, typed OCaml representation of a todo item
Update state
Set target's value to none | open Mithril
open Brr
module Date = struct
type t = Jv.t
let date = Jv.get Jv.global "Date"
let now () =
let d = Jv.new' date [||] in
let date = Jv.call d "toLocaleDateString" [||] |> Jv.to_string in
let time = Jv.call d "toLocaleTimeString" [||] |> Jv.to_string in
date ^ " " ^ time
end
module Todo = struct
type t = { text : string; mutable completed : bool; created : string }
let v text =
Brr.Console.log [ Date.now () ];
{ text; completed = false; created = Date.now () }
let toggle t = t.completed <- not t.completed
let equal = Stdlib.( = )
end
let choose a b c = if a then b else c
let todos, add_todo, remove_todo =
let t = ref [] in
let add e =
let open Ev in
let event = of_jv e in
let code = Keyboard.key (as_type event) |> Jstr.to_string in
let target = Ev.target event |> Ev.target_to_jv in
match (code, Jv.find target "value") with
| "Enter", Some s when Jv.is_some s ->
t := Todo.v (Jv.to_string s) :: !t;
Jv.set target "value" Jv.null
| _ -> ()
in
let remove todo =
t := List.filter (fun todo' -> not (Todo.equal todo todo')) !t
in
(t, add, remove)
let todos =
let key = Attr.(v [| attr "onkeypress" (Jv.repr add_todo) |]) in
let todo t =
let remove =
Attr.(v [| attr "onclick" (Jv.repr (fun () -> remove_todo t)) |])
in
let toggle =
Attr.(v [| attr "onclick" (Jv.repr (fun () -> Todo.toggle t)) |])
in
M.v
("div.todo" ^ choose t.completed ".completed" "")
~children:
(`Vnodes
[
M.v "p" ~children:(`String t.text);
M.v "p" ~children:(`String t.created);
M.v "button.remove" ~attr:remove ~children:(`String "Remove");
M.v "button.complete" ~attr:toggle
~children:(`String (choose t.completed "Uncomplete" "Complete"));
])
in
let input =
M.(
v ~attr:key "input#new-todo[placeholder='What's to be done?'][autofocus]")
in
let view _ =
M.(
v "div.main"
~children:
(`Vnodes
[
v "h1" ~children:(`String "Todo Stack");
input;
v "div.todo-list" ~children:(`Vnodes (List.map todo !todos));
]))
in
Component.v view
let () =
let body = Brr.(Document.body G.document) in
M.(mount body todos)
|
961228f2bdbd8357159bce833db0001e959ddaecbb7909a163ef08c948cace4e | haskell-suite/haskell-src-exts | DataHeadParen.hs | # LANGUAGE TypeOperators #
module DataHeadParen where
data (a1 :< a2) = Foo
| null | https://raw.githubusercontent.com/haskell-suite/haskell-src-exts/84a4930e0e5c051b7d9efd20ef7c822d5fc1c33b/tests/examples/DataHeadParen.hs | haskell | # LANGUAGE TypeOperators #
module DataHeadParen where
data (a1 :< a2) = Foo
| |
58e3dc3b3024045f4543dc1ec0ce6ffb528f475d362486db1b794528418d5d0d | rizo/snowflake-os | optcompile.mli | (***********************************************************************)
(* *)
(* Objective Caml *)
(* *)
, projet Cristal , INRIA Rocquencourt
(* *)
Copyright 1996 Institut National de Recherche en Informatique et
en Automatique . All rights reserved . This file is distributed
under the terms of the Q Public License version 1.0 .
(* *)
(***********************************************************************)
$ Id$
Compile a .ml or .mli file
open Format
val interface: formatter -> string -> string -> unit
val implementation: formatter -> string -> string -> unit
val c_file: string -> unit
val initial_env: unit -> Env.t
val init_path: unit -> unit
| null | https://raw.githubusercontent.com/rizo/snowflake-os/51df43d9ba715532d325e8880d3b8b2c589cd075/plugins/ocamlopt.opt/driver/optcompile.mli | ocaml | *********************************************************************
Objective Caml
********************************************************************* | , projet Cristal , INRIA Rocquencourt
Copyright 1996 Institut National de Recherche en Informatique et
en Automatique . All rights reserved . This file is distributed
under the terms of the Q Public License version 1.0 .
$ Id$
Compile a .ml or .mli file
open Format
val interface: formatter -> string -> string -> unit
val implementation: formatter -> string -> string -> unit
val c_file: string -> unit
val initial_env: unit -> Env.t
val init_path: unit -> unit
|
c0c48e031ab33cde8f8430bedeb1d6409874d340b61b2e506b4e4f56787fba8d | con-kitty/categorifier-c | Gen.hs | # LANGUAGE MonoLocalBinds #
# LANGUAGE NoMonomorphismRestriction #
| The core code - generation functions for ' KGen ' .
module Categorifier.C.KGenGenerate.FFI.Gen
( -- * Code generation of functions
mkCgFromArraysFun,
mkCgFromPolyVecFun,
codeGenWithBindings,
SBVSpec,
)
where
import qualified Barbies
import qualified Categorifier.C.Barbies as Barbies
import Categorifier.C.Codegen.FFI.Spec (SBVSpec, Spec (..))
import Categorifier.C.KGen.KGen (KGen (..))
import Categorifier.C.KGenGenerate.FFI.Bindings (mkFFIBindingModule)
import Categorifier.C.KGenGenerate.FFI.Spec (cgStateToSpec, genFunSpec, specFileName)
import Categorifier.C.KTypes.C (C (..))
import Categorifier.C.KTypes.KLiteral (false)
import Categorifier.C.PolyVec (PolyVec, pdevectorize, pvectorize, pvlengths)
import Categorifier.C.Prim (ArrayCount (..), ArrayName (..), Arrays (..), arrayNames)
import qualified Categorifier.Common.IO.Exception as Exception
import Control.Monad (unless, (<=<))
import Control.Monad.IO.Class (liftIO)
import Control.Monad.Trans.State.Lazy (StateT (..))
import Data.Functor.Compose (Compose (..))
import qualified Data.IORef as IORef
import Data.Proxy (Proxy (..))
import Data.SBV.Internals (SBV, SBVCodeGen (..))
import qualified Data.SBV.Internals as SBV
import qualified Data.SBV.Tools.CodeGen as SBV
import qualified Data.Text as Text (unpack)
import qualified Data.Vector as V
import qualified Text.Casing as Casing
| Convenience function to wrap ` mkCgFromArraysFun ` with PolyVec types .
mkCgFromPolyVecFun :: forall a b. (PolyVec KGen a, PolyVec KGen b) => (a -> b) -> SBVCodeGen SBVSpec
mkCgFromPolyVecFun polyVecFun = mkCgFromArraysFun arraysFun inputCounts
where
arraysFun =
Exception.throwIOLeft . pvectorize @V.Vector @KGen @b . polyVecFun
<=< Exception.throwIOLeft . pdevectorize @V.Vector @KGen @a
inputCounts = pvlengths (Proxy @KGen) (Proxy @a)
Note to implementors : keep in mind that SBV can not deal with empty input or output arrays , so
even if this function has arrays of zero size in the ' counts ' argument we pass it , our resulting
' SBVCodeGen ' action ( and the ' CgState ' accumulated therein ) will generate all arrays with a
-- minimum size of one. In other words, the generated code will _not_ exactly match the 'Arrays
ArrayCount ' you get from polyvectorization . See ' arrayCountsToSpec ' and ' FFIArrayCount ' for some
-- more info.
-- | This function takes a polyvectorized function and its input specification and gives you an
-- 'SBVCodeGen' action you can pass to 'codeGenWithBindings' to generate the corresponding C code
and FFI tools .
mkCgFromArraysFun ::
(Arrays (Compose V.Vector KGen) -> IO (Arrays (Compose V.Vector KGen))) ->
Arrays ArrayCount ->
SBVCodeGen SBVSpec
mkCgFromArraysFun f counts = do
inputArrays <-
Barbies.bzipWithMC @SBV.SymVal genInArr' arrayNames counts ::
SBVCodeGen (Arrays (Compose V.Vector KGen))
outputArrays <- liftIO $ f inputArrays
let outcounts = Barbies.bmap (ArrayCount . V.length . getCompose) outputArrays
Barbies.bzipWith3MC_ @SBV.SymVal
genOutArr'
arrayNames
outputArrays
outputsIfZeroLength
SBV.cgOverwriteFiles True
SBV.cgGenerateDriver False
SBV.cgGenerateMakefile False
pure $ Spec counts outcounts
where
genInArr' ::
forall a. SBV.SymVal a => ArrayName a -> ArrayCount a -> SBVCodeGen (Compose V.Vector KGen a)
genInArr' (ArrayName name) (ArrayCount count) =
Compose <$> genInArr ("in_" <> Text.unpack name) count
genInArr :: forall a. SBV.SymVal a => String -> Int -> SBVCodeGen (V.Vector (KGen a))
genInArr name 0 = do
_ <- SBV.cgInputArr 1 name :: SBVCodeGen [SBV a]
pure V.empty
genInArr name count =
V.fromList . fmap KGen <$> SBV.cgInputArr (fromIntegral count) name
genOutArr' ::
forall a. SBV.SymVal a => ArrayName a -> Compose V.Vector KGen a -> C a -> SBVCodeGen ()
genOutArr' (ArrayName name) (Compose out) outputIfZeroLength =
genOutArr ("out_" <> Text.unpack name) out outputIfZeroLength
genOutArr :: forall a. SBV.SymVal a => String -> V.Vector (KGen a) -> C a -> SBVCodeGen ()
genOutArr name outArr outputIfZeroLength
| V.null outArr = SBV.cgOutputArr name (pure . SBV.literal $ unsafeC outputIfZeroLength)
| otherwise = SBV.cgOutputArr name (V.toList (fmap getKGen outArr))
outputsIfZeroLength :: Arrays C
outputsIfZeroLength =
Arrays
{ arrayBool = false,
arrayInt8 = 0,
arrayInt16 = 0,
arrayInt32 = 0,
arrayInt64 = 0,
arrayWord8 = 0,
arrayWord16 = 0,
arrayWord32 = 0,
arrayWord64 = 0,
arrayFloat = 0,
arrayDouble = 0
}
| ' codeGenWithBindings quiet path funName gen ' generates C code and various associated FFI helper
-- tools:
--
* an FFI binding that allows calling the function directly from TODO(MP ): Not yet
-- implemented
-- * a set of C functions that can be called to get the input and output specifications
--
-- @quiet@ determines whether stdout receives a lot of spam. @path@ determines where the code is
-- generated. @funName@ is the name of the function to be generated. This module attempts to deal
with the casing conventions in Haskell and C , so passing the - style @myFunctionName@ will
correspond to @my_function_name@ in the generated C code . @gen@ is the code - generation result ,
-- which you can compute using 'mkCgFromArraysFun'.
--
The specification functions include one function to find the number of pointer arguments ( which
-- should always be the number of primitive types for which we support code-generation; enums are
mapped to a ' Word ' of some size ) and one function to find the expected array sizes corresponding
to each of these pointers . There are two sets of such function pairs : one for the input
arguments and one for the output arguments .
codeGenWithBindings ::
-- | @quiet@
Bool ->
-- | @path@
Maybe FilePath ->
-- | @funName@
String ->
-- | @gen@
SBVCodeGen SBVSpec ->
IO SBVSpec
codeGenWithBindings quiet path funName' fun = do
stateStore <-
IORef.newIORef $ error "Uninitialized stateStore in Categorifier.C.KGenGenerate.FFI.codeGenWithBindings!"
specStore <-
IORef.newIORef $ error "Uninitialized specStore in Categorifier.C.KGenGenerate.FFI.codeGenWithBindings!"
codeGenWithState funName fun path stateStore specStore
cgState <- IORef.readIORef stateStore
cgSpec <- IORef.readIORef specStore
let moduleText = mkFFIBindingModule funName cgSpec
case path of
Nothing -> pure ()
Just pth -> do
let fullPath = pth <> "/" <> moduleName <> ".hs"
specSrcPath = pth <> "/" <> specFileName funName <> ".c"
specHeaderPath = pth <> "/" <> specFileName funName <> ".h"
unless quiet . putStrLn $
"Haskell binding generation: \"" <> fullPath <> "\".."
writeFile fullPath moduleText
unless quiet . putStrLn $
"SBV (KGen) spec helpers: \"" <> specSrcPath <> "\".."
let (specSrc, specHeader) =
genFunSpec funName $ cgStateToSpec cgState
writeFile specSrcPath specSrc
writeFile specHeaderPath specHeader
pure cgSpec
where
funName = funName' <> "SBV"
moduleName = Casing.pascal funName
extractState :: SBVCodeGen SBV.CgState
extractState = SBVCodeGen . StateT $ \st -> pure (st, st)
codeGenWithState ::
String ->
SBVCodeGen SBVSpec ->
Maybe FilePath ->
IORef.IORef SBV.CgState ->
IORef.IORef SBVSpec ->
IO ()
codeGenWithState funName fun path finalState specvar =
SBV.compileToC path funName f
where
f = do
spec <- fun
liftIO $ IORef.writeIORef specvar spec
extractState >>= liftIO . IORef.writeIORef finalState
| null | https://raw.githubusercontent.com/con-kitty/categorifier-c/a34ff2603529b4da7ad6ffe681dad095f102d1b9/test-lib/Categorifier/C/KGenGenerate/FFI/Gen.hs | haskell | * Code generation of functions
minimum size of one. In other words, the generated code will _not_ exactly match the 'Arrays
more info.
| This function takes a polyvectorized function and its input specification and gives you an
'SBVCodeGen' action you can pass to 'codeGenWithBindings' to generate the corresponding C code
tools:
implemented
* a set of C functions that can be called to get the input and output specifications
@quiet@ determines whether stdout receives a lot of spam. @path@ determines where the code is
generated. @funName@ is the name of the function to be generated. This module attempts to deal
which you can compute using 'mkCgFromArraysFun'.
should always be the number of primitive types for which we support code-generation; enums are
| @quiet@
| @path@
| @funName@
| @gen@ | # LANGUAGE MonoLocalBinds #
# LANGUAGE NoMonomorphismRestriction #
| The core code - generation functions for ' KGen ' .
module Categorifier.C.KGenGenerate.FFI.Gen
mkCgFromArraysFun,
mkCgFromPolyVecFun,
codeGenWithBindings,
SBVSpec,
)
where
import qualified Barbies
import qualified Categorifier.C.Barbies as Barbies
import Categorifier.C.Codegen.FFI.Spec (SBVSpec, Spec (..))
import Categorifier.C.KGen.KGen (KGen (..))
import Categorifier.C.KGenGenerate.FFI.Bindings (mkFFIBindingModule)
import Categorifier.C.KGenGenerate.FFI.Spec (cgStateToSpec, genFunSpec, specFileName)
import Categorifier.C.KTypes.C (C (..))
import Categorifier.C.KTypes.KLiteral (false)
import Categorifier.C.PolyVec (PolyVec, pdevectorize, pvectorize, pvlengths)
import Categorifier.C.Prim (ArrayCount (..), ArrayName (..), Arrays (..), arrayNames)
import qualified Categorifier.Common.IO.Exception as Exception
import Control.Monad (unless, (<=<))
import Control.Monad.IO.Class (liftIO)
import Control.Monad.Trans.State.Lazy (StateT (..))
import Data.Functor.Compose (Compose (..))
import qualified Data.IORef as IORef
import Data.Proxy (Proxy (..))
import Data.SBV.Internals (SBV, SBVCodeGen (..))
import qualified Data.SBV.Internals as SBV
import qualified Data.SBV.Tools.CodeGen as SBV
import qualified Data.Text as Text (unpack)
import qualified Data.Vector as V
import qualified Text.Casing as Casing
| Convenience function to wrap ` mkCgFromArraysFun ` with PolyVec types .
mkCgFromPolyVecFun :: forall a b. (PolyVec KGen a, PolyVec KGen b) => (a -> b) -> SBVCodeGen SBVSpec
mkCgFromPolyVecFun polyVecFun = mkCgFromArraysFun arraysFun inputCounts
where
arraysFun =
Exception.throwIOLeft . pvectorize @V.Vector @KGen @b . polyVecFun
<=< Exception.throwIOLeft . pdevectorize @V.Vector @KGen @a
inputCounts = pvlengths (Proxy @KGen) (Proxy @a)
Note to implementors : keep in mind that SBV can not deal with empty input or output arrays , so
even if this function has arrays of zero size in the ' counts ' argument we pass it , our resulting
' SBVCodeGen ' action ( and the ' CgState ' accumulated therein ) will generate all arrays with a
ArrayCount ' you get from polyvectorization . See ' arrayCountsToSpec ' and ' FFIArrayCount ' for some
and FFI tools .
mkCgFromArraysFun ::
(Arrays (Compose V.Vector KGen) -> IO (Arrays (Compose V.Vector KGen))) ->
Arrays ArrayCount ->
SBVCodeGen SBVSpec
mkCgFromArraysFun f counts = do
inputArrays <-
Barbies.bzipWithMC @SBV.SymVal genInArr' arrayNames counts ::
SBVCodeGen (Arrays (Compose V.Vector KGen))
outputArrays <- liftIO $ f inputArrays
let outcounts = Barbies.bmap (ArrayCount . V.length . getCompose) outputArrays
Barbies.bzipWith3MC_ @SBV.SymVal
genOutArr'
arrayNames
outputArrays
outputsIfZeroLength
SBV.cgOverwriteFiles True
SBV.cgGenerateDriver False
SBV.cgGenerateMakefile False
pure $ Spec counts outcounts
where
genInArr' ::
forall a. SBV.SymVal a => ArrayName a -> ArrayCount a -> SBVCodeGen (Compose V.Vector KGen a)
genInArr' (ArrayName name) (ArrayCount count) =
Compose <$> genInArr ("in_" <> Text.unpack name) count
genInArr :: forall a. SBV.SymVal a => String -> Int -> SBVCodeGen (V.Vector (KGen a))
genInArr name 0 = do
_ <- SBV.cgInputArr 1 name :: SBVCodeGen [SBV a]
pure V.empty
genInArr name count =
V.fromList . fmap KGen <$> SBV.cgInputArr (fromIntegral count) name
genOutArr' ::
forall a. SBV.SymVal a => ArrayName a -> Compose V.Vector KGen a -> C a -> SBVCodeGen ()
genOutArr' (ArrayName name) (Compose out) outputIfZeroLength =
genOutArr ("out_" <> Text.unpack name) out outputIfZeroLength
genOutArr :: forall a. SBV.SymVal a => String -> V.Vector (KGen a) -> C a -> SBVCodeGen ()
genOutArr name outArr outputIfZeroLength
| V.null outArr = SBV.cgOutputArr name (pure . SBV.literal $ unsafeC outputIfZeroLength)
| otherwise = SBV.cgOutputArr name (V.toList (fmap getKGen outArr))
outputsIfZeroLength :: Arrays C
outputsIfZeroLength =
Arrays
{ arrayBool = false,
arrayInt8 = 0,
arrayInt16 = 0,
arrayInt32 = 0,
arrayInt64 = 0,
arrayWord8 = 0,
arrayWord16 = 0,
arrayWord32 = 0,
arrayWord64 = 0,
arrayFloat = 0,
arrayDouble = 0
}
| ' codeGenWithBindings quiet path funName gen ' generates C code and various associated FFI helper
* an FFI binding that allows calling the function directly from TODO(MP ): Not yet
with the casing conventions in Haskell and C , so passing the - style @myFunctionName@ will
correspond to @my_function_name@ in the generated C code . @gen@ is the code - generation result ,
The specification functions include one function to find the number of pointer arguments ( which
mapped to a ' Word ' of some size ) and one function to find the expected array sizes corresponding
to each of these pointers . There are two sets of such function pairs : one for the input
arguments and one for the output arguments .
codeGenWithBindings ::
Bool ->
Maybe FilePath ->
String ->
SBVCodeGen SBVSpec ->
IO SBVSpec
codeGenWithBindings quiet path funName' fun = do
stateStore <-
IORef.newIORef $ error "Uninitialized stateStore in Categorifier.C.KGenGenerate.FFI.codeGenWithBindings!"
specStore <-
IORef.newIORef $ error "Uninitialized specStore in Categorifier.C.KGenGenerate.FFI.codeGenWithBindings!"
codeGenWithState funName fun path stateStore specStore
cgState <- IORef.readIORef stateStore
cgSpec <- IORef.readIORef specStore
let moduleText = mkFFIBindingModule funName cgSpec
case path of
Nothing -> pure ()
Just pth -> do
let fullPath = pth <> "/" <> moduleName <> ".hs"
specSrcPath = pth <> "/" <> specFileName funName <> ".c"
specHeaderPath = pth <> "/" <> specFileName funName <> ".h"
unless quiet . putStrLn $
"Haskell binding generation: \"" <> fullPath <> "\".."
writeFile fullPath moduleText
unless quiet . putStrLn $
"SBV (KGen) spec helpers: \"" <> specSrcPath <> "\".."
let (specSrc, specHeader) =
genFunSpec funName $ cgStateToSpec cgState
writeFile specSrcPath specSrc
writeFile specHeaderPath specHeader
pure cgSpec
where
funName = funName' <> "SBV"
moduleName = Casing.pascal funName
extractState :: SBVCodeGen SBV.CgState
extractState = SBVCodeGen . StateT $ \st -> pure (st, st)
codeGenWithState ::
String ->
SBVCodeGen SBVSpec ->
Maybe FilePath ->
IORef.IORef SBV.CgState ->
IORef.IORef SBVSpec ->
IO ()
codeGenWithState funName fun path finalState specvar =
SBV.compileToC path funName f
where
f = do
spec <- fun
liftIO $ IORef.writeIORef specvar spec
extractState >>= liftIO . IORef.writeIORef finalState
|
b839268358fe9c0125b5fd3e42a6f41171feda47a6ef35489f51618958c8b23f | reborg/clojure-essential-reference | 5.clj | (require '[clojure.pprint :as pprint])
< 1 >
;; (0
1
2
;; ...
;; 99)nil
< 2 >
(pprint/write (range 100)))
( 0 1 2 ... 99)nil
(alter-var-root #'pprint/*print-pretty* (constantly false)) ; <3>
(pprint/write (range 100))
( 0 1 2 ... 99)nil
< 4 > | null | https://raw.githubusercontent.com/reborg/clojure-essential-reference/9a3eb82024c8e5fbe17412af541c2cd30820c92e/DynamicVariablesintheStandardLibrary/Prettyprintingvariables/5.clj | clojure | (0
...
99)nil
<3> | (require '[clojure.pprint :as pprint])
< 1 >
1
2
< 2 >
(pprint/write (range 100)))
( 0 1 2 ... 99)nil
(pprint/write (range 100))
( 0 1 2 ... 99)nil
< 4 > |
8e1c7191e82c455cec402311bf866dd8d7f588431b08b6242221cfaa68cae248 | artemeff/raven-erlang | raven_app_test.erl | %% @doc Tests for raven_app.
-module(raven_app_test).
-include_lib("eunit/include/eunit.hrl").
%%%%%%%%%%%%%%%%%%%%%%%%%%
%%% TESTS DESCRIPTIONS %%%
%%%%%%%%%%%%%%%%%%%%%%%%%%
load_configuration_test_() ->
[
{"Loads configuration from application env",
fun() ->
{StartAppStatus, _} = application:ensure_all_started(raven_erlang),
?assertEqual(ok, StartAppStatus),
Config = raven:get_config(),
{cfg,"","PUBLIC_KEY",PrivateKey,"1",inet6} = Config,
?assert(PrivateKey == "PRIVATE_KEY" orelse PrivateKey == ""),
ok = application:stop(raven_erlang)
end},
{"Loads a default value (inet) for ipfamily if not specified",
fun() ->
ok = application:unset_env(raven_erlang, ipfamily),
{StartAppStatus, _} = application:ensure_all_started(raven_erlang),
?assertEqual(ok, StartAppStatus),
Config = raven:get_config(),
{cfg,"","PUBLIC_KEY",PrivateKey,"1",inet} = Config,
?assert(PrivateKey == "PRIVATE_KEY" orelse PrivateKey == ""),
ok = application:stop(raven_erlang)
end}
].
capture_event_test_() ->
[
{"We can start the app and capture a simple event",
fun() ->
{StartAppStatus, _} = application:ensure_all_started(raven_erlang),
?assertEqual(ok, StartAppStatus),
ok = raven:capture("Test event", []),
ok = application:stop(raven_erlang)
end}
].
| null | https://raw.githubusercontent.com/artemeff/raven-erlang/9a2ac47e1c4145c490be3c56c0cc9cc0da751cbf/test/raven_app_test.erl | erlang | @doc Tests for raven_app.
TESTS DESCRIPTIONS %%%
|
-module(raven_app_test).
-include_lib("eunit/include/eunit.hrl").
load_configuration_test_() ->
[
{"Loads configuration from application env",
fun() ->
{StartAppStatus, _} = application:ensure_all_started(raven_erlang),
?assertEqual(ok, StartAppStatus),
Config = raven:get_config(),
{cfg,"","PUBLIC_KEY",PrivateKey,"1",inet6} = Config,
?assert(PrivateKey == "PRIVATE_KEY" orelse PrivateKey == ""),
ok = application:stop(raven_erlang)
end},
{"Loads a default value (inet) for ipfamily if not specified",
fun() ->
ok = application:unset_env(raven_erlang, ipfamily),
{StartAppStatus, _} = application:ensure_all_started(raven_erlang),
?assertEqual(ok, StartAppStatus),
Config = raven:get_config(),
{cfg,"","PUBLIC_KEY",PrivateKey,"1",inet} = Config,
?assert(PrivateKey == "PRIVATE_KEY" orelse PrivateKey == ""),
ok = application:stop(raven_erlang)
end}
].
capture_event_test_() ->
[
{"We can start the app and capture a simple event",
fun() ->
{StartAppStatus, _} = application:ensure_all_started(raven_erlang),
?assertEqual(ok, StartAppStatus),
ok = raven:capture("Test event", []),
ok = application:stop(raven_erlang)
end}
].
|
b434f08c3aca4eb2599d45f5d2cc9e14608c1cae187147a2e75d4a69d8f3c188 | rescript-lang/rescript-compiler | ounit_cmd_util.ml | let (//) = Filename.concat
* may nonterminate when [ cwd ] is ' . '
let rec unsafe_root_dir_aux cwd =
if Sys.file_exists (cwd//Literals.bsconfig_json) then cwd
else unsafe_root_dir_aux (Filename.dirname cwd)
let project_root = unsafe_root_dir_aux (Sys.getcwd ())
let jscomp = project_root // "jscomp"
let dune_bin_dir = project_root // "_build" // "install" // "default" // "bin"
let bsc_exe = dune_bin_dir // "bsc"
let runtime_dir = jscomp // "runtime"
let others_dir = jscomp // "others"
let stdlib_dir = jscomp // "stdlib-406"
let rec safe_dup fd =
let new_fd = Unix.dup fd in
if ( Obj.magic new_fd : int ) > = 3 then
new_fd ( * [ dup ] can not be 0 , 1 , 2
let new_fd = Unix.dup fd in
if (Obj.magic new_fd : int) >= 3 then
new_fd (* [dup] can not be 0, 1, 2*)
else begin
let res = safe_dup fd in
Unix.close new_fd;
res
end *)
let safe_close fd =
try Unix.close fd with Unix.Unix_error(_,_,_) -> ()
type output = {
stderr : string ;
stdout : string ;
exit_code : int
}
let perform command args =
let new_fd_in, new_fd_out = Unix.pipe () in
let err_fd_in, err_fd_out = Unix.pipe () in
match Unix.fork () with
| 0 ->
begin try
safe_close new_fd_in;
safe_close err_fd_in;
Unix.dup2 err_fd_out Unix.stderr ;
Unix.dup2 new_fd_out Unix.stdout;
Unix.execv command args
with _ ->
exit 127
end
| pid ->
when all the descriptors on a pipe 's input are closed and the pipe is
empty , a call to [ read ] on its output returns zero : end of file .
when all the descriptiors on a pipe 's output are closed , a call to
[ write ] on its input kills the writing process ( EPIPE ) .
empty, a call to [read] on its output returns zero: end of file.
when all the descriptiors on a pipe's output are closed, a call to
[write] on its input kills the writing process (EPIPE).
*)
safe_close new_fd_out ;
safe_close err_fd_out ;
let in_chan = Unix.in_channel_of_descr new_fd_in in
let err_in_chan = Unix.in_channel_of_descr err_fd_in in
let buf = Buffer.create 1024 in
let err_buf = Buffer.create 1024 in
(try
while true do
Buffer.add_string buf (input_line in_chan );
Buffer.add_char buf '\n'
done;
with
End_of_file -> ()) ;
(try
while true do
Buffer.add_string err_buf (input_line err_in_chan );
Buffer.add_char err_buf '\n'
done;
with
End_of_file -> ()) ;
let exit_code = match snd @@ Unix.waitpid [] pid with
| Unix.WEXITED exit_code -> exit_code
| Unix.WSIGNALED _signal_number
| Unix.WSTOPPED _signal_number -> 127 in
{
stdout = Buffer.contents buf ;
stderr = Buffer.contents err_buf;
exit_code
}
let perform_bsc args =
perform bsc_exe
(Array.append
[|bsc_exe ;
"-bs-package-name" ; "bs-platform";
"-bs-no-version-header";
"-bs-cross-module-opt";
"-w";
"-40";
"-I" ;
runtime_dir ;
"-I";
others_dir ;
"-I" ;
stdlib_dir
|] args)
let bsc_check_eval str =
perform_bsc [|"-bs-eval"; str|]
let debug_output o =
Printf.printf "\nexit_code:%d\nstdout:%s\nstderr:%s\n"
o.exit_code o.stdout o.stderr
| null | https://raw.githubusercontent.com/rescript-lang/rescript-compiler/81a3dc63ca387b2af23fed297db283254ae3ab20/jscomp/ounit_tests/ounit_cmd_util.ml | ocaml | [dup] can not be 0, 1, 2 | let (//) = Filename.concat
* may nonterminate when [ cwd ] is ' . '
let rec unsafe_root_dir_aux cwd =
if Sys.file_exists (cwd//Literals.bsconfig_json) then cwd
else unsafe_root_dir_aux (Filename.dirname cwd)
let project_root = unsafe_root_dir_aux (Sys.getcwd ())
let jscomp = project_root // "jscomp"
let dune_bin_dir = project_root // "_build" // "install" // "default" // "bin"
let bsc_exe = dune_bin_dir // "bsc"
let runtime_dir = jscomp // "runtime"
let others_dir = jscomp // "others"
let stdlib_dir = jscomp // "stdlib-406"
let rec safe_dup fd =
let new_fd = Unix.dup fd in
if ( Obj.magic new_fd : int ) > = 3 then
new_fd ( * [ dup ] can not be 0 , 1 , 2
let new_fd = Unix.dup fd in
if (Obj.magic new_fd : int) >= 3 then
else begin
let res = safe_dup fd in
Unix.close new_fd;
res
end *)
let safe_close fd =
try Unix.close fd with Unix.Unix_error(_,_,_) -> ()
type output = {
stderr : string ;
stdout : string ;
exit_code : int
}
let perform command args =
let new_fd_in, new_fd_out = Unix.pipe () in
let err_fd_in, err_fd_out = Unix.pipe () in
match Unix.fork () with
| 0 ->
begin try
safe_close new_fd_in;
safe_close err_fd_in;
Unix.dup2 err_fd_out Unix.stderr ;
Unix.dup2 new_fd_out Unix.stdout;
Unix.execv command args
with _ ->
exit 127
end
| pid ->
when all the descriptors on a pipe 's input are closed and the pipe is
empty , a call to [ read ] on its output returns zero : end of file .
when all the descriptiors on a pipe 's output are closed , a call to
[ write ] on its input kills the writing process ( EPIPE ) .
empty, a call to [read] on its output returns zero: end of file.
when all the descriptiors on a pipe's output are closed, a call to
[write] on its input kills the writing process (EPIPE).
*)
safe_close new_fd_out ;
safe_close err_fd_out ;
let in_chan = Unix.in_channel_of_descr new_fd_in in
let err_in_chan = Unix.in_channel_of_descr err_fd_in in
let buf = Buffer.create 1024 in
let err_buf = Buffer.create 1024 in
(try
while true do
Buffer.add_string buf (input_line in_chan );
Buffer.add_char buf '\n'
done;
with
End_of_file -> ()) ;
(try
while true do
Buffer.add_string err_buf (input_line err_in_chan );
Buffer.add_char err_buf '\n'
done;
with
End_of_file -> ()) ;
let exit_code = match snd @@ Unix.waitpid [] pid with
| Unix.WEXITED exit_code -> exit_code
| Unix.WSIGNALED _signal_number
| Unix.WSTOPPED _signal_number -> 127 in
{
stdout = Buffer.contents buf ;
stderr = Buffer.contents err_buf;
exit_code
}
let perform_bsc args =
perform bsc_exe
(Array.append
[|bsc_exe ;
"-bs-package-name" ; "bs-platform";
"-bs-no-version-header";
"-bs-cross-module-opt";
"-w";
"-40";
"-I" ;
runtime_dir ;
"-I";
others_dir ;
"-I" ;
stdlib_dir
|] args)
let bsc_check_eval str =
perform_bsc [|"-bs-eval"; str|]
let debug_output o =
Printf.printf "\nexit_code:%d\nstdout:%s\nstderr:%s\n"
o.exit_code o.stdout o.stderr
|
c39e91d4b10fd5e51391a4742d6c06d5f66317e71ff8c38663923dc541dbdae7 | paurkedal/ocaml-prime | unprime_char.ml | Copyright ( C ) 2013 - -2022 Petter A. Urkedal < >
*
* This library is free software ; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation , either version 3 of the License , or ( at your
* option ) any later version , with the LGPL-3.0 Linking Exception .
*
* This library is distributed in the hope that it will be useful , but WITHOUT
* ANY WARRANTY ; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE . See the GNU Lesser General Public
* License for more details .
*
* You should have received a copy of the GNU Lesser General Public License
* and the LGPL-3.0 Linking Exception along with this library . If not , see
* < / > and < > , respectively .
*
* This library is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or (at your
* option) any later version, with the LGPL-3.0 Linking Exception.
*
* This library is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
* License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* and the LGPL-3.0 Linking Exception along with this library. If not, see
* </> and <>, respectively.
*)
module Char = struct
include Char
include Prime_char
end
| null | https://raw.githubusercontent.com/paurkedal/ocaml-prime/42efa85317069d726e8e3989e51c24ba03c56b47/lib/unprime_char.ml | ocaml | Copyright ( C ) 2013 - -2022 Petter A. Urkedal < >
*
* This library is free software ; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation , either version 3 of the License , or ( at your
* option ) any later version , with the LGPL-3.0 Linking Exception .
*
* This library is distributed in the hope that it will be useful , but WITHOUT
* ANY WARRANTY ; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE . See the GNU Lesser General Public
* License for more details .
*
* You should have received a copy of the GNU Lesser General Public License
* and the LGPL-3.0 Linking Exception along with this library . If not , see
* < / > and < > , respectively .
*
* This library is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or (at your
* option) any later version, with the LGPL-3.0 Linking Exception.
*
* This library is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
* License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* and the LGPL-3.0 Linking Exception along with this library. If not, see
* </> and <>, respectively.
*)
module Char = struct
include Char
include Prime_char
end
| |
a575e20580661047ae0dd19ef994424debd0e0674ad58b4bb515da716a673d1b | bmeurer/ocaml-experimental | odoc_str.mli | (***********************************************************************)
(* OCamldoc *)
(* *)
, projet Cristal , INRIA Rocquencourt
(* *)
Copyright 2001 Institut National de Recherche en Informatique et
en Automatique . All rights reserved . This file is distributed
under the terms of the Q Public License version 1.0 .
(* *)
(***********************************************************************)
$ Id$
(** The functions to get a string from different kinds of elements (types, modules, ...). *)
(** @return the variance string for the given type and (covariant, contravariant) information. *)
val string_of_variance : Odoc_type.t_type -> (bool * bool) -> string
(** This function returns a string to represent the given list of types,
with a given separator.
@param par can be used to force the addition or not of parentheses around the returned string.
*)
val string_of_type_list : ?par: bool -> string -> Types.type_expr list -> string
(** This function returns a string to represent the list of type parameters
for the given type. *)
val string_of_type_param_list : Odoc_type.t_type -> string
(** This function returns a string to represent the given list of
type parameters of a class or class type,
with a given separator. *)
val string_of_class_type_param_list : Types.type_expr list -> string
(** @return a string to describe the given type. *)
val string_of_type : Odoc_type.t_type -> string
(** @return a string to display the parameters of the given class,
in the same form as the compiler. *)
val string_of_class_params : Odoc_class.t_class -> string
(** @return a string to describe the given exception. *)
val string_of_exception : Odoc_exception.t_exception -> string
(** @return a string to describe the given value. *)
val string_of_value : Odoc_value.t_value -> string
(** @return a string to describe the given attribute. *)
val string_of_attribute : Odoc_value.t_attribute -> string
(** @return a string to describe the given method. *)
val string_of_method : Odoc_value.t_method -> string
| null | https://raw.githubusercontent.com/bmeurer/ocaml-experimental/fe5c10cdb0499e43af4b08f35a3248e5c1a8b541/ocamldoc/odoc_str.mli | ocaml | *********************************************************************
OCamldoc
*********************************************************************
* The functions to get a string from different kinds of elements (types, modules, ...).
* @return the variance string for the given type and (covariant, contravariant) information.
* This function returns a string to represent the given list of types,
with a given separator.
@param par can be used to force the addition or not of parentheses around the returned string.
* This function returns a string to represent the list of type parameters
for the given type.
* This function returns a string to represent the given list of
type parameters of a class or class type,
with a given separator.
* @return a string to describe the given type.
* @return a string to display the parameters of the given class,
in the same form as the compiler.
* @return a string to describe the given exception.
* @return a string to describe the given value.
* @return a string to describe the given attribute.
* @return a string to describe the given method. | , projet Cristal , INRIA Rocquencourt
Copyright 2001 Institut National de Recherche en Informatique et
en Automatique . All rights reserved . This file is distributed
under the terms of the Q Public License version 1.0 .
$ Id$
val string_of_variance : Odoc_type.t_type -> (bool * bool) -> string
val string_of_type_list : ?par: bool -> string -> Types.type_expr list -> string
val string_of_type_param_list : Odoc_type.t_type -> string
val string_of_class_type_param_list : Types.type_expr list -> string
val string_of_type : Odoc_type.t_type -> string
val string_of_class_params : Odoc_class.t_class -> string
val string_of_exception : Odoc_exception.t_exception -> string
val string_of_value : Odoc_value.t_value -> string
val string_of_attribute : Odoc_value.t_attribute -> string
val string_of_method : Odoc_value.t_method -> string
|
d2b8db0e56cd9f4b7ead8e9144b3502a3281f275c1f002bbeddf7428d5b3d162 | expipiplus1/vulkan | Constants.hs | module Julia.Constants
where
import Data.Word
juliaWorkgroupX, juliaWorkgroupY :: Word32
juliaWorkgroupX = 8
juliaWorkgroupY = 8
| null | https://raw.githubusercontent.com/expipiplus1/vulkan/b1e33d1031779b4740c279c68879d05aee371659/examples/resize/Julia/Constants.hs | haskell | module Julia.Constants
where
import Data.Word
juliaWorkgroupX, juliaWorkgroupY :: Word32
juliaWorkgroupX = 8
juliaWorkgroupY = 8
| |
443c0ea80e377aeb2d7b37af20b583cae8caea3c41576e95e2dc2340fa4f431a | philnguyen/soft-contract | ocm.rkt | #lang racket/base
(provide
min-entry
make-ocm
(prefix-out ocm- min-entry)
(prefix-out ocm- min-index)
)
;; -----------------------------------------------------------------------------
(require
require-typed-check
"ocm-struct.rkt"
(only-in racket/list argmin)
(only-in racket/sequence sequence->list)
(only-in racket/vector vector-drop vector-append)
(for-syntax racket/base racket/syntax))
;; =============================================================================
(define (assert v p)
(unless (p v) (error 'ocm "assertion failure"))
v)
(define (index-type? v)
(and (integer? v) (<= 0 v)))
;; =============================================================================
(: select - elements ( ( Any ) ( ) - > ( Any ) ) )
(define (select-elements xs is)
(map (λ(i) (list-ref xs i)) is))
(: odd - elements ( ( Any ) - > ( Any ) ) )
(define (odd-elements xs)
(select-elements xs (sequence->list (in-range 1 (length xs) 2))))
(: vector - odd - elements ( All ( A ) ( - > ( ) ( ) ) ) )
(define (vector-odd-elements xs)
: ( )
([i (in-range (vector-length xs))] #:when (odd? i))
(vector-ref xs i)))
(: even - elements ( ( Any ) - > ( Any ) ) )
(define (even-elements xs)
(select-elements xs (sequence->list (in-range 0 (length xs) 2))))
;; Wrapper for the matrix procedure
;; that automatically maintains a hash cache of previously-calculated values
;; because the minima operations tend to hit the same values.
;; Assuming here that (matrix i j) is invariant
;; and that the matrix function is more expensive than the cache lookup.
(define-syntax-rule (vector-append-entry xs value)
(vector-append xs (vector value)))
(define-syntax-rule (vector-append-index xs value)
(vector-append xs (vector value)))
(: vector - set ( All ( a ) ( ( a ) Integer a - > ( a ) ) ) )
(define (vector-set vec idx val)
(vector-set! vec idx val)
vec)
(define-syntax-rule (vector-cdr vec)
(vector-drop vec 1))
(: ( ( ) ( ) Matrix - Proc - Type Entry->Value - Type - > ( ) ) )
(define (reduce2 row-indices col-indices matrix-proc entry->value)
(let find-survivors ([rows row-indices][survivors '()])
(cond
[(= 0 (vector-length rows))
(list->vector (reverse survivors))]
[else
(define challenger-row (vector-ref rows 0))
(cond
no survivors yet , so push first row and keep going
[(eq? '() survivors) (find-survivors (vector-cdr rows) (cons challenger-row survivors))]
[else
(define index-of-last-survivor (sub1 (length survivors)))
(define col-head (vector-ref col-indices index-of-last-survivor))
(define-syntax-rule (test-function r) (entry->value (matrix-proc r col-head)))
(cond
;; this is the challenge: is the head cell of challenger a new minimum?
;; use < not <=, so the recorded winner is the earliest row with the new minimum, not the latest row
;; if yes, challenger wins. pop element from stack, and let challenger try again (= leave rows alone)
[(< (test-function challenger-row) (test-function (car survivors))) (find-survivors rows (cdr survivors))]
;; if not, challenger lost.
;; If we're in the last column, ignore the loser by recurring on the same values
[(= col-head (vector-last col-indices)) (find-survivors (vector-cdr rows) survivors)]
;; otherwise challenger lost and we're not in last column,
;; so add challenger to survivor stack
[else (find-survivors (vector-cdr rows) (cons challenger-row survivors))])])])))
;; define a special type so it can be reused in `interpolate`
;; it is (cons value row-idx)
(define minima-idx-key 'row-idx)
(define minima-payload-key 'entry)
;(define-type Make-Minimum-Input (Pair Any Index-Type))
;(: make-minimum (Make-Minimum-Input -> (HashTable Any Any)))
(define (make-minimum value-rowidx-pair)
(define ht (make-hash))
(! ht minima-payload-key (car value-rowidx-pair))
(! ht minima-idx-key (cdr value-rowidx-pair))
ht)
Interpolate phase : in the minima hash , add results for even rows
(define-syntax-rule (vector-last v)
(vector-ref v (sub1 (vector-length v))))
(: interpolate - proc ( ( HashTable Any Any ) ( ) ( ) Matrix - Proc - Type Entry->Value - Type - > ( HashTable Any Any ) ) )
(define (interpolate-proc minima row-indices col-indices matrix-proc entry->value)
(define idx-of-last-col (sub1 (vector-length col-indices)))
(define (smallest-value-entry col idx-of-last-row)
(argmin (λ(x) (entry->value (car x)))
(for/list ([row-idx (stop-after (in-vector row-indices) (λ(x) (= idx-of-last-row x)))])
(cons (matrix-proc row-idx col) row-idx))))
(for ([(col col-idx) (in-indexed col-indices)] #:when (even? col-idx))
(define idx-of-last-row (assert (if (= col-idx idx-of-last-col)
(vector-last row-indices)
(hash-ref (assert (hash-ref minima (vector-ref col-indices (add1 col-idx))) hash?) minima-idx-key)) index-type?))
(! minima col (make-minimum (smallest-value-entry col idx-of-last-row))))
minima)
;; The return value `minima` is a hash:
;; the keys are col-indices (integers)
;; the values are pairs of (value row-index).
(: concave - minima ( ( ) ( ) Matrix - Proc - Type Entry->Value - Type - > ( HashTable Any Any ) ) )
(define (concave-minima row-indices col-indices matrix-proc entry->value)
(define reduce-proc reduce2)
(if (= 0 (vector-length col-indices))
(make-hash)
(let ([row-indices (reduce-proc row-indices col-indices matrix-proc entry->value)])
(: odd - column - minima ( HashTable Any Any ) )
(define odd-column-minima
(concave-minima row-indices
(vector-odd-elements col-indices)
matrix-proc entry->value))
(interpolate-proc odd-column-minima row-indices col-indices matrix-proc entry->value))))
(define no-value 'none)
(define @ hash-ref)
;(define-syntax-rule (@ hashtable key)
; (hash-ref hashtable key))
(define ! hash-set!)
(: make - ocm ( ( Matrix - Proc - Type ( Entry - Type - > Value - Type ) ) ( Entry - Type ) . - > * . OCM - Type ) )
(define (make-ocm matrix-proc entry->value [initial-entry 0.0])
;(log-ocm-debug "making new ocm")
($ocm (vector initial-entry) (vector no-value) 0 matrix-proc entry->value 0 0))
Return min { Matrix(i , j ) | i < j } .
;(: min-entry (OCM-Type Index-Type -> Entry-Type))
(define (min-entry ocm j)
(if (< ($ocm-finished ocm) j)
(begin (advance! ocm) (min-entry ocm j))
(vector-ref ($ocm-min-entrys ocm) j)))
;; ;; same as min-entry, but converts to raw value
( define / typed ( min - value j )
;; (OCM-Type Index-Type -> Value-Type)
;; (($ocm-entry->value ocm) (min-entry ocm j)))
Return argmin { Matrix(i , j ) | i < j } .
;(: min-index (OCM-Type Index-Type -> (U Index-Type No-Value-Type)))
(define (min-index ocm j)
(if (< ($ocm-finished ocm) j)
(begin (advance! ocm) (min-index ocm j))
(vector-ref ($ocm-min-row-indices ocm) j)))
;; Finish another value,index pair.
;(: advance! (OCM-Type -> Void))
(define (advance! ocm)
(define next (add1 ($ocm-finished ocm)))
(cond
First case : we have already advanced past the previous tentative
value . We make a new tentative value by applying ConcaveMinima
;; to the largest square submatrix that fits under the base.
[(> next ($ocm-tentative ocm))
(define rows (list->vector (sequence->list (in-range ($ocm-base ocm) next))))
(set-$ocm-tentative! ocm (+ ($ocm-finished ocm) (vector-length rows)))
(define cols (list->vector (sequence->list (in-range next (add1 ($ocm-tentative ocm))))))
(define minima (concave-minima rows cols ($ocm-matrix-proc ocm) ($ocm-entry->value ocm)))
(for ([col (in-vector cols)])
(define HT
(assert (@ minima col) hash?))
(cond
[(>= col (vector-length ($ocm-min-entrys ocm)))
(set-$ocm-min-entrys! ocm (vector-append-entry
($ocm-min-entrys ocm)
(@ HT
minima-payload-key)))
(set-$ocm-min-row-indices! ocm
(vector-append-index ($ocm-min-row-indices ocm)
(assert (@ HT minima-idx-key) index-type?)))]
[(< (($ocm-entry->value ocm)
(@ HT minima-payload-key))
(($ocm-entry->value ocm) (vector-ref ($ocm-min-entrys ocm) col)))
(set-$ocm-min-entrys! ocm
( vector-set
($ocm-min-entrys ocm) col
(@ HT minima-payload-key)))
(set-$ocm-min-row-indices! ocm
( vector-set
($ocm-min-row-indices ocm) col
(assert (@ HT minima-idx-key) index-type?)))]))
(set-$ocm-finished! ocm next)]
[else
Second case : the new column minimum is on the diagonal .
;; All subsequent ones will be at least as low,
;; so we can clear out all our work from higher rows.
As in the fourth case , the loss of tentative is
;; amortized against the increase in base.
(define diag (($ocm-matrix-proc ocm) (sub1 next) next))
(cond
[(< (($ocm-entry->value ocm) diag) (($ocm-entry->value ocm) (vector-ref ($ocm-min-entrys ocm) next)))
(set-$ocm-min-entrys! ocm (vector-set ($ocm-min-entrys ocm) next diag))
(set-$ocm-min-row-indices! ocm (vector-set ($ocm-min-row-indices ocm) next (sub1 next)))
(set-$ocm-base! ocm (sub1 next))
(set-$ocm-tentative! ocm next)
(set-$ocm-finished! ocm next)]
Third case : row i-1 does not supply a column minimum in
;; any column up to tentative. We simply advance finished
;; while maintaining the invariant.
[(>= (($ocm-entry->value ocm) (($ocm-matrix-proc ocm) (sub1 next) ($ocm-tentative ocm)))
(($ocm-entry->value ocm) (vector-ref ($ocm-min-entrys ocm) ($ocm-tentative ocm))))
(set-$ocm-finished! ocm next)]
Fourth and final case : a new column minimum at self._tentative .
;; This allows us to make progress by incorporating rows
;; prior to finished into the base. The base invariant holds
;; because these rows cannot supply any later column minima.
;; The work done when we last advanced tentative (and undone by
;; this step) can be amortized against the increase in base.
[else
(set-$ocm-base! ocm (sub1 next))
(set-$ocm-tentative! ocm next)
(set-$ocm-finished! ocm next)])]))
| null | https://raw.githubusercontent.com/philnguyen/soft-contract/5e07dc2d622ee80b961f4e8aebd04ce950720239/soft-contract/test/gradual-typing-benchmarks/quadBG/ocm.rkt | racket | -----------------------------------------------------------------------------
=============================================================================
=============================================================================
Wrapper for the matrix procedure
that automatically maintains a hash cache of previously-calculated values
because the minima operations tend to hit the same values.
Assuming here that (matrix i j) is invariant
and that the matrix function is more expensive than the cache lookup.
this is the challenge: is the head cell of challenger a new minimum?
use < not <=, so the recorded winner is the earliest row with the new minimum, not the latest row
if yes, challenger wins. pop element from stack, and let challenger try again (= leave rows alone)
if not, challenger lost.
If we're in the last column, ignore the loser by recurring on the same values
otherwise challenger lost and we're not in last column,
so add challenger to survivor stack
define a special type so it can be reused in `interpolate`
it is (cons value row-idx)
(define-type Make-Minimum-Input (Pair Any Index-Type))
(: make-minimum (Make-Minimum-Input -> (HashTable Any Any)))
The return value `minima` is a hash:
the keys are col-indices (integers)
the values are pairs of (value row-index).
(define-syntax-rule (@ hashtable key)
(hash-ref hashtable key))
(log-ocm-debug "making new ocm")
(: min-entry (OCM-Type Index-Type -> Entry-Type))
;; same as min-entry, but converts to raw value
(OCM-Type Index-Type -> Value-Type)
(($ocm-entry->value ocm) (min-entry ocm j)))
(: min-index (OCM-Type Index-Type -> (U Index-Type No-Value-Type)))
Finish another value,index pair.
(: advance! (OCM-Type -> Void))
to the largest square submatrix that fits under the base.
All subsequent ones will be at least as low,
so we can clear out all our work from higher rows.
amortized against the increase in base.
any column up to tentative. We simply advance finished
while maintaining the invariant.
This allows us to make progress by incorporating rows
prior to finished into the base. The base invariant holds
because these rows cannot supply any later column minima.
The work done when we last advanced tentative (and undone by
this step) can be amortized against the increase in base. | #lang racket/base
(provide
min-entry
make-ocm
(prefix-out ocm- min-entry)
(prefix-out ocm- min-index)
)
(require
require-typed-check
"ocm-struct.rkt"
(only-in racket/list argmin)
(only-in racket/sequence sequence->list)
(only-in racket/vector vector-drop vector-append)
(for-syntax racket/base racket/syntax))
(define (assert v p)
(unless (p v) (error 'ocm "assertion failure"))
v)
(define (index-type? v)
(and (integer? v) (<= 0 v)))
(: select - elements ( ( Any ) ( ) - > ( Any ) ) )
(define (select-elements xs is)
(map (λ(i) (list-ref xs i)) is))
(: odd - elements ( ( Any ) - > ( Any ) ) )
(define (odd-elements xs)
(select-elements xs (sequence->list (in-range 1 (length xs) 2))))
(: vector - odd - elements ( All ( A ) ( - > ( ) ( ) ) ) )
(define (vector-odd-elements xs)
: ( )
([i (in-range (vector-length xs))] #:when (odd? i))
(vector-ref xs i)))
(: even - elements ( ( Any ) - > ( Any ) ) )
(define (even-elements xs)
(select-elements xs (sequence->list (in-range 0 (length xs) 2))))
(define-syntax-rule (vector-append-entry xs value)
(vector-append xs (vector value)))
(define-syntax-rule (vector-append-index xs value)
(vector-append xs (vector value)))
(: vector - set ( All ( a ) ( ( a ) Integer a - > ( a ) ) ) )
(define (vector-set vec idx val)
(vector-set! vec idx val)
vec)
(define-syntax-rule (vector-cdr vec)
(vector-drop vec 1))
(: ( ( ) ( ) Matrix - Proc - Type Entry->Value - Type - > ( ) ) )
(define (reduce2 row-indices col-indices matrix-proc entry->value)
(let find-survivors ([rows row-indices][survivors '()])
(cond
[(= 0 (vector-length rows))
(list->vector (reverse survivors))]
[else
(define challenger-row (vector-ref rows 0))
(cond
no survivors yet , so push first row and keep going
[(eq? '() survivors) (find-survivors (vector-cdr rows) (cons challenger-row survivors))]
[else
(define index-of-last-survivor (sub1 (length survivors)))
(define col-head (vector-ref col-indices index-of-last-survivor))
(define-syntax-rule (test-function r) (entry->value (matrix-proc r col-head)))
(cond
[(< (test-function challenger-row) (test-function (car survivors))) (find-survivors rows (cdr survivors))]
[(= col-head (vector-last col-indices)) (find-survivors (vector-cdr rows) survivors)]
[else (find-survivors (vector-cdr rows) (cons challenger-row survivors))])])])))
(define minima-idx-key 'row-idx)
(define minima-payload-key 'entry)
(define (make-minimum value-rowidx-pair)
(define ht (make-hash))
(! ht minima-payload-key (car value-rowidx-pair))
(! ht minima-idx-key (cdr value-rowidx-pair))
ht)
Interpolate phase : in the minima hash , add results for even rows
(define-syntax-rule (vector-last v)
(vector-ref v (sub1 (vector-length v))))
(: interpolate - proc ( ( HashTable Any Any ) ( ) ( ) Matrix - Proc - Type Entry->Value - Type - > ( HashTable Any Any ) ) )
(define (interpolate-proc minima row-indices col-indices matrix-proc entry->value)
(define idx-of-last-col (sub1 (vector-length col-indices)))
(define (smallest-value-entry col idx-of-last-row)
(argmin (λ(x) (entry->value (car x)))
(for/list ([row-idx (stop-after (in-vector row-indices) (λ(x) (= idx-of-last-row x)))])
(cons (matrix-proc row-idx col) row-idx))))
(for ([(col col-idx) (in-indexed col-indices)] #:when (even? col-idx))
(define idx-of-last-row (assert (if (= col-idx idx-of-last-col)
(vector-last row-indices)
(hash-ref (assert (hash-ref minima (vector-ref col-indices (add1 col-idx))) hash?) minima-idx-key)) index-type?))
(! minima col (make-minimum (smallest-value-entry col idx-of-last-row))))
minima)
(: concave - minima ( ( ) ( ) Matrix - Proc - Type Entry->Value - Type - > ( HashTable Any Any ) ) )
(define (concave-minima row-indices col-indices matrix-proc entry->value)
(define reduce-proc reduce2)
(if (= 0 (vector-length col-indices))
(make-hash)
(let ([row-indices (reduce-proc row-indices col-indices matrix-proc entry->value)])
(: odd - column - minima ( HashTable Any Any ) )
(define odd-column-minima
(concave-minima row-indices
(vector-odd-elements col-indices)
matrix-proc entry->value))
(interpolate-proc odd-column-minima row-indices col-indices matrix-proc entry->value))))
(define no-value 'none)
(define @ hash-ref)
(define ! hash-set!)
(: make - ocm ( ( Matrix - Proc - Type ( Entry - Type - > Value - Type ) ) ( Entry - Type ) . - > * . OCM - Type ) )
(define (make-ocm matrix-proc entry->value [initial-entry 0.0])
($ocm (vector initial-entry) (vector no-value) 0 matrix-proc entry->value 0 0))
Return min { Matrix(i , j ) | i < j } .
(define (min-entry ocm j)
(if (< ($ocm-finished ocm) j)
(begin (advance! ocm) (min-entry ocm j))
(vector-ref ($ocm-min-entrys ocm) j)))
( define / typed ( min - value j )
Return argmin { Matrix(i , j ) | i < j } .
(define (min-index ocm j)
(if (< ($ocm-finished ocm) j)
(begin (advance! ocm) (min-index ocm j))
(vector-ref ($ocm-min-row-indices ocm) j)))
(define (advance! ocm)
(define next (add1 ($ocm-finished ocm)))
(cond
First case : we have already advanced past the previous tentative
value . We make a new tentative value by applying ConcaveMinima
[(> next ($ocm-tentative ocm))
(define rows (list->vector (sequence->list (in-range ($ocm-base ocm) next))))
(set-$ocm-tentative! ocm (+ ($ocm-finished ocm) (vector-length rows)))
(define cols (list->vector (sequence->list (in-range next (add1 ($ocm-tentative ocm))))))
(define minima (concave-minima rows cols ($ocm-matrix-proc ocm) ($ocm-entry->value ocm)))
(for ([col (in-vector cols)])
(define HT
(assert (@ minima col) hash?))
(cond
[(>= col (vector-length ($ocm-min-entrys ocm)))
(set-$ocm-min-entrys! ocm (vector-append-entry
($ocm-min-entrys ocm)
(@ HT
minima-payload-key)))
(set-$ocm-min-row-indices! ocm
(vector-append-index ($ocm-min-row-indices ocm)
(assert (@ HT minima-idx-key) index-type?)))]
[(< (($ocm-entry->value ocm)
(@ HT minima-payload-key))
(($ocm-entry->value ocm) (vector-ref ($ocm-min-entrys ocm) col)))
(set-$ocm-min-entrys! ocm
( vector-set
($ocm-min-entrys ocm) col
(@ HT minima-payload-key)))
(set-$ocm-min-row-indices! ocm
( vector-set
($ocm-min-row-indices ocm) col
(assert (@ HT minima-idx-key) index-type?)))]))
(set-$ocm-finished! ocm next)]
[else
Second case : the new column minimum is on the diagonal .
As in the fourth case , the loss of tentative is
(define diag (($ocm-matrix-proc ocm) (sub1 next) next))
(cond
[(< (($ocm-entry->value ocm) diag) (($ocm-entry->value ocm) (vector-ref ($ocm-min-entrys ocm) next)))
(set-$ocm-min-entrys! ocm (vector-set ($ocm-min-entrys ocm) next diag))
(set-$ocm-min-row-indices! ocm (vector-set ($ocm-min-row-indices ocm) next (sub1 next)))
(set-$ocm-base! ocm (sub1 next))
(set-$ocm-tentative! ocm next)
(set-$ocm-finished! ocm next)]
Third case : row i-1 does not supply a column minimum in
[(>= (($ocm-entry->value ocm) (($ocm-matrix-proc ocm) (sub1 next) ($ocm-tentative ocm)))
(($ocm-entry->value ocm) (vector-ref ($ocm-min-entrys ocm) ($ocm-tentative ocm))))
(set-$ocm-finished! ocm next)]
Fourth and final case : a new column minimum at self._tentative .
[else
(set-$ocm-base! ocm (sub1 next))
(set-$ocm-tentative! ocm next)
(set-$ocm-finished! ocm next)])]))
|
905f5c9f96278a33fdbf12dd54143d51a5af4843d9ff5f953550d54fdb13d583 | ocamllabs/ocaml-effects | nativeint.mli | (***********************************************************************)
(* *)
(* 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 Library General Public License , with
(* the special exception on linking described in file ../LICENSE. *)
(* *)
(***********************************************************************)
* Processor - native integers .
This module provides operations on the type [ nativeint ] of
signed 32 - bit integers ( on 32 - bit platforms ) or
signed 64 - bit integers ( on 64 - bit platforms ) .
This integer type has exactly the same width as that of a
pointer type in the C compiler . All arithmetic operations over
[ nativeint ] are taken modulo 2{^32 } or 2{^64 } depending
on the word size of the architecture .
Performance notice : values of type [ nativeint ] occupy more memory
space than values of type [ int ] , and arithmetic operations on
[ nativeint ] are generally slower than those on [ int ] . Use [ nativeint ]
only when the application requires the extra bit of precision
over the [ int ] type .
This module provides operations on the type [nativeint] of
signed 32-bit integers (on 32-bit platforms) or
signed 64-bit integers (on 64-bit platforms).
This integer type has exactly the same width as that of a
pointer type in the C compiler. All arithmetic operations over
[nativeint] are taken modulo 2{^32} or 2{^64} depending
on the word size of the architecture.
Performance notice: values of type [nativeint] occupy more memory
space than values of type [int], and arithmetic operations on
[nativeint] are generally slower than those on [int]. Use [nativeint]
only when the application requires the extra bit of precision
over the [int] type.
*)
val zero : nativeint
(** The native integer 0.*)
val one : nativeint
* The native integer 1 .
val minus_one : nativeint
(** The native integer -1.*)
external neg : nativeint -> nativeint = "%nativeint_neg"
(** Unary negation. *)
external add : nativeint -> nativeint -> nativeint = "%nativeint_add"
(** Addition. *)
external sub : nativeint -> nativeint -> nativeint = "%nativeint_sub"
(** Subtraction. *)
external mul : nativeint -> nativeint -> nativeint = "%nativeint_mul"
(** Multiplication. *)
external div : nativeint -> nativeint -> nativeint = "%nativeint_div"
* Integer division . Raise [ Division_by_zero ] if the second
argument is zero . This division rounds the real quotient of
its arguments towards zero , as specified for { ! Pervasives.(/ ) } .
argument is zero. This division rounds the real quotient of
its arguments towards zero, as specified for {!Pervasives.(/)}. *)
external rem : nativeint -> nativeint -> nativeint = "%nativeint_mod"
* Integer remainder . If [ y ] is not zero , the result
of [ x y ] satisfies the following properties :
[ Nativeint.zero < = x y < Nativeint.abs y ] and
[ x = Nativeint.add ( Nativeint.mul ( Nativeint.div x y ) y )
( x y ) ] .
If [ y = 0 ] , [ x y ] raises [ Division_by_zero ] .
of [Nativeint.rem x y] satisfies the following properties:
[Nativeint.zero <= Nativeint.rem x y < Nativeint.abs y] and
[x = Nativeint.add (Nativeint.mul (Nativeint.div x y) y)
(Nativeint.rem x y)].
If [y = 0], [Nativeint.rem x y] raises [Division_by_zero]. *)
val succ : nativeint -> nativeint
(** Successor.
[Nativeint.succ x] is [Nativeint.add x Nativeint.one]. *)
val pred : nativeint -> nativeint
* Predecessor .
[ Nativeint.pred x ] is [ Nativeint.sub x Nativeint.one ] .
[Nativeint.pred x] is [Nativeint.sub x Nativeint.one]. *)
val abs : nativeint -> nativeint
(** Return the absolute value of its argument. *)
val size : int
* The size in bits of a native integer . This is equal to [ 32 ]
on a 32 - bit platform and to [ 64 ] on a 64 - bit platform .
on a 32-bit platform and to [64] on a 64-bit platform. *)
val max_int : nativeint
* The greatest representable native integer ,
either 2{^31 } - 1 on a 32 - bit platform ,
or 2{^63 } - 1 on a 64 - bit platform .
either 2{^31} - 1 on a 32-bit platform,
or 2{^63} - 1 on a 64-bit platform. *)
val min_int : nativeint
* The greatest representable native integer ,
either -2{^31 } on a 32 - bit platform ,
or -2{^63 } on a 64 - bit platform .
either -2{^31} on a 32-bit platform,
or -2{^63} on a 64-bit platform. *)
external logand : nativeint -> nativeint -> nativeint = "%nativeint_and"
(** Bitwise logical and. *)
external logor : nativeint -> nativeint -> nativeint = "%nativeint_or"
(** Bitwise logical or. *)
external logxor : nativeint -> nativeint -> nativeint = "%nativeint_xor"
(** Bitwise logical exclusive or. *)
val lognot : nativeint -> nativeint
(** Bitwise logical negation *)
external shift_left : nativeint -> int -> nativeint = "%nativeint_lsl"
* [ Nativeint.shift_left x y ] shifts [ x ] to the left by [ y ] bits .
The result is unspecified if [ y < 0 ] or [ y > = bitsize ] ,
where [ bitsize ] is [ 32 ] on a 32 - bit platform and
[ 64 ] on a 64 - bit platform .
The result is unspecified if [y < 0] or [y >= bitsize],
where [bitsize] is [32] on a 32-bit platform and
[64] on a 64-bit platform. *)
external shift_right : nativeint -> int -> nativeint = "%nativeint_asr"
* [ Nativeint.shift_right x y ] shifts [ x ] to the right by [ y ] bits .
This is an arithmetic shift : the sign bit of [ x ] is replicated
and inserted in the vacated bits .
The result is unspecified if [ y < 0 ] or [ y > = bitsize ] .
This is an arithmetic shift: the sign bit of [x] is replicated
and inserted in the vacated bits.
The result is unspecified if [y < 0] or [y >= bitsize]. *)
external shift_right_logical :
nativeint -> int -> nativeint = "%nativeint_lsr"
* [ Nativeint.shift_right_logical x y ] shifts [ x ] to the right
by [ y ] bits .
This is a logical shift : zeroes are inserted in the vacated bits
regardless of the sign of [ x ] .
The result is unspecified if [ y < 0 ] or [ y > = bitsize ] .
by [y] bits.
This is a logical shift: zeroes are inserted in the vacated bits
regardless of the sign of [x].
The result is unspecified if [y < 0] or [y >= bitsize]. *)
external of_int : int -> nativeint = "%nativeint_of_int"
(** Convert the given integer (type [int]) to a native integer
(type [nativeint]). *)
external to_int : nativeint -> int = "%nativeint_to_int"
(** Convert the given native integer (type [nativeint]) to an
integer (type [int]). The high-order bit is lost during
the conversion. *)
external of_float : float -> nativeint = "caml_nativeint_of_float"
(** Convert the given floating-point number to a native integer,
discarding the fractional part (truncate towards 0).
The result of the conversion is undefined if, after truncation,
the number is outside the range
\[{!Nativeint.min_int}, {!Nativeint.max_int}\]. *)
external to_float : nativeint -> float = "caml_nativeint_to_float"
(** Convert the given native integer to a floating-point number. *)
external of_int32 : int32 -> nativeint = "%nativeint_of_int32"
* Convert the given 32 - bit integer ( type [ int32 ] )
to a native integer .
to a native integer. *)
external to_int32 : nativeint -> int32 = "%nativeint_to_int32"
* Convert the given native integer to a
32 - bit integer ( type [ int32 ] ) . On 64 - bit platforms ,
the 64 - bit native integer is taken modulo 2{^32 } ,
i.e. the top 32 bits are lost . On 32 - bit platforms ,
the conversion is exact .
32-bit integer (type [int32]). On 64-bit platforms,
the 64-bit native integer is taken modulo 2{^32},
i.e. the top 32 bits are lost. On 32-bit platforms,
the conversion is exact. *)
external of_string : string -> nativeint = "caml_nativeint_of_string"
* Convert the given string to a native integer .
The string is read in decimal ( by default ) or in hexadecimal ,
octal or binary if the string begins with [ 0x ] , [ 0o ] or [ 0b ]
respectively .
Raise [ Failure " int_of_string " ] if the given string is not
a valid representation of an integer , or if the integer represented
exceeds the range of integers representable in type [ nativeint ] .
The string is read in decimal (by default) or in hexadecimal,
octal or binary if the string begins with [0x], [0o] or [0b]
respectively.
Raise [Failure "int_of_string"] if the given string is not
a valid representation of an integer, or if the integer represented
exceeds the range of integers representable in type [nativeint]. *)
val to_string : nativeint -> string
(** Return the string representation of its argument, in decimal. *)
type t = nativeint
(** An alias for the type of native integers. *)
val compare: t -> t -> int
* The comparison function for native integers , with the same specification as
{ ! Pervasives.compare } . Along with the type [ t ] , this function [ compare ]
allows the module [ Nativeint ] to be passed as argument to the functors
{ ! Set . Make } and { ! Map . Make } .
{!Pervasives.compare}. Along with the type [t], this function [compare]
allows the module [Nativeint] to be passed as argument to the functors
{!Set.Make} and {!Map.Make}. *)
val equal: t -> t -> bool
* The equal function for natives ints .
@since 4.03.0
@since 4.03.0 *)
(**/**)
* { 6 Deprecated functions }
external format : string -> nativeint -> string = "caml_nativeint_format"
(** [Nativeint.format fmt n] return the string representation of the
native integer [n] in the format specified by [fmt].
[fmt] is a [Printf]-style format consisting of exactly
one [%d], [%i], [%u], [%x], [%X] or [%o] conversion specification.
This function is deprecated; use {!Printf.sprintf} with a [%nx] format
instead. *)
| null | https://raw.githubusercontent.com/ocamllabs/ocaml-effects/36008b741adc201bf9b547545344507da603ae31/stdlib/nativeint.mli | ocaml | *********************************************************************
OCaml
the special exception on linking described in file ../LICENSE.
*********************************************************************
* The native integer 0.
* The native integer -1.
* Unary negation.
* Addition.
* Subtraction.
* Multiplication.
* Successor.
[Nativeint.succ x] is [Nativeint.add x Nativeint.one].
* Return the absolute value of its argument.
* Bitwise logical and.
* Bitwise logical or.
* Bitwise logical exclusive or.
* Bitwise logical negation
* Convert the given integer (type [int]) to a native integer
(type [nativeint]).
* Convert the given native integer (type [nativeint]) to an
integer (type [int]). The high-order bit is lost during
the conversion.
* Convert the given floating-point number to a native integer,
discarding the fractional part (truncate towards 0).
The result of the conversion is undefined if, after truncation,
the number is outside the range
\[{!Nativeint.min_int}, {!Nativeint.max_int}\].
* Convert the given native integer to a floating-point number.
* Return the string representation of its argument, in decimal.
* An alias for the type of native integers.
*/*
* [Nativeint.format fmt n] return the string representation of the
native integer [n] in the format specified by [fmt].
[fmt] is a [Printf]-style format consisting of exactly
one [%d], [%i], [%u], [%x], [%X] or [%o] conversion specification.
This function is deprecated; use {!Printf.sprintf} with a [%nx] format
instead. | , projet Cristal , INRIA Rocquencourt
Copyright 1996 Institut National de Recherche en Informatique et
en Automatique . All rights reserved . This file is distributed
under the terms of the GNU Library General Public License , with
* Processor - native integers .
This module provides operations on the type [ nativeint ] of
signed 32 - bit integers ( on 32 - bit platforms ) or
signed 64 - bit integers ( on 64 - bit platforms ) .
This integer type has exactly the same width as that of a
pointer type in the C compiler . All arithmetic operations over
[ nativeint ] are taken modulo 2{^32 } or 2{^64 } depending
on the word size of the architecture .
Performance notice : values of type [ nativeint ] occupy more memory
space than values of type [ int ] , and arithmetic operations on
[ nativeint ] are generally slower than those on [ int ] . Use [ nativeint ]
only when the application requires the extra bit of precision
over the [ int ] type .
This module provides operations on the type [nativeint] of
signed 32-bit integers (on 32-bit platforms) or
signed 64-bit integers (on 64-bit platforms).
This integer type has exactly the same width as that of a
pointer type in the C compiler. All arithmetic operations over
[nativeint] are taken modulo 2{^32} or 2{^64} depending
on the word size of the architecture.
Performance notice: values of type [nativeint] occupy more memory
space than values of type [int], and arithmetic operations on
[nativeint] are generally slower than those on [int]. Use [nativeint]
only when the application requires the extra bit of precision
over the [int] type.
*)
val zero : nativeint
val one : nativeint
* The native integer 1 .
val minus_one : nativeint
external neg : nativeint -> nativeint = "%nativeint_neg"
external add : nativeint -> nativeint -> nativeint = "%nativeint_add"
external sub : nativeint -> nativeint -> nativeint = "%nativeint_sub"
external mul : nativeint -> nativeint -> nativeint = "%nativeint_mul"
external div : nativeint -> nativeint -> nativeint = "%nativeint_div"
* Integer division . Raise [ Division_by_zero ] if the second
argument is zero . This division rounds the real quotient of
its arguments towards zero , as specified for { ! Pervasives.(/ ) } .
argument is zero. This division rounds the real quotient of
its arguments towards zero, as specified for {!Pervasives.(/)}. *)
external rem : nativeint -> nativeint -> nativeint = "%nativeint_mod"
* Integer remainder . If [ y ] is not zero , the result
of [ x y ] satisfies the following properties :
[ Nativeint.zero < = x y < Nativeint.abs y ] and
[ x = Nativeint.add ( Nativeint.mul ( Nativeint.div x y ) y )
( x y ) ] .
If [ y = 0 ] , [ x y ] raises [ Division_by_zero ] .
of [Nativeint.rem x y] satisfies the following properties:
[Nativeint.zero <= Nativeint.rem x y < Nativeint.abs y] and
[x = Nativeint.add (Nativeint.mul (Nativeint.div x y) y)
(Nativeint.rem x y)].
If [y = 0], [Nativeint.rem x y] raises [Division_by_zero]. *)
val succ : nativeint -> nativeint
val pred : nativeint -> nativeint
* Predecessor .
[ Nativeint.pred x ] is [ Nativeint.sub x Nativeint.one ] .
[Nativeint.pred x] is [Nativeint.sub x Nativeint.one]. *)
val abs : nativeint -> nativeint
val size : int
* The size in bits of a native integer . This is equal to [ 32 ]
on a 32 - bit platform and to [ 64 ] on a 64 - bit platform .
on a 32-bit platform and to [64] on a 64-bit platform. *)
val max_int : nativeint
* The greatest representable native integer ,
either 2{^31 } - 1 on a 32 - bit platform ,
or 2{^63 } - 1 on a 64 - bit platform .
either 2{^31} - 1 on a 32-bit platform,
or 2{^63} - 1 on a 64-bit platform. *)
val min_int : nativeint
* The greatest representable native integer ,
either -2{^31 } on a 32 - bit platform ,
or -2{^63 } on a 64 - bit platform .
either -2{^31} on a 32-bit platform,
or -2{^63} on a 64-bit platform. *)
external logand : nativeint -> nativeint -> nativeint = "%nativeint_and"
external logor : nativeint -> nativeint -> nativeint = "%nativeint_or"
external logxor : nativeint -> nativeint -> nativeint = "%nativeint_xor"
val lognot : nativeint -> nativeint
external shift_left : nativeint -> int -> nativeint = "%nativeint_lsl"
* [ Nativeint.shift_left x y ] shifts [ x ] to the left by [ y ] bits .
The result is unspecified if [ y < 0 ] or [ y > = bitsize ] ,
where [ bitsize ] is [ 32 ] on a 32 - bit platform and
[ 64 ] on a 64 - bit platform .
The result is unspecified if [y < 0] or [y >= bitsize],
where [bitsize] is [32] on a 32-bit platform and
[64] on a 64-bit platform. *)
external shift_right : nativeint -> int -> nativeint = "%nativeint_asr"
* [ Nativeint.shift_right x y ] shifts [ x ] to the right by [ y ] bits .
This is an arithmetic shift : the sign bit of [ x ] is replicated
and inserted in the vacated bits .
The result is unspecified if [ y < 0 ] or [ y > = bitsize ] .
This is an arithmetic shift: the sign bit of [x] is replicated
and inserted in the vacated bits.
The result is unspecified if [y < 0] or [y >= bitsize]. *)
external shift_right_logical :
nativeint -> int -> nativeint = "%nativeint_lsr"
* [ Nativeint.shift_right_logical x y ] shifts [ x ] to the right
by [ y ] bits .
This is a logical shift : zeroes are inserted in the vacated bits
regardless of the sign of [ x ] .
The result is unspecified if [ y < 0 ] or [ y > = bitsize ] .
by [y] bits.
This is a logical shift: zeroes are inserted in the vacated bits
regardless of the sign of [x].
The result is unspecified if [y < 0] or [y >= bitsize]. *)
external of_int : int -> nativeint = "%nativeint_of_int"
external to_int : nativeint -> int = "%nativeint_to_int"
external of_float : float -> nativeint = "caml_nativeint_of_float"
external to_float : nativeint -> float = "caml_nativeint_to_float"
external of_int32 : int32 -> nativeint = "%nativeint_of_int32"
* Convert the given 32 - bit integer ( type [ int32 ] )
to a native integer .
to a native integer. *)
external to_int32 : nativeint -> int32 = "%nativeint_to_int32"
* Convert the given native integer to a
32 - bit integer ( type [ int32 ] ) . On 64 - bit platforms ,
the 64 - bit native integer is taken modulo 2{^32 } ,
i.e. the top 32 bits are lost . On 32 - bit platforms ,
the conversion is exact .
32-bit integer (type [int32]). On 64-bit platforms,
the 64-bit native integer is taken modulo 2{^32},
i.e. the top 32 bits are lost. On 32-bit platforms,
the conversion is exact. *)
external of_string : string -> nativeint = "caml_nativeint_of_string"
* Convert the given string to a native integer .
The string is read in decimal ( by default ) or in hexadecimal ,
octal or binary if the string begins with [ 0x ] , [ 0o ] or [ 0b ]
respectively .
Raise [ Failure " int_of_string " ] if the given string is not
a valid representation of an integer , or if the integer represented
exceeds the range of integers representable in type [ nativeint ] .
The string is read in decimal (by default) or in hexadecimal,
octal or binary if the string begins with [0x], [0o] or [0b]
respectively.
Raise [Failure "int_of_string"] if the given string is not
a valid representation of an integer, or if the integer represented
exceeds the range of integers representable in type [nativeint]. *)
val to_string : nativeint -> string
type t = nativeint
val compare: t -> t -> int
* The comparison function for native integers , with the same specification as
{ ! Pervasives.compare } . Along with the type [ t ] , this function [ compare ]
allows the module [ Nativeint ] to be passed as argument to the functors
{ ! Set . Make } and { ! Map . Make } .
{!Pervasives.compare}. Along with the type [t], this function [compare]
allows the module [Nativeint] to be passed as argument to the functors
{!Set.Make} and {!Map.Make}. *)
val equal: t -> t -> bool
* The equal function for natives ints .
@since 4.03.0
@since 4.03.0 *)
* { 6 Deprecated functions }
external format : string -> nativeint -> string = "caml_nativeint_format"
|
2640b9d5aae35975abf0fb05ed625a113acdb791fa2a44bc5eb6a975986c3f08 | tek/helic | LoadTest.hs | module Helic.Test.LoadTest where
import Polysemy.Chronos (ChronosTime, interpretTimeChronosConstant)
import Polysemy.Conc (interpretAtomic)
import Polysemy.Log (interpretLogNull)
import Polysemy.Test (UnitTest, assertEq, assertJust, runTestAuto)
import Helic.Data.AgentId (AgentId (AgentId))
import qualified Helic.Data.Event as Event
import Helic.Data.Event (Event)
import Helic.Data.InstanceName (InstanceName)
import Helic.Effect.Agent (AgentNet, AgentTmux, AgentX)
import qualified Helic.Effect.History as History
import Helic.Interpreter.Agent (interpretAgent)
import Helic.Interpreter.History (interpretHistory)
import Helic.Test.Fixtures (testTime)
event ::
Members [ChronosTime, Reader InstanceName] r =>
Int ->
Sem r Event
event n =
Event.now (AgentId "test") (show n)
test_load :: UnitTest
test_load =
runTestAuto $
interpretTimeChronosConstant testTime $
interpretLogNull $
runReader "test" $
interpretAtomic def $
interpretAgent @AgentNet (const unit) $
interpretAgent @AgentTmux (const unit) $
interpretAgent @AgentX (const unit) $
interpretHistory Nothing do
atomicPut =<< traverse event [1..10]
ev5 <- event 6
assertJust ev5 =<< History.load 4
assertEq Nothing =<< History.load 11
assertEq (show <$> ([1..5] ++ [7..10] ++ [6 :: Int])) . fmap Event.content =<< History.get
| null | https://raw.githubusercontent.com/tek/helic/317b7b1b356a9e2d3612e7a50f1facd02e7a9765/packages/helic/test/Helic/Test/LoadTest.hs | haskell | module Helic.Test.LoadTest where
import Polysemy.Chronos (ChronosTime, interpretTimeChronosConstant)
import Polysemy.Conc (interpretAtomic)
import Polysemy.Log (interpretLogNull)
import Polysemy.Test (UnitTest, assertEq, assertJust, runTestAuto)
import Helic.Data.AgentId (AgentId (AgentId))
import qualified Helic.Data.Event as Event
import Helic.Data.Event (Event)
import Helic.Data.InstanceName (InstanceName)
import Helic.Effect.Agent (AgentNet, AgentTmux, AgentX)
import qualified Helic.Effect.History as History
import Helic.Interpreter.Agent (interpretAgent)
import Helic.Interpreter.History (interpretHistory)
import Helic.Test.Fixtures (testTime)
event ::
Members [ChronosTime, Reader InstanceName] r =>
Int ->
Sem r Event
event n =
Event.now (AgentId "test") (show n)
test_load :: UnitTest
test_load =
runTestAuto $
interpretTimeChronosConstant testTime $
interpretLogNull $
runReader "test" $
interpretAtomic def $
interpretAgent @AgentNet (const unit) $
interpretAgent @AgentTmux (const unit) $
interpretAgent @AgentX (const unit) $
interpretHistory Nothing do
atomicPut =<< traverse event [1..10]
ev5 <- event 6
assertJust ev5 =<< History.load 4
assertEq Nothing =<< History.load 11
assertEq (show <$> ([1..5] ++ [7..10] ++ [6 :: Int])) . fmap Event.content =<< History.get
| |
903cfa48495db7a946953811ceb1908f7fc0239caa42dccf667b07fe3767bb85 | waldheinz/bling | Examples.hs |
module Examples (
imageFilters
) where
import Control.Monad ( forM_ )
import Graphics.Bling
imageFilters :: IO ()
imageFilters = do
let
flts =
[ ("box" , mkBoxFilter)
, ("gauss" , mkGaussFilter 3 3 2)
, ("mitchell", mkMitchellFilter 3 3 (1/3) (1/3))
, ("sinc" , mkSincFilter 3 3 3)
, ("triangle", mkTriangleFilter 3 3)
]
width = 480
height = 270
offs = [0, 0.2, 0.4, 0.6, 0.8]
fltTest = do
pixels <- fmap coverWindow sampleExtent'
forM_ [(px, sx, sy) | px <-pixels, sx <- offs, sy <- offs] $
\((px, py), sx, sy) -> do
let
(x, y) = (fromIntegral px + sx, fromIntegral py + sy) -- shift to center of pixel
sz = min (fromIntegral width) (fromIntegral height)
(dx, dy) = (x / sz - 0.5, 1 - y / sz)
d = abs (sin $ (150 * (dx * dx + dy * dy)))
addSample' x y $ rgbToSpectrumIllum (d, d, d)
showSize = 64
fltShow flt = do
pixels <- fmap coverWindow sampleExtent'
forM_ pixels $ \(px, py) -> do
let
(x, y) = (fromIntegral px, fromIntegral py)
(x', y') = ((x / fromIntegral showSize - 0.5) * 4, (y / fromIntegral showSize - 0.5) * 4)
d = evalFilter flt x' y'
c = if d > 0 then (d, 0, 0) else (0, -d, 0)
addSample' x y $ rgbToSpectrumIllum c
forM_ flts $ \(fname, flt) -> do
putStrLn fname
imgShow <- execImageT (fltShow flt) $ mkImage mkBoxFilter (showSize, showSize)
writePng imgShow $ "filter-show-" ++ fname ++ ".png"
imgTest <- execImageT fltTest $ mkImage flt (width, height)
writePng imgTest $ "filter-test-" ++ fname ++ ".png"
| null | https://raw.githubusercontent.com/waldheinz/bling/1f338f4b8dbd6a2708cb10787f4a2ac55f66d5a8/src/cmdline/Examples.hs | haskell | shift to center of pixel |
module Examples (
imageFilters
) where
import Control.Monad ( forM_ )
import Graphics.Bling
imageFilters :: IO ()
imageFilters = do
let
flts =
[ ("box" , mkBoxFilter)
, ("gauss" , mkGaussFilter 3 3 2)
, ("mitchell", mkMitchellFilter 3 3 (1/3) (1/3))
, ("sinc" , mkSincFilter 3 3 3)
, ("triangle", mkTriangleFilter 3 3)
]
width = 480
height = 270
offs = [0, 0.2, 0.4, 0.6, 0.8]
fltTest = do
pixels <- fmap coverWindow sampleExtent'
forM_ [(px, sx, sy) | px <-pixels, sx <- offs, sy <- offs] $
\((px, py), sx, sy) -> do
let
sz = min (fromIntegral width) (fromIntegral height)
(dx, dy) = (x / sz - 0.5, 1 - y / sz)
d = abs (sin $ (150 * (dx * dx + dy * dy)))
addSample' x y $ rgbToSpectrumIllum (d, d, d)
showSize = 64
fltShow flt = do
pixels <- fmap coverWindow sampleExtent'
forM_ pixels $ \(px, py) -> do
let
(x, y) = (fromIntegral px, fromIntegral py)
(x', y') = ((x / fromIntegral showSize - 0.5) * 4, (y / fromIntegral showSize - 0.5) * 4)
d = evalFilter flt x' y'
c = if d > 0 then (d, 0, 0) else (0, -d, 0)
addSample' x y $ rgbToSpectrumIllum c
forM_ flts $ \(fname, flt) -> do
putStrLn fname
imgShow <- execImageT (fltShow flt) $ mkImage mkBoxFilter (showSize, showSize)
writePng imgShow $ "filter-show-" ++ fname ++ ".png"
imgTest <- execImageT fltTest $ mkImage flt (width, height)
writePng imgTest $ "filter-test-" ++ fname ++ ".png"
|
4b000801c82206f74434add4d044c2f1fd0397058a784d19736cd0aa413c4c4d | Bogdanp/racket-http-easy | timeout.rkt | #lang racket/base
(require racket/contract)
(provide
timeout/c
make-timeout-config
timeout-config?
timeout-config-lease
timeout-config-connect
timeout-config-request)
(define timeout/c
(or/c false/c (and/c real? positive?)))
(struct timeout-config (lease connect request)
#:transparent)
(define/contract (make-timeout-config #:lease [lease 5]
#:connect [connect 5]
#:request [request 30])
(->* ()
(#:lease timeout/c
#:connect timeout/c
#:request timeout/c)
timeout-config?)
(timeout-config lease connect request))
| null | https://raw.githubusercontent.com/Bogdanp/racket-http-easy/630a982a282a51fd7fd85dc5e2f3f581c564b5e4/http-easy-lib/http-easy/private/timeout.rkt | racket | #lang racket/base
(require racket/contract)
(provide
timeout/c
make-timeout-config
timeout-config?
timeout-config-lease
timeout-config-connect
timeout-config-request)
(define timeout/c
(or/c false/c (and/c real? positive?)))
(struct timeout-config (lease connect request)
#:transparent)
(define/contract (make-timeout-config #:lease [lease 5]
#:connect [connect 5]
#:request [request 30])
(->* ()
(#:lease timeout/c
#:connect timeout/c
#:request timeout/c)
timeout-config?)
(timeout-config lease connect request))
| |
3de47a90b4634c078267dfc40f1a172b77b3ea9d87550d8a9fcbfc7da5d16647 | clingen-data-model/genegraph | omim_test.clj | (ns genegraph.transform.omim-test
(:require [clojure.test :refer :all]
[genegraph.database.util :refer [with-test-database]]
[genegraph.database.load :as l]
[genegraph.database.query :as q]
[genegraph.sink.stream :as s]
[genegraph.source.graphql.gene-dosage :as d]
[genegraph.transform.omim :as omim])
(:import [org.apache.kafka.clients.consumer ConsumerRecord]))
;; (def base-triples
;; [["" :rdf/type :owl/Class]
;; ["" :rdf/type (q/resource "")]
[ " " : rdfs / label " disease type 4B " ]
;; ["" :owl/equivalent-class (q/resource "")]
;; ])
(def gene-dosage-record
(ConsumerRecord. "gene_dosage_beta"
0
22125
1567164840234
org.apache.kafka.common.record.TimestampType/CREATE_TIME
3122576107
-1
2495
nil
"{
\"@context\" : {
\"id\" : \"@id\",
\"type\" : \"@type\",
\"SEPIO\" : \"\",
\"PMID\" : \"/\",
\"BFO\" : \"\",
\"CG\" : \"/\",
\"DC\" : \"/\",
\"OMIM\" : \"\",
\"MONDO\" : \"\",
\"FALDO\" : \"#\",
\"NCBI_NU\" : \"/\",
\"RDFS\" : \"-schema#\",
\"GENO\" : \"\",
\"IAO\" : \"\",
\"DCT\" : \"/\",
\"has_evidence_with_item\" : {
\"@id\" : \"SEPIO:0000189\",
\"@type\" : \"@id\"
},
\"has_predicate\" : {
\"@id\" : \"SEPIO:0000389\",
\"@type\" : \"@id\"
},
\"has_subject\" : {
\"@id\" : \"SEPIO:0000388\",
\"@type\" : \"@id\"
},
\"has_object\" : {
\"@id\" : \"SEPIO:0000390\",
\"@type\" : \"@id\"
},
\"qualified_contribution\" : {
\"@id\" : \"SEPIO:0000159\",
\"@type\" : \"@id\"
},
\"is_specified_by\" : {
\"@id\" : \"SEPIO:0000041\",
\"@type\" : \"@id\"
},
\"reference\" : {
\"@id\" : \"FALDO:reference\",
\"@type\" : \"@id\"
},
\"realizes\" : {
\"@id\" : \"BFO:0000055\",
\"@type\" : \"@id\"
},
\"source\" : {
\"@id\" : \"DCT:source\",
\"@type\" : \"@id\"
},
\"is_feature_affected_by\" : {
\"@id\" : \"GENO:0000445\",
\"@type\" : \"@id\"
},
\"label\" : \"RDFS:label\",
\"activity_date\" : \"SEPIO:0000160\",
\"has_count\" : \"GENO:0000917\",
\"start_position\" : \"GENO:0000894\",
\"end_position\" : \"GENO:0000895\",
\"description\" : \"DC:description\"
},
\"id\" : \"-2046x1-2011-11-17T20:07:39Z\",
\"qualified_contribution\" : {
\"activity_date\" : \"2011-11-17T20:07:39Z\",
\"realizes\" : \"SEPIO:0000331\"
},
\"has_subject\" : {
\"id\" : \"-2046x1\",
\"has_subject\" : {
\"is_feature_affected_by\" : \"\",
\"type\" : \"GENO:0000963\",
\"has_count\" : 1
},
\"has_predicate\" : \"GENO:0000840\",
\"type\" : \"SEPIO:0002003\",
\"has_object\" : \"MONDO:0000001\"
},
\"is_specified_by\" : \"SEPIO:0002004\",
\"has_predicate\" : \"SEPIO:0002505\",
\"has_object\" : \"SEPIO:0002502\",
\"type\" : \"SEPIO:0002014\"
}"))
(def genemap2-rows2
"#
#
#
#
syndrome , type 4b , , 613090 ( 3 ) , recessive ( MGI:1329026 ) " )
(def genemap2-rows
"#
#
#
#
chr1 16043781 16057325 1p36 1p36.13 602023 CLCNKB Chloride channel, kidney, B CLCNKB 1188 ENSG00000184908 unequal crossingover with CLCNKA Bartter syndrome, type 4b, digenic, 613090 (3), Digenic recessive Clcnka (MGI:1329026)")
| null | https://raw.githubusercontent.com/clingen-data-model/genegraph/8c217e4c3820b3bd0a0937a6e331a6e6a49b8c14/test/genegraph/transform/omim_test.clj | clojure | (def base-triples
[["" :rdf/type :owl/Class]
["" :rdf/type (q/resource "")]
["" :owl/equivalent-class (q/resource "")]
]) | (ns genegraph.transform.omim-test
(:require [clojure.test :refer :all]
[genegraph.database.util :refer [with-test-database]]
[genegraph.database.load :as l]
[genegraph.database.query :as q]
[genegraph.sink.stream :as s]
[genegraph.source.graphql.gene-dosage :as d]
[genegraph.transform.omim :as omim])
(:import [org.apache.kafka.clients.consumer ConsumerRecord]))
[ " " : rdfs / label " disease type 4B " ]
(def gene-dosage-record
(ConsumerRecord. "gene_dosage_beta"
0
22125
1567164840234
org.apache.kafka.common.record.TimestampType/CREATE_TIME
3122576107
-1
2495
nil
"{
\"@context\" : {
\"id\" : \"@id\",
\"type\" : \"@type\",
\"SEPIO\" : \"\",
\"PMID\" : \"/\",
\"BFO\" : \"\",
\"CG\" : \"/\",
\"DC\" : \"/\",
\"OMIM\" : \"\",
\"MONDO\" : \"\",
\"FALDO\" : \"#\",
\"NCBI_NU\" : \"/\",
\"RDFS\" : \"-schema#\",
\"GENO\" : \"\",
\"IAO\" : \"\",
\"DCT\" : \"/\",
\"has_evidence_with_item\" : {
\"@id\" : \"SEPIO:0000189\",
\"@type\" : \"@id\"
},
\"has_predicate\" : {
\"@id\" : \"SEPIO:0000389\",
\"@type\" : \"@id\"
},
\"has_subject\" : {
\"@id\" : \"SEPIO:0000388\",
\"@type\" : \"@id\"
},
\"has_object\" : {
\"@id\" : \"SEPIO:0000390\",
\"@type\" : \"@id\"
},
\"qualified_contribution\" : {
\"@id\" : \"SEPIO:0000159\",
\"@type\" : \"@id\"
},
\"is_specified_by\" : {
\"@id\" : \"SEPIO:0000041\",
\"@type\" : \"@id\"
},
\"reference\" : {
\"@id\" : \"FALDO:reference\",
\"@type\" : \"@id\"
},
\"realizes\" : {
\"@id\" : \"BFO:0000055\",
\"@type\" : \"@id\"
},
\"source\" : {
\"@id\" : \"DCT:source\",
\"@type\" : \"@id\"
},
\"is_feature_affected_by\" : {
\"@id\" : \"GENO:0000445\",
\"@type\" : \"@id\"
},
\"label\" : \"RDFS:label\",
\"activity_date\" : \"SEPIO:0000160\",
\"has_count\" : \"GENO:0000917\",
\"start_position\" : \"GENO:0000894\",
\"end_position\" : \"GENO:0000895\",
\"description\" : \"DC:description\"
},
\"id\" : \"-2046x1-2011-11-17T20:07:39Z\",
\"qualified_contribution\" : {
\"activity_date\" : \"2011-11-17T20:07:39Z\",
\"realizes\" : \"SEPIO:0000331\"
},
\"has_subject\" : {
\"id\" : \"-2046x1\",
\"has_subject\" : {
\"is_feature_affected_by\" : \"\",
\"type\" : \"GENO:0000963\",
\"has_count\" : 1
},
\"has_predicate\" : \"GENO:0000840\",
\"type\" : \"SEPIO:0002003\",
\"has_object\" : \"MONDO:0000001\"
},
\"is_specified_by\" : \"SEPIO:0002004\",
\"has_predicate\" : \"SEPIO:0002505\",
\"has_object\" : \"SEPIO:0002502\",
\"type\" : \"SEPIO:0002014\"
}"))
(def genemap2-rows2
"#
#
#
#
syndrome , type 4b , , 613090 ( 3 ) , recessive ( MGI:1329026 ) " )
(def genemap2-rows
"#
#
#
#
chr1 16043781 16057325 1p36 1p36.13 602023 CLCNKB Chloride channel, kidney, B CLCNKB 1188 ENSG00000184908 unequal crossingover with CLCNKA Bartter syndrome, type 4b, digenic, 613090 (3), Digenic recessive Clcnka (MGI:1329026)")
|
e4cb25675f6778397f4b059f39b90815e14af1b30e636991892661349706e332 | Yleisradio/http-kit-aws4 | aws_credentials.clj | (ns http-kit-aws4.aws-credentials
(:require [cheshire.core :as json]
[clojure.core.memoize :as memo]
[org.httpkit.client :as http-client]
[camel-snake-kebab.core :refer [->kebab-case-keyword]]))
(def ^:private aws-container-credentials-url
(when-let [relative-uri (System/getenv "AWS_CONTAINER_CREDENTIALS_RELATIVE_URI")]
(str "" relative-uri)))
(defn- get-aws-container-credentials [url]
(let [{:keys [status body error]} @(http-client/request
{:url url
:method :get
:timeout 1000})]
(cond (some? error) (throw error)
(not (<= 200 status 299)) (throw (ex-info (str "Expected status 2xx, got " status)
{:error error :body body}))
:else (json/parse-string body ->kebab-case-keyword))))
(def ^:private aws-environment-credentials
{:access-key-id (System/getenv "AWS_ACCESS_KEY_ID")
:secret-access-key (System/getenv "AWS_SECRET_ACCESS_KEY")
:token (System/getenv "AWS_SESSION_TOKEN")})
(defn- get-aws-credentials!
"Returns a map of AWS credentials provided by (in order of precedence)
- AWS ECS Agent, via AWS_CONTAINER_CREDENTIALS_RELATIVE_URI, when running in an ECS container
- environment variables AWS_ACCESS_KEY_ID etc"
[]
(if aws-container-credentials-url
(get-aws-container-credentials aws-container-credentials-url)
aws-environment-credentials))
(def get-aws-credentials
(memo/ttl get-aws-credentials! :ttl/threshold 60000))
| null | https://raw.githubusercontent.com/Yleisradio/http-kit-aws4/a2ef738fad8a5fbfdee40df0573aa5e2ff96e324/src/http_kit_aws4/aws_credentials.clj | clojure | (ns http-kit-aws4.aws-credentials
(:require [cheshire.core :as json]
[clojure.core.memoize :as memo]
[org.httpkit.client :as http-client]
[camel-snake-kebab.core :refer [->kebab-case-keyword]]))
(def ^:private aws-container-credentials-url
(when-let [relative-uri (System/getenv "AWS_CONTAINER_CREDENTIALS_RELATIVE_URI")]
(str "" relative-uri)))
(defn- get-aws-container-credentials [url]
(let [{:keys [status body error]} @(http-client/request
{:url url
:method :get
:timeout 1000})]
(cond (some? error) (throw error)
(not (<= 200 status 299)) (throw (ex-info (str "Expected status 2xx, got " status)
{:error error :body body}))
:else (json/parse-string body ->kebab-case-keyword))))
(def ^:private aws-environment-credentials
{:access-key-id (System/getenv "AWS_ACCESS_KEY_ID")
:secret-access-key (System/getenv "AWS_SECRET_ACCESS_KEY")
:token (System/getenv "AWS_SESSION_TOKEN")})
(defn- get-aws-credentials!
"Returns a map of AWS credentials provided by (in order of precedence)
- AWS ECS Agent, via AWS_CONTAINER_CREDENTIALS_RELATIVE_URI, when running in an ECS container
- environment variables AWS_ACCESS_KEY_ID etc"
[]
(if aws-container-credentials-url
(get-aws-container-credentials aws-container-credentials-url)
aws-environment-credentials))
(def get-aws-credentials
(memo/ttl get-aws-credentials! :ttl/threshold 60000))
| |
cf32c4ac5d965a6c3759b0fad9bf88c429dc4c678689a4d23df462f378675260 | g000001/tagger | variable-storage.lisp | -*- Package : VARIABLE - STORAGE ; Mode : Lisp ; Base : 10 -*-
Copyright ( c ) 1990 , 1991 by Xerox Corporation
;;; Resource facility for variable sized objects
#|(cl:defpackage :variable-storage
(:use :common-lisp :cons-resource)
(:use :tagger.internal)
(:export #:make-variable-storage #:clear-variable-storage
#:count-variable-storage #:print-variable-storage
#:alloc-item #:free-item
#:with-storage-balance))|#
(cl:in-package :variable-storage)
;;;BIT MANIPULATION FUNCTIONS
;;;fast integer length
(cltl1-eval-when (compile eval load)
(deftype fixnum-vector () `(simple-array fixnum (*)))
(defmacro fash (x y)
`(the fixnum (ash (the fixnum ,x) (the fixnum ,y))))
(defmacro f+ (x y)
`(the fixnum (+ (the fixnum ,x) (the fixnum ,y))))
(declaim (ftype (function (fixnum) fixnum) fast-integer-length))
(let ((length-table (make-array #X100 :element-type 'fixnum)))
(declare (type fixnum-vector length-table))
(dotimes (i #X100)
(declare (fixnum i))
(setf (aref length-table i) (integer-length i)))
(defun fast-integer-length (x)
(declare (fixnum x))
(let ((ans 0))
(declare (fixnum ans))
#-(or x86_64 x86-64)
(progn
(unless (zerop (fash x -16))
(setf ans 16
x (fash x -16)))
(unless (zerop (fash x -8))
(setf ans (f+ ans 8)
x (fash x -8)))
(f+ ans (aref length-table x)))
#+(or x86_64 x86-64)
(progn
(unless (zerop (fash x -32))
(setf ans 32
x (fash x -32)))
(unless (zerop (fash x -16))
(setf ans (f+ ans 16)
x (fash x -16)))
(unless (zerop (fash x -8))
(setf ans (f+ ans 8)
x (fash x -8)))
(f+ ans (aref length-table x)))))))
ash-1 is like ash , except it shift in ones rather than zeros if you shift
;;left.
(cltl1-eval-when (compile load eval)
(defmacro int (n)
`(the fixnum ,n))
(defmacro ash-1 (i count)
`(int (lognot (int (ash (lognot ,i) ,count)))))
(defconstant +significant-bits+ 1)
(defconstant +significant-bit-mask+
(ash-1 0 +significant-bits+))
(defconstant +significant-bit-shift+ (1+ +significant-bits+)))
plan is for hi - bits to be the < significant - bits > bits following the msb of
;;;the input number n. these form the low end of an index whose high end is
;;;the integer length of the number.
(cltl1-eval-when (compile eval load)
(defun size-bucket (n)
(declare (fixnum n))
(let* ((len (fast-integer-length n))
(hi-bits (logand (int (ash n (- +significant-bit-shift+ len)))
+significant-bit-mask+))
(index (logior (int (ash len +significant-bits+)) hi-bits)))
(declare (fixnum len hi-bits index))
;;; (format t "~&~4d: len ~d hi-bits ~d index ~d" n len hi-bits index)
index)))
the largest number which can end up in a bucket is one whose msb is the one
;;;defined by the length field (high order bits) of the bucket, and whose next
;;;lower bits are the ones specified in the low field of the bucket, and all of
;;;whose other bits are one.
(defun bucket-size (b)
(declare (fixnum b))
(let* ((hi-bits (logand b +significant-bit-mask+))
(len (ash b (- +significant-bits+)))
(num (int (ash-1 (logior hi-bits (int (ash 1 +significant-bits+)))
(- len +significant-bit-shift+)))))
(declare (fixnum hi-bits len num))
;; (format t "~&~4d: len ~d hi-bits ~d num ~d" b len hi-bits num)
num))
(defun round-bucket (size)
(declare (fixnum size))
(logior size
(ash-1 0 (the fixnum
(- (the fixnum (fast-integer-length size))
(the fixnum +significant-bit-shift+))))))
(defmacro fits-bucket-p (size)
`(= (the fixnum ,size) (the fixnum (round-bucket ,size))))
;;;STORAGE ALLOCATOR
(cltl1-eval-when (compile load eval)
(defconstant +largest-bucket+ (size-bucket most-positive-fixnum))
(defconstant +end-buckets+ (1+ +largest-bucket+)))
(defvar *all-buckets* nil)
(declaim (fixnum *storage-count*))
(defvar *storage-count* 0)
(defstruct (storage-bucket
(:conc-name sb-)
(:print-function print-storage-bucket))
name
(buckets (make-array +end-buckets+) :type (simple-array t *))
(out-size 0 :type fixnum)
(out-count 0 :type fixnum)
(cons-fn #'default-cons :type (function (fixnum &optional t) t)))
(defun print-storage-bucket (sb &optional (stream t) depth)
(declare (ignore depth))
(let* ((counts (map 'vector #'(lambda (x) (if (listp x) (length x) 0))
(sb-buckets sb)))
(in-count 0)
(in-size 0))
(declare (fixnum in-count in-size)
#|(type (vector fixnum *) counts)|#)
(dotimes (i +end-buckets+)
(declare (fixnum i))
(incf in-count (aref counts i))
(incf in-size (* (aref counts i) (bucket-size i))))
(format stream "~&#<Storage bucket ~A." (sb-name sb))
(format stream "~&Free: items ~d, size ~d. Used: items ~d, size ~d."
in-count in-size (sb-out-count sb) (sb-out-size sb))
(format stream "~&Bucket counts ~S>" counts)))
(defun default-cons (size &optional will-reclaim-p)
(declare (ignore will-reclaim-p))
(make-array size))
(defun make-variable-storage (cons-fn &optional name)
(let ((bucket (make-storage-bucket :name name :cons-fn cons-fn)))
(push bucket *all-buckets*)
bucket))
(defun clear-variable-storage (&optional sb)
(if sb
(let ((buckets (sb-buckets sb)))
(setf (sb-out-count sb) 0)
(setf (sb-out-size sb) 0)
(dotimes (i +end-buckets+)
(declare (fixnum i))
(setf (svref buckets i) nil)))
(progn
(setf *storage-count* 0)
(mapc #'clear-variable-storage *all-buckets*))))
(defun print-variable-storage (&optional (sb *all-buckets*))
(format t "Storage outstanding: ~D~&" *storage-count*)
(print sb)
nil)
ITEM ALLOCATOR
(defvar *hash-storage-p* nil)
(defvar *allocated-items* (make-hash-table :test #'eq))
BUG --- exact will get consed in static space and never reclaimed .
;;;SOLUTION: give cons-fn an optional argument consisting of whether requested
;;;object will be dropped on the floor.
(defun alloc-item (size sb &key (exact nil))
(declare (fixnum size))
(let ((result
(let ((rounded-size (round-bucket size)))
(declare (fixnum rounded-size))
(if (and exact (/= size rounded-size))
(progn
(incf *storage-count* size)
(funcall (sb-cons-fn sb) size nil)) ;signal won't reclaim
(let ((bucket (size-bucket size)))
(declare (fixnum bucket))
(incf *storage-count* rounded-size)
(incf (sb-out-count sb))
(incf (sb-out-size sb) rounded-size)
(or (%pop (svref (sb-buckets sb) bucket))
(funcall (sb-cons-fn sb) rounded-size)))))))
(when *hash-storage-p*
(setf (gethash result *allocated-items*) result))
result))
(defun free-item (item size sb)
(declare (fixnum size))
(decf *storage-count* size)
(when *hash-storage-p*
( assert ( gethash item * allocated - items * ) ( item )
;; "attempt to free non-allocated storage ~S" item)
(unless (gethash item *allocated-items*)
(error "attempt to free non-allocated storage ~S" item))
(remhash item *allocated-items*))
(when (= size (int (round-bucket size)))
(let ((bucket (size-bucket size)))
(declare (fixnum bucket))
(decf (sb-out-count sb))
(decf (sb-out-size sb) size)
(%push item (svref (sb-buckets sb) bucket)))))
#-nodebug
(defmacro with-storage-balance (&body body)
(let ((start-storage (gensym "STORAGE")))
`(let ((,start-storage *storage-count*))
(declare (fixnum ,start-storage))
(prog1 (progn ,@body)
(assert (= ,start-storage (the fixnum *storage-count*)) ()
"unbalanced storage allocation")))))
#+nodebug
(defmacro with-storage-balance (&body body)
`(progn ,@body))
| null | https://raw.githubusercontent.com/g000001/tagger/a4e0650c55aba44250871b96e2220e1b4953c6ab/util/variable-storage.lisp | lisp | Mode : Lisp ; Base : 10 -*-
Resource facility for variable sized objects
(cl:defpackage :variable-storage
(:use :common-lisp :cons-resource)
(:use :tagger.internal)
(:export #:make-variable-storage #:clear-variable-storage
#:count-variable-storage #:print-variable-storage
#:alloc-item #:free-item
#:with-storage-balance))
BIT MANIPULATION FUNCTIONS
fast integer length
left.
the input number n. these form the low end of an index whose high end is
the integer length of the number.
(format t "~&~4d: len ~d hi-bits ~d index ~d" n len hi-bits index)
defined by the length field (high order bits) of the bucket, and whose next
lower bits are the ones specified in the low field of the bucket, and all of
whose other bits are one.
(format t "~&~4d: len ~d hi-bits ~d num ~d" b len hi-bits num)
STORAGE ALLOCATOR
(type (vector fixnum *) counts)
SOLUTION: give cons-fn an optional argument consisting of whether requested
object will be dropped on the floor.
signal won't reclaim
"attempt to free non-allocated storage ~S" item) |
Copyright ( c ) 1990 , 1991 by Xerox Corporation
(cl:in-package :variable-storage)
(cltl1-eval-when (compile eval load)
(deftype fixnum-vector () `(simple-array fixnum (*)))
(defmacro fash (x y)
`(the fixnum (ash (the fixnum ,x) (the fixnum ,y))))
(defmacro f+ (x y)
`(the fixnum (+ (the fixnum ,x) (the fixnum ,y))))
(declaim (ftype (function (fixnum) fixnum) fast-integer-length))
(let ((length-table (make-array #X100 :element-type 'fixnum)))
(declare (type fixnum-vector length-table))
(dotimes (i #X100)
(declare (fixnum i))
(setf (aref length-table i) (integer-length i)))
(defun fast-integer-length (x)
(declare (fixnum x))
(let ((ans 0))
(declare (fixnum ans))
#-(or x86_64 x86-64)
(progn
(unless (zerop (fash x -16))
(setf ans 16
x (fash x -16)))
(unless (zerop (fash x -8))
(setf ans (f+ ans 8)
x (fash x -8)))
(f+ ans (aref length-table x)))
#+(or x86_64 x86-64)
(progn
(unless (zerop (fash x -32))
(setf ans 32
x (fash x -32)))
(unless (zerop (fash x -16))
(setf ans (f+ ans 16)
x (fash x -16)))
(unless (zerop (fash x -8))
(setf ans (f+ ans 8)
x (fash x -8)))
(f+ ans (aref length-table x)))))))
ash-1 is like ash , except it shift in ones rather than zeros if you shift
(cltl1-eval-when (compile load eval)
(defmacro int (n)
`(the fixnum ,n))
(defmacro ash-1 (i count)
`(int (lognot (int (ash (lognot ,i) ,count)))))
(defconstant +significant-bits+ 1)
(defconstant +significant-bit-mask+
(ash-1 0 +significant-bits+))
(defconstant +significant-bit-shift+ (1+ +significant-bits+)))
plan is for hi - bits to be the < significant - bits > bits following the msb of
(cltl1-eval-when (compile eval load)
(defun size-bucket (n)
(declare (fixnum n))
(let* ((len (fast-integer-length n))
(hi-bits (logand (int (ash n (- +significant-bit-shift+ len)))
+significant-bit-mask+))
(index (logior (int (ash len +significant-bits+)) hi-bits)))
(declare (fixnum len hi-bits index))
index)))
the largest number which can end up in a bucket is one whose msb is the one
(defun bucket-size (b)
(declare (fixnum b))
(let* ((hi-bits (logand b +significant-bit-mask+))
(len (ash b (- +significant-bits+)))
(num (int (ash-1 (logior hi-bits (int (ash 1 +significant-bits+)))
(- len +significant-bit-shift+)))))
(declare (fixnum hi-bits len num))
num))
(defun round-bucket (size)
(declare (fixnum size))
(logior size
(ash-1 0 (the fixnum
(- (the fixnum (fast-integer-length size))
(the fixnum +significant-bit-shift+))))))
(defmacro fits-bucket-p (size)
`(= (the fixnum ,size) (the fixnum (round-bucket ,size))))
(cltl1-eval-when (compile load eval)
(defconstant +largest-bucket+ (size-bucket most-positive-fixnum))
(defconstant +end-buckets+ (1+ +largest-bucket+)))
(defvar *all-buckets* nil)
(declaim (fixnum *storage-count*))
(defvar *storage-count* 0)
(defstruct (storage-bucket
(:conc-name sb-)
(:print-function print-storage-bucket))
name
(buckets (make-array +end-buckets+) :type (simple-array t *))
(out-size 0 :type fixnum)
(out-count 0 :type fixnum)
(cons-fn #'default-cons :type (function (fixnum &optional t) t)))
(defun print-storage-bucket (sb &optional (stream t) depth)
(declare (ignore depth))
(let* ((counts (map 'vector #'(lambda (x) (if (listp x) (length x) 0))
(sb-buckets sb)))
(in-count 0)
(in-size 0))
(declare (fixnum in-count in-size)
(dotimes (i +end-buckets+)
(declare (fixnum i))
(incf in-count (aref counts i))
(incf in-size (* (aref counts i) (bucket-size i))))
(format stream "~&#<Storage bucket ~A." (sb-name sb))
(format stream "~&Free: items ~d, size ~d. Used: items ~d, size ~d."
in-count in-size (sb-out-count sb) (sb-out-size sb))
(format stream "~&Bucket counts ~S>" counts)))
(defun default-cons (size &optional will-reclaim-p)
(declare (ignore will-reclaim-p))
(make-array size))
(defun make-variable-storage (cons-fn &optional name)
(let ((bucket (make-storage-bucket :name name :cons-fn cons-fn)))
(push bucket *all-buckets*)
bucket))
(defun clear-variable-storage (&optional sb)
(if sb
(let ((buckets (sb-buckets sb)))
(setf (sb-out-count sb) 0)
(setf (sb-out-size sb) 0)
(dotimes (i +end-buckets+)
(declare (fixnum i))
(setf (svref buckets i) nil)))
(progn
(setf *storage-count* 0)
(mapc #'clear-variable-storage *all-buckets*))))
(defun print-variable-storage (&optional (sb *all-buckets*))
(format t "Storage outstanding: ~D~&" *storage-count*)
(print sb)
nil)
ITEM ALLOCATOR
(defvar *hash-storage-p* nil)
(defvar *allocated-items* (make-hash-table :test #'eq))
BUG --- exact will get consed in static space and never reclaimed .
(defun alloc-item (size sb &key (exact nil))
(declare (fixnum size))
(let ((result
(let ((rounded-size (round-bucket size)))
(declare (fixnum rounded-size))
(if (and exact (/= size rounded-size))
(progn
(incf *storage-count* size)
(let ((bucket (size-bucket size)))
(declare (fixnum bucket))
(incf *storage-count* rounded-size)
(incf (sb-out-count sb))
(incf (sb-out-size sb) rounded-size)
(or (%pop (svref (sb-buckets sb) bucket))
(funcall (sb-cons-fn sb) rounded-size)))))))
(when *hash-storage-p*
(setf (gethash result *allocated-items*) result))
result))
(defun free-item (item size sb)
(declare (fixnum size))
(decf *storage-count* size)
(when *hash-storage-p*
( assert ( gethash item * allocated - items * ) ( item )
(unless (gethash item *allocated-items*)
(error "attempt to free non-allocated storage ~S" item))
(remhash item *allocated-items*))
(when (= size (int (round-bucket size)))
(let ((bucket (size-bucket size)))
(declare (fixnum bucket))
(decf (sb-out-count sb))
(decf (sb-out-size sb) size)
(%push item (svref (sb-buckets sb) bucket)))))
#-nodebug
(defmacro with-storage-balance (&body body)
(let ((start-storage (gensym "STORAGE")))
`(let ((,start-storage *storage-count*))
(declare (fixnum ,start-storage))
(prog1 (progn ,@body)
(assert (= ,start-storage (the fixnum *storage-count*)) ()
"unbalanced storage allocation")))))
#+nodebug
(defmacro with-storage-balance (&body body)
`(progn ,@body))
|
1f7af6a9aa7ef89f76e46d1c1967461c0215cd992a962a8c8090ca02b2f0c971 | ryanpbrewster/haskell | P018.hs | module Problems.P018
( process
) where
- 018.hs
- Project Euler problem 18
- There is a triangle located in 018.in
- Find the path from the top of the triangle to the bottom
- which has the largest sum
- 018.hs
- Project Euler problem 18
- There is a triangle located in 018.in
- Find the path from the top of the triangle to the bottom
- which has the largest sum
-}
type FileContents = String
process :: FileContents -> String
process txt = show $ problem018 txt
bestRow takes in two rows , the first one shorter than the second
It returns the second row , modified by adding the maximum of the
two numbers above
--
Example : [ 3 1 4 ]
-- [1 5 9 2]
-- yields:
-- [4 8 13 6]
-- Since:
The 1 inherits 3 , yielding 4
The 5 inherits max(3,1 ) , yielding 8
The 9 inherits max(1,4 ) yielding 13
The 2 inherits 4 , yielding 6
bestRow :: [Integer] -> [Integer] -> [Integer]
bestRow a b = zipWith3 bestAdd b (0 : a) (a ++ [0])
where
bestAdd x y z = x + max y z
-- maxPath takes in the whole triangle and returns the best path
-- It does this by propogating down the best choice you can make
-- at each row, using bestRow
maxPath :: [[Integer]] -> Integer
maxPath (fr:sr:rest) = maxPath $ bestRow fr sr : rest
maxPath tri = maximum $ head tri
problem018 :: FileContents -> Integer
problem018 txt = maxPath [map read (words line) | line <- lines txt]
| null | https://raw.githubusercontent.com/ryanpbrewster/haskell/6edd0afe234008a48b4871032dedfd143ca6e412/project-euler/src/Problems/P018.hs | haskell |
[1 5 9 2]
yields:
[4 8 13 6]
Since:
maxPath takes in the whole triangle and returns the best path
It does this by propogating down the best choice you can make
at each row, using bestRow | module Problems.P018
( process
) where
- 018.hs
- Project Euler problem 18
- There is a triangle located in 018.in
- Find the path from the top of the triangle to the bottom
- which has the largest sum
- 018.hs
- Project Euler problem 18
- There is a triangle located in 018.in
- Find the path from the top of the triangle to the bottom
- which has the largest sum
-}
type FileContents = String
process :: FileContents -> String
process txt = show $ problem018 txt
bestRow takes in two rows , the first one shorter than the second
It returns the second row , modified by adding the maximum of the
two numbers above
Example : [ 3 1 4 ]
The 1 inherits 3 , yielding 4
The 5 inherits max(3,1 ) , yielding 8
The 9 inherits max(1,4 ) yielding 13
The 2 inherits 4 , yielding 6
bestRow :: [Integer] -> [Integer] -> [Integer]
bestRow a b = zipWith3 bestAdd b (0 : a) (a ++ [0])
where
bestAdd x y z = x + max y z
maxPath :: [[Integer]] -> Integer
maxPath (fr:sr:rest) = maxPath $ bestRow fr sr : rest
maxPath tri = maximum $ head tri
problem018 :: FileContents -> Integer
problem018 txt = maxPath [map read (words line) | line <- lines txt]
|
30e992b133d3ec525c14ac3bbb03e002860d1e4ede5e05e60f605d60a0da9987 | slagyr/gaeshi | generate.clj | (ns gaeshi.kuzushi.commands.generate
(:use
[joodo.kuzushi.common :only (symbolize)]
[joodo.kuzushi.generation :only (create-templater add-tokens ->path ->name)]
[joodo.kuzushi.commands.help :only (usage-for)]
[joodo.kuzushi.commands.generate :as joodo :only (generate-controller)])
(:import
[filecabinet FileSystem Templater]
[mmargs Arguments]))
(def arg-spec joodo/arg-spec)
(defn parse-args [& args] (apply joodo/parse-args args))
(defn execute
"Generates files for various components at the specified namespace:
controller - new controller and spec file"
[options]
(println "options: " options)
(let [templater (create-templater options)
generator (.toLowerCase (:generator options))]
(cond
(= "controller" generator) (generate-controller templater options)
:else (usage-for "generate" [(str "Unknown generator: " generator)]))))
| null | https://raw.githubusercontent.com/slagyr/gaeshi/a5677ed1c8d9269d412f07a7ab33bbc40aa7011a/lein-gaeshi/src/gaeshi/kuzushi/commands/generate.clj | clojure | (ns gaeshi.kuzushi.commands.generate
(:use
[joodo.kuzushi.common :only (symbolize)]
[joodo.kuzushi.generation :only (create-templater add-tokens ->path ->name)]
[joodo.kuzushi.commands.help :only (usage-for)]
[joodo.kuzushi.commands.generate :as joodo :only (generate-controller)])
(:import
[filecabinet FileSystem Templater]
[mmargs Arguments]))
(def arg-spec joodo/arg-spec)
(defn parse-args [& args] (apply joodo/parse-args args))
(defn execute
"Generates files for various components at the specified namespace:
controller - new controller and spec file"
[options]
(println "options: " options)
(let [templater (create-templater options)
generator (.toLowerCase (:generator options))]
(cond
(= "controller" generator) (generate-controller templater options)
:else (usage-for "generate" [(str "Unknown generator: " generator)]))))
| |
aebebbfe9b29cb1312143d79cc54d2a5a689dd2c09c2ff7c6e8fe562d0bc6b60 | jadahl/mod_restful | tests.erl | %%%----------------------------------------------------------------------
File : mod_restful.erl
Author : < >
%%% Purpose : Tests for mod_restful
Created : 28 Nov 2010 by < >
%%%
%%%
Copyright ( C ) 2010
%%%
%%% This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License as
published by the Free Software Foundation ; either version 2 of the
%%% License, or (at your option) any later version.
%%%
%%% This program is distributed in the hope that it will be useful,
%%% but WITHOUT ANY WARRANTY; without even the implied warranty of
%%% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
%%% General Public License for more details.
%%%
You should have received a copy of the GNU General Public License
%%% along with this program; if not, write to the Free Software
Foundation , Inc. , 59 Temple Place , Suite 330 , Boston , MA
02111 - 1307 USA
%%%
%%%----------------------------------------------------------------------
-module(tests).
-include_lib("eunit/include/eunit.hrl").
-define(TESTS, [
mod_restful_tests,
mod_restful_admin_tests,
mod_restful_register_tests
]).
all_test() ->
lists:foreach(fun(Test) -> eunit:test(Test, [verbose]) end, ?TESTS).
| null | https://raw.githubusercontent.com/jadahl/mod_restful/3a4995e0facd29879a6c2949547177a1ac618474/tests/tests.erl | erlang | ----------------------------------------------------------------------
Purpose : Tests for mod_restful
This program is free software; you can redistribute it and/or
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
General Public License for more details.
along with this program; if not, write to the Free Software
---------------------------------------------------------------------- | File : mod_restful.erl
Author : < >
Created : 28 Nov 2010 by < >
Copyright ( C ) 2010
modify it under the terms of the GNU General Public License as
published by the Free Software Foundation ; either version 2 of the
You should have received a copy of the GNU General Public License
Foundation , Inc. , 59 Temple Place , Suite 330 , Boston , MA
02111 - 1307 USA
-module(tests).
-include_lib("eunit/include/eunit.hrl").
-define(TESTS, [
mod_restful_tests,
mod_restful_admin_tests,
mod_restful_register_tests
]).
all_test() ->
lists:foreach(fun(Test) -> eunit:test(Test, [verbose]) end, ?TESTS).
|
283bde9b6811608c3478bd7242fd0ee5bcf9bac009ccd3671706f914d30e8ac9 | TrustInSoft/tis-kernel | unroll_loops.ml | (**************************************************************************)
(* *)
This file is part of .
(* *)
is a fork of Frama - C. All the differences are :
Copyright ( C ) 2016 - 2017
(* *)
is released under GPLv2
(* *)
(**************************************************************************)
(**************************************************************************)
(* *)
This file is part of Frama - C.
(* *)
Copyright ( C ) 2007 - 2015
CEA ( Commissariat à l'énergie atomique et aux énergies
(* alternatives) *)
(* *)
(* you can redistribute it and/or modify it under the terms of the GNU *)
Lesser General Public License as published by the Free Software
Foundation , version 2.1 .
(* *)
(* It is distributed in the hope that it will be useful, *)
(* but WITHOUT ANY WARRANTY; without even the implied warranty of *)
(* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *)
(* GNU Lesser General Public License for more details. *)
(* *)
See the GNU Lesser General Public License version 2.1
for more details ( enclosed in the file licenses / LGPLv2.1 ) .
(* *)
(**************************************************************************)
* Syntactic loop unrolling .
open Cil_types
open Cil
open Visitor
let dkey = Kernel.register_category "ulevel"
let rec fold_itv f b e acc =
if Integer.equal b e then f acc b
else fold_itv f (Integer.succ b) e (f acc b)
(* Find the initializer for index [i] in [init] *)
let find_init_by_index init i =
let same_offset (off, _) = match off with
| Index (i', NoOffset) ->
Integer.equal i (Extlib.the (Cil.isInteger i'))
| _ -> false
in
snd (List.find same_offset init)
(* Find the initializer for field [f] in [init] *)
let find_init_by_field init f =
let same_offset (off, _) = match off with
| Field (f', NoOffset) -> f == f'
| _ -> false
in
snd (List.find same_offset init)
exception CannotSimplify
(* Evaluate the bounds of the range [b..e] as constants. The array being
indexed has type [typ]. If [b] or [e] are not specified, use default
values. *)
let const_fold_trange_bounds typ b e =
let extract = function None -> raise CannotSimplify | Some i -> i in
let b = match b with
| Some tb -> extract (Logic_utils.constFoldTermToInt tb)
| None -> Integer.zero
in
let e = match e with
| Some te -> extract (Logic_utils.constFoldTermToInt te)
| None ->
match Cil.unrollType typ with
| TArray (_, Some size, _, _) ->
Integer.pred (extract (Cil.isInteger size))
| _ -> raise CannotSimplify
in
b, e
* Find the value corresponding to the logic offset [ loff ] inside the
initialiser [ init ] . Zero is used as a default value when the initialiser is
incomplete . [ loff ] must have an integral type . Returns a set of values
when [ loff ] contains ranges .
initialiser [init]. Zero is used as a default value when the initialiser is
incomplete. [loff] must have an integral type. Returns a set of values
when [loff] contains ranges. *)
let find_initial_value init loff =
let module S = Datatype.Integer.Set in
let extract = function None -> raise CannotSimplify | Some i -> i in
let rec aux loff init =
match loff, init with
| TNoOffset, SingleInit e -> S.singleton (extract (Cil.constFoldToInt e))
| TIndex (i, loff), CompoundInit (typ, l) -> begin
(* Add the initializer at offset [Index(i, loff)] to [acc]. *)
let add_index acc i =
let vi =
try aux loff (find_init_by_index l i)
with Not_found -> S.singleton Integer.zero
in
S.union acc vi
in
match i.term_node with
| Tunion tl ->
let conv t = extract (Logic_utils.constFoldTermToInt t) in
List.fold_left add_index S.empty (List.map conv tl)
| Trange (b, e) ->
let b, e = const_fold_trange_bounds typ b e in
fold_itv add_index b e S.empty
| _ ->
let i = extract (Logic_utils.constFoldTermToInt i) in
add_index S.empty i
end
| TField (f, loff), CompoundInit (_, l) ->
if f.fcomp.cstruct then
try aux loff (find_init_by_field l f)
with Not_found -> S.singleton Integer.zero
else (* too complex, a value might be written through another field *)
raise CannotSimplify
| TNoOffset, CompoundInit _
| (TIndex _ | TField _), SingleInit _ -> assert false
| TModel _, _ -> raise CannotSimplify
in
try
match init with
| None -> Some (S.singleton Integer.zero)
| Some init -> Some (aux loff init)
with CannotSimplify -> None
(** Evaluate the given term l-value in the initial state *)
let eval_term_lval (lhost, loff) =
match lhost with
| TVar lvi -> begin
(** See if we can evaluate the l-value using the initializer of lvi*)
let off_type = Cil.typeTermOffset lvi.lv_type loff in
if Logic_const.plain_or_set Cil.isLogicIntegralType off_type then
match lvi.lv_origin with
| Some vi when vi.vglob && Cil.typeHasQualifier "const" vi.vtype ->
find_initial_value (Globals.Vars.find vi).init loff
| _ -> None
else None
end
| _ -> None
class simplify_const_lval = object (self)
inherit Visitor.frama_c_copy (Project.current ())
method! vterm t =
match t.term_node with
| TLval tlv -> begin
(* simplify recursively tlv before attempting evaluation *)
let tlv = Visitor.visitFramacTermLval (self :> frama_c_visitor) tlv in
match eval_term_lval tlv with
| None -> Cil.SkipChildren
| Some itvs ->
(* Replace the value/set of values found by something that has the
expected logic type (plain/Set) *)
let typ = Logic_const.plain_or_set Extlib.id t.term_type in
let aux i l = Logic_const.term (TConst (Integer (i,None))) typ :: l in
let l = Datatype.Integer.Set.fold aux itvs [] in
match l, Logic_const.is_plain_type t.term_type with
| [i], true -> Cil.ChangeTo i
| _, false -> Cil.ChangeTo (Logic_const.term (Tunion l) t.term_type)
| _ -> Cil.SkipChildren
end
| _ -> Cil.DoChildren
end
type loop_pragmas_info =
{ unroll_number: int option;
total_unroll: Emitter.t option;
ignore_unroll: bool }
let empty_info =
{ unroll_number = None; total_unroll = None; ignore_unroll = false }
let update_info emitter info spec =
match spec with
| { term_type = typ; _ } when Logic_typing.is_integral_type typ ->
if Extlib.has_some info.unroll_number && not info.ignore_unroll then begin
Kernel.warning ~once:true ~current:true
"ignoring unrolling directive (directive already defined)";
info
end else begin
try
begin
let t = Visitor.visitFramacTerm (new simplify_const_lval) spec in
let i = Logic_utils.constFoldTermToInt t in
match i with
| Some i -> { info with unroll_number = Some (Integer.to_int i) }
| None ->
Kernel.warning ~once:true ~current:true
"ignoring unrolling directive (not an understood constant \
expression)";
info
end
with Invalid_argument s ->
Kernel.warning ~once:true ~current:true
"ignoring unrolling directive (%s)" s;
info
end
| { term_node = TConst LStr "done"; _ } -> { info with ignore_unroll = true }
| { term_node = TConst LStr "completely"; _ } ->
if Extlib.has_some info.total_unroll then begin
Kernel.warning ~once:true ~current:true
"found two total unroll pragmas";
info
end else { info with total_unroll = Some emitter }
| _ ->
Kernel.warning ~once:true ~current:true
"ignoring invalid unrolling directive";
info
let extract_from_pragmas s =
let filter _ a = Logic_utils.is_loop_pragma a in
let pragmas = Annotations.code_annot_emitter ~filter s in
let get_infos info (a,e) =
match a.annot_content with
| APragma (Loop_pragma (Unroll_specs specs)) ->
List.fold_left (update_info e) info specs
| APragma (Loop_pragma _) -> info
| _ -> assert false (* should have been filtered above. *)
in
List.fold_left get_infos empty_info pragmas
let fresh_label =
let counter = ref (-1) in
fun ?loc ?label_name () ->
decr counter;
let loc, orig = match loc with
| None -> CurrentLoc.get (), false
| Some loc -> loc, true
and new_label_name =
let prefix = match label_name with None -> "" | Some s -> s ^ "_"
in Format.sprintf "%sunrolling_%d_loop" prefix (- !counter)
in Label (new_label_name,
loc,
orig)
let copy_var =
let counter = ref (-1) in
(* [VP] I fail too see the purpose of this argument instead of changing
the counter at each variable's copy: copy_var () is called once per
copy of block with local variables, bearing no relationship with the
number of unrolling. counter could thus be an arbitrary integer as well.
*)
fun () ->
decr counter;
fun vi ->
let vi' = Cil_const.copy_with_new_vid vi in
let name = vi.vname ^ "_unroll_" ^ (string_of_int (- !counter)) in
Cil_const.change_varinfo_name vi' name;
vi'
let refresh_vars old_var new_var =
let assoc = List.combine old_var new_var in
let visit = object
inherit Visitor.frama_c_inplace
method! vvrbl vi =
try ChangeTo (snd (List.find (fun (x,_) -> x.vid = vi.vid) assoc))
with Not_found -> SkipChildren
end
in
fun b -> ignore (Visitor.visitFramacBlock visit b)
(* Takes care of local gotos and labels into C. *)
let update_gotos sid_tbl block =
let goto_updater =
object
inherit nopCilVisitor
method! vstmt s = match s.skind with
| Goto(sref,_loc) ->
(try (* A deep copy has already be done. Just modifies the reference in place. *)
let new_stmt = Cil_datatype.Stmt.Map.find !sref sid_tbl in
sref := new_stmt
with Not_found -> ()) ;
DoChildren
| _ -> DoChildren
(* speed up: skip non interesting subtrees *)
method! vvdec _ = SkipChildren (* via visitCilFunction *)
method! vspec _ = SkipChildren (* via visitCilFunction *)
via Code_annot stmt
via stmt such as Return , IF , ...
via stmt such as Set , Call , Asm , ...
via Asm stmt
end
in visitCilBlock (goto_updater:>cilVisitor) block
let is_referenced stmt l =
let module Found = struct exception Found end in
let vis = object
inherit Visitor.frama_c_inplace
method! vlogic_label l =
match l with
| StmtLabel s when !s == stmt -> raise Found.Found
| _ -> DoChildren
end
in
try
List.iter (fun x -> ignore (Visitor.visitFramacStmt vis x)) l;
false
with Found.Found -> true
(* Deep copy of annotations taking care of labels into annotations. *)
let copy_annotations kf assoc labelled_stmt_tbl (break_continue_must_change, stmt_src,stmt_dst) =
let fresh_annotation a =
let visitor = object
inherit Visitor.frama_c_copy (Project.current())
method! vlogic_var_use vi =
match vi.lv_origin with
None -> SkipChildren
| Some vi ->
begin
try
let vi'= snd (List.find (fun (x,_) -> x.vid = vi.vid) assoc) in
ChangeTo (Extlib.the vi'.vlogic_var_assoc)
with Not_found -> SkipChildren
| Invalid_argument _ ->
Kernel.abort
"Loop unrolling: cannot find new representative for \
local var %a"
Printer.pp_varinfo vi
end
method! vlogic_label (label:logic_label) =
match label with
| StmtLabel (stmt) ->
(try (* A deep copy has already been done.
Just modifies the reference in place. *)
let new_stmt = Cil_datatype.Stmt.Map.find !stmt labelled_stmt_tbl
in ChangeTo (StmtLabel (ref new_stmt))
with Not_found -> SkipChildren) ;
| LogicLabel (None, _str) -> SkipChildren
| LogicLabel (Some _stmt, str) -> ChangeTo (LogicLabel (None, str))
end
in visitCilCodeAnnotation (visitor:>cilVisitor) (Logic_const.refresh_code_annotation a)
in
let filter_annotation a = (* Special cases for some "breaks" and "continues" clauses. *)
(* Note: it would be preferable to do that job in the visitor of 'fresh_annotation'... *)
Kernel.debug ~dkey
"Copying an annotation to stmt %d from stmt %d@."
stmt_dst.sid stmt_src.sid;
TODO : transforms ' breaks ' and ' continues ' clauses into unimplemented
' ' clause ( still undefined clause into ACSL ! ) .
'gotos' clause (still undefined clause into ACSL!). *)
WORKS AROUND : since ' breaks ' and ' continues ' clauses have not be preserved
into the unrolled stmts , and are not yet transformed into ' ' ( see . TODO ) ,
they are not copied .
into the unrolled stmts, and are not yet transformed into 'gotos' (see. TODO),
they are not copied. *)
match break_continue_must_change, a with
| (None, None), _ -> Some a (* 'breaks' and 'continues' can be kept *)
| _, { annot_content = AStmtSpec (s,spec); _ } ->
let filter_post_cond = function
| Breaks, _ when (fst break_continue_must_change) != None ->
Kernel.debug ~dkey "Uncopied 'breaks' clause to stmt %d@." stmt_dst.sid;
false
| Continues, _ when (snd break_continue_must_change) != None ->
Kernel.debug ~dkey "Uncopied 'continues' clause to stmt %d@." stmt_dst.sid;
false
| _ -> true in
let filter_behavior acc bhv =
let bhv = { bhv with b_post_cond = List.filter filter_post_cond bhv.b_post_cond } in
(* The default behavior cannot be removed if another behavior remains... *)
if (Cil.is_empty_behavior bhv) && not (Cil.is_default_behavior bhv) then acc
else bhv::acc
in
let filter_behaviors bhvs =
(*... so the default behavior is removed there if it is alone. *)
match List.fold_left filter_behavior [] bhvs with
| [bhv] when Cil.is_empty_behavior bhv -> []
| bhvs -> List.rev bhvs
in
let spec = { spec with spec_behavior = filter_behaviors spec.spec_behavior } in
if Cil.is_empty_funspec spec then None (* No statement contract will be added *)
else Some { a with annot_content=AStmtSpec (s,spec) }
| _, _ -> Some a
in
let new_annots =
Annotations.fold_code_annot
(fun emitter annot acc ->
match filter_annotation annot with
| None -> acc
| Some filtred_annot -> (emitter, fresh_annotation filtred_annot) :: acc)
stmt_src
[]
in
List.iter
(fun (e, a) -> Annotations.add_code_annot e ~kf stmt_dst a)
new_annots
let update_loop_current kf loop_current block =
let vis = object(self)
inherit Visitor.frama_c_inplace
initializer self#set_current_kf kf
method! vlogic_label =
function
| LogicLabel(_,"LoopCurrent") -> ChangeTo (StmtLabel (ref loop_current))
| _ -> DoChildren
method! vstmt_aux s =
match s.skind with
| Loop _ -> SkipChildren (* loop init and current are not the same here. *)
| _ -> DoChildren
end in
ignore (Visitor.visitFramacBlock vis block)
let update_loop_entry kf loop_entry stmt =
let vis = object(self)
inherit Visitor.frama_c_inplace
initializer self#set_current_kf kf
method! vlogic_label =
function
| LogicLabel(_,"LoopEntry") -> ChangeTo (StmtLabel (ref loop_entry))
| _ -> DoChildren
method! vstmt_aux s =
match s.skind with
| Loop _ -> SkipChildren (* loop init and current are not the same here. *)
| _ -> DoChildren
end in
ignore (Visitor.visitFramacStmt vis stmt)
(* Deep copy of a block taking care of local gotos and labels into C code and
annotations. *)
let copy_block kf break_continue_must_change bl =
let assoc = ref [] in
let fundec =
try Kernel_function.get_definition kf
with Kernel_function.No_Definition -> assert false
and annotated_stmts = ref [] (* for copying the annotations later. *)
and labelled_stmt_tbl = Cil_datatype.Stmt.Map.empty
and calls_tbl = Cil_datatype.Stmt.Map.empty
in
let rec copy_stmt
break_continue_must_change labelled_stmt_tbl calls_tbl stmt =
let result =
{ labels = [];
sid = Sid.next ();
succs = [];
preds = [];
skind = stmt.skind;
ghost = stmt.ghost}
in
let new_labels,labelled_stmt_tbl =
if stmt.labels = [] then
[], labelled_stmt_tbl
else
let new_tbl = Cil_datatype.Stmt.Map.add stmt result labelled_stmt_tbl
and new_labels =
List.fold_left
(fun lbls -> function
| Label (s, loc, gen) ->
(if gen
then fresh_label ~label_name:s ()
else fresh_label ~label_name:s ~loc ()
) :: lbls
| Case _ | Default _ as lbl -> lbl :: lbls
)
[]
stmt.labels
in new_labels, new_tbl
in
let new_calls_tbl = match stmt.skind with
| Instr(Call _) -> Cil_datatype.Stmt.Map.add stmt result calls_tbl
| _ -> calls_tbl
in
let new_stmkind,new_labelled_stmt_tbl, new_calls_tbl =
copy_stmtkind
break_continue_must_change labelled_stmt_tbl new_calls_tbl stmt.skind
in
if stmt.labels <> [] then result.labels <- new_labels;
result.skind <- new_stmkind;
if Annotations.has_code_annot stmt then
begin
Kernel.debug ~dkey
"Found an annotation to copy for stmt %d from stmt %d@."
result.sid stmt.sid;
annotated_stmts := (break_continue_must_change, stmt,result) :: !annotated_stmts;
end;
result, new_labelled_stmt_tbl, new_calls_tbl
and copy_stmtkind
break_continue_must_change labelled_stmt_tbl calls_tbl stkind =
match stkind with
| (Instr _ | Return _ | Throw _) as keep ->
keep,labelled_stmt_tbl,calls_tbl
| Goto (stmt_ref, loc) -> Goto (ref !stmt_ref, loc),labelled_stmt_tbl,calls_tbl
| If (exp,bl1,bl2,loc) ->
CurrentLoc.set loc;
let new_block1,labelled_stmt_tbl,calls_tbl =
copy_block break_continue_must_change labelled_stmt_tbl calls_tbl bl1
in
let new_block2,labelled_stmt_tbl,calls_tbl =
copy_block break_continue_must_change labelled_stmt_tbl calls_tbl bl2
in
If(exp,new_block1,new_block2,loc),labelled_stmt_tbl,calls_tbl
| Loop (a,bl,loc,_,_) ->
CurrentLoc.set loc;
let new_block,labelled_stmt_tbl,calls_tbl =
copy_block
(None, None) (* from now on break and continue can be kept *)
labelled_stmt_tbl
calls_tbl
bl
in
Loop (a,new_block,loc,None,None),labelled_stmt_tbl,calls_tbl
| Block bl ->
let new_block,labelled_stmt_tbl,calls_tbl =
copy_block break_continue_must_change labelled_stmt_tbl calls_tbl bl
in
Block (new_block),labelled_stmt_tbl,calls_tbl
| UnspecifiedSequence seq ->
let change_calls lst calls_tbl =
List.map
(fun x -> ref (Cil_datatype.Stmt.Map.find !x calls_tbl)) lst
in
let new_seq,labelled_stmt_tbl,calls_tbl =
List.fold_left
(fun (seq,labelled_stmt_tbl,calls_tbl) (stmt,modified,writes,reads,calls) ->
let stmt,labelled_stmt_tbl,calls_tbl =
copy_stmt
break_continue_must_change labelled_stmt_tbl calls_tbl stmt
in
(stmt,modified,writes,reads,change_calls calls calls_tbl)::seq,
labelled_stmt_tbl,calls_tbl)
([],labelled_stmt_tbl,calls_tbl)
seq
in
UnspecifiedSequence (List.rev new_seq),labelled_stmt_tbl,calls_tbl
| Break loc ->
(match break_continue_must_change with
| None, _ -> stkind (* kept *)
| (Some (brk_lbl_stmt)), _ -> Goto ((ref brk_lbl_stmt),loc)),
labelled_stmt_tbl,
calls_tbl
| Continue loc ->
(match break_continue_must_change with
| _,None -> stkind (* kept *)
| _,(Some (continue_lbl_stmt)) ->
Goto ((ref continue_lbl_stmt),loc)),
labelled_stmt_tbl,
calls_tbl
| Switch (e,block,stmts,loc) ->
(* from now on break only can be kept *)
let new_block,new_labelled_stmt_tbl,calls_tbl =
copy_block (None, (snd break_continue_must_change)) labelled_stmt_tbl calls_tbl block
in
let stmts' =
List.map
(fun s -> Cil_datatype.Stmt.Map.find s new_labelled_stmt_tbl) stmts
in
Switch(e,new_block,stmts',loc),new_labelled_stmt_tbl,calls_tbl
| TryCatch(t,c,loc) ->
let t', labs, calls =
copy_block break_continue_must_change labelled_stmt_tbl calls_tbl t
in
let treat_one_extra_binding mv mv' (bindings, labs, calls) (v,b) =
let v' = copy_var () v in
assoc := (v,v')::!assoc;
let b', labs', calls' =
copy_block break_continue_must_change labs calls b
in
refresh_vars [mv; v] [mv'; v'] b';
(v',b')::bindings, labs', calls'
in
let treat_one_catch (catches, labs, calls) (v,b) =
let v', vorig, vnew, labs', calls' =
match v with
| Catch_all -> Catch_all, [], [], labs, calls
| Catch_exn(v,l) ->
let v' = copy_var () v in
assoc:=(v,v')::!assoc;
let l', labs', calls' =
List.fold_left
(treat_one_extra_binding v v') ([],labs, calls) l
in
Catch_exn(v', List.rev l'), [v], [v'], labs', calls'
in
let (b', labs', calls') =
copy_block break_continue_must_change labs' calls' b
in
refresh_vars vorig vnew b';
(v', b')::catches, labs', calls'
in
let c', labs', calls' =
List.fold_left treat_one_catch ([],labs, calls) c
in
TryCatch(t',List.rev c',loc), labs', calls'
| TryFinally _ | TryExcept _ -> assert false
and copy_block break_continue_must_change labelled_stmt_tbl calls_tbl bl =
let new_stmts,labelled_stmt_tbl,calls_tbl =
List.fold_left
(fun (block_l,labelled_stmt_tbl,calls_tbl) v ->
let new_block,labelled_stmt_tbl,calls_tbl =
copy_stmt break_continue_must_change labelled_stmt_tbl calls_tbl v
in
new_block::block_l, labelled_stmt_tbl,calls_tbl)
([],labelled_stmt_tbl,calls_tbl)
bl.bstmts
in
let new_locals =
List.map (copy_var ()) bl.blocals
in
fundec.slocals <- fundec.slocals @ new_locals;
assoc:=(List.combine bl.blocals new_locals) @ !assoc;
let new_block = mkBlock (List.rev new_stmts) in
refresh_vars bl.blocals new_locals new_block;
new_block.blocals <- new_locals;
new_block,labelled_stmt_tbl,calls_tbl
in
let new_block, labelled_stmt_tbl, _calls_tbl =
(* [calls_tbl] is internal. No need to fix references afterwards here. *)
copy_block break_continue_must_change labelled_stmt_tbl calls_tbl bl
in
List.iter (copy_annotations kf !assoc labelled_stmt_tbl) !annotated_stmts ;
update_gotos labelled_stmt_tbl new_block
let ast_has_changed = ref false
(* Update to take into account annotations*)
class do_it ((force:bool),(times:int)) = object(self)
inherit Visitor.frama_c_inplace
initializer ast_has_changed := false;
We sometimes need to move labels between statements . This table
maps the old statement to the new one
maps the old statement to the new one *)
val moved_labels = Cil_datatype.Stmt.Hashtbl.create 17
val mutable gotos = [] ;
val mutable has_unrolled_loop = false ;
val mutable file_has_unrolled_loop = false ;
method get_file_has_unrolled_loop () = file_has_unrolled_loop ;
method! vfunc fundec =
assert (gotos = []) ;
assert (not has_unrolled_loop) ;
let post_goto_updater =
(fun id ->
if has_unrolled_loop then begin
List.iter
(fun s -> match s.skind with Goto(sref,_loc) ->
(try
let new_stmt =
Cil_datatype.Stmt.Hashtbl.find moved_labels !sref
in
sref := new_stmt
with Not_found -> ())
| _ -> assert false)
gotos;
File.must_recompute_cfg id;
ast_has_changed:=true
end;
has_unrolled_loop <- false ;
gotos <- [] ;
Cil_datatype.Stmt.Hashtbl.clear moved_labels ;
id) in
ChangeDoChildrenPost (fundec, post_goto_updater)
method! vstmt_aux s = match s.skind with
| Goto _ ->
gotos <- s::gotos; (* gotos that may need to be updated *)
DoChildren
| Switch _ -> (* Update the labels pointed to by the switch if needed *)
let update s =
if has_unrolled_loop then
(match s.skind with
| Switch (e', b', lbls', loc') ->
let labels_moved = ref false in
let update_label s =
try
let s = Cil_datatype.Stmt.Hashtbl.find moved_labels s
in labels_moved := true ; s
with Not_found -> s
in let moved_lbls = List.map update_label lbls' in
if !labels_moved then
s.skind <- Switch (e', b', moved_lbls, loc');
| _ -> ());
s
in
ChangeDoChildrenPost (s, update)
| Loop _ ->
let infos = extract_from_pragmas s in
let number = Extlib.opt_conv times infos.unroll_number in
let total_unrolling = infos.total_unroll in
let is_ignored_unrolling = not force && infos.ignore_unroll in
let f sloop =
Kernel.debug ~dkey
"Unrolling loop stmt %d (%d times) inside function %a@."
sloop.sid number Kernel_function.pretty (Extlib.the self#current_kf);
file_has_unrolled_loop <- true ;
has_unrolled_loop <- true ;
match sloop.skind with
| Loop(_,block,loc,_,_) ->
(* Note: loop annotations are kept into the remaining loops,
but are not transformed into statement contracts inside the
unrolled parts. *)
(* Note: a goto from outside a loop to inside that loop will still
goes into the remaining loop. *)
(* TODO: transforms loop annotations into statement contracts
inside the unrolled parts. *)
CurrentLoc.set loc;
let break_lbl_stmt =
let break_label = fresh_label () in
let break_lbl_stmt = mkEmptyStmt () in
break_lbl_stmt.labels <- [break_label];
break_lbl_stmt.sid <- Cil.Sid.next ();
break_lbl_stmt
in
let mk_continue () =
let continue_label = fresh_label () in
let continue_lbl_stmt = mkEmptyStmt () in
continue_lbl_stmt.labels <- [continue_label] ;
continue_lbl_stmt.sid <- Cil.Sid.next ();
continue_lbl_stmt
in
let current_continue = ref (mk_continue ()) in
let new_stmts = ref [sloop] in
for _i=0 to number-1 do
new_stmts:=!current_continue::!new_stmts;
let new_block =
copy_block
(Extlib.the self#current_kf)
((Some break_lbl_stmt),(Some !current_continue))
block
in
current_continue := mk_continue ();
update_loop_current (Extlib.the self#current_kf) !current_continue new_block;
(match new_block.blocals with
[] -> new_stmts:= new_block.bstmts @ !new_stmts;
| _ -> (* keep the block in order to preserve locals decl *)
new_stmts:= mkStmt (Block new_block) :: !new_stmts);
done;
let new_stmt = match !new_stmts with
| [ s ] -> s
| l ->
List.iter (update_loop_entry (Extlib.the self#current_kf) !current_continue) l;
let l = if is_referenced !current_continue l then !current_continue :: l else l in
let new_stmts = l @ [break_lbl_stmt] in
let new_block = mkBlock new_stmts in
let snew = mkStmt (Block new_block) in
(* Move the labels in front of the original loop at the top of the
new code *)
Cil_datatype.Stmt.Hashtbl.add moved_labels sloop snew;
snew.labels <- sloop.labels;
sloop.labels <- [];
snew;
in new_stmt
| _ -> assert false
in
let g sloop new_stmts = (* Adds "loop invariant \false;" to the remaining
loop when "completely" unrolled. *)
(* Note: since a goto from outside the loop to inside the loop
still goes into the remaining loop...*)
match total_unrolling with
| None -> new_stmts
| Some emitter ->
let annot =
Logic_const.new_code_annotation
(AInvariant ([],true,Logic_const.pfalse))
in
Annotations.add_code_annot
emitter ~kf:(Extlib.the self#current_kf) sloop annot;
new_stmts
in
let h sloop new_stmts = (* To indicate that the unrolling has been done *)
let specs = Unroll_specs [(Logic_const.term (TConst (LStr "done"))
(Ctype Cil.charPtrType)) ;
Logic_const.tinteger number
] in
let annot =
Logic_const.new_code_annotation (APragma (Loop_pragma specs))
in
Annotations.add_code_annot
Emitter.end_user ~kf:(Extlib.the self#current_kf) sloop annot;
new_stmts
in
let fgh sloop = h sloop (g sloop (f sloop)) in
let fgh =
if (number > 0) && not is_ignored_unrolling then fgh else (fun s -> s)
in
ChangeDoChildrenPost (s, fgh)
| _ -> DoChildren
end
(* Performs unrolling transformation without using -ulevel option.
Do not forget to apply [transformations_closure] afterwards. *)
let apply_transformation ?(force=true) nb file =
(* [nb] default number of unrolling used when there is no UNROLL loop pragma.
When [nb] is negative, no unrolling is done; all UNROLL loop pragmas
are ignored. *)
if nb >= 0 then
let visitor = new do_it (force, nb) in
Kernel.debug ~dkey "Using -ulevel %d option and UNROLL loop pragmas@." nb;
visitFramacFileSameGlobals (visitor:>Visitor.frama_c_visitor) file;
if !ast_has_changed then Ast.mark_as_changed ()
else begin
Kernel.debug ~dkey
"No unrolling is done; all UNROLL loop pragmas are ignored@."
end
(* Performs and closes all syntactic transformations *)
let compute file =
let nb = Kernel.UnrollingLevel.get () in
let force = Kernel.UnrollingForce.get () in
apply_transformation ~force nb file
let unroll_transform =
File.register_code_transformation_category "loop unrolling"
let () =
File.add_code_transformation_after_cleanup
~deps:[(module Kernel.UnrollingLevel:Parameter_sig.S);
(module Kernel.UnrollingForce:Parameter_sig.S)]
unroll_transform compute
(*
Local Variables:
compile-command: "make -C ../../.."
End:
*)
| null | https://raw.githubusercontent.com/TrustInSoft/tis-kernel/748d28baba90c03c0f5f4654d2e7bb47dfbe4e7d/src/kernel_internals/typing/unroll_loops.ml | ocaml | ************************************************************************
************************************************************************
************************************************************************
alternatives)
you can redistribute it and/or modify it under the terms of the GNU
It is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
************************************************************************
Find the initializer for index [i] in [init]
Find the initializer for field [f] in [init]
Evaluate the bounds of the range [b..e] as constants. The array being
indexed has type [typ]. If [b] or [e] are not specified, use default
values.
Add the initializer at offset [Index(i, loff)] to [acc].
too complex, a value might be written through another field
* Evaluate the given term l-value in the initial state
* See if we can evaluate the l-value using the initializer of lvi
simplify recursively tlv before attempting evaluation
Replace the value/set of values found by something that has the
expected logic type (plain/Set)
should have been filtered above.
[VP] I fail too see the purpose of this argument instead of changing
the counter at each variable's copy: copy_var () is called once per
copy of block with local variables, bearing no relationship with the
number of unrolling. counter could thus be an arbitrary integer as well.
Takes care of local gotos and labels into C.
A deep copy has already be done. Just modifies the reference in place.
speed up: skip non interesting subtrees
via visitCilFunction
via visitCilFunction
Deep copy of annotations taking care of labels into annotations.
A deep copy has already been done.
Just modifies the reference in place.
Special cases for some "breaks" and "continues" clauses.
Note: it would be preferable to do that job in the visitor of 'fresh_annotation'...
'breaks' and 'continues' can be kept
The default behavior cannot be removed if another behavior remains...
... so the default behavior is removed there if it is alone.
No statement contract will be added
loop init and current are not the same here.
loop init and current are not the same here.
Deep copy of a block taking care of local gotos and labels into C code and
annotations.
for copying the annotations later.
from now on break and continue can be kept
kept
kept
from now on break only can be kept
[calls_tbl] is internal. No need to fix references afterwards here.
Update to take into account annotations
gotos that may need to be updated
Update the labels pointed to by the switch if needed
Note: loop annotations are kept into the remaining loops,
but are not transformed into statement contracts inside the
unrolled parts.
Note: a goto from outside a loop to inside that loop will still
goes into the remaining loop.
TODO: transforms loop annotations into statement contracts
inside the unrolled parts.
keep the block in order to preserve locals decl
Move the labels in front of the original loop at the top of the
new code
Adds "loop invariant \false;" to the remaining
loop when "completely" unrolled.
Note: since a goto from outside the loop to inside the loop
still goes into the remaining loop...
To indicate that the unrolling has been done
Performs unrolling transformation without using -ulevel option.
Do not forget to apply [transformations_closure] afterwards.
[nb] default number of unrolling used when there is no UNROLL loop pragma.
When [nb] is negative, no unrolling is done; all UNROLL loop pragmas
are ignored.
Performs and closes all syntactic transformations
Local Variables:
compile-command: "make -C ../../.."
End:
| This file is part of .
is a fork of Frama - C. All the differences are :
Copyright ( C ) 2016 - 2017
is released under GPLv2
This file is part of Frama - C.
Copyright ( C ) 2007 - 2015
CEA ( Commissariat à l'énergie atomique et aux énergies
Lesser General Public License as published by the Free Software
Foundation , version 2.1 .
See the GNU Lesser General Public License version 2.1
for more details ( enclosed in the file licenses / LGPLv2.1 ) .
* Syntactic loop unrolling .
open Cil_types
open Cil
open Visitor
let dkey = Kernel.register_category "ulevel"
let rec fold_itv f b e acc =
if Integer.equal b e then f acc b
else fold_itv f (Integer.succ b) e (f acc b)
let find_init_by_index init i =
let same_offset (off, _) = match off with
| Index (i', NoOffset) ->
Integer.equal i (Extlib.the (Cil.isInteger i'))
| _ -> false
in
snd (List.find same_offset init)
let find_init_by_field init f =
let same_offset (off, _) = match off with
| Field (f', NoOffset) -> f == f'
| _ -> false
in
snd (List.find same_offset init)
exception CannotSimplify
let const_fold_trange_bounds typ b e =
let extract = function None -> raise CannotSimplify | Some i -> i in
let b = match b with
| Some tb -> extract (Logic_utils.constFoldTermToInt tb)
| None -> Integer.zero
in
let e = match e with
| Some te -> extract (Logic_utils.constFoldTermToInt te)
| None ->
match Cil.unrollType typ with
| TArray (_, Some size, _, _) ->
Integer.pred (extract (Cil.isInteger size))
| _ -> raise CannotSimplify
in
b, e
* Find the value corresponding to the logic offset [ loff ] inside the
initialiser [ init ] . Zero is used as a default value when the initialiser is
incomplete . [ loff ] must have an integral type . Returns a set of values
when [ loff ] contains ranges .
initialiser [init]. Zero is used as a default value when the initialiser is
incomplete. [loff] must have an integral type. Returns a set of values
when [loff] contains ranges. *)
let find_initial_value init loff =
let module S = Datatype.Integer.Set in
let extract = function None -> raise CannotSimplify | Some i -> i in
let rec aux loff init =
match loff, init with
| TNoOffset, SingleInit e -> S.singleton (extract (Cil.constFoldToInt e))
| TIndex (i, loff), CompoundInit (typ, l) -> begin
let add_index acc i =
let vi =
try aux loff (find_init_by_index l i)
with Not_found -> S.singleton Integer.zero
in
S.union acc vi
in
match i.term_node with
| Tunion tl ->
let conv t = extract (Logic_utils.constFoldTermToInt t) in
List.fold_left add_index S.empty (List.map conv tl)
| Trange (b, e) ->
let b, e = const_fold_trange_bounds typ b e in
fold_itv add_index b e S.empty
| _ ->
let i = extract (Logic_utils.constFoldTermToInt i) in
add_index S.empty i
end
| TField (f, loff), CompoundInit (_, l) ->
if f.fcomp.cstruct then
try aux loff (find_init_by_field l f)
with Not_found -> S.singleton Integer.zero
raise CannotSimplify
| TNoOffset, CompoundInit _
| (TIndex _ | TField _), SingleInit _ -> assert false
| TModel _, _ -> raise CannotSimplify
in
try
match init with
| None -> Some (S.singleton Integer.zero)
| Some init -> Some (aux loff init)
with CannotSimplify -> None
let eval_term_lval (lhost, loff) =
match lhost with
| TVar lvi -> begin
let off_type = Cil.typeTermOffset lvi.lv_type loff in
if Logic_const.plain_or_set Cil.isLogicIntegralType off_type then
match lvi.lv_origin with
| Some vi when vi.vglob && Cil.typeHasQualifier "const" vi.vtype ->
find_initial_value (Globals.Vars.find vi).init loff
| _ -> None
else None
end
| _ -> None
class simplify_const_lval = object (self)
inherit Visitor.frama_c_copy (Project.current ())
method! vterm t =
match t.term_node with
| TLval tlv -> begin
let tlv = Visitor.visitFramacTermLval (self :> frama_c_visitor) tlv in
match eval_term_lval tlv with
| None -> Cil.SkipChildren
| Some itvs ->
let typ = Logic_const.plain_or_set Extlib.id t.term_type in
let aux i l = Logic_const.term (TConst (Integer (i,None))) typ :: l in
let l = Datatype.Integer.Set.fold aux itvs [] in
match l, Logic_const.is_plain_type t.term_type with
| [i], true -> Cil.ChangeTo i
| _, false -> Cil.ChangeTo (Logic_const.term (Tunion l) t.term_type)
| _ -> Cil.SkipChildren
end
| _ -> Cil.DoChildren
end
type loop_pragmas_info =
{ unroll_number: int option;
total_unroll: Emitter.t option;
ignore_unroll: bool }
let empty_info =
{ unroll_number = None; total_unroll = None; ignore_unroll = false }
let update_info emitter info spec =
match spec with
| { term_type = typ; _ } when Logic_typing.is_integral_type typ ->
if Extlib.has_some info.unroll_number && not info.ignore_unroll then begin
Kernel.warning ~once:true ~current:true
"ignoring unrolling directive (directive already defined)";
info
end else begin
try
begin
let t = Visitor.visitFramacTerm (new simplify_const_lval) spec in
let i = Logic_utils.constFoldTermToInt t in
match i with
| Some i -> { info with unroll_number = Some (Integer.to_int i) }
| None ->
Kernel.warning ~once:true ~current:true
"ignoring unrolling directive (not an understood constant \
expression)";
info
end
with Invalid_argument s ->
Kernel.warning ~once:true ~current:true
"ignoring unrolling directive (%s)" s;
info
end
| { term_node = TConst LStr "done"; _ } -> { info with ignore_unroll = true }
| { term_node = TConst LStr "completely"; _ } ->
if Extlib.has_some info.total_unroll then begin
Kernel.warning ~once:true ~current:true
"found two total unroll pragmas";
info
end else { info with total_unroll = Some emitter }
| _ ->
Kernel.warning ~once:true ~current:true
"ignoring invalid unrolling directive";
info
let extract_from_pragmas s =
let filter _ a = Logic_utils.is_loop_pragma a in
let pragmas = Annotations.code_annot_emitter ~filter s in
let get_infos info (a,e) =
match a.annot_content with
| APragma (Loop_pragma (Unroll_specs specs)) ->
List.fold_left (update_info e) info specs
| APragma (Loop_pragma _) -> info
in
List.fold_left get_infos empty_info pragmas
let fresh_label =
let counter = ref (-1) in
fun ?loc ?label_name () ->
decr counter;
let loc, orig = match loc with
| None -> CurrentLoc.get (), false
| Some loc -> loc, true
and new_label_name =
let prefix = match label_name with None -> "" | Some s -> s ^ "_"
in Format.sprintf "%sunrolling_%d_loop" prefix (- !counter)
in Label (new_label_name,
loc,
orig)
let copy_var =
let counter = ref (-1) in
fun () ->
decr counter;
fun vi ->
let vi' = Cil_const.copy_with_new_vid vi in
let name = vi.vname ^ "_unroll_" ^ (string_of_int (- !counter)) in
Cil_const.change_varinfo_name vi' name;
vi'
let refresh_vars old_var new_var =
let assoc = List.combine old_var new_var in
let visit = object
inherit Visitor.frama_c_inplace
method! vvrbl vi =
try ChangeTo (snd (List.find (fun (x,_) -> x.vid = vi.vid) assoc))
with Not_found -> SkipChildren
end
in
fun b -> ignore (Visitor.visitFramacBlock visit b)
let update_gotos sid_tbl block =
let goto_updater =
object
inherit nopCilVisitor
method! vstmt s = match s.skind with
| Goto(sref,_loc) ->
let new_stmt = Cil_datatype.Stmt.Map.find !sref sid_tbl in
sref := new_stmt
with Not_found -> ()) ;
DoChildren
| _ -> DoChildren
via Code_annot stmt
via stmt such as Return , IF , ...
via stmt such as Set , Call , Asm , ...
via Asm stmt
end
in visitCilBlock (goto_updater:>cilVisitor) block
let is_referenced stmt l =
let module Found = struct exception Found end in
let vis = object
inherit Visitor.frama_c_inplace
method! vlogic_label l =
match l with
| StmtLabel s when !s == stmt -> raise Found.Found
| _ -> DoChildren
end
in
try
List.iter (fun x -> ignore (Visitor.visitFramacStmt vis x)) l;
false
with Found.Found -> true
let copy_annotations kf assoc labelled_stmt_tbl (break_continue_must_change, stmt_src,stmt_dst) =
let fresh_annotation a =
let visitor = object
inherit Visitor.frama_c_copy (Project.current())
method! vlogic_var_use vi =
match vi.lv_origin with
None -> SkipChildren
| Some vi ->
begin
try
let vi'= snd (List.find (fun (x,_) -> x.vid = vi.vid) assoc) in
ChangeTo (Extlib.the vi'.vlogic_var_assoc)
with Not_found -> SkipChildren
| Invalid_argument _ ->
Kernel.abort
"Loop unrolling: cannot find new representative for \
local var %a"
Printer.pp_varinfo vi
end
method! vlogic_label (label:logic_label) =
match label with
| StmtLabel (stmt) ->
let new_stmt = Cil_datatype.Stmt.Map.find !stmt labelled_stmt_tbl
in ChangeTo (StmtLabel (ref new_stmt))
with Not_found -> SkipChildren) ;
| LogicLabel (None, _str) -> SkipChildren
| LogicLabel (Some _stmt, str) -> ChangeTo (LogicLabel (None, str))
end
in visitCilCodeAnnotation (visitor:>cilVisitor) (Logic_const.refresh_code_annotation a)
in
Kernel.debug ~dkey
"Copying an annotation to stmt %d from stmt %d@."
stmt_dst.sid stmt_src.sid;
TODO : transforms ' breaks ' and ' continues ' clauses into unimplemented
' ' clause ( still undefined clause into ACSL ! ) .
'gotos' clause (still undefined clause into ACSL!). *)
WORKS AROUND : since ' breaks ' and ' continues ' clauses have not be preserved
into the unrolled stmts , and are not yet transformed into ' ' ( see . TODO ) ,
they are not copied .
into the unrolled stmts, and are not yet transformed into 'gotos' (see. TODO),
they are not copied. *)
match break_continue_must_change, a with
| _, { annot_content = AStmtSpec (s,spec); _ } ->
let filter_post_cond = function
| Breaks, _ when (fst break_continue_must_change) != None ->
Kernel.debug ~dkey "Uncopied 'breaks' clause to stmt %d@." stmt_dst.sid;
false
| Continues, _ when (snd break_continue_must_change) != None ->
Kernel.debug ~dkey "Uncopied 'continues' clause to stmt %d@." stmt_dst.sid;
false
| _ -> true in
let filter_behavior acc bhv =
let bhv = { bhv with b_post_cond = List.filter filter_post_cond bhv.b_post_cond } in
if (Cil.is_empty_behavior bhv) && not (Cil.is_default_behavior bhv) then acc
else bhv::acc
in
let filter_behaviors bhvs =
match List.fold_left filter_behavior [] bhvs with
| [bhv] when Cil.is_empty_behavior bhv -> []
| bhvs -> List.rev bhvs
in
let spec = { spec with spec_behavior = filter_behaviors spec.spec_behavior } in
else Some { a with annot_content=AStmtSpec (s,spec) }
| _, _ -> Some a
in
let new_annots =
Annotations.fold_code_annot
(fun emitter annot acc ->
match filter_annotation annot with
| None -> acc
| Some filtred_annot -> (emitter, fresh_annotation filtred_annot) :: acc)
stmt_src
[]
in
List.iter
(fun (e, a) -> Annotations.add_code_annot e ~kf stmt_dst a)
new_annots
let update_loop_current kf loop_current block =
let vis = object(self)
inherit Visitor.frama_c_inplace
initializer self#set_current_kf kf
method! vlogic_label =
function
| LogicLabel(_,"LoopCurrent") -> ChangeTo (StmtLabel (ref loop_current))
| _ -> DoChildren
method! vstmt_aux s =
match s.skind with
| _ -> DoChildren
end in
ignore (Visitor.visitFramacBlock vis block)
let update_loop_entry kf loop_entry stmt =
let vis = object(self)
inherit Visitor.frama_c_inplace
initializer self#set_current_kf kf
method! vlogic_label =
function
| LogicLabel(_,"LoopEntry") -> ChangeTo (StmtLabel (ref loop_entry))
| _ -> DoChildren
method! vstmt_aux s =
match s.skind with
| _ -> DoChildren
end in
ignore (Visitor.visitFramacStmt vis stmt)
let copy_block kf break_continue_must_change bl =
let assoc = ref [] in
let fundec =
try Kernel_function.get_definition kf
with Kernel_function.No_Definition -> assert false
and labelled_stmt_tbl = Cil_datatype.Stmt.Map.empty
and calls_tbl = Cil_datatype.Stmt.Map.empty
in
let rec copy_stmt
break_continue_must_change labelled_stmt_tbl calls_tbl stmt =
let result =
{ labels = [];
sid = Sid.next ();
succs = [];
preds = [];
skind = stmt.skind;
ghost = stmt.ghost}
in
let new_labels,labelled_stmt_tbl =
if stmt.labels = [] then
[], labelled_stmt_tbl
else
let new_tbl = Cil_datatype.Stmt.Map.add stmt result labelled_stmt_tbl
and new_labels =
List.fold_left
(fun lbls -> function
| Label (s, loc, gen) ->
(if gen
then fresh_label ~label_name:s ()
else fresh_label ~label_name:s ~loc ()
) :: lbls
| Case _ | Default _ as lbl -> lbl :: lbls
)
[]
stmt.labels
in new_labels, new_tbl
in
let new_calls_tbl = match stmt.skind with
| Instr(Call _) -> Cil_datatype.Stmt.Map.add stmt result calls_tbl
| _ -> calls_tbl
in
let new_stmkind,new_labelled_stmt_tbl, new_calls_tbl =
copy_stmtkind
break_continue_must_change labelled_stmt_tbl new_calls_tbl stmt.skind
in
if stmt.labels <> [] then result.labels <- new_labels;
result.skind <- new_stmkind;
if Annotations.has_code_annot stmt then
begin
Kernel.debug ~dkey
"Found an annotation to copy for stmt %d from stmt %d@."
result.sid stmt.sid;
annotated_stmts := (break_continue_must_change, stmt,result) :: !annotated_stmts;
end;
result, new_labelled_stmt_tbl, new_calls_tbl
and copy_stmtkind
break_continue_must_change labelled_stmt_tbl calls_tbl stkind =
match stkind with
| (Instr _ | Return _ | Throw _) as keep ->
keep,labelled_stmt_tbl,calls_tbl
| Goto (stmt_ref, loc) -> Goto (ref !stmt_ref, loc),labelled_stmt_tbl,calls_tbl
| If (exp,bl1,bl2,loc) ->
CurrentLoc.set loc;
let new_block1,labelled_stmt_tbl,calls_tbl =
copy_block break_continue_must_change labelled_stmt_tbl calls_tbl bl1
in
let new_block2,labelled_stmt_tbl,calls_tbl =
copy_block break_continue_must_change labelled_stmt_tbl calls_tbl bl2
in
If(exp,new_block1,new_block2,loc),labelled_stmt_tbl,calls_tbl
| Loop (a,bl,loc,_,_) ->
CurrentLoc.set loc;
let new_block,labelled_stmt_tbl,calls_tbl =
copy_block
labelled_stmt_tbl
calls_tbl
bl
in
Loop (a,new_block,loc,None,None),labelled_stmt_tbl,calls_tbl
| Block bl ->
let new_block,labelled_stmt_tbl,calls_tbl =
copy_block break_continue_must_change labelled_stmt_tbl calls_tbl bl
in
Block (new_block),labelled_stmt_tbl,calls_tbl
| UnspecifiedSequence seq ->
let change_calls lst calls_tbl =
List.map
(fun x -> ref (Cil_datatype.Stmt.Map.find !x calls_tbl)) lst
in
let new_seq,labelled_stmt_tbl,calls_tbl =
List.fold_left
(fun (seq,labelled_stmt_tbl,calls_tbl) (stmt,modified,writes,reads,calls) ->
let stmt,labelled_stmt_tbl,calls_tbl =
copy_stmt
break_continue_must_change labelled_stmt_tbl calls_tbl stmt
in
(stmt,modified,writes,reads,change_calls calls calls_tbl)::seq,
labelled_stmt_tbl,calls_tbl)
([],labelled_stmt_tbl,calls_tbl)
seq
in
UnspecifiedSequence (List.rev new_seq),labelled_stmt_tbl,calls_tbl
| Break loc ->
(match break_continue_must_change with
| (Some (brk_lbl_stmt)), _ -> Goto ((ref brk_lbl_stmt),loc)),
labelled_stmt_tbl,
calls_tbl
| Continue loc ->
(match break_continue_must_change with
| _,(Some (continue_lbl_stmt)) ->
Goto ((ref continue_lbl_stmt),loc)),
labelled_stmt_tbl,
calls_tbl
| Switch (e,block,stmts,loc) ->
let new_block,new_labelled_stmt_tbl,calls_tbl =
copy_block (None, (snd break_continue_must_change)) labelled_stmt_tbl calls_tbl block
in
let stmts' =
List.map
(fun s -> Cil_datatype.Stmt.Map.find s new_labelled_stmt_tbl) stmts
in
Switch(e,new_block,stmts',loc),new_labelled_stmt_tbl,calls_tbl
| TryCatch(t,c,loc) ->
let t', labs, calls =
copy_block break_continue_must_change labelled_stmt_tbl calls_tbl t
in
let treat_one_extra_binding mv mv' (bindings, labs, calls) (v,b) =
let v' = copy_var () v in
assoc := (v,v')::!assoc;
let b', labs', calls' =
copy_block break_continue_must_change labs calls b
in
refresh_vars [mv; v] [mv'; v'] b';
(v',b')::bindings, labs', calls'
in
let treat_one_catch (catches, labs, calls) (v,b) =
let v', vorig, vnew, labs', calls' =
match v with
| Catch_all -> Catch_all, [], [], labs, calls
| Catch_exn(v,l) ->
let v' = copy_var () v in
assoc:=(v,v')::!assoc;
let l', labs', calls' =
List.fold_left
(treat_one_extra_binding v v') ([],labs, calls) l
in
Catch_exn(v', List.rev l'), [v], [v'], labs', calls'
in
let (b', labs', calls') =
copy_block break_continue_must_change labs' calls' b
in
refresh_vars vorig vnew b';
(v', b')::catches, labs', calls'
in
let c', labs', calls' =
List.fold_left treat_one_catch ([],labs, calls) c
in
TryCatch(t',List.rev c',loc), labs', calls'
| TryFinally _ | TryExcept _ -> assert false
and copy_block break_continue_must_change labelled_stmt_tbl calls_tbl bl =
let new_stmts,labelled_stmt_tbl,calls_tbl =
List.fold_left
(fun (block_l,labelled_stmt_tbl,calls_tbl) v ->
let new_block,labelled_stmt_tbl,calls_tbl =
copy_stmt break_continue_must_change labelled_stmt_tbl calls_tbl v
in
new_block::block_l, labelled_stmt_tbl,calls_tbl)
([],labelled_stmt_tbl,calls_tbl)
bl.bstmts
in
let new_locals =
List.map (copy_var ()) bl.blocals
in
fundec.slocals <- fundec.slocals @ new_locals;
assoc:=(List.combine bl.blocals new_locals) @ !assoc;
let new_block = mkBlock (List.rev new_stmts) in
refresh_vars bl.blocals new_locals new_block;
new_block.blocals <- new_locals;
new_block,labelled_stmt_tbl,calls_tbl
in
let new_block, labelled_stmt_tbl, _calls_tbl =
copy_block break_continue_must_change labelled_stmt_tbl calls_tbl bl
in
List.iter (copy_annotations kf !assoc labelled_stmt_tbl) !annotated_stmts ;
update_gotos labelled_stmt_tbl new_block
let ast_has_changed = ref false
class do_it ((force:bool),(times:int)) = object(self)
inherit Visitor.frama_c_inplace
initializer ast_has_changed := false;
We sometimes need to move labels between statements . This table
maps the old statement to the new one
maps the old statement to the new one *)
val moved_labels = Cil_datatype.Stmt.Hashtbl.create 17
val mutable gotos = [] ;
val mutable has_unrolled_loop = false ;
val mutable file_has_unrolled_loop = false ;
method get_file_has_unrolled_loop () = file_has_unrolled_loop ;
method! vfunc fundec =
assert (gotos = []) ;
assert (not has_unrolled_loop) ;
let post_goto_updater =
(fun id ->
if has_unrolled_loop then begin
List.iter
(fun s -> match s.skind with Goto(sref,_loc) ->
(try
let new_stmt =
Cil_datatype.Stmt.Hashtbl.find moved_labels !sref
in
sref := new_stmt
with Not_found -> ())
| _ -> assert false)
gotos;
File.must_recompute_cfg id;
ast_has_changed:=true
end;
has_unrolled_loop <- false ;
gotos <- [] ;
Cil_datatype.Stmt.Hashtbl.clear moved_labels ;
id) in
ChangeDoChildrenPost (fundec, post_goto_updater)
method! vstmt_aux s = match s.skind with
| Goto _ ->
DoChildren
let update s =
if has_unrolled_loop then
(match s.skind with
| Switch (e', b', lbls', loc') ->
let labels_moved = ref false in
let update_label s =
try
let s = Cil_datatype.Stmt.Hashtbl.find moved_labels s
in labels_moved := true ; s
with Not_found -> s
in let moved_lbls = List.map update_label lbls' in
if !labels_moved then
s.skind <- Switch (e', b', moved_lbls, loc');
| _ -> ());
s
in
ChangeDoChildrenPost (s, update)
| Loop _ ->
let infos = extract_from_pragmas s in
let number = Extlib.opt_conv times infos.unroll_number in
let total_unrolling = infos.total_unroll in
let is_ignored_unrolling = not force && infos.ignore_unroll in
let f sloop =
Kernel.debug ~dkey
"Unrolling loop stmt %d (%d times) inside function %a@."
sloop.sid number Kernel_function.pretty (Extlib.the self#current_kf);
file_has_unrolled_loop <- true ;
has_unrolled_loop <- true ;
match sloop.skind with
| Loop(_,block,loc,_,_) ->
CurrentLoc.set loc;
let break_lbl_stmt =
let break_label = fresh_label () in
let break_lbl_stmt = mkEmptyStmt () in
break_lbl_stmt.labels <- [break_label];
break_lbl_stmt.sid <- Cil.Sid.next ();
break_lbl_stmt
in
let mk_continue () =
let continue_label = fresh_label () in
let continue_lbl_stmt = mkEmptyStmt () in
continue_lbl_stmt.labels <- [continue_label] ;
continue_lbl_stmt.sid <- Cil.Sid.next ();
continue_lbl_stmt
in
let current_continue = ref (mk_continue ()) in
let new_stmts = ref [sloop] in
for _i=0 to number-1 do
new_stmts:=!current_continue::!new_stmts;
let new_block =
copy_block
(Extlib.the self#current_kf)
((Some break_lbl_stmt),(Some !current_continue))
block
in
current_continue := mk_continue ();
update_loop_current (Extlib.the self#current_kf) !current_continue new_block;
(match new_block.blocals with
[] -> new_stmts:= new_block.bstmts @ !new_stmts;
new_stmts:= mkStmt (Block new_block) :: !new_stmts);
done;
let new_stmt = match !new_stmts with
| [ s ] -> s
| l ->
List.iter (update_loop_entry (Extlib.the self#current_kf) !current_continue) l;
let l = if is_referenced !current_continue l then !current_continue :: l else l in
let new_stmts = l @ [break_lbl_stmt] in
let new_block = mkBlock new_stmts in
let snew = mkStmt (Block new_block) in
Cil_datatype.Stmt.Hashtbl.add moved_labels sloop snew;
snew.labels <- sloop.labels;
sloop.labels <- [];
snew;
in new_stmt
| _ -> assert false
in
match total_unrolling with
| None -> new_stmts
| Some emitter ->
let annot =
Logic_const.new_code_annotation
(AInvariant ([],true,Logic_const.pfalse))
in
Annotations.add_code_annot
emitter ~kf:(Extlib.the self#current_kf) sloop annot;
new_stmts
in
let specs = Unroll_specs [(Logic_const.term (TConst (LStr "done"))
(Ctype Cil.charPtrType)) ;
Logic_const.tinteger number
] in
let annot =
Logic_const.new_code_annotation (APragma (Loop_pragma specs))
in
Annotations.add_code_annot
Emitter.end_user ~kf:(Extlib.the self#current_kf) sloop annot;
new_stmts
in
let fgh sloop = h sloop (g sloop (f sloop)) in
let fgh =
if (number > 0) && not is_ignored_unrolling then fgh else (fun s -> s)
in
ChangeDoChildrenPost (s, fgh)
| _ -> DoChildren
end
let apply_transformation ?(force=true) nb file =
if nb >= 0 then
let visitor = new do_it (force, nb) in
Kernel.debug ~dkey "Using -ulevel %d option and UNROLL loop pragmas@." nb;
visitFramacFileSameGlobals (visitor:>Visitor.frama_c_visitor) file;
if !ast_has_changed then Ast.mark_as_changed ()
else begin
Kernel.debug ~dkey
"No unrolling is done; all UNROLL loop pragmas are ignored@."
end
let compute file =
let nb = Kernel.UnrollingLevel.get () in
let force = Kernel.UnrollingForce.get () in
apply_transformation ~force nb file
let unroll_transform =
File.register_code_transformation_category "loop unrolling"
let () =
File.add_code_transformation_after_cleanup
~deps:[(module Kernel.UnrollingLevel:Parameter_sig.S);
(module Kernel.UnrollingForce:Parameter_sig.S)]
unroll_transform compute
|
a8efb52288d2470b81f7ab14c75c18f8c4b9665ee1379f8f37a0c259aae4b36a | squaresLab/footpatch | symExec.ml |
* Copyright ( c ) 2009 - 2013 Monoidics ltd .
* Copyright ( c ) 2013 - present Facebook , Inc.
* All rights reserved .
*
* This source code is licensed under the BSD style license found in the
* LICENSE file in the root directory of this source tree . An additional grant
* of patent rights can be found in the PATENTS file in the same directory .
* Copyright (c) 2009 - 2013 Monoidics ltd.
* Copyright (c) 2013 - present Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*)
open! Utils
(** Symbolic Execution *)
module L = Logging
module F = Format
let rec fldlist_assoc fld = function
| [] -> raise Not_found
| (fld', x, _):: l -> if Ident.fieldname_equal fld fld' then x else fldlist_assoc fld l
let unroll_type tenv (typ: Typ.t) (off: Sil.offset) =
let fail fld_to_string fld =
L.d_strln ".... Invalid Field Access ....";
L.d_str ("Fld : " ^ fld_to_string fld); L.d_ln ();
L.d_str "Type : "; Typ.d_full typ; L.d_ln ();
raise (Exceptions.Bad_footprint __POS__)
in
match (typ, off) with
| Tstruct name, Off_fld (fld, _) -> (
match Tenv.lookup tenv name with
| Some { fields; statics } -> (
try fldlist_assoc fld (fields @ statics)
with Not_found -> fail Ident.fieldname_to_string fld
)
| None ->
fail Ident.fieldname_to_string fld
)
| Tarray (typ', _), Off_index _ ->
typ'
| _, Off_index (Const (Cint i)) when IntLit.iszero i ->
typ
| _ ->
fail Sil.offset_to_string off
(** Given a node, returns a list of pvar of blocks that have been nullified in the block. *)
let get_blocks_nullified node =
let null_blocks = IList.flatten(IList.map (fun i -> match i with
| Sil.Nullify(pvar, _) when Sil.is_block_pvar pvar -> [pvar]
| _ -> []) (Cfg.Node.get_instrs node)) in
null_blocks
(** Given a proposition and an objc block checks whether by existentially quantifying
captured variables in the block we obtain a leak. *)
let check_block_retain_cycle tenv caller_pname prop block_nullified =
let mblock = Pvar.get_name block_nullified in
let block_pname = Procname.mangled_objc_block (Mangled.to_string mblock) in
let block_captured =
match AttributesTable.load_attributes block_pname with
| Some attributes ->
fst (IList.split attributes.ProcAttributes.captured)
| None ->
[] in
let prop' = Cfg.remove_seed_captured_vars_block tenv block_captured prop in
let prop'' = Prop.prop_rename_fav_with_existentials tenv prop' in
let _ : Prop.normal Prop.t = Abs.abstract_junk ~original_prop: prop caller_pname tenv prop'' in
()
* Apply function [ f ] to the expression at position [ offlist ] in [ strexp ] .
If not found , expand [ strexp ] and apply [ f ] to [ None ] .
The routine should maintain the invariant that strexp and typ correspond to
each other exactly , without involving any re - interpretation of some type t
as the t array . The [ fp_root ] parameter indicates whether the kind of the
root expression of the corresponding pointsto predicate is a footprint identifier .
The function can expand a list of higher - order [ hpara_psto ] predicates , if
the list is stored at [ offlist ] in [ strexp ] initially . The expanded list
is returned as a part of the result . All these happen under [ p ] , so that it
is sound to call the prover with [ p ] . Finally , before running this function ,
the tool should run strexp_extend_value in rearrange.ml for the same strexp
and offlist , so that all the necessary extensions of strexp are done before
this function . If the tool follows this protocol , it will never hit the assert
false cases for field and array accesses .
If not found, expand [strexp] and apply [f] to [None].
The routine should maintain the invariant that strexp and typ correspond to
each other exactly, without involving any re - interpretation of some type t
as the t array. The [fp_root] parameter indicates whether the kind of the
root expression of the corresponding pointsto predicate is a footprint identifier.
The function can expand a list of higher - order [hpara_psto] predicates, if
the list is stored at [offlist] in [strexp] initially. The expanded list
is returned as a part of the result. All these happen under [p], so that it
is sound to call the prover with [p]. Finally, before running this function,
the tool should run strexp_extend_value in rearrange.ml for the same strexp
and offlist, so that all the necessary extensions of strexp are done before
this function. If the tool follows this protocol, it will never hit the assert
false cases for field and array accesses. *)
let rec apply_offlist
pdesc tenv p fp_root nullify_struct (root_lexp, strexp, typ) offlist
(f: Exp.t option -> Exp.t) inst lookup_inst =
let pname = Cfg.Procdesc.get_proc_name pdesc in
let pp_error () =
L.d_strln ".... Invalid Field ....";
L.d_str "strexp : "; Sil.d_sexp strexp; L.d_ln ();
L.d_str "offlist : "; Sil.d_offset_list offlist; L.d_ln ();
L.d_str "type : "; Typ.d_full typ; L.d_ln ();
L.d_str "prop : "; Prop.d_prop p; L.d_ln (); L.d_ln () in
match offlist, strexp, typ with
| [], Sil.Eexp (e, inst_curr), _ ->
let inst_is_uninitialized = function
| Sil.Ialloc ->
(* java allocation initializes with default values *)
!Config.curr_language <> Config.Java
| Sil.Iinitial -> true
| _ -> false in
let is_hidden_field () =
match State.get_instr () with
| Some (Sil.Load (_, Exp.Lfield (_, fieldname, _), _, _)) ->
Ident.fieldname_is_hidden fieldname
| _ -> false in
let inst_new = match inst with
| Sil.Ilookup when inst_is_uninitialized inst_curr && not (is_hidden_field()) ->
(* we are in a lookup of an uninitialized value *)
lookup_inst := Some inst_curr;
let alloc_attribute_opt =
if inst_curr = Sil.Iinitial then None
else Attribute.get_undef tenv p root_lexp in
let deref_str = Localise.deref_str_uninitialized alloc_attribute_opt in
let err_desc = Errdesc.explain_memory_access tenv deref_str p (State.get_loc ()) in
let exn = (Exceptions.Uninitialized_value (err_desc, __POS__)) in
let pre_opt = State.get_normalized_pre (Abs.abstract_no_symop pname) in
Reporting.log_warning pname ?pre:pre_opt exn;
Sil.update_inst inst_curr inst
| Sil.Ilookup -> (* a lookup does not change an inst unless it is inst_initial *)
lookup_inst := Some inst_curr;
inst_curr
| _ -> Sil.update_inst inst_curr inst in
let e' = f (Some e) in
(e', Sil.Eexp (e', inst_new), typ, None)
| [], Sil.Estruct (fesl, inst'), _ ->
if not nullify_struct then (f None, Sil.Estruct (fesl, inst'), typ, None)
else if fp_root then (pp_error(); assert false)
else
begin
L.d_strln "WARNING: struct assignment treated as nondeterministic assignment";
(f None, Prop.create_strexp_of_type tenv Prop.Fld_init typ None inst, typ, None)
end
| [], Sil.Earray _, _ ->
let offlist' = (Sil.Off_index Exp.zero):: offlist in
apply_offlist
pdesc tenv p fp_root nullify_struct (root_lexp, strexp, typ) offlist' f inst lookup_inst
| (Sil.Off_fld _) :: _, Sil.Earray _, _ ->
let offlist_new = Sil.Off_index(Exp.zero) :: offlist in
apply_offlist
pdesc tenv p fp_root nullify_struct (root_lexp, strexp, typ) offlist_new f inst lookup_inst
| (Sil.Off_fld (fld, fld_typ)) :: offlist', Sil.Estruct (fsel, inst'), Typ.Tstruct name -> (
match Tenv.lookup tenv name with
| Some ({fields} as struct_typ) -> (
let t' = unroll_type tenv typ (Sil.Off_fld (fld, fld_typ)) in
match IList.find (fun fse -> Ident.fieldname_equal fld (fst fse)) fsel with
| _, se' ->
let res_e', res_se', res_t', res_pred_insts_op' =
apply_offlist
pdesc tenv p fp_root nullify_struct
(root_lexp, se', t') offlist' f inst lookup_inst in
let replace_fse fse =
if Ident.fieldname_equal fld (fst fse) then (fld, res_se') else fse in
let res_se = Sil.Estruct (IList.map replace_fse fsel, inst') in
let replace_fta (f, t, a) =
if Ident.fieldname_equal fld f then (fld, res_t', a) else (f, t, a) in
let fields' = IList.map replace_fta fields in
ignore (Tenv.mk_struct tenv ~default:struct_typ ~fields:fields' name) ;
(res_e', res_se, typ, res_pred_insts_op')
| exception Not_found ->
(* This case should not happen. The rearrangement should
have materialized all the accessed cells. *)
pp_error();
assert false
)
| None ->
pp_error();
assert false
)
| (Sil.Off_fld _) :: _, _, _ ->
pp_error();
assert false
| (Sil.Off_index idx) :: offlist', Sil.Earray (len, esel, inst1), Typ.Tarray (t', len') -> (
let nidx = Prop.exp_normalize_prop tenv p idx in
try
let idx_ese', se' = IList.find (fun ese -> Prover.check_equal tenv p nidx (fst ese)) esel in
let res_e', res_se', res_t', res_pred_insts_op' =
apply_offlist
pdesc tenv p fp_root nullify_struct
(root_lexp, se', t') offlist' f inst lookup_inst in
let replace_ese ese =
if Exp.equal idx_ese' (fst ese)
then (idx_ese', res_se')
else ese in
let res_se = Sil.Earray (len, IList.map replace_ese esel, inst1) in
let res_t = Typ.Tarray (res_t', len') in
(res_e', res_se, res_t, res_pred_insts_op')
with Not_found ->
(* return a nondeterministic value if the index is not found after rearrangement *)
L.d_str "apply_offlist: index "; Sil.d_exp idx;
L.d_strln " not materialized -- returning nondeterministic value";
let res_e' = Exp.Var (Ident.create_fresh Ident.kprimed) in
(res_e', strexp, typ, None)
)
| (Sil.Off_index _) :: _, _, _ ->
(* This case should not happen. The rearrangement should
have materialized all the accessed cells. *)
pp_error();
raise (Exceptions.Internal_error (Localise.verbatim_desc "Array out of bounds in Symexec"))
* Given [ |- > se : typ ] , if the location [ offlist ] exists in [ se ] ,
function [ ptsto_lookup p ( , se , ) offlist i d ] returns a tuple .
The first component of the tuple is an expression at position [ offlist ] in [ se ] .
The second component is an expansion of the predicate [ |- > se : typ ] ,
where the entity at [ offlist ] in [ se ] is expanded if the entity is a list of
higher - order parameters [ hpara_psto ] . If this expansion happens ,
the last component of the tuple is a list of pi - sigma pairs obtained
by instantiating the [ hpara_psto ] list . Otherwise , the last component is None .
All these steps happen under [ p ] . So , we can call a prover with [ p ] .
Finally , before running this function , the tool should run strexp_extend_value
in rearrange.ml for the same se and offlist , so that all the necessary
extensions of se are done before this function .
function [ptsto_lookup p (lexp, se, typ) offlist id] returns a tuple.
The first component of the tuple is an expression at position [offlist] in [se].
The second component is an expansion of the predicate [lexp |-> se: typ],
where the entity at [offlist] in [se] is expanded if the entity is a list of
higher - order parameters [hpara_psto]. If this expansion happens,
the last component of the tuple is a list of pi - sigma pairs obtained
by instantiating the [hpara_psto] list. Otherwise, the last component is None.
All these steps happen under [p]. So, we can call a prover with [p].
Finally, before running this function, the tool should run strexp_extend_value
in rearrange.ml for the same se and offlist, so that all the necessary
extensions of se are done before this function. *)
let ptsto_lookup pdesc tenv p (lexp, se, typ, len, st) offlist id =
let f =
function Some exp -> exp | None -> Exp.Var id in
let fp_root =
match lexp with Exp.Var id -> Ident.is_footprint id | _ -> false in
let lookup_inst = ref None in
let e', se', typ', pred_insts_op' =
apply_offlist
pdesc tenv p fp_root false (lexp, se, typ) offlist f Sil.inst_lookup lookup_inst in
let lookup_uninitialized = (* true if we have looked up an uninitialized value *)
match !lookup_inst with
| Some (Sil.Iinitial | Sil.Ialloc | Sil.Ilookup) -> true
| _ -> false in
let ptsto' = Prop.mk_ptsto tenv lexp se' (Exp.Sizeof (typ', len, st)) in
(e', ptsto', pred_insts_op', lookup_uninitialized)
* [ ptsto_update p ( , se , ) offlist exp ] takes
[ |- > se : typ ] , and updates [ se ] by replacing the
expression at [ offlist ] with [ exp ] . Then , it returns
the updated pointsto predicate . If [ |- > se : typ ] gets
expanded during this update , the generated pi - sigma list from
the expansion gets returned , and otherwise , None is returned .
All these happen under the proposition [ p ] , so it is ok call
prover with [ p ] . Finally , before running this function ,
the tool should run strexp_extend_value in rearrange.ml for the same
se and offlist , so that all the necessary extensions of se are done
before this function .
[lexp |-> se: typ], and updates [se] by replacing the
expression at [offlist] with [exp]. Then, it returns
the updated pointsto predicate. If [lexp |-> se: typ] gets
expanded during this update, the generated pi - sigma list from
the expansion gets returned, and otherwise, None is returned.
All these happen under the proposition [p], so it is ok call
prover with [p]. Finally, before running this function,
the tool should run strexp_extend_value in rearrange.ml for the same
se and offlist, so that all the necessary extensions of se are done
before this function. *)
let ptsto_update pdesc tenv p (lexp, se, typ, len, st) offlist exp =
let f _ = exp in
let fp_root =
match lexp with Exp.Var id -> Ident.is_footprint id | _ -> false in
let lookup_inst = ref None in
let _, se', typ', pred_insts_op' =
let pos = State.get_path_pos () in
apply_offlist
pdesc tenv p fp_root true (lexp, se, typ) offlist f (State.get_inst_update pos) lookup_inst in
let ptsto' = Prop.mk_ptsto tenv lexp se' (Exp.Sizeof (typ', len, st)) in
(ptsto', pred_insts_op')
let update_iter iter pi sigma =
let iter' = Prop.prop_iter_update_current_by_list iter sigma in
IList.fold_left (Prop.prop_iter_add_atom false) iter' pi
* Precondition : se should not include hpara_psto
that could mean nonempty heaps .
that could mean nonempty heaps. *)
let rec execute_nullify_se = function
| Sil.Eexp _ ->
Sil.Eexp (Exp.zero, Sil.inst_nullify)
| Sil.Estruct (fsel, _) ->
let fsel' = IList.map (fun (fld, se) -> (fld, execute_nullify_se se)) fsel in
Sil.Estruct (fsel', Sil.inst_nullify)
| Sil.Earray (len, esel, _) ->
let esel' = IList.map (fun (idx, se) -> (idx, execute_nullify_se se)) esel in
Sil.Earray (len, esel', Sil.inst_nullify)
(** Do pruning for conditional [if (e1 != e2) ] if [positive] is true
and [(if (e1 == e2)] if [positive] is false *)
let prune_ne tenv ~positive e1 e2 prop =
let is_inconsistent =
if positive then Prover.check_equal tenv prop e1 e2
else Prover.check_disequal tenv prop e1 e2 in
if is_inconsistent then Propset.empty
else
let conjoin = if positive then Prop.conjoin_neq else Prop.conjoin_eq in
let new_prop = conjoin tenv ~footprint: (!Config.footprint) e1 e2 prop in
if Prover.check_inconsistency tenv new_prop then Propset.empty
else Propset.singleton tenv new_prop
* Do pruning for conditional " if ( [ e1 ] CMP [ e2 ] ) " if [ positive ] is
true and " if ( ! ( [ e1 ] CMP [ e2 ] ) ) " if [ positive ] is false , where CMP
is " < " if [ is_strict ] is true and " < = " if [ is_strict ] is false .
true and "if (!([e1] CMP [e2]))" if [positive] is false, where CMP
is "<" if [is_strict] is true and "<=" if [is_strict] is false.
*)
let prune_ineq tenv ~is_strict ~positive prop e1 e2 =
if Exp.equal e1 e2 then
if (positive && not is_strict) || (not positive && is_strict) then
Propset.singleton tenv prop
else Propset.empty
else
(* build the pruning condition and its negation, as explained in
the comment above *)
build [ e1 ] CMP [ e2 ]
let cmp = if is_strict then Binop.Lt else Binop.Le in
let e1_cmp_e2 = Exp.BinOp (cmp, e1, e2) in
build ! ( [ e1 ] CMP [ e2 ] )
let dual_cmp = if is_strict then Binop.Le else Binop.Lt in
let not_e1_cmp_e2 = Exp.BinOp (dual_cmp, e2, e1) in
(* take polarity into account *)
let (prune_cond, not_prune_cond) =
if positive then (e1_cmp_e2, not_e1_cmp_e2)
else (not_e1_cmp_e2, e1_cmp_e2) in
let is_inconsistent = Prover.check_atom tenv prop (Prop.mk_inequality tenv not_prune_cond) in
if is_inconsistent then Propset.empty
else
let footprint = !Config.footprint in
let prop_with_ineq = Prop.conjoin_eq tenv ~footprint prune_cond Exp.one prop in
Propset.singleton tenv prop_with_ineq
let rec prune tenv ~positive condition prop =
match condition with
| Exp.Var _ | Exp.Lvar _ ->
prune_ne tenv ~positive condition Exp.zero prop
| Exp.Const (Const.Cint i) when IntLit.iszero i ->
if positive then Propset.empty else Propset.singleton tenv prop
| Exp.Const (Const.Cint _ | Const.Cstr _ | Const.Cclass _) | Exp.Sizeof _ ->
if positive then Propset.singleton tenv prop else Propset.empty
| Exp.Const _ ->
assert false
| Exp.Cast (_, condition') ->
prune tenv ~positive condition' prop
| Exp.UnOp (Unop.LNot, condition', _) ->
prune tenv ~positive:(not positive) condition' prop
| Exp.UnOp _ ->
assert false
| Exp.BinOp (Binop.Eq, e, Exp.Const (Const.Cint i))
| Exp.BinOp (Binop.Eq, Exp.Const (Const.Cint i), e)
when IntLit.iszero i && not (IntLit.isnull i) ->
prune tenv ~positive:(not positive) e prop
| Exp.BinOp (Binop.Eq, e1, e2) ->
prune_ne tenv ~positive:(not positive) e1 e2 prop
| Exp.BinOp (Binop.Ne, e, Exp.Const (Const.Cint i))
| Exp.BinOp (Binop.Ne, Exp.Const (Const.Cint i), e)
when IntLit.iszero i && not (IntLit.isnull i) ->
prune tenv ~positive e prop
| Exp.BinOp (Binop.Ne, e1, e2) ->
prune_ne tenv ~positive e1 e2 prop
| Exp.BinOp (Binop.Ge, e2, e1) | Exp.BinOp (Binop.Le, e1, e2) ->
prune_ineq tenv ~is_strict:false ~positive prop e1 e2
| Exp.BinOp (Binop.Gt, e2, e1) | Exp.BinOp (Binop.Lt, e1, e2) ->
prune_ineq tenv ~is_strict:true ~positive prop e1 e2
| Exp.BinOp (Binop.LAnd, condition1, condition2) ->
let pruner = if positive then prune_inter tenv else prune_union tenv in
pruner ~positive condition1 condition2 prop
| Exp.BinOp (Binop.LOr, condition1, condition2) ->
let pruner = if positive then prune_union tenv else prune_inter tenv in
pruner ~positive condition1 condition2 prop
| Exp.BinOp _ | Exp.Lfield _ | Exp.Lindex _ ->
prune_ne tenv ~positive condition Exp.zero prop
| Exp.Exn _ ->
assert false
| Exp.Closure _ ->
assert false
and prune_inter tenv ~positive condition1 condition2 prop =
let res = ref Propset.empty in
let pset1 = prune tenv ~positive condition1 prop in
let do_p p =
res := Propset.union (prune tenv ~positive condition2 p) !res in
Propset.iter do_p pset1;
!res
and prune_union tenv ~positive condition1 condition2 prop =
let pset1 = prune tenv ~positive condition1 prop in
let pset2 = prune tenv ~positive condition2 prop in
Propset.union pset1 pset2
let dangerous_functions =
let dangerous_list = ["gets"] in
ref ((IList.map Procname.from_string_c_fun) dangerous_list)
let check_inherently_dangerous_function caller_pname callee_pname =
if IList.exists (Procname.equal callee_pname) !dangerous_functions then
let exn =
Exceptions.Inherently_dangerous_function
(Localise.desc_inherently_dangerous_function callee_pname) in
let pre_opt = State.get_normalized_pre (Abs.abstract_no_symop caller_pname) in
Reporting.log_warning caller_pname ?pre:pre_opt exn
let proc_is_defined proc_name =
match AttributesTable.load_attributes proc_name with
| Some attributes ->
attributes.ProcAttributes.is_defined
| None ->
false
let call_should_be_skipped callee_pname summary =
(* check skip flag *)
Specs.get_flag callee_pname proc_flag_skip <> None
(* skip abstract methods *)
|| summary.Specs.attributes.ProcAttributes.is_abstract
(* treat calls with no specs as skip functions in angelic mode *)
|| (Config.angelic_execution && Specs.get_specs_from_payload summary == [])
(** In case of constant string dereference, return the result immediately *)
let check_constant_string_dereference lexp =
let string_lookup s n =
let c = try Char.code (String.get s (IntLit.to_int n)) with Invalid_argument _ -> 0 in
Exp.int (IntLit.of_int c) in
match lexp with
| Exp.BinOp(Binop.PlusPI, Exp.Const (Const.Cstr s), e)
| Exp.Lindex (Exp.Const (Const.Cstr s), e) ->
let value = match e with
| Exp.Const (Const.Cint n)
when IntLit.geq n IntLit.zero &&
IntLit.leq n (IntLit.of_int (String.length s)) ->
string_lookup s n
| _ -> Exp.get_undefined false in
Some value
| Exp.Const (Const.Cstr s) ->
Some (string_lookup s IntLit.zero)
| _ -> None
(** Normalize an expression and check for arithmetic problems *)
let check_arith_norm_exp tenv pname exp prop =
match Attribute.find_arithmetic_problem tenv (State.get_path_pos ()) prop exp with
| Some (Attribute.Div0 div), prop' ->
let desc = Errdesc.explain_divide_by_zero tenv div (State.get_node ()) (State.get_loc ()) in
let exn = Exceptions.Divide_by_zero (desc, __POS__) in
let pre_opt = State.get_normalized_pre (Abs.abstract_no_symop pname) in
Reporting.log_warning pname ?pre:pre_opt exn;
Prop.exp_normalize_prop tenv prop exp, prop'
| Some (Attribute.UminusUnsigned (e, typ)), prop' ->
let desc =
Errdesc.explain_unary_minus_applied_to_unsigned_expression tenv
e typ (State.get_node ()) (State.get_loc ()) in
let exn = Exceptions.Unary_minus_applied_to_unsigned_expression (desc, __POS__) in
let pre_opt = State.get_normalized_pre (Abs.abstract_no_symop pname) in
Reporting.log_warning pname ?pre:pre_opt exn;
Prop.exp_normalize_prop tenv prop exp, prop'
| None, prop' -> Prop.exp_normalize_prop tenv prop exp, prop'
(** Check if [cond] is testing for NULL a pointer already dereferenced *)
let check_already_dereferenced tenv pname cond prop =
let find_hpred lhs =
try Some (IList.find (function
| Sil.Hpointsto (e, _, _) -> Exp.equal e lhs
| _ -> false) prop.Prop.sigma)
with Not_found -> None in
let rec is_check_zero = function
| Exp.Var id ->
Some id
| Exp.UnOp(Unop.LNot, e, _) ->
is_check_zero e
| Exp.BinOp ((Binop.Eq | Binop.Ne), Exp.Const Const.Cint i, Exp.Var id)
| Exp.BinOp ((Binop.Eq | Binop.Ne), Exp.Var id, Exp.Const Const.Cint i) when IntLit.iszero i ->
Some id
| _ -> None in
let dereferenced_line = match is_check_zero cond with
| Some id ->
(match find_hpred (Prop.exp_normalize_prop tenv prop (Exp.Var id)) with
| Some (Sil.Hpointsto (_, se, _)) ->
(match Tabulation.find_dereference_without_null_check_in_sexp se with
| Some n -> Some (id, n)
| None -> None)
| _ -> None)
| None ->
None in
match dereferenced_line with
| Some (id, (n, _)) ->
let desc =
Errdesc.explain_null_test_after_dereference tenv
(Exp.Var id) (State.get_node ()) n (State.get_loc ()) in
let exn =
(Exceptions.Null_test_after_dereference (desc, __POS__)) in
let pre_opt = State.get_normalized_pre (Abs.abstract_no_symop pname) in
Reporting.log_warning pname ?pre:pre_opt exn
| None -> ()
(** Check whether symbolic execution de-allocated a stack variable or a constant string,
raising an exception in that case *)
let check_deallocate_static_memory prop_after =
let check_deallocated_attribute = function
| Sil.Apred (Aresource ({ ra_kind = Rrelease } as ra), [Lvar pv])
when Pvar.is_local pv || Pvar.is_global pv ->
let freed_desc = Errdesc.explain_deallocate_stack_var pv ra in
raise (Exceptions.Deallocate_stack_variable freed_desc)
| Sil.Apred (Aresource ({ ra_kind = Rrelease } as ra), [Const (Cstr s)]) ->
let freed_desc = Errdesc.explain_deallocate_constant_string s ra in
raise (Exceptions.Deallocate_static_memory freed_desc)
| _ -> () in
let exp_att_list = Attribute.get_all prop_after in
IList.iter check_deallocated_attribute exp_att_list;
prop_after
let method_exists right_proc_name methods =
if !Config.curr_language = Config.Java then
IList.exists (fun meth_name -> Procname.equal right_proc_name meth_name) methods
else (* ObjC/C++ case : The attribute map will only exist when we have code for the method or
the method has been called directly somewhere. It can still be that this is not the
case but we have a model for the method. *)
match AttributesTable.load_attributes right_proc_name with
| Some attrs -> attrs.ProcAttributes.is_defined
| None -> Specs.summary_exists_in_models right_proc_name
let resolve_method tenv class_name proc_name =
let found_class =
let visited = ref Typename.Set.empty in
let rec resolve class_name =
visited := Typename.Set.add class_name !visited;
let right_proc_name =
Procname.replace_class proc_name (Typename.name class_name) in
match Tenv.lookup tenv class_name with
| Some { name = TN_csu (Class _, _); methods; supers } ->
if method_exists right_proc_name methods then
Some right_proc_name
else
(match supers with
| super_classname:: _ ->
if not (Typename.Set.mem super_classname !visited)
then resolve super_classname
else None
| _ -> None)
| _ -> None in
resolve class_name in
match found_class with
| None ->
Logging.d_strln
("Couldn't find method in the hierarchy of type "^(Typename.name class_name));
proc_name
| Some proc_name ->
proc_name
let resolve_typename prop receiver_exp =
let typexp_opt =
let rec loop = function
| [] -> None
| Sil.Hpointsto(e, _, typexp) :: _ when Exp.equal e receiver_exp -> Some typexp
| _ :: hpreds -> loop hpreds in
loop prop.Prop.sigma in
match typexp_opt with
| Some (Exp.Sizeof (Tstruct name, _, _)) -> Some name
| _ -> None
* If the dynamic type of the receiver actual T_actual is a subtype of the reciever type T_formal
in the signature of [ pname ] , resolve [ pname ] to T_actual.[pname ] .
in the signature of [pname], resolve [pname] to T_actual.[pname]. *)
let resolve_virtual_pname tenv prop actuals callee_pname call_flags : Procname.t list =
let resolve receiver_exp pname prop = match resolve_typename prop receiver_exp with
| Some class_name -> resolve_method tenv class_name pname
| None -> pname in
let get_receiver_typ pname fallback_typ =
match pname with
| Procname.Java pname_java ->
begin
match Tenv.lookup_declaring_class tenv pname_java with
| Some {name} -> Typ.Tptr (Tstruct name, Pk_pointer)
| None -> fallback_typ
end
| _ ->
fallback_typ in
let receiver_types_equal pname actual_receiver_typ =
(* the type of the receiver according to the function signature *)
let formal_receiver_typ = get_receiver_typ pname actual_receiver_typ in
Typ.equal formal_receiver_typ actual_receiver_typ in
let do_resolve called_pname receiver_exp actual_receiver_typ =
if receiver_types_equal called_pname actual_receiver_typ
then resolve receiver_exp called_pname prop
else called_pname in
match actuals with
| _ when not (call_flags.CallFlags.cf_virtual || call_flags.CallFlags.cf_interface) ->
(* if this is not a virtual or interface call, there's no need for resolution *)
[callee_pname]
| (receiver_exp, actual_receiver_typ) :: _ ->
if !Config.curr_language <> Config.Java then
(* default mode for Obj-C/C++/Java virtual calls: resolution only *)
[do_resolve callee_pname receiver_exp actual_receiver_typ]
else if Config.sound_dynamic_dispatch then
let targets =
if call_flags.CallFlags.cf_virtual
then
(* virtual call--either [called_pname] or an override in some subtype may be called *)
callee_pname :: call_flags.CallFlags.cf_targets
else
(* interface call--[called_pname] has no implementation), we don't want to consider *)
call_flags.CallFlags.cf_targets (* interface call, don't want to consider *) in
(* return true if (receiver typ of [target_pname]) <: [actual_receiver_typ] *)
let may_dispatch_to target_pname =
let target_receiver_typ = get_receiver_typ target_pname actual_receiver_typ in
Prover.Subtyping_check.check_subtype tenv target_receiver_typ actual_receiver_typ in
let resolved_pname = do_resolve callee_pname receiver_exp actual_receiver_typ in
let feasible_targets = IList.filter may_dispatch_to targets in
(* make sure [resolved_pname] is not a duplicate *)
if IList.mem Procname.equal resolved_pname feasible_targets
then feasible_targets
else resolved_pname :: feasible_targets
else
begin
match call_flags.CallFlags.cf_targets with
| target :: _ when call_flags.CallFlags.cf_interface &&
receiver_types_equal callee_pname actual_receiver_typ ->
" production mode " of dynamic dispatch for Java : unsound , but faster . the handling
is restricted to interfaces : if we ca n't resolve an interface call , we pick the
first implementation of the interface and call it
is restricted to interfaces: if we can't resolve an interface call, we pick the
first implementation of the interface and call it *)
[target]
| _ ->
default mode for Java virtual calls : resolution only
[do_resolve callee_pname receiver_exp actual_receiver_typ]
end
| _ -> failwith "A virtual call must have a receiver"
(** Resolve the name of the procedure to call based on the type of the arguments *)
let resolve_java_pname tenv prop args pname_java call_flags : Procname.java =
let resolve_from_args resolved_pname_java args =
let parameters = Procname.java_get_parameters resolved_pname_java in
if IList.length args <> IList.length parameters then
resolved_pname_java
else
let resolved_params =
IList.fold_left2
(fun accu (arg_exp, _) name ->
match resolve_typename prop arg_exp with
| Some class_name ->
(Procname.split_classname (Typename.name class_name)) :: accu
| None -> name :: accu)
[] args (Procname.java_get_parameters resolved_pname_java) |> IList.rev in
Procname.java_replace_parameters resolved_pname_java resolved_params in
let resolved_pname_java, other_args =
match args with
| [] ->
pname_java, []
| (first_arg, _) :: other_args when call_flags.CallFlags.cf_virtual ->
let resolved =
begin
match resolve_typename prop first_arg with
| Some class_name ->
begin
match resolve_method tenv class_name (Procname.Java pname_java) with
| Procname.Java resolved_pname_java ->
resolved_pname_java
| _ ->
pname_java
end
| None ->
pname_java
end in
resolved, other_args
| _ :: other_args when Procname.is_constructor (Procname.Java pname_java) ->
pname_java, other_args
| args ->
pname_java, args in
resolve_from_args resolved_pname_java other_args
(** Resolve the procedure name and run the analysis of the resolved procedure
if not already analyzed *)
let resolve_and_analyze
tenv caller_pdesc prop args callee_proc_name call_flags : Procname.t * Specs.summary option =
TODO ( # 9333890 ): Fix conflict with method overloading by encoding in the procedure name
whether the method is defined or generated by the specialization
whether the method is defined or generated by the specialization *)
let analyze_ondemand resolved_pname : unit =
if Procname.equal resolved_pname callee_proc_name then
Ondemand.analyze_proc_name tenv ~propagate_exceptions:true caller_pdesc callee_proc_name
else
(* Create the type sprecialized procedure description and analyze it directly *)
Option.may
(fun specialized_pdesc ->
Ondemand.analyze_proc_desc tenv ~propagate_exceptions:true caller_pdesc specialized_pdesc)
(match Ondemand.get_proc_desc resolved_pname with
| Some resolved_proc_desc ->
Some resolved_proc_desc
| None ->
begin
Option.map
(fun callee_proc_desc ->
Cfg.specialize_types callee_proc_desc resolved_pname args)
(Ondemand.get_proc_desc callee_proc_name)
end) in
let resolved_pname = match callee_proc_name with
| Procname.Java callee_proc_name_java ->
Procname.Java
(resolve_java_pname tenv prop args callee_proc_name_java call_flags)
| _ ->
callee_proc_name in
analyze_ondemand resolved_pname;
resolved_pname, Specs.get_summary resolved_pname
(** recognize calls to the constructor java.net.URL and splits the argument string
to be only the protocol. *)
let call_constructor_url_update_args pname actual_params =
let url_pname =
Procname.Java
(Procname.java
((Some "java.net"), "URL") None "<init>"
[(Some "java.lang"), "String"] Procname.Non_Static) in
if (Procname.equal url_pname pname) then
(match actual_params with
| [this; (Exp.Const (Const.Cstr s), atype)] ->
let parts = Str.split (Str.regexp_string "://") s in
(match parts with
| frst:: _ ->
if frst = "http" ||
frst = "ftp" ||
frst = "https" ||
frst = "mailto" ||
frst = "jar"
then
[this; (Exp.Const (Const.Cstr frst), atype)]
else actual_params
| _ -> actual_params)
| [this; _, atype] -> [this; (Exp.Const (Const.Cstr "file"), atype)]
| _ -> actual_params)
else actual_params
(* This method is used to handle the special semantics of ObjC instance method calls. *)
(* res = [obj foo] *)
1 . We know that obj is null , then we return null
2 . We do n't know , but obj could be null , we return both options ,
(* (obj = null, res = null), (obj != null, res = [obj foo]) *)
(* We want the same behavior even when we are going to skip the function. *)
let handle_objc_instance_method_call_or_skip tenv actual_pars path callee_pname pre ret_ids res =
let path_description =
"Message " ^
(Procname.to_simplified_string callee_pname) ^
" with receiver nil returns nil." in
let receiver = (match actual_pars with
| (e, _):: _ -> e
| _ -> raise
(Exceptions.Internal_error
(Localise.verbatim_desc
"In Objective-C instance method call there should be a receiver."))) in
let is_receiver_null =
match actual_pars with
| (e, _) :: _
when Exp.equal e Exp.zero ||
Option.is_some (Attribute.get_objc_null tenv pre e) -> true
| _ -> false in
let add_objc_null_attribute_or_nullify_result prop =
match ret_ids with
| [ret_id] -> (
match Attribute.find_equal_formal_path tenv receiver prop with
| Some vfs ->
Attribute.add_or_replace tenv prop (Apred (Aobjc_null, [Exp.Var ret_id; vfs]))
| None ->
Prop.conjoin_eq tenv (Exp.Var ret_id) Exp.zero prop
)
| _ -> prop in
if is_receiver_null then
(* objective-c instance method with a null receiver just return objc_null(res) *)
let path = Paths.Path.add_description path path_description in
L.d_strln
("Object-C method " ^
Procname.to_string callee_pname ^
" called with nil receiver. Returning 0/nil");
(* We wish to nullify the result. However, in some cases,
we want to add the attribute OBJC_NULL to it so that we *)
can keep track of how this object became null ,
so that in a NPE we can separate it into a different error type
so that in a NPE we can separate it into a different error type *)
[(add_objc_null_attribute_or_nullify_result pre, path)]
else
let is_undef = Option.is_some (Attribute.get_undef tenv pre receiver) in
if !Config.footprint && not is_undef then
let res_null = (* returns: (objc_null(res) /\ receiver=0) or an empty list of results *)
let pre_with_attr_or_null = add_objc_null_attribute_or_nullify_result pre in
let propset = prune_ne tenv ~positive:false receiver Exp.zero pre_with_attr_or_null in
if Propset.is_empty propset then []
else
let prop = IList.hd (Propset.to_proplist propset) in
let path = Paths.Path.add_description path path_description in
[(prop, path)] in
res_null @ (res ())
else res () (* Not known if receiver = 0 and not footprint. Standard tabulation *)
(* This method handles ObjC instance method calls, in particular the fact that calling a method *)
(* with nil returns nil. The exec_call function is either standard call execution or execution *)
(* of ObjC getters and setters using a builtin. *)
let handle_objc_instance_method_call actual_pars actual_params pre tenv ret_ids pdesc callee_pname
loc path exec_call =
let res () = exec_call tenv ret_ids pdesc callee_pname loc actual_params pre path in
handle_objc_instance_method_call_or_skip tenv actual_pars path callee_pname pre ret_ids res
let normalize_params tenv pdesc prop actual_params =
let norm_arg (p, args) (e, t) =
let e', p' = check_arith_norm_exp tenv pdesc e p in
(p', (e', t) :: args) in
let prop, args = IList.fold_left norm_arg (prop, []) actual_params in
(prop, IList.rev args)
let do_error_checks tenv node_opt instr pname pdesc = match node_opt with
| Some node ->
if !Config.curr_language = Config.Java then
PrintfArgs.check_printf_args_ok tenv node instr pname pdesc
| None ->
()
let add_strexp_to_footprint tenv strexp abduced_pv typ prop =
let abduced_lvar = Exp.Lvar abduced_pv in
let lvar_pt_fpvar =
let sizeof_exp = Exp.Sizeof (typ, None, Subtype.subtypes) in
Prop.mk_ptsto tenv abduced_lvar strexp sizeof_exp in
let sigma_fp = prop.Prop.sigma_fp in
Prop.normalize tenv (Prop.set prop ~sigma_fp:(lvar_pt_fpvar :: sigma_fp))
let add_to_footprint tenv abduced_pv typ prop =
let fresh_fp_var = Exp.Var (Ident.create_fresh Ident.kfootprint) in
let prop' =
add_strexp_to_footprint tenv (Sil.Eexp (fresh_fp_var, Sil.Inone)) abduced_pv typ prop in
prop', fresh_fp_var
(* the current abduction mechanism treats struct values differently than all other types. abduction
on struct values adds a a struct whose fields are initialized to fresh footprint vars to the
footprint. regular abduction just adds a fresh footprint value of the correct type to the
footprint. we can get rid of this special case if we fix the abduction on struct values *)
let add_struct_value_to_footprint tenv abduced_pv typ prop =
let struct_strexp =
Prop.create_strexp_of_type tenv Prop.Fld_init typ None Sil.inst_none in
let prop' = add_strexp_to_footprint tenv struct_strexp abduced_pv typ prop in
prop', struct_strexp
let add_constraints_on_retval tenv pdesc prop ret_exp ~has_nullable_annot typ callee_pname callee_loc=
if Procname.is_infer_undefined callee_pname then prop
else
let is_rec_call pname = (* TODO: (t7147096) extend this to detect mutual recursion *)
Procname.equal pname (Cfg.Procdesc.get_proc_name pdesc) in
let already_has_abduced_retval p abduced_ret_pv =
IList.exists
(fun hpred -> match hpred with
| Sil.Hpointsto (Exp.Lvar pv, _, _) -> Pvar.equal pv abduced_ret_pv
| _ -> false)
p.Prop.sigma_fp in
(* find an hpred [abduced] |-> A in [prop] and add [exp] = A to prop *)
let bind_exp_to_abduced_val exp_to_bind abduced prop =
let bind_exp prop = function
| Sil.Hpointsto (Exp.Lvar pv, Sil.Eexp (rhs, _), _)
when Pvar.equal pv abduced ->
Prop.conjoin_eq tenv exp_to_bind rhs prop
| _ -> prop in
IList.fold_left bind_exp prop prop.Prop.sigma in
(* To avoid obvious false positives, assume skip functions do not return null pointers *)
let add_ret_non_null exp typ prop =
if has_nullable_annot
then
do n't assume if the procedure is annotated with @Nullable
else
match typ with
| Typ.Tptr _ -> Prop.conjoin_neq tenv exp Exp.zero prop
| _ -> prop in
let add_tainted_post ret_exp callee_pname prop =
Attribute.add_or_replace tenv prop (Apred (Ataint callee_pname, [ret_exp])) in
if Config.angelic_execution && not (is_rec_call callee_pname) then
(* introduce a fresh program variable to allow abduction on the return value *)
let abduced_ret_pv = Pvar.mk_abduced_ret callee_pname callee_loc in
(* prevent introducing multiple abduced retvals for a single call site in a loop *)
if already_has_abduced_retval prop abduced_ret_pv then prop
else
let prop' =
if !Config.footprint then
let (prop', fresh_fp_var) = add_to_footprint tenv abduced_ret_pv typ prop in
Prop.conjoin_eq tenv ~footprint: true ret_exp fresh_fp_var prop'
else
(* bind return id to the abduced value pointed to by the pvar we introduced *)
bind_exp_to_abduced_val ret_exp abduced_ret_pv prop in
let prop'' = add_ret_non_null ret_exp typ prop' in
if Config.taint_analysis then
match Taint.returns_tainted callee_pname None with
| Some taint_kind ->
add_tainted_post ret_exp { taint_source = callee_pname; taint_kind; } prop''
| None -> prop''
else prop''
else add_ret_non_null ret_exp typ prop
let add_taint prop lhs_id rhs_exp pname tenv =
let add_attribute_if_field_tainted prop fieldname struct_typ =
if Taint.has_taint_annotation fieldname struct_typ
then
let taint_info = { PredSymb.taint_source = pname; taint_kind = Tk_unknown; } in
Attribute.add_or_replace tenv prop (Apred (Ataint taint_info, [Exp.Var lhs_id]))
else
prop in
match rhs_exp with
| Exp.Lfield (_, fieldname, (Tstruct typname | Tptr (Tstruct typname, _))) ->
begin
match Tenv.lookup tenv typname with
| Some struct_typ -> add_attribute_if_field_tainted prop fieldname struct_typ
| None -> prop
end
| _ -> prop
let execute_load ?(report_deref_errors=true) pname pdesc tenv id rhs_exp typ loc prop_ =
let execute_load_ pdesc tenv id loc acc_in iter =
let iter_ren = Prop.prop_iter_make_id_primed tenv id iter in
let prop_ren = Prop.prop_iter_to_prop tenv iter_ren in
match Prop.prop_iter_current tenv iter_ren with
| (Sil.Hpointsto(lexp, strexp, Exp.Sizeof (typ, len, st)), offlist) ->
let contents, new_ptsto, pred_insts_op, lookup_uninitialized =
ptsto_lookup pdesc tenv prop_ren (lexp, strexp, typ, len, st) offlist id in
let update acc (pi, sigma) =
let pi' = Sil.Aeq (Exp.Var(id), contents):: pi in
let sigma' = new_ptsto:: sigma in
let iter' = update_iter iter_ren pi' sigma' in
let prop' = Prop.prop_iter_to_prop tenv iter' in
let prop'' =
if lookup_uninitialized then
Attribute.add_or_replace tenv prop' (Apred (Adangling DAuninit, [Exp.Var id]))
else prop' in
let prop''' =
if Config.taint_analysis
then add_taint prop'' id rhs_exp pname tenv
else prop'' in
prop''' :: acc in
begin
match pred_insts_op with
| None -> update acc_in ([],[])
| Some pred_insts -> IList.rev (IList.fold_left update acc_in pred_insts)
end
| (Sil.Hpointsto _, _) ->
Errdesc.warning_err loc "no offset access in execute_load -- treating as skip@.";
(Prop.prop_iter_to_prop tenv iter_ren) :: acc_in
| _ ->
(* The implementation of this case means that we
ignore this dereferencing operator. When the analyzer treats
numerical information and arrays more precisely later, we
should change the implementation here. *)
assert false in
try
let n_rhs_exp, prop = check_arith_norm_exp tenv pname rhs_exp prop_ in
let n_rhs_exp' = Prop.exp_collapse_consecutive_indices_prop typ n_rhs_exp in
match check_constant_string_dereference n_rhs_exp' with
| Some value ->
[Prop.conjoin_eq tenv (Exp.Var id) value prop]
| None ->
let exp_get_undef_attr exp =
let fold_undef_pname callee_opt atom =
match callee_opt, atom with
| None, Sil.Apred (Aundef _, _) -> Some atom
| _ -> callee_opt in
IList.fold_left fold_undef_pname None (Attribute.get_for_exp tenv prop exp) in
let prop' =
if Config.angelic_execution then
(* when we try to deref an undefined value, add it to the footprint *)
match exp_get_undef_attr n_rhs_exp' with
| Some (Apred (Aundef (callee_pname, ret_annots, callee_loc, _), _)) ->
let has_nullable_annot = Annotations.ia_is_nullable ret_annots in
add_constraints_on_retval tenv
pdesc prop n_rhs_exp' ~has_nullable_annot typ callee_pname callee_loc
| _ -> prop
else prop in
let iter_list =
Rearrange.rearrange ~report_deref_errors pdesc tenv n_rhs_exp' typ prop' loc in
IList.rev (IList.fold_left (execute_load_ pdesc tenv id loc) [] iter_list)
with Rearrange.ARRAY_ACCESS ->
if (Config.array_level = 0) then assert false
else
let undef = Exp.get_undefined false in
[Prop.conjoin_eq tenv (Exp.Var id) undef prop_]
let load_ret_annots pname =
match AttributesTable.load_attributes pname with
| Some attrs ->
let ret_annots, _ = attrs.ProcAttributes.method_annotation in
ret_annots
| None ->
Typ.item_annotation_empty
let execute_store ?(report_deref_errors=true) pname pdesc tenv lhs_exp typ rhs_exp loc prop_ =
let execute_store_ pdesc tenv rhs_exp acc_in iter =
let (lexp, strexp, typ, len, st, offlist) =
match Prop.prop_iter_current tenv iter with
| (Sil.Hpointsto(lexp, strexp, Exp.Sizeof (typ, len, st)), offlist) ->
(lexp, strexp, typ, len, st, offlist)
| _ -> assert false in
let p = Prop.prop_iter_to_prop tenv iter in
let new_ptsto, pred_insts_op =
ptsto_update pdesc tenv p (lexp, strexp, typ, len, st) offlist rhs_exp in
let update acc (pi, sigma) =
let sigma' = new_ptsto:: sigma in
let iter' = update_iter iter pi sigma' in
let prop' = Prop.prop_iter_to_prop tenv iter' in
prop' :: acc in
match pred_insts_op with
| None -> update acc_in ([],[])
| Some pred_insts -> IList.fold_left update acc_in pred_insts in
try
let n_lhs_exp, prop_' = check_arith_norm_exp tenv pname lhs_exp prop_ in
let n_rhs_exp, prop = check_arith_norm_exp tenv pname rhs_exp prop_' in
let prop = Attribute.replace_objc_null tenv prop n_lhs_exp n_rhs_exp in
let n_lhs_exp' = Prop.exp_collapse_consecutive_indices_prop typ n_lhs_exp in
let iter_list = Rearrange.rearrange ~report_deref_errors pdesc tenv n_lhs_exp' typ prop loc in
IList.rev (IList.fold_left (execute_store_ pdesc tenv n_rhs_exp) [] iter_list)
with Rearrange.ARRAY_ACCESS ->
if (Config.array_level = 0) then assert false
else [prop_]
(** Execute [instr] with a symbolic heap [prop].*)
let rec sym_exec tenv current_pdesc _instr (prop_: Prop.normal Prop.t) path
: (Prop.normal Prop.t * Paths.Path.t) list =
let current_pname = Cfg.Procdesc.get_proc_name current_pdesc in
State.set_instr _instr; (* mark instruction last seen *)
mark prop , tenv , pdesc last seen
pay one symop
let ret_old_path pl = (* return the old path unchanged *)
IList.map (fun p -> (p, path)) pl in
let instr = match _instr with
| Sil.Call (ret, exp, par, loc, call_flags) ->
let exp' = Prop.exp_normalize_prop tenv prop_ exp in
let instr' = match exp' with
| Exp.Closure c ->
let proc_exp = Exp.Const (Const.Cfun c.name) in
let proc_exp' = Prop.exp_normalize_prop tenv prop_ proc_exp in
let par' = IList.map (fun (id_exp, _, typ) -> (id_exp, typ)) c.captured_vars in
Sil.Call (ret, proc_exp', par' @ par, loc, call_flags)
| _ ->
Sil.Call (ret, exp', par, loc, call_flags) in
instr'
| _ -> _instr in
let skip_call ?(is_objc_instance_method=false) prop path callee_pname ret_annots loc ret_ids
ret_typ_opt actual_args =
let skip_res () =
let exn = Exceptions.Skip_function (Localise.desc_skip_function callee_pname) in
Reporting.log_info current_pname exn;
L.d_strln
("Undefined function " ^ Procname.to_string callee_pname
^ ", returning undefined value.");
(match Specs.get_summary current_pname with
| None -> ()
| Some summary ->
Specs.CallStats.trace
summary.Specs.stats.Specs.call_stats callee_pname loc
(Specs.CallStats.CR_skip) !Config.footprint);
unknown_or_scan_call ~is_scan:false ret_typ_opt ret_annots Builtin.{
pdesc= current_pdesc; instr; tenv; prop_= prop; path; ret_ids; args= actual_args;
proc_name= callee_pname; loc; } in
if is_objc_instance_method then
handle_objc_instance_method_call_or_skip tenv actual_args path callee_pname prop ret_ids skip_res
else skip_res () in
let call_args prop_ proc_name args ret_ids loc = {
Builtin.pdesc = current_pdesc; instr; tenv; prop_; path; ret_ids; args; proc_name; loc; } in
match instr with
| Sil.Load (id, rhs_exp, typ, loc) ->
execute_load current_pname current_pdesc tenv id rhs_exp typ loc prop_
|> ret_old_path
| Sil.Store (lhs_exp, typ, rhs_exp, loc) ->
execute_store current_pname current_pdesc tenv lhs_exp typ rhs_exp loc prop_
|> ret_old_path
| Sil.Prune (cond, loc, true_branch, ik) ->
let prop__ = Attribute.nullify_exp_with_objc_null tenv prop_ cond in
let check_condition_always_true_false () =
let report_condition_always_true_false i =
let skip_loop = match ik with
| Sil.Ik_while | Sil.Ik_for ->
skip wile(1 ) and for (; 1 ;)
| Sil.Ik_dowhile ->
true (* skip do..while *)
| Sil.Ik_land_lor ->
true (* skip subpart of a condition obtained from compilation of && and || *)
| _ -> false in
true_branch && not skip_loop in
match Prop.exp_normalize_prop tenv Prop.prop_emp cond with
| Exp.Const (Const.Cint i) when report_condition_always_true_false i ->
let node = State.get_node () in
let desc = Errdesc.explain_condition_always_true_false tenv i cond node loc in
let exn =
Exceptions.Condition_always_true_false (desc, not (IntLit.iszero i), __POS__) in
let pre_opt = State.get_normalized_pre (Abs.abstract_no_symop current_pname) in
Reporting.log_warning current_pname ?pre:pre_opt exn
| _ -> () in
if not Config.report_runtime_exceptions then
check_already_dereferenced tenv current_pname cond prop__;
check_condition_always_true_false ();
let n_cond, prop = check_arith_norm_exp tenv current_pname cond prop__ in
ret_old_path (Propset.to_proplist (prune tenv ~positive:true n_cond prop))
| Sil.Call (ret_ids, Exp.Const (Const.Cfun callee_pname), args, loc, _)
when Builtin.is_registered callee_pname ->
let sym_exe_builtin = Builtin.get callee_pname in
sym_exe_builtin (call_args prop_ callee_pname args ret_ids loc)
| Sil.Call (ret_ids,
Exp.Const (Const.Cfun ((Procname.Java callee_pname_java) as callee_pname)),
actual_params, loc, call_flags)
when Config.lazy_dynamic_dispatch ->
let norm_prop, norm_args = normalize_params tenv current_pname prop_ actual_params in
let exec_skip_call skipped_pname ret_annots ret_type =
skip_call norm_prop path skipped_pname ret_annots loc ret_ids (Some ret_type) norm_args in
let resolved_pname, summary_opt =
resolve_and_analyze tenv current_pdesc norm_prop norm_args callee_pname call_flags in
begin
match summary_opt with
| None ->
let ret_typ = Typ.java_proc_return_typ callee_pname_java in
let ret_annots = load_ret_annots callee_pname in
exec_skip_call resolved_pname ret_annots ret_typ
| Some summary when call_should_be_skipped resolved_pname summary ->
let proc_attrs = summary.Specs.attributes in
let ret_annots, _ = proc_attrs.ProcAttributes.method_annotation in
exec_skip_call resolved_pname ret_annots proc_attrs.ProcAttributes.ret_type
| Some summary ->
proc_call summary (call_args prop_ callee_pname norm_args ret_ids loc)
end
| Sil.Call (ret_ids,
Exp.Const (Const.Cfun ((Procname.Java callee_pname_java) as callee_pname)),
actual_params, loc, call_flags) ->
do_error_checks tenv (Paths.Path.curr_node path) instr current_pname current_pdesc;
let norm_prop, norm_args = normalize_params tenv current_pname prop_ actual_params in
let url_handled_args =
call_constructor_url_update_args callee_pname norm_args in
let resolved_pnames =
resolve_virtual_pname tenv norm_prop url_handled_args callee_pname call_flags in
let exec_one_pname pname =
Ondemand.analyze_proc_name tenv ~propagate_exceptions:true current_pdesc pname;
let exec_skip_call ret_annots ret_type =
skip_call norm_prop path pname ret_annots loc ret_ids (Some ret_type) url_handled_args in
match Specs.get_summary pname with
| None ->
let ret_typ = Typ.java_proc_return_typ callee_pname_java in
let ret_annots = load_ret_annots callee_pname in
exec_skip_call ret_annots ret_typ
| Some summary when call_should_be_skipped pname summary ->
let proc_attrs = summary.Specs.attributes in
let ret_annots, _ = proc_attrs.ProcAttributes.method_annotation in
exec_skip_call ret_annots proc_attrs.ProcAttributes.ret_type
| Some summary ->
proc_call summary (call_args norm_prop pname url_handled_args ret_ids loc) in
IList.fold_left (fun acc pname -> exec_one_pname pname @ acc) [] resolved_pnames
| Sil.Call (ret_ids, Exp.Const (Const.Cfun callee_pname), actual_params, loc, call_flags) ->
Generic fun call with known name
let (prop_r, n_actual_params) = normalize_params tenv current_pname prop_ actual_params in
let resolved_pname =
match resolve_virtual_pname tenv prop_r n_actual_params callee_pname call_flags with
| resolved_pname :: _ -> resolved_pname
| [] -> callee_pname in
Ondemand.analyze_proc_name tenv ~propagate_exceptions:true current_pdesc resolved_pname;
let callee_pdesc_opt = Ondemand.get_proc_desc resolved_pname in
let ret_typ_opt = Option.map Cfg.Procdesc.get_ret_type callee_pdesc_opt in
let sentinel_result =
if !Config.curr_language = Config.Clang then
check_variadic_sentinel_if_present
(call_args prop_r callee_pname actual_params ret_ids loc)
else [(prop_r, path)] in
let do_call (prop, path) =
let summary = Specs.get_summary resolved_pname in
let should_skip resolved_pname summary =
match summary with
| None -> true
| Some summary -> call_should_be_skipped resolved_pname summary in
if should_skip resolved_pname summary then
(* If it's an ObjC getter or setter, call the builtin rather than skipping *)
let attrs_opt =
let attr_opt = Option.map Cfg.Procdesc.get_attributes callee_pdesc_opt in
match attr_opt, resolved_pname with
| Some attrs, Procname.ObjC_Cpp _ -> Some attrs
| None, Procname.ObjC_Cpp _ -> AttributesTable.load_attributes resolved_pname
| _ -> None in
let objc_property_accessor_ret_typ_opt =
match attrs_opt with
| Some attrs ->
(match attrs.ProcAttributes.objc_accessor with
| Some objc_accessor -> Some (objc_accessor, attrs.ProcAttributes.ret_type)
| None -> None)
| None -> None in
match objc_property_accessor_ret_typ_opt with
| Some (objc_property_accessor, ret_typ) ->
handle_objc_instance_method_call
n_actual_params n_actual_params prop tenv ret_ids
current_pdesc callee_pname loc path
(sym_exec_objc_accessor objc_property_accessor ret_typ)
| None ->
let ret_annots = match summary with
| Some summ ->
let ret_annots, _ = summ.Specs.attributes.ProcAttributes.method_annotation in
ret_annots
| None ->
load_ret_annots resolved_pname in
let is_objc_instance_method =
match attrs_opt with
| Some attrs -> attrs.ProcAttributes.is_objc_instance_method
| None -> false in
skip_call ~is_objc_instance_method prop path resolved_pname ret_annots loc ret_ids
ret_typ_opt n_actual_params
else
proc_call (Option.get summary)
(call_args prop resolved_pname n_actual_params ret_ids loc) in
IList.flatten (IList.map do_call sentinel_result)
| Sil.Call (ret_ids, fun_exp, actual_params, loc, call_flags) -> (* Call via function pointer *)
let (prop_r, n_actual_params) = normalize_params tenv current_pname prop_ actual_params in
if call_flags.CallFlags.cf_is_objc_block then
Rearrange.check_call_to_objc_block_error tenv current_pdesc prop_r fun_exp loc;
Rearrange.check_dereference_error tenv current_pdesc prop_r fun_exp loc;
if call_flags.CallFlags.cf_noreturn then begin
L.d_str "Unknown function pointer with noreturn attribute ";
Sil.d_exp fun_exp; L.d_strln ", diverging.";
diverge prop_r path
end else begin
L.d_str "Unknown function pointer "; Sil.d_exp fun_exp;
L.d_strln ", returning undefined value.";
let callee_pname = Procname.from_string_c_fun "__function_pointer__" in
unknown_or_scan_call ~is_scan:false None Typ.item_annotation_empty Builtin.{
pdesc= current_pdesc; instr; tenv; prop_= prop_r; path; ret_ids; args= n_actual_params;
proc_name= callee_pname; loc; }
end
| Sil.Nullify (pvar, _) ->
begin
let eprop = Prop.expose prop_ in
match IList.partition
(function
| Sil.Hpointsto (Exp.Lvar pvar', _, _) -> Pvar.equal pvar pvar'
| _ -> false) eprop.Prop.sigma with
| [Sil.Hpointsto(e, se, typ)], sigma' ->
let sigma'' =
let se' = execute_nullify_se se in
Sil.Hpointsto(e, se', typ):: sigma' in
let eprop_res = Prop.set eprop ~sigma:sigma'' in
ret_old_path [Prop.normalize tenv eprop_res]
| [], _ ->
ret_old_path [prop_]
| _ ->
L.err "Pvar %a appears on the LHS of >1 heap predicate!@." (Pvar.pp pe_text) pvar;
assert false
end
| Sil.Abstract _ ->
let node = State.get_node () in
let blocks_nullified = get_blocks_nullified node in
IList.iter (check_block_retain_cycle tenv current_pname prop_) blocks_nullified;
if Prover.check_inconsistency tenv prop_
then
ret_old_path []
else
ret_old_path
[Abs.remove_redundant_array_elements current_pname tenv
(Abs.abstract current_pname tenv prop_)]
| Sil.Remove_temps (temps, _) ->
ret_old_path [Prop.exist_quantify tenv (Sil.fav_from_list temps) prop_]
| Sil.Declare_locals (ptl, _) ->
let sigma_locals =
let add_None (x, y) = (x, Exp.Sizeof (y, None, Subtype.exact), None) in
let sigma_locals () =
IList.map
(Prop.mk_ptsto_lvar tenv Prop.Fld_init Sil.inst_initial)
(IList.map add_None ptl) in
Config.run_in_re_execution_mode (* no footprint vars for locals *)
sigma_locals () in
let sigma' = prop_.Prop.sigma @ sigma_locals in
let prop' = Prop.normalize tenv (Prop.set prop_ ~sigma:sigma') in
ret_old_path [prop']
and diverge prop path =
State.add_diverging_states (Paths.PathSet.from_renamed_list [(prop, path)]); (* diverge *)
[]
(** Symbolic execution of a sequence of instructions.
If errors occur and [mask_errors] is true, just treat as skip. *)
and instrs ?(mask_errors=false) tenv pdesc instrs ppl =
let exe_instr instr (p, path) =
L.d_str "Executing Generated Instruction "; Sil.d_instr instr; L.d_ln ();
try sym_exec tenv pdesc instr p path
with exn when SymOp.exn_not_failure exn && mask_errors ->
let err_name, _, ml_source, _ , _, _, _ = Exceptions.recognize_exception exn in
let loc = (match ml_source with
| Some ml_loc -> "at " ^ (L.ml_loc_to_string ml_loc)
| None -> "") in
L.d_warning
("Generated Instruction Failed with: " ^
(Localise.to_string err_name)^loc ); L.d_ln();
[(p, path)] in
let f plist instr = IList.flatten (IList.map (exe_instr instr) plist) in
IList.fold_left f ppl instrs
and add_constraints_on_actuals_by_ref tenv prop actuals_by_ref callee_pname callee_loc =
(* replace an hpred of the form actual_var |-> _ with new_hpred in prop *)
let replace_actual_hpred actual_var new_hpred prop =
let sigma' =
IList.map
(function
| Sil.Hpointsto (lhs, _, _) when Exp.equal lhs actual_var -> new_hpred
| hpred -> hpred)
prop.Prop.sigma in
Prop.normalize tenv (Prop.set prop ~sigma:sigma') in
let add_actual_by_ref_to_footprint prop (actual, actual_typ, _) =
match actual with
| Exp.Lvar actual_pv ->
(* introduce a fresh program variable to allow abduction on the return value *)
let abduced_ref_pv =
Pvar.mk_abduced_ref_param callee_pname actual_pv callee_loc in
let already_has_abduced_retval p =
IList.exists
(fun hpred -> match hpred with
| Sil.Hpointsto (Exp.Lvar pv, _, _) -> Pvar.equal pv abduced_ref_pv
| _ -> false)
p.Prop.sigma_fp in
(* prevent introducing multiple abduced retvals for a single call site in a loop *)
if already_has_abduced_retval prop then prop
else
if !Config.footprint then
let prop', abduced_strexp =
match actual_typ with
| Typ.Tptr ((Tstruct _) as typ, _) ->
(* for struct types passed by reference, do abduction on the fields of the
struct *)
add_struct_value_to_footprint tenv abduced_ref_pv typ prop
| Typ.Tptr (typ, _) ->
(* for pointer types passed by reference, do abduction directly on the pointer *)
let (prop', fresh_fp_var) =
add_to_footprint tenv abduced_ref_pv typ prop in
prop', Sil.Eexp (fresh_fp_var, Sil.Inone)
| typ ->
failwith
("No need for abduction on non-pointer type " ^
(Typ.to_string typ)) in
(* replace [actual] |-> _ with [actual] |-> [fresh_fp_var] *)
let filtered_sigma =
IList.map
(function
| Sil.Hpointsto (lhs, _, typ_exp) when Exp.equal lhs actual ->
Sil.Hpointsto (lhs, abduced_strexp, typ_exp)
| hpred -> hpred)
prop'.Prop.sigma in
Prop.normalize tenv (Prop.set prop' ~sigma:filtered_sigma)
else
(* bind actual passed by ref to the abduced value pointed to by the synthetic pvar *)
let prop' =
let filtered_sigma =
IList.filter
(function
| Sil.Hpointsto (lhs, _, _) when Exp.equal lhs actual ->
false
| _ -> true)
prop.Prop.sigma in
Prop.normalize tenv (Prop.set prop ~sigma:filtered_sigma) in
IList.fold_left
(fun p hpred ->
match hpred with
| Sil.Hpointsto (Exp.Lvar pv, rhs, texp) when Pvar.equal pv abduced_ref_pv ->
let new_hpred = Sil.Hpointsto (actual, rhs, texp) in
Prop.normalize tenv (Prop.set p ~sigma:(new_hpred :: prop'.Prop.sigma))
| _ -> p)
prop'
prop'.Prop.sigma
| _ -> assert false in
(* non-angelic mode; havoc each var passed by reference by assigning it to a fresh id *)
let havoc_actual_by_ref prop (actual, actual_typ, _) =
let actual_pt_havocd_var =
let havocd_var = Exp.Var (Ident.create_fresh Ident.kprimed) in
let sizeof_exp = Exp.Sizeof (Typ.strip_ptr actual_typ, None, Subtype.subtypes) in
Prop.mk_ptsto tenv actual (Sil.Eexp (havocd_var, Sil.Inone)) sizeof_exp in
replace_actual_hpred actual actual_pt_havocd_var prop in
let do_actual_by_ref =
if Config.angelic_execution then add_actual_by_ref_to_footprint
else havoc_actual_by_ref in
let non_const_actuals_by_ref =
let is_not_const (e, _, i) =
match AttributesTable.load_attributes callee_pname with
| Some attrs ->
let is_const = IList.mem int_equal i attrs.ProcAttributes.const_formals in
if is_const then (
L.d_str (Printf.sprintf "Not havocing const argument number %d: " i);
Sil.d_exp e;
L.d_ln ()
);
not is_const
| None ->
true in
IList.filter is_not_const actuals_by_ref in
IList.fold_left do_actual_by_ref prop non_const_actuals_by_ref
and check_untainted tenv exp taint_kind caller_pname callee_pname prop =
match Attribute.get_taint tenv prop exp with
| Some (Apred (Ataint taint_info, _)) ->
let err_desc =
Errdesc.explain_tainted_value_reaching_sensitive_function
prop
exp
taint_info
callee_pname
(State.get_loc ()) in
let exn =
Exceptions.Tainted_value_reaching_sensitive_function
(err_desc, __POS__) in
Reporting.log_warning caller_pname exn;
Attribute.add_or_replace tenv prop (Apred (Auntaint taint_info, [exp]))
| _ ->
if !Config.footprint then
let taint_info = { PredSymb.taint_source = callee_pname; taint_kind; } in
(* add untained(n_lexp) to the footprint *)
Attribute.add tenv ~footprint:true prop (Auntaint taint_info) [exp]
else prop
(** execute a call for an unknown or scan function *)
and unknown_or_scan_call ~is_scan ret_type_option ret_annots
{ Builtin.tenv; pdesc; prop_= pre; path; ret_ids;
args; proc_name= callee_pname; loc; instr; } =
let remove_file_attribute prop =
let do_exp p (e, _) =
let do_attribute q atom =
match atom with
| Sil.Apred ((Aresource {ra_res = Rfile} as res), _) -> Attribute.remove_for_attr tenv q res
| _ -> q in
IList.fold_left do_attribute p (Attribute.get_for_exp tenv p e) in
let filtered_args =
match args, instr with
| _:: other_args, Sil.Call (_, _, _, _, { CallFlags.cf_virtual }) when cf_virtual ->
(* Do not remove the file attribute on the reciver for virtual calls *)
other_args
| _ -> args in
IList.fold_left do_exp prop filtered_args in
let add_tainted_pre prop actuals caller_pname callee_pname =
if Config.taint_analysis then
match Taint.accepts_sensitive_params callee_pname None with
| [] -> prop
| param_nums ->
let check_taint_if_nums_match (prop_acc, param_num) (actual_exp, _actual_typ) =
let prop_acc' =
try
let _, taint_kind = IList.find (fun (num, _) -> num = param_num) param_nums in
check_untainted tenv actual_exp taint_kind caller_pname callee_pname prop_acc
with Not_found -> prop_acc in
prop_acc', param_num + 1 in
IList.fold_left
check_taint_if_nums_match
(prop, 0)
actuals
|> fst
else prop in
let actuals_by_ref =
IList.flatten_options (IList.mapi
(fun i actual -> match actual with
| (Exp.Lvar _ as e, (Typ.Tptr _ as t)) -> Some (e, t, i)
| _ -> None)
args) in
let has_nullable_annot = Annotations.ia_is_nullable ret_annots in
let pre_final =
in Java , assume that skip functions close resources passed as params
let pre_1 =
if Procname.is_java callee_pname
then remove_file_attribute pre
else pre in
let pre_2 = match ret_ids, ret_type_option with
| [ret_id], Some ret_typ ->
add_constraints_on_retval tenv
pdesc pre_1 (Exp.Var ret_id) ret_typ ~has_nullable_annot callee_pname loc
| _ ->
pre_1 in
let pre_3 = add_constraints_on_actuals_by_ref tenv pre_2 actuals_by_ref callee_pname loc in
let caller_pname = Cfg.Procdesc.get_proc_name pdesc in
add_tainted_pre pre_3 args caller_pname callee_pname in
if is_scan (* if scan function, don't mark anything with undef attributes *)
then [(Tabulation.remove_constant_string_class tenv pre_final, path)]
else
(* otherwise, add undefined attribute to retvals and actuals passed by ref *)
let exps_to_mark =
let ret_exps = IList.map (fun ret_id -> Exp.Var ret_id) ret_ids in
IList.fold_left
(fun exps_to_mark (exp, _, _) -> exp :: exps_to_mark) ret_exps actuals_by_ref in
let prop_with_undef_attr =
let path_pos = State.get_path_pos () in
Attribute.mark_vars_as_undefined tenv
pre_final exps_to_mark callee_pname ret_annots loc path_pos in
[(prop_with_undef_attr, path)]
and check_variadic_sentinel
?(fails_on_nil = false) n_formals (sentinel, null_pos)
{ Builtin.pdesc; tenv; prop_; path; args; proc_name; loc; }
=
(* from clang's lib/Sema/SemaExpr.cpp: *)
(* "nullPos" is the number of formal parameters at the end which *)
(* effectively count as part of the variadic arguments. This is *)
(* useful if you would prefer to not have *any* formal parameters, *)
but the language forces you to have at least one .
let first_var_arg_pos = if null_pos > n_formals then 0 else n_formals - null_pos in
let nargs = IList.length args in
(* sentinels start counting from the last argument to the function *)
let sentinel_pos = nargs - sentinel - 1 in
let mk_non_terminal_argsi (acc, i) a =
if i < first_var_arg_pos || i >= sentinel_pos then (acc, i +1)
else ((a, i):: acc, i +1) in
(* IList.fold_left reverses the arguments *)
let non_terminal_argsi = fst (IList.fold_left mk_non_terminal_argsi ([], 0) args) in
let check_allocated result ((lexp, typ), i) =
(* simulate a Load for [lexp] *)
let tmp_id_deref = Ident.create_fresh Ident.kprimed in
let load_instr = Sil.Load (tmp_id_deref, lexp, typ, loc) in
try
instrs tenv pdesc [load_instr] result
with e when SymOp.exn_not_failure e ->
if not fails_on_nil then
let deref_str = Localise.deref_str_nil_argument_in_variadic_method proc_name nargs i in
let err_desc =
Errdesc.explain_dereference tenv ~use_buckets: true ~is_premature_nil: true
deref_str prop_ loc in
raise (Exceptions.Premature_nil_termination (err_desc, __POS__))
else
raise e in
(* IList.fold_left reverses the arguments back so that we report an *)
error on the first premature nil argument
IList.fold_left check_allocated [(prop_, path)] non_terminal_argsi
and check_variadic_sentinel_if_present
({ Builtin.prop_; path; proc_name; } as builtin_args) =
match Specs.proc_resolve_attributes proc_name with
| None ->
[(prop_, path)]
| Some callee_attributes ->
match PredSymb.get_sentinel_func_attribute_value
callee_attributes.ProcAttributes.func_attributes with
| None -> [(prop_, path)]
| Some sentinel_arg ->
let formals = callee_attributes.ProcAttributes.formals in
check_variadic_sentinel (IList.length formals) sentinel_arg builtin_args
and sym_exec_objc_getter field_name ret_typ tenv ret_ids pdesc pname loc args prop =
L.d_strln ("No custom getter found. Executing the ObjC builtin getter with ivar "^
(Ident.fieldname_to_string field_name)^".");
let ret_id =
match ret_ids with
| [ret_id] -> ret_id
| _ -> assert false in
match args with
| [(lexp, (Typ.Tstruct _ as typ | Tptr (Tstruct _ as typ, _)))] ->
let field_access_exp = Exp.Lfield (lexp, field_name, typ) in
execute_load
~report_deref_errors:false pname pdesc tenv ret_id field_access_exp ret_typ loc prop
| _ -> raise (Exceptions.Wrong_argument_number __POS__)
and sym_exec_objc_setter field_name _ tenv _ pdesc pname loc args prop =
L.d_strln ("No custom setter found. Executing the ObjC builtin setter with ivar "^
(Ident.fieldname_to_string field_name)^".");
match args with
| (lexp1, (Typ.Tstruct _ as typ1 | Tptr (typ1, _))) :: (lexp2, typ2) :: _ ->
let field_access_exp = Exp.Lfield (lexp1, field_name, typ1) in
execute_store ~report_deref_errors:false pname pdesc tenv field_access_exp typ2 lexp2 loc prop
| _ -> raise (Exceptions.Wrong_argument_number __POS__)
and sym_exec_objc_accessor property_accesor ret_typ tenv ret_ids pdesc _ loc args prop path
: Builtin.ret_typ =
let f_accessor =
match property_accesor with
| ProcAttributes.Objc_getter field_name -> sym_exec_objc_getter field_name
| ProcAttributes.Objc_setter field_name -> sym_exec_objc_setter field_name in
(* we want to execute in the context of the current procedure, not in the context of callee_pname,
since this is the procname of the setter/getter method *)
let cur_pname = Cfg.Procdesc.get_proc_name pdesc in
f_accessor ret_typ tenv ret_ids pdesc cur_pname loc args prop
|> IList.map (fun p -> (p, path))
(** Perform symbolic execution for a function call *)
and proc_call summary {Builtin.pdesc; tenv; prop_= pre; path; ret_ids; args= actual_pars; loc; } =
let caller_pname = Cfg.Procdesc.get_proc_name pdesc in
let callee_pname = Specs.get_proc_name summary in
let ret_typ = Specs.get_ret_type summary in
let check_return_value_ignored () =
(* check if the return value of the call is ignored, and issue a warning *)
let is_ignored = match ret_typ, ret_ids with
| Typ.Tvoid, _ -> false
| Typ.Tint _, _ when not (proc_is_defined callee_pname) ->
if the proc returns and is not defined ,
(* don't report ignored return value *)
false
| _, [] -> true
| _, [id] -> Errdesc.id_is_assigned_then_dead (State.get_node ()) id
| _ -> false in
if is_ignored
&& Specs.get_flag callee_pname proc_flag_ignore_return = None then
let err_desc = Localise.desc_return_value_ignored callee_pname loc in
let exn = (Exceptions.Return_value_ignored (err_desc, __POS__)) in
let pre_opt = State.get_normalized_pre (Abs.abstract_no_symop caller_pname) in
Reporting.log_warning caller_pname ?pre:pre_opt exn in
check_inherently_dangerous_function caller_pname callee_pname;
begin
let formal_types = IList.map (fun (_, typ) -> typ) (Specs.get_formals summary) in
let rec comb actual_pars formal_types =
match actual_pars, formal_types with
| [], [] -> actual_pars
| (e, t_e):: etl', _:: tl' ->
(e, t_e) :: comb etl' tl'
| _,[] ->
Errdesc.warning_err
(State.get_loc ())
"likely use of variable-arguments function, or function prototype missing@.";
L.d_warning
"likely use of variable-arguments function, or function prototype missing";
L.d_ln();
L.d_str "actual parameters: "; Sil.d_exp_list (IList.map fst actual_pars); L.d_ln ();
L.d_str "formal parameters: "; Typ.d_list formal_types; L.d_ln ();
actual_pars
| [], _ ->
L.d_str ("**** ERROR: Procedure " ^ Procname.to_string callee_pname);
L.d_strln (" mismatch in the number of parameters ****");
L.d_str "actual parameters: "; Sil.d_exp_list (IList.map fst actual_pars); L.d_ln ();
L.d_str "formal parameters: "; Typ.d_list formal_types; L.d_ln ();
raise (Exceptions.Wrong_argument_number __POS__) in
let actual_params = comb actual_pars formal_types in
(* Actual parameters are associated to their formal
parameter type if there are enough formal parameters, and
to their actual type otherwise. The latter case happens
with variable - arguments functions *)
check_return_value_ignored ();
(* In case we call an objc instance method we add and extra spec *)
were the receiver is null and the semantics of the call is nop
let callee_attrs = Specs.get_attributes summary in
if (!Config.curr_language <> Config.Java) &&
(Specs.get_attributes summary).ProcAttributes.is_objc_instance_method then
handle_objc_instance_method_call actual_pars actual_params pre tenv ret_ids pdesc
callee_pname loc path (Tabulation.exe_function_call callee_attrs)
else (* non-objective-c method call. Standard tabulation *)
Tabulation.exe_function_call
callee_attrs tenv ret_ids pdesc callee_pname loc actual_params pre path
end
(** perform symbolic execution for a single prop, and check for junk *)
and sym_exec_wrapper handle_exn tenv pdesc instr ((prop: Prop.normal Prop.t), path)
: Paths.PathSet.t =
let pname = Cfg.Procdesc.get_proc_name pdesc in
let prop_primed_to_normal p = (* Rename primed vars with fresh normal vars, and return them *)
let fav = Prop.prop_fav p in
Sil.fav_filter_ident fav Ident.is_primed;
let ids_primed = Sil.fav_to_list fav in
let ids_primed_normal =
IList.map (fun id -> (id, Ident.create_fresh Ident.knormal)) ids_primed in
let ren_sub =
Sil.sub_of_list (IList.map
(fun (id1, id2) -> (id1, Exp.Var id2)) ids_primed_normal) in
let p' = Prop.normalize tenv (Prop.prop_sub ren_sub p) in
let fav_normal = Sil.fav_from_list (IList.map snd ids_primed_normal) in
p', fav_normal in
let prop_normal_to_primed fav_normal p = (* rename given normal vars to fresh primed *)
if Sil.fav_to_list fav_normal = [] then p
else Prop.exist_quantify tenv fav_normal p in
try
let pre_process_prop p =
let p', fav =
if Sil.instr_is_auxiliary instr
then p, Sil.fav_new ()
else prop_primed_to_normal p in
let p'' =
let map_res_action e ra = (* update the vpath in resource attributes *)
let vpath, _ = Errdesc.vpath_find tenv p' e in
{ ra with PredSymb.ra_vpath = vpath } in
Attribute.map_resource tenv p' map_res_action in
p'', fav in
let post_process_result fav_normal p path =
let p' = prop_normal_to_primed fav_normal p in
State.set_path path None;
let node_has_abstraction node =
let instr_is_abstraction = function
| Sil.Abstract _ -> true
| _ -> false in
IList.exists instr_is_abstraction (Cfg.Node.get_instrs node) in
let curr_node = State.get_node () in
match Cfg.Node.get_kind curr_node with
| Cfg.Node.Prune_node _ when not (node_has_abstraction curr_node) ->
(* don't check for leaks in prune nodes, unless there is abstraction anyway,*)
(* but force them into either branch *)
p'
| _ ->
check_deallocate_static_memory (Abs.abstract_junk ~original_prop: p
pname tenv p') in
~~~~~~~~~~~~~~~~~~~FOOTPATCH START~~~~~~~~~~~~~~~~~~
L.d_str "Instruction ";
Sil.d_instr instr;
L.d_ln ();
let prop', fav_normal = pre_process_prop prop in
let res_list =
no exp abstraction during sym exe
Config.run_with_abs_val_equal_zero
(fun () -> sym_exec tenv pdesc instr prop' path)
()
in
let res_list_nojunk =
IList.map
(fun (p, path) -> (post_process_result fav_normal p path, path))
res_list
in
let results =
IList.map
(fun (p, path) -> (Prop.prop_rename_primed_footprint_vars tenv p, path))
res_list_nojunk in
L.d_strln "Instruction Returns";
let printenv = Utils.pe_text in
begin
match IList.map fst results with
| hd :: _ ->
let propgraph1 = Propgraph.from_prop prop in
let propgraph2 = Propgraph.from_prop hd in
let diff = Propgraph.compute_diff Blue propgraph1 propgraph2 in
let cmap_norm = Propgraph.diff_get_colormap false diff in
let cmap_fp = Propgraph.diff_get_colormap true diff in
let pi = hd.Prop.pi in
let sigma = hd.Prop.sigma in
let pi_fp = hd.Prop.pi_fp in
let sigma_fp = hd.Prop.sigma_fp in
let sigma_all = sigma @ sigma_fp in
let pi_all = pi @ pi_fp in
let f = Footpatch_utils.new_mem_predsymb in
let g = Footpatch_utils.exn_is_changed in
let open Footpatch_assert_spec in
(* XXX RVT disable *)
let check_instantiate_fn_with_cmap fn cmap =
IList.iter
(fun v ->
match fn cmap v with
| Some pvar ->
begin
match
Footpatch_utils.lookup_hpred_typ_from_new_mem_pvar
pvar sigma
with
| Some typname ->
let curr_node = State.get_node () in
let c =
{ typ = Null_instantiate
; fixes_var_type =
Some
(Footpatch_utils.normalize_java_type_name @@
Typename.to_string typname)
; node = curr_node
; pvar = Some pvar
; insn = instr
}
in
Footpatch_assert_spec.save c
| None ->
(* No type *)
let curr_node = State.get_node () in
let c =
{ typ = Null_instantiate
; fixes_var_type = None
; node = curr_node
; pvar = Some pvar
; insn = instr
}
in
Footpatch_assert_spec.save c
end
| None -> ()) pi_all in
check_instantiate_fn_with_cmap f cmap_norm;
check_instantiate_fn_with_cmap f cmap_fp;
let check_exn_fn_with_cmap fn cmap =
IList.iter (fun v ->
L.d_strln
@@ Format.sprintf "Checking %s"
@@ Utils.pp_to_string (Sil.pp_hpred printenv) v;
match fn cmap v with
| true ->
let curr_node = State.get_node () in
let c =
{ typ = Null_exn
; fixes_var_type = None
; node = curr_node
; pvar = None
; insn = instr
}
in
Footpatch_assert_spec.save c
| false -> ()) sigma_all in
check_exn_fn_with_cmap g cmap_norm;
check_exn_fn_with_cmap g cmap_fp
| _ -> ()
end;
begin
match instr with
| Sil.Call _ ->
let open Candidate.Top_down in
let c =
{ insn = instr
; pre = prop
; post = (IList.map fst results)
; loc = Sil.instr_get_loc instr
; f = None
; pname = Procname.to_string pname
}
in
L.d_strln @@ Candidate.Top_down.to_string c;
Candidate.Top_down.save c;
| Sil.Prune _ ->
begin
try
let pre = prop in
let post = IList.map fst results |> IList.hd in
let pvar, typ =
Footpatch_utils.assert_pvar_null pre post in
let p = { Footpatch_assert_spec.pvar; typ; insn = instr } in
Footpatch_assert_spec.save_prune p
with Failure _ -> ()
end
| _ -> ()
end;
~~~~~~~~~~~~~~~~~~~FOOTPATCH END~~~~~~~~~~~~~~~~~~~~~
State.mark_instr_ok ();
Paths.PathSet.from_renamed_list results
with exn when Exceptions.handle_exception exn && !Config.footprint ->
calls State.mark_instr_fail
if Config.nonstop
then
(* in nonstop mode treat the instruction as skip *)
(Paths.PathSet.from_renamed_list [(prop, path)])
else
Paths.PathSet.empty
(** {2 Lifted Abstract Transfer Functions} *)
let node handle_exn tenv node (pset : Paths.PathSet.t) : Paths.PathSet.t =
let pdesc = Cfg.Node.get_proc_desc node in
let pname = Cfg.Procdesc.get_proc_name pdesc in
let exe_instr_prop instr p tr (pset1: Paths.PathSet.t) =
let pset2 =
if Tabulation.prop_is_exn pname p && not (Sil.instr_is_auxiliary instr)
&& Cfg.Node.get_kind node <> Cfg.Node.exn_handler_kind
(* skip normal instructions if an exception was thrown,
unless this is an exception handler node *)
then
begin
L.d_str "Skipping instr "; Sil.d_instr instr; L.d_strln " due to exception";
Paths.PathSet.from_renamed_list [(p, tr)]
end
else sym_exec_wrapper handle_exn tenv pdesc instr (p, tr) in
Paths.PathSet.union pset2 pset1 in
let exe_instr_pset pset instr =
Paths.PathSet.fold (exe_instr_prop instr) pset Paths.PathSet.empty in
IList.fold_left exe_instr_pset pset (Cfg.Node.get_instrs node)
| null | https://raw.githubusercontent.com/squaresLab/footpatch/8b79c1964d89b833179aed7ed4fde0638a435782/infer/src/backend/symExec.ml | ocaml | * Symbolic Execution
* Given a node, returns a list of pvar of blocks that have been nullified in the block.
* Given a proposition and an objc block checks whether by existentially quantifying
captured variables in the block we obtain a leak.
java allocation initializes with default values
we are in a lookup of an uninitialized value
a lookup does not change an inst unless it is inst_initial
This case should not happen. The rearrangement should
have materialized all the accessed cells.
return a nondeterministic value if the index is not found after rearrangement
This case should not happen. The rearrangement should
have materialized all the accessed cells.
true if we have looked up an uninitialized value
* Do pruning for conditional [if (e1 != e2) ] if [positive] is true
and [(if (e1 == e2)] if [positive] is false
build the pruning condition and its negation, as explained in
the comment above
take polarity into account
check skip flag
skip abstract methods
treat calls with no specs as skip functions in angelic mode
* In case of constant string dereference, return the result immediately
* Normalize an expression and check for arithmetic problems
* Check if [cond] is testing for NULL a pointer already dereferenced
* Check whether symbolic execution de-allocated a stack variable or a constant string,
raising an exception in that case
ObjC/C++ case : The attribute map will only exist when we have code for the method or
the method has been called directly somewhere. It can still be that this is not the
case but we have a model for the method.
the type of the receiver according to the function signature
if this is not a virtual or interface call, there's no need for resolution
default mode for Obj-C/C++/Java virtual calls: resolution only
virtual call--either [called_pname] or an override in some subtype may be called
interface call--[called_pname] has no implementation), we don't want to consider
interface call, don't want to consider
return true if (receiver typ of [target_pname]) <: [actual_receiver_typ]
make sure [resolved_pname] is not a duplicate
* Resolve the name of the procedure to call based on the type of the arguments
* Resolve the procedure name and run the analysis of the resolved procedure
if not already analyzed
Create the type sprecialized procedure description and analyze it directly
* recognize calls to the constructor java.net.URL and splits the argument string
to be only the protocol.
This method is used to handle the special semantics of ObjC instance method calls.
res = [obj foo]
(obj = null, res = null), (obj != null, res = [obj foo])
We want the same behavior even when we are going to skip the function.
objective-c instance method with a null receiver just return objc_null(res)
We wish to nullify the result. However, in some cases,
we want to add the attribute OBJC_NULL to it so that we
returns: (objc_null(res) /\ receiver=0) or an empty list of results
Not known if receiver = 0 and not footprint. Standard tabulation
This method handles ObjC instance method calls, in particular the fact that calling a method
with nil returns nil. The exec_call function is either standard call execution or execution
of ObjC getters and setters using a builtin.
the current abduction mechanism treats struct values differently than all other types. abduction
on struct values adds a a struct whose fields are initialized to fresh footprint vars to the
footprint. regular abduction just adds a fresh footprint value of the correct type to the
footprint. we can get rid of this special case if we fix the abduction on struct values
TODO: (t7147096) extend this to detect mutual recursion
find an hpred [abduced] |-> A in [prop] and add [exp] = A to prop
To avoid obvious false positives, assume skip functions do not return null pointers
introduce a fresh program variable to allow abduction on the return value
prevent introducing multiple abduced retvals for a single call site in a loop
bind return id to the abduced value pointed to by the pvar we introduced
The implementation of this case means that we
ignore this dereferencing operator. When the analyzer treats
numerical information and arrays more precisely later, we
should change the implementation here.
when we try to deref an undefined value, add it to the footprint
* Execute [instr] with a symbolic heap [prop].
mark instruction last seen
return the old path unchanged
skip do..while
skip subpart of a condition obtained from compilation of && and ||
If it's an ObjC getter or setter, call the builtin rather than skipping
Call via function pointer
no footprint vars for locals
diverge
* Symbolic execution of a sequence of instructions.
If errors occur and [mask_errors] is true, just treat as skip.
replace an hpred of the form actual_var |-> _ with new_hpred in prop
introduce a fresh program variable to allow abduction on the return value
prevent introducing multiple abduced retvals for a single call site in a loop
for struct types passed by reference, do abduction on the fields of the
struct
for pointer types passed by reference, do abduction directly on the pointer
replace [actual] |-> _ with [actual] |-> [fresh_fp_var]
bind actual passed by ref to the abduced value pointed to by the synthetic pvar
non-angelic mode; havoc each var passed by reference by assigning it to a fresh id
add untained(n_lexp) to the footprint
* execute a call for an unknown or scan function
Do not remove the file attribute on the reciver for virtual calls
if scan function, don't mark anything with undef attributes
otherwise, add undefined attribute to retvals and actuals passed by ref
from clang's lib/Sema/SemaExpr.cpp:
"nullPos" is the number of formal parameters at the end which
effectively count as part of the variadic arguments. This is
useful if you would prefer to not have *any* formal parameters,
sentinels start counting from the last argument to the function
IList.fold_left reverses the arguments
simulate a Load for [lexp]
IList.fold_left reverses the arguments back so that we report an
we want to execute in the context of the current procedure, not in the context of callee_pname,
since this is the procname of the setter/getter method
* Perform symbolic execution for a function call
check if the return value of the call is ignored, and issue a warning
don't report ignored return value
Actual parameters are associated to their formal
parameter type if there are enough formal parameters, and
to their actual type otherwise. The latter case happens
with variable - arguments functions
In case we call an objc instance method we add and extra spec
non-objective-c method call. Standard tabulation
* perform symbolic execution for a single prop, and check for junk
Rename primed vars with fresh normal vars, and return them
rename given normal vars to fresh primed
update the vpath in resource attributes
don't check for leaks in prune nodes, unless there is abstraction anyway,
but force them into either branch
XXX RVT disable
No type
in nonstop mode treat the instruction as skip
* {2 Lifted Abstract Transfer Functions}
skip normal instructions if an exception was thrown,
unless this is an exception handler node |
* Copyright ( c ) 2009 - 2013 Monoidics ltd .
* Copyright ( c ) 2013 - present Facebook , Inc.
* All rights reserved .
*
* This source code is licensed under the BSD style license found in the
* LICENSE file in the root directory of this source tree . An additional grant
* of patent rights can be found in the PATENTS file in the same directory .
* Copyright (c) 2009 - 2013 Monoidics ltd.
* Copyright (c) 2013 - present Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*)
open! Utils
module L = Logging
module F = Format
let rec fldlist_assoc fld = function
| [] -> raise Not_found
| (fld', x, _):: l -> if Ident.fieldname_equal fld fld' then x else fldlist_assoc fld l
let unroll_type tenv (typ: Typ.t) (off: Sil.offset) =
let fail fld_to_string fld =
L.d_strln ".... Invalid Field Access ....";
L.d_str ("Fld : " ^ fld_to_string fld); L.d_ln ();
L.d_str "Type : "; Typ.d_full typ; L.d_ln ();
raise (Exceptions.Bad_footprint __POS__)
in
match (typ, off) with
| Tstruct name, Off_fld (fld, _) -> (
match Tenv.lookup tenv name with
| Some { fields; statics } -> (
try fldlist_assoc fld (fields @ statics)
with Not_found -> fail Ident.fieldname_to_string fld
)
| None ->
fail Ident.fieldname_to_string fld
)
| Tarray (typ', _), Off_index _ ->
typ'
| _, Off_index (Const (Cint i)) when IntLit.iszero i ->
typ
| _ ->
fail Sil.offset_to_string off
let get_blocks_nullified node =
let null_blocks = IList.flatten(IList.map (fun i -> match i with
| Sil.Nullify(pvar, _) when Sil.is_block_pvar pvar -> [pvar]
| _ -> []) (Cfg.Node.get_instrs node)) in
null_blocks
let check_block_retain_cycle tenv caller_pname prop block_nullified =
let mblock = Pvar.get_name block_nullified in
let block_pname = Procname.mangled_objc_block (Mangled.to_string mblock) in
let block_captured =
match AttributesTable.load_attributes block_pname with
| Some attributes ->
fst (IList.split attributes.ProcAttributes.captured)
| None ->
[] in
let prop' = Cfg.remove_seed_captured_vars_block tenv block_captured prop in
let prop'' = Prop.prop_rename_fav_with_existentials tenv prop' in
let _ : Prop.normal Prop.t = Abs.abstract_junk ~original_prop: prop caller_pname tenv prop'' in
()
* Apply function [ f ] to the expression at position [ offlist ] in [ strexp ] .
If not found , expand [ strexp ] and apply [ f ] to [ None ] .
The routine should maintain the invariant that strexp and typ correspond to
each other exactly , without involving any re - interpretation of some type t
as the t array . The [ fp_root ] parameter indicates whether the kind of the
root expression of the corresponding pointsto predicate is a footprint identifier .
The function can expand a list of higher - order [ hpara_psto ] predicates , if
the list is stored at [ offlist ] in [ strexp ] initially . The expanded list
is returned as a part of the result . All these happen under [ p ] , so that it
is sound to call the prover with [ p ] . Finally , before running this function ,
the tool should run strexp_extend_value in rearrange.ml for the same strexp
and offlist , so that all the necessary extensions of strexp are done before
this function . If the tool follows this protocol , it will never hit the assert
false cases for field and array accesses .
If not found, expand [strexp] and apply [f] to [None].
The routine should maintain the invariant that strexp and typ correspond to
each other exactly, without involving any re - interpretation of some type t
as the t array. The [fp_root] parameter indicates whether the kind of the
root expression of the corresponding pointsto predicate is a footprint identifier.
The function can expand a list of higher - order [hpara_psto] predicates, if
the list is stored at [offlist] in [strexp] initially. The expanded list
is returned as a part of the result. All these happen under [p], so that it
is sound to call the prover with [p]. Finally, before running this function,
the tool should run strexp_extend_value in rearrange.ml for the same strexp
and offlist, so that all the necessary extensions of strexp are done before
this function. If the tool follows this protocol, it will never hit the assert
false cases for field and array accesses. *)
let rec apply_offlist
pdesc tenv p fp_root nullify_struct (root_lexp, strexp, typ) offlist
(f: Exp.t option -> Exp.t) inst lookup_inst =
let pname = Cfg.Procdesc.get_proc_name pdesc in
let pp_error () =
L.d_strln ".... Invalid Field ....";
L.d_str "strexp : "; Sil.d_sexp strexp; L.d_ln ();
L.d_str "offlist : "; Sil.d_offset_list offlist; L.d_ln ();
L.d_str "type : "; Typ.d_full typ; L.d_ln ();
L.d_str "prop : "; Prop.d_prop p; L.d_ln (); L.d_ln () in
match offlist, strexp, typ with
| [], Sil.Eexp (e, inst_curr), _ ->
let inst_is_uninitialized = function
| Sil.Ialloc ->
!Config.curr_language <> Config.Java
| Sil.Iinitial -> true
| _ -> false in
let is_hidden_field () =
match State.get_instr () with
| Some (Sil.Load (_, Exp.Lfield (_, fieldname, _), _, _)) ->
Ident.fieldname_is_hidden fieldname
| _ -> false in
let inst_new = match inst with
| Sil.Ilookup when inst_is_uninitialized inst_curr && not (is_hidden_field()) ->
lookup_inst := Some inst_curr;
let alloc_attribute_opt =
if inst_curr = Sil.Iinitial then None
else Attribute.get_undef tenv p root_lexp in
let deref_str = Localise.deref_str_uninitialized alloc_attribute_opt in
let err_desc = Errdesc.explain_memory_access tenv deref_str p (State.get_loc ()) in
let exn = (Exceptions.Uninitialized_value (err_desc, __POS__)) in
let pre_opt = State.get_normalized_pre (Abs.abstract_no_symop pname) in
Reporting.log_warning pname ?pre:pre_opt exn;
Sil.update_inst inst_curr inst
lookup_inst := Some inst_curr;
inst_curr
| _ -> Sil.update_inst inst_curr inst in
let e' = f (Some e) in
(e', Sil.Eexp (e', inst_new), typ, None)
| [], Sil.Estruct (fesl, inst'), _ ->
if not nullify_struct then (f None, Sil.Estruct (fesl, inst'), typ, None)
else if fp_root then (pp_error(); assert false)
else
begin
L.d_strln "WARNING: struct assignment treated as nondeterministic assignment";
(f None, Prop.create_strexp_of_type tenv Prop.Fld_init typ None inst, typ, None)
end
| [], Sil.Earray _, _ ->
let offlist' = (Sil.Off_index Exp.zero):: offlist in
apply_offlist
pdesc tenv p fp_root nullify_struct (root_lexp, strexp, typ) offlist' f inst lookup_inst
| (Sil.Off_fld _) :: _, Sil.Earray _, _ ->
let offlist_new = Sil.Off_index(Exp.zero) :: offlist in
apply_offlist
pdesc tenv p fp_root nullify_struct (root_lexp, strexp, typ) offlist_new f inst lookup_inst
| (Sil.Off_fld (fld, fld_typ)) :: offlist', Sil.Estruct (fsel, inst'), Typ.Tstruct name -> (
match Tenv.lookup tenv name with
| Some ({fields} as struct_typ) -> (
let t' = unroll_type tenv typ (Sil.Off_fld (fld, fld_typ)) in
match IList.find (fun fse -> Ident.fieldname_equal fld (fst fse)) fsel with
| _, se' ->
let res_e', res_se', res_t', res_pred_insts_op' =
apply_offlist
pdesc tenv p fp_root nullify_struct
(root_lexp, se', t') offlist' f inst lookup_inst in
let replace_fse fse =
if Ident.fieldname_equal fld (fst fse) then (fld, res_se') else fse in
let res_se = Sil.Estruct (IList.map replace_fse fsel, inst') in
let replace_fta (f, t, a) =
if Ident.fieldname_equal fld f then (fld, res_t', a) else (f, t, a) in
let fields' = IList.map replace_fta fields in
ignore (Tenv.mk_struct tenv ~default:struct_typ ~fields:fields' name) ;
(res_e', res_se, typ, res_pred_insts_op')
| exception Not_found ->
pp_error();
assert false
)
| None ->
pp_error();
assert false
)
| (Sil.Off_fld _) :: _, _, _ ->
pp_error();
assert false
| (Sil.Off_index idx) :: offlist', Sil.Earray (len, esel, inst1), Typ.Tarray (t', len') -> (
let nidx = Prop.exp_normalize_prop tenv p idx in
try
let idx_ese', se' = IList.find (fun ese -> Prover.check_equal tenv p nidx (fst ese)) esel in
let res_e', res_se', res_t', res_pred_insts_op' =
apply_offlist
pdesc tenv p fp_root nullify_struct
(root_lexp, se', t') offlist' f inst lookup_inst in
let replace_ese ese =
if Exp.equal idx_ese' (fst ese)
then (idx_ese', res_se')
else ese in
let res_se = Sil.Earray (len, IList.map replace_ese esel, inst1) in
let res_t = Typ.Tarray (res_t', len') in
(res_e', res_se, res_t, res_pred_insts_op')
with Not_found ->
L.d_str "apply_offlist: index "; Sil.d_exp idx;
L.d_strln " not materialized -- returning nondeterministic value";
let res_e' = Exp.Var (Ident.create_fresh Ident.kprimed) in
(res_e', strexp, typ, None)
)
| (Sil.Off_index _) :: _, _, _ ->
pp_error();
raise (Exceptions.Internal_error (Localise.verbatim_desc "Array out of bounds in Symexec"))
* Given [ |- > se : typ ] , if the location [ offlist ] exists in [ se ] ,
function [ ptsto_lookup p ( , se , ) offlist i d ] returns a tuple .
The first component of the tuple is an expression at position [ offlist ] in [ se ] .
The second component is an expansion of the predicate [ |- > se : typ ] ,
where the entity at [ offlist ] in [ se ] is expanded if the entity is a list of
higher - order parameters [ hpara_psto ] . If this expansion happens ,
the last component of the tuple is a list of pi - sigma pairs obtained
by instantiating the [ hpara_psto ] list . Otherwise , the last component is None .
All these steps happen under [ p ] . So , we can call a prover with [ p ] .
Finally , before running this function , the tool should run strexp_extend_value
in rearrange.ml for the same se and offlist , so that all the necessary
extensions of se are done before this function .
function [ptsto_lookup p (lexp, se, typ) offlist id] returns a tuple.
The first component of the tuple is an expression at position [offlist] in [se].
The second component is an expansion of the predicate [lexp |-> se: typ],
where the entity at [offlist] in [se] is expanded if the entity is a list of
higher - order parameters [hpara_psto]. If this expansion happens,
the last component of the tuple is a list of pi - sigma pairs obtained
by instantiating the [hpara_psto] list. Otherwise, the last component is None.
All these steps happen under [p]. So, we can call a prover with [p].
Finally, before running this function, the tool should run strexp_extend_value
in rearrange.ml for the same se and offlist, so that all the necessary
extensions of se are done before this function. *)
let ptsto_lookup pdesc tenv p (lexp, se, typ, len, st) offlist id =
let f =
function Some exp -> exp | None -> Exp.Var id in
let fp_root =
match lexp with Exp.Var id -> Ident.is_footprint id | _ -> false in
let lookup_inst = ref None in
let e', se', typ', pred_insts_op' =
apply_offlist
pdesc tenv p fp_root false (lexp, se, typ) offlist f Sil.inst_lookup lookup_inst in
match !lookup_inst with
| Some (Sil.Iinitial | Sil.Ialloc | Sil.Ilookup) -> true
| _ -> false in
let ptsto' = Prop.mk_ptsto tenv lexp se' (Exp.Sizeof (typ', len, st)) in
(e', ptsto', pred_insts_op', lookup_uninitialized)
* [ ptsto_update p ( , se , ) offlist exp ] takes
[ |- > se : typ ] , and updates [ se ] by replacing the
expression at [ offlist ] with [ exp ] . Then , it returns
the updated pointsto predicate . If [ |- > se : typ ] gets
expanded during this update , the generated pi - sigma list from
the expansion gets returned , and otherwise , None is returned .
All these happen under the proposition [ p ] , so it is ok call
prover with [ p ] . Finally , before running this function ,
the tool should run strexp_extend_value in rearrange.ml for the same
se and offlist , so that all the necessary extensions of se are done
before this function .
[lexp |-> se: typ], and updates [se] by replacing the
expression at [offlist] with [exp]. Then, it returns
the updated pointsto predicate. If [lexp |-> se: typ] gets
expanded during this update, the generated pi - sigma list from
the expansion gets returned, and otherwise, None is returned.
All these happen under the proposition [p], so it is ok call
prover with [p]. Finally, before running this function,
the tool should run strexp_extend_value in rearrange.ml for the same
se and offlist, so that all the necessary extensions of se are done
before this function. *)
let ptsto_update pdesc tenv p (lexp, se, typ, len, st) offlist exp =
let f _ = exp in
let fp_root =
match lexp with Exp.Var id -> Ident.is_footprint id | _ -> false in
let lookup_inst = ref None in
let _, se', typ', pred_insts_op' =
let pos = State.get_path_pos () in
apply_offlist
pdesc tenv p fp_root true (lexp, se, typ) offlist f (State.get_inst_update pos) lookup_inst in
let ptsto' = Prop.mk_ptsto tenv lexp se' (Exp.Sizeof (typ', len, st)) in
(ptsto', pred_insts_op')
let update_iter iter pi sigma =
let iter' = Prop.prop_iter_update_current_by_list iter sigma in
IList.fold_left (Prop.prop_iter_add_atom false) iter' pi
* Precondition : se should not include hpara_psto
that could mean nonempty heaps .
that could mean nonempty heaps. *)
let rec execute_nullify_se = function
| Sil.Eexp _ ->
Sil.Eexp (Exp.zero, Sil.inst_nullify)
| Sil.Estruct (fsel, _) ->
let fsel' = IList.map (fun (fld, se) -> (fld, execute_nullify_se se)) fsel in
Sil.Estruct (fsel', Sil.inst_nullify)
| Sil.Earray (len, esel, _) ->
let esel' = IList.map (fun (idx, se) -> (idx, execute_nullify_se se)) esel in
Sil.Earray (len, esel', Sil.inst_nullify)
let prune_ne tenv ~positive e1 e2 prop =
let is_inconsistent =
if positive then Prover.check_equal tenv prop e1 e2
else Prover.check_disequal tenv prop e1 e2 in
if is_inconsistent then Propset.empty
else
let conjoin = if positive then Prop.conjoin_neq else Prop.conjoin_eq in
let new_prop = conjoin tenv ~footprint: (!Config.footprint) e1 e2 prop in
if Prover.check_inconsistency tenv new_prop then Propset.empty
else Propset.singleton tenv new_prop
* Do pruning for conditional " if ( [ e1 ] CMP [ e2 ] ) " if [ positive ] is
true and " if ( ! ( [ e1 ] CMP [ e2 ] ) ) " if [ positive ] is false , where CMP
is " < " if [ is_strict ] is true and " < = " if [ is_strict ] is false .
true and "if (!([e1] CMP [e2]))" if [positive] is false, where CMP
is "<" if [is_strict] is true and "<=" if [is_strict] is false.
*)
let prune_ineq tenv ~is_strict ~positive prop e1 e2 =
if Exp.equal e1 e2 then
if (positive && not is_strict) || (not positive && is_strict) then
Propset.singleton tenv prop
else Propset.empty
else
build [ e1 ] CMP [ e2 ]
let cmp = if is_strict then Binop.Lt else Binop.Le in
let e1_cmp_e2 = Exp.BinOp (cmp, e1, e2) in
build ! ( [ e1 ] CMP [ e2 ] )
let dual_cmp = if is_strict then Binop.Le else Binop.Lt in
let not_e1_cmp_e2 = Exp.BinOp (dual_cmp, e2, e1) in
let (prune_cond, not_prune_cond) =
if positive then (e1_cmp_e2, not_e1_cmp_e2)
else (not_e1_cmp_e2, e1_cmp_e2) in
let is_inconsistent = Prover.check_atom tenv prop (Prop.mk_inequality tenv not_prune_cond) in
if is_inconsistent then Propset.empty
else
let footprint = !Config.footprint in
let prop_with_ineq = Prop.conjoin_eq tenv ~footprint prune_cond Exp.one prop in
Propset.singleton tenv prop_with_ineq
let rec prune tenv ~positive condition prop =
match condition with
| Exp.Var _ | Exp.Lvar _ ->
prune_ne tenv ~positive condition Exp.zero prop
| Exp.Const (Const.Cint i) when IntLit.iszero i ->
if positive then Propset.empty else Propset.singleton tenv prop
| Exp.Const (Const.Cint _ | Const.Cstr _ | Const.Cclass _) | Exp.Sizeof _ ->
if positive then Propset.singleton tenv prop else Propset.empty
| Exp.Const _ ->
assert false
| Exp.Cast (_, condition') ->
prune tenv ~positive condition' prop
| Exp.UnOp (Unop.LNot, condition', _) ->
prune tenv ~positive:(not positive) condition' prop
| Exp.UnOp _ ->
assert false
| Exp.BinOp (Binop.Eq, e, Exp.Const (Const.Cint i))
| Exp.BinOp (Binop.Eq, Exp.Const (Const.Cint i), e)
when IntLit.iszero i && not (IntLit.isnull i) ->
prune tenv ~positive:(not positive) e prop
| Exp.BinOp (Binop.Eq, e1, e2) ->
prune_ne tenv ~positive:(not positive) e1 e2 prop
| Exp.BinOp (Binop.Ne, e, Exp.Const (Const.Cint i))
| Exp.BinOp (Binop.Ne, Exp.Const (Const.Cint i), e)
when IntLit.iszero i && not (IntLit.isnull i) ->
prune tenv ~positive e prop
| Exp.BinOp (Binop.Ne, e1, e2) ->
prune_ne tenv ~positive e1 e2 prop
| Exp.BinOp (Binop.Ge, e2, e1) | Exp.BinOp (Binop.Le, e1, e2) ->
prune_ineq tenv ~is_strict:false ~positive prop e1 e2
| Exp.BinOp (Binop.Gt, e2, e1) | Exp.BinOp (Binop.Lt, e1, e2) ->
prune_ineq tenv ~is_strict:true ~positive prop e1 e2
| Exp.BinOp (Binop.LAnd, condition1, condition2) ->
let pruner = if positive then prune_inter tenv else prune_union tenv in
pruner ~positive condition1 condition2 prop
| Exp.BinOp (Binop.LOr, condition1, condition2) ->
let pruner = if positive then prune_union tenv else prune_inter tenv in
pruner ~positive condition1 condition2 prop
| Exp.BinOp _ | Exp.Lfield _ | Exp.Lindex _ ->
prune_ne tenv ~positive condition Exp.zero prop
| Exp.Exn _ ->
assert false
| Exp.Closure _ ->
assert false
and prune_inter tenv ~positive condition1 condition2 prop =
let res = ref Propset.empty in
let pset1 = prune tenv ~positive condition1 prop in
let do_p p =
res := Propset.union (prune tenv ~positive condition2 p) !res in
Propset.iter do_p pset1;
!res
and prune_union tenv ~positive condition1 condition2 prop =
let pset1 = prune tenv ~positive condition1 prop in
let pset2 = prune tenv ~positive condition2 prop in
Propset.union pset1 pset2
let dangerous_functions =
let dangerous_list = ["gets"] in
ref ((IList.map Procname.from_string_c_fun) dangerous_list)
let check_inherently_dangerous_function caller_pname callee_pname =
if IList.exists (Procname.equal callee_pname) !dangerous_functions then
let exn =
Exceptions.Inherently_dangerous_function
(Localise.desc_inherently_dangerous_function callee_pname) in
let pre_opt = State.get_normalized_pre (Abs.abstract_no_symop caller_pname) in
Reporting.log_warning caller_pname ?pre:pre_opt exn
let proc_is_defined proc_name =
match AttributesTable.load_attributes proc_name with
| Some attributes ->
attributes.ProcAttributes.is_defined
| None ->
false
let call_should_be_skipped callee_pname summary =
Specs.get_flag callee_pname proc_flag_skip <> None
|| summary.Specs.attributes.ProcAttributes.is_abstract
|| (Config.angelic_execution && Specs.get_specs_from_payload summary == [])
let check_constant_string_dereference lexp =
let string_lookup s n =
let c = try Char.code (String.get s (IntLit.to_int n)) with Invalid_argument _ -> 0 in
Exp.int (IntLit.of_int c) in
match lexp with
| Exp.BinOp(Binop.PlusPI, Exp.Const (Const.Cstr s), e)
| Exp.Lindex (Exp.Const (Const.Cstr s), e) ->
let value = match e with
| Exp.Const (Const.Cint n)
when IntLit.geq n IntLit.zero &&
IntLit.leq n (IntLit.of_int (String.length s)) ->
string_lookup s n
| _ -> Exp.get_undefined false in
Some value
| Exp.Const (Const.Cstr s) ->
Some (string_lookup s IntLit.zero)
| _ -> None
let check_arith_norm_exp tenv pname exp prop =
match Attribute.find_arithmetic_problem tenv (State.get_path_pos ()) prop exp with
| Some (Attribute.Div0 div), prop' ->
let desc = Errdesc.explain_divide_by_zero tenv div (State.get_node ()) (State.get_loc ()) in
let exn = Exceptions.Divide_by_zero (desc, __POS__) in
let pre_opt = State.get_normalized_pre (Abs.abstract_no_symop pname) in
Reporting.log_warning pname ?pre:pre_opt exn;
Prop.exp_normalize_prop tenv prop exp, prop'
| Some (Attribute.UminusUnsigned (e, typ)), prop' ->
let desc =
Errdesc.explain_unary_minus_applied_to_unsigned_expression tenv
e typ (State.get_node ()) (State.get_loc ()) in
let exn = Exceptions.Unary_minus_applied_to_unsigned_expression (desc, __POS__) in
let pre_opt = State.get_normalized_pre (Abs.abstract_no_symop pname) in
Reporting.log_warning pname ?pre:pre_opt exn;
Prop.exp_normalize_prop tenv prop exp, prop'
| None, prop' -> Prop.exp_normalize_prop tenv prop exp, prop'
let check_already_dereferenced tenv pname cond prop =
let find_hpred lhs =
try Some (IList.find (function
| Sil.Hpointsto (e, _, _) -> Exp.equal e lhs
| _ -> false) prop.Prop.sigma)
with Not_found -> None in
let rec is_check_zero = function
| Exp.Var id ->
Some id
| Exp.UnOp(Unop.LNot, e, _) ->
is_check_zero e
| Exp.BinOp ((Binop.Eq | Binop.Ne), Exp.Const Const.Cint i, Exp.Var id)
| Exp.BinOp ((Binop.Eq | Binop.Ne), Exp.Var id, Exp.Const Const.Cint i) when IntLit.iszero i ->
Some id
| _ -> None in
let dereferenced_line = match is_check_zero cond with
| Some id ->
(match find_hpred (Prop.exp_normalize_prop tenv prop (Exp.Var id)) with
| Some (Sil.Hpointsto (_, se, _)) ->
(match Tabulation.find_dereference_without_null_check_in_sexp se with
| Some n -> Some (id, n)
| None -> None)
| _ -> None)
| None ->
None in
match dereferenced_line with
| Some (id, (n, _)) ->
let desc =
Errdesc.explain_null_test_after_dereference tenv
(Exp.Var id) (State.get_node ()) n (State.get_loc ()) in
let exn =
(Exceptions.Null_test_after_dereference (desc, __POS__)) in
let pre_opt = State.get_normalized_pre (Abs.abstract_no_symop pname) in
Reporting.log_warning pname ?pre:pre_opt exn
| None -> ()
let check_deallocate_static_memory prop_after =
let check_deallocated_attribute = function
| Sil.Apred (Aresource ({ ra_kind = Rrelease } as ra), [Lvar pv])
when Pvar.is_local pv || Pvar.is_global pv ->
let freed_desc = Errdesc.explain_deallocate_stack_var pv ra in
raise (Exceptions.Deallocate_stack_variable freed_desc)
| Sil.Apred (Aresource ({ ra_kind = Rrelease } as ra), [Const (Cstr s)]) ->
let freed_desc = Errdesc.explain_deallocate_constant_string s ra in
raise (Exceptions.Deallocate_static_memory freed_desc)
| _ -> () in
let exp_att_list = Attribute.get_all prop_after in
IList.iter check_deallocated_attribute exp_att_list;
prop_after
let method_exists right_proc_name methods =
if !Config.curr_language = Config.Java then
IList.exists (fun meth_name -> Procname.equal right_proc_name meth_name) methods
match AttributesTable.load_attributes right_proc_name with
| Some attrs -> attrs.ProcAttributes.is_defined
| None -> Specs.summary_exists_in_models right_proc_name
let resolve_method tenv class_name proc_name =
let found_class =
let visited = ref Typename.Set.empty in
let rec resolve class_name =
visited := Typename.Set.add class_name !visited;
let right_proc_name =
Procname.replace_class proc_name (Typename.name class_name) in
match Tenv.lookup tenv class_name with
| Some { name = TN_csu (Class _, _); methods; supers } ->
if method_exists right_proc_name methods then
Some right_proc_name
else
(match supers with
| super_classname:: _ ->
if not (Typename.Set.mem super_classname !visited)
then resolve super_classname
else None
| _ -> None)
| _ -> None in
resolve class_name in
match found_class with
| None ->
Logging.d_strln
("Couldn't find method in the hierarchy of type "^(Typename.name class_name));
proc_name
| Some proc_name ->
proc_name
let resolve_typename prop receiver_exp =
let typexp_opt =
let rec loop = function
| [] -> None
| Sil.Hpointsto(e, _, typexp) :: _ when Exp.equal e receiver_exp -> Some typexp
| _ :: hpreds -> loop hpreds in
loop prop.Prop.sigma in
match typexp_opt with
| Some (Exp.Sizeof (Tstruct name, _, _)) -> Some name
| _ -> None
* If the dynamic type of the receiver actual T_actual is a subtype of the reciever type T_formal
in the signature of [ pname ] , resolve [ pname ] to T_actual.[pname ] .
in the signature of [pname], resolve [pname] to T_actual.[pname]. *)
let resolve_virtual_pname tenv prop actuals callee_pname call_flags : Procname.t list =
let resolve receiver_exp pname prop = match resolve_typename prop receiver_exp with
| Some class_name -> resolve_method tenv class_name pname
| None -> pname in
let get_receiver_typ pname fallback_typ =
match pname with
| Procname.Java pname_java ->
begin
match Tenv.lookup_declaring_class tenv pname_java with
| Some {name} -> Typ.Tptr (Tstruct name, Pk_pointer)
| None -> fallback_typ
end
| _ ->
fallback_typ in
let receiver_types_equal pname actual_receiver_typ =
let formal_receiver_typ = get_receiver_typ pname actual_receiver_typ in
Typ.equal formal_receiver_typ actual_receiver_typ in
let do_resolve called_pname receiver_exp actual_receiver_typ =
if receiver_types_equal called_pname actual_receiver_typ
then resolve receiver_exp called_pname prop
else called_pname in
match actuals with
| _ when not (call_flags.CallFlags.cf_virtual || call_flags.CallFlags.cf_interface) ->
[callee_pname]
| (receiver_exp, actual_receiver_typ) :: _ ->
if !Config.curr_language <> Config.Java then
[do_resolve callee_pname receiver_exp actual_receiver_typ]
else if Config.sound_dynamic_dispatch then
let targets =
if call_flags.CallFlags.cf_virtual
then
callee_pname :: call_flags.CallFlags.cf_targets
else
let may_dispatch_to target_pname =
let target_receiver_typ = get_receiver_typ target_pname actual_receiver_typ in
Prover.Subtyping_check.check_subtype tenv target_receiver_typ actual_receiver_typ in
let resolved_pname = do_resolve callee_pname receiver_exp actual_receiver_typ in
let feasible_targets = IList.filter may_dispatch_to targets in
if IList.mem Procname.equal resolved_pname feasible_targets
then feasible_targets
else resolved_pname :: feasible_targets
else
begin
match call_flags.CallFlags.cf_targets with
| target :: _ when call_flags.CallFlags.cf_interface &&
receiver_types_equal callee_pname actual_receiver_typ ->
" production mode " of dynamic dispatch for Java : unsound , but faster . the handling
is restricted to interfaces : if we ca n't resolve an interface call , we pick the
first implementation of the interface and call it
is restricted to interfaces: if we can't resolve an interface call, we pick the
first implementation of the interface and call it *)
[target]
| _ ->
default mode for Java virtual calls : resolution only
[do_resolve callee_pname receiver_exp actual_receiver_typ]
end
| _ -> failwith "A virtual call must have a receiver"
let resolve_java_pname tenv prop args pname_java call_flags : Procname.java =
let resolve_from_args resolved_pname_java args =
let parameters = Procname.java_get_parameters resolved_pname_java in
if IList.length args <> IList.length parameters then
resolved_pname_java
else
let resolved_params =
IList.fold_left2
(fun accu (arg_exp, _) name ->
match resolve_typename prop arg_exp with
| Some class_name ->
(Procname.split_classname (Typename.name class_name)) :: accu
| None -> name :: accu)
[] args (Procname.java_get_parameters resolved_pname_java) |> IList.rev in
Procname.java_replace_parameters resolved_pname_java resolved_params in
let resolved_pname_java, other_args =
match args with
| [] ->
pname_java, []
| (first_arg, _) :: other_args when call_flags.CallFlags.cf_virtual ->
let resolved =
begin
match resolve_typename prop first_arg with
| Some class_name ->
begin
match resolve_method tenv class_name (Procname.Java pname_java) with
| Procname.Java resolved_pname_java ->
resolved_pname_java
| _ ->
pname_java
end
| None ->
pname_java
end in
resolved, other_args
| _ :: other_args when Procname.is_constructor (Procname.Java pname_java) ->
pname_java, other_args
| args ->
pname_java, args in
resolve_from_args resolved_pname_java other_args
let resolve_and_analyze
tenv caller_pdesc prop args callee_proc_name call_flags : Procname.t * Specs.summary option =
TODO ( # 9333890 ): Fix conflict with method overloading by encoding in the procedure name
whether the method is defined or generated by the specialization
whether the method is defined or generated by the specialization *)
let analyze_ondemand resolved_pname : unit =
if Procname.equal resolved_pname callee_proc_name then
Ondemand.analyze_proc_name tenv ~propagate_exceptions:true caller_pdesc callee_proc_name
else
Option.may
(fun specialized_pdesc ->
Ondemand.analyze_proc_desc tenv ~propagate_exceptions:true caller_pdesc specialized_pdesc)
(match Ondemand.get_proc_desc resolved_pname with
| Some resolved_proc_desc ->
Some resolved_proc_desc
| None ->
begin
Option.map
(fun callee_proc_desc ->
Cfg.specialize_types callee_proc_desc resolved_pname args)
(Ondemand.get_proc_desc callee_proc_name)
end) in
let resolved_pname = match callee_proc_name with
| Procname.Java callee_proc_name_java ->
Procname.Java
(resolve_java_pname tenv prop args callee_proc_name_java call_flags)
| _ ->
callee_proc_name in
analyze_ondemand resolved_pname;
resolved_pname, Specs.get_summary resolved_pname
let call_constructor_url_update_args pname actual_params =
let url_pname =
Procname.Java
(Procname.java
((Some "java.net"), "URL") None "<init>"
[(Some "java.lang"), "String"] Procname.Non_Static) in
if (Procname.equal url_pname pname) then
(match actual_params with
| [this; (Exp.Const (Const.Cstr s), atype)] ->
let parts = Str.split (Str.regexp_string "://") s in
(match parts with
| frst:: _ ->
if frst = "http" ||
frst = "ftp" ||
frst = "https" ||
frst = "mailto" ||
frst = "jar"
then
[this; (Exp.Const (Const.Cstr frst), atype)]
else actual_params
| _ -> actual_params)
| [this; _, atype] -> [this; (Exp.Const (Const.Cstr "file"), atype)]
| _ -> actual_params)
else actual_params
1 . We know that obj is null , then we return null
2 . We do n't know , but obj could be null , we return both options ,
let handle_objc_instance_method_call_or_skip tenv actual_pars path callee_pname pre ret_ids res =
let path_description =
"Message " ^
(Procname.to_simplified_string callee_pname) ^
" with receiver nil returns nil." in
let receiver = (match actual_pars with
| (e, _):: _ -> e
| _ -> raise
(Exceptions.Internal_error
(Localise.verbatim_desc
"In Objective-C instance method call there should be a receiver."))) in
let is_receiver_null =
match actual_pars with
| (e, _) :: _
when Exp.equal e Exp.zero ||
Option.is_some (Attribute.get_objc_null tenv pre e) -> true
| _ -> false in
let add_objc_null_attribute_or_nullify_result prop =
match ret_ids with
| [ret_id] -> (
match Attribute.find_equal_formal_path tenv receiver prop with
| Some vfs ->
Attribute.add_or_replace tenv prop (Apred (Aobjc_null, [Exp.Var ret_id; vfs]))
| None ->
Prop.conjoin_eq tenv (Exp.Var ret_id) Exp.zero prop
)
| _ -> prop in
if is_receiver_null then
let path = Paths.Path.add_description path path_description in
L.d_strln
("Object-C method " ^
Procname.to_string callee_pname ^
" called with nil receiver. Returning 0/nil");
can keep track of how this object became null ,
so that in a NPE we can separate it into a different error type
so that in a NPE we can separate it into a different error type *)
[(add_objc_null_attribute_or_nullify_result pre, path)]
else
let is_undef = Option.is_some (Attribute.get_undef tenv pre receiver) in
if !Config.footprint && not is_undef then
let pre_with_attr_or_null = add_objc_null_attribute_or_nullify_result pre in
let propset = prune_ne tenv ~positive:false receiver Exp.zero pre_with_attr_or_null in
if Propset.is_empty propset then []
else
let prop = IList.hd (Propset.to_proplist propset) in
let path = Paths.Path.add_description path path_description in
[(prop, path)] in
res_null @ (res ())
let handle_objc_instance_method_call actual_pars actual_params pre tenv ret_ids pdesc callee_pname
loc path exec_call =
let res () = exec_call tenv ret_ids pdesc callee_pname loc actual_params pre path in
handle_objc_instance_method_call_or_skip tenv actual_pars path callee_pname pre ret_ids res
let normalize_params tenv pdesc prop actual_params =
let norm_arg (p, args) (e, t) =
let e', p' = check_arith_norm_exp tenv pdesc e p in
(p', (e', t) :: args) in
let prop, args = IList.fold_left norm_arg (prop, []) actual_params in
(prop, IList.rev args)
let do_error_checks tenv node_opt instr pname pdesc = match node_opt with
| Some node ->
if !Config.curr_language = Config.Java then
PrintfArgs.check_printf_args_ok tenv node instr pname pdesc
| None ->
()
let add_strexp_to_footprint tenv strexp abduced_pv typ prop =
let abduced_lvar = Exp.Lvar abduced_pv in
let lvar_pt_fpvar =
let sizeof_exp = Exp.Sizeof (typ, None, Subtype.subtypes) in
Prop.mk_ptsto tenv abduced_lvar strexp sizeof_exp in
let sigma_fp = prop.Prop.sigma_fp in
Prop.normalize tenv (Prop.set prop ~sigma_fp:(lvar_pt_fpvar :: sigma_fp))
let add_to_footprint tenv abduced_pv typ prop =
let fresh_fp_var = Exp.Var (Ident.create_fresh Ident.kfootprint) in
let prop' =
add_strexp_to_footprint tenv (Sil.Eexp (fresh_fp_var, Sil.Inone)) abduced_pv typ prop in
prop', fresh_fp_var
let add_struct_value_to_footprint tenv abduced_pv typ prop =
let struct_strexp =
Prop.create_strexp_of_type tenv Prop.Fld_init typ None Sil.inst_none in
let prop' = add_strexp_to_footprint tenv struct_strexp abduced_pv typ prop in
prop', struct_strexp
let add_constraints_on_retval tenv pdesc prop ret_exp ~has_nullable_annot typ callee_pname callee_loc=
if Procname.is_infer_undefined callee_pname then prop
else
Procname.equal pname (Cfg.Procdesc.get_proc_name pdesc) in
let already_has_abduced_retval p abduced_ret_pv =
IList.exists
(fun hpred -> match hpred with
| Sil.Hpointsto (Exp.Lvar pv, _, _) -> Pvar.equal pv abduced_ret_pv
| _ -> false)
p.Prop.sigma_fp in
let bind_exp_to_abduced_val exp_to_bind abduced prop =
let bind_exp prop = function
| Sil.Hpointsto (Exp.Lvar pv, Sil.Eexp (rhs, _), _)
when Pvar.equal pv abduced ->
Prop.conjoin_eq tenv exp_to_bind rhs prop
| _ -> prop in
IList.fold_left bind_exp prop prop.Prop.sigma in
let add_ret_non_null exp typ prop =
if has_nullable_annot
then
do n't assume if the procedure is annotated with @Nullable
else
match typ with
| Typ.Tptr _ -> Prop.conjoin_neq tenv exp Exp.zero prop
| _ -> prop in
let add_tainted_post ret_exp callee_pname prop =
Attribute.add_or_replace tenv prop (Apred (Ataint callee_pname, [ret_exp])) in
if Config.angelic_execution && not (is_rec_call callee_pname) then
let abduced_ret_pv = Pvar.mk_abduced_ret callee_pname callee_loc in
if already_has_abduced_retval prop abduced_ret_pv then prop
else
let prop' =
if !Config.footprint then
let (prop', fresh_fp_var) = add_to_footprint tenv abduced_ret_pv typ prop in
Prop.conjoin_eq tenv ~footprint: true ret_exp fresh_fp_var prop'
else
bind_exp_to_abduced_val ret_exp abduced_ret_pv prop in
let prop'' = add_ret_non_null ret_exp typ prop' in
if Config.taint_analysis then
match Taint.returns_tainted callee_pname None with
| Some taint_kind ->
add_tainted_post ret_exp { taint_source = callee_pname; taint_kind; } prop''
| None -> prop''
else prop''
else add_ret_non_null ret_exp typ prop
let add_taint prop lhs_id rhs_exp pname tenv =
let add_attribute_if_field_tainted prop fieldname struct_typ =
if Taint.has_taint_annotation fieldname struct_typ
then
let taint_info = { PredSymb.taint_source = pname; taint_kind = Tk_unknown; } in
Attribute.add_or_replace tenv prop (Apred (Ataint taint_info, [Exp.Var lhs_id]))
else
prop in
match rhs_exp with
| Exp.Lfield (_, fieldname, (Tstruct typname | Tptr (Tstruct typname, _))) ->
begin
match Tenv.lookup tenv typname with
| Some struct_typ -> add_attribute_if_field_tainted prop fieldname struct_typ
| None -> prop
end
| _ -> prop
let execute_load ?(report_deref_errors=true) pname pdesc tenv id rhs_exp typ loc prop_ =
let execute_load_ pdesc tenv id loc acc_in iter =
let iter_ren = Prop.prop_iter_make_id_primed tenv id iter in
let prop_ren = Prop.prop_iter_to_prop tenv iter_ren in
match Prop.prop_iter_current tenv iter_ren with
| (Sil.Hpointsto(lexp, strexp, Exp.Sizeof (typ, len, st)), offlist) ->
let contents, new_ptsto, pred_insts_op, lookup_uninitialized =
ptsto_lookup pdesc tenv prop_ren (lexp, strexp, typ, len, st) offlist id in
let update acc (pi, sigma) =
let pi' = Sil.Aeq (Exp.Var(id), contents):: pi in
let sigma' = new_ptsto:: sigma in
let iter' = update_iter iter_ren pi' sigma' in
let prop' = Prop.prop_iter_to_prop tenv iter' in
let prop'' =
if lookup_uninitialized then
Attribute.add_or_replace tenv prop' (Apred (Adangling DAuninit, [Exp.Var id]))
else prop' in
let prop''' =
if Config.taint_analysis
then add_taint prop'' id rhs_exp pname tenv
else prop'' in
prop''' :: acc in
begin
match pred_insts_op with
| None -> update acc_in ([],[])
| Some pred_insts -> IList.rev (IList.fold_left update acc_in pred_insts)
end
| (Sil.Hpointsto _, _) ->
Errdesc.warning_err loc "no offset access in execute_load -- treating as skip@.";
(Prop.prop_iter_to_prop tenv iter_ren) :: acc_in
| _ ->
assert false in
try
let n_rhs_exp, prop = check_arith_norm_exp tenv pname rhs_exp prop_ in
let n_rhs_exp' = Prop.exp_collapse_consecutive_indices_prop typ n_rhs_exp in
match check_constant_string_dereference n_rhs_exp' with
| Some value ->
[Prop.conjoin_eq tenv (Exp.Var id) value prop]
| None ->
let exp_get_undef_attr exp =
let fold_undef_pname callee_opt atom =
match callee_opt, atom with
| None, Sil.Apred (Aundef _, _) -> Some atom
| _ -> callee_opt in
IList.fold_left fold_undef_pname None (Attribute.get_for_exp tenv prop exp) in
let prop' =
if Config.angelic_execution then
match exp_get_undef_attr n_rhs_exp' with
| Some (Apred (Aundef (callee_pname, ret_annots, callee_loc, _), _)) ->
let has_nullable_annot = Annotations.ia_is_nullable ret_annots in
add_constraints_on_retval tenv
pdesc prop n_rhs_exp' ~has_nullable_annot typ callee_pname callee_loc
| _ -> prop
else prop in
let iter_list =
Rearrange.rearrange ~report_deref_errors pdesc tenv n_rhs_exp' typ prop' loc in
IList.rev (IList.fold_left (execute_load_ pdesc tenv id loc) [] iter_list)
with Rearrange.ARRAY_ACCESS ->
if (Config.array_level = 0) then assert false
else
let undef = Exp.get_undefined false in
[Prop.conjoin_eq tenv (Exp.Var id) undef prop_]
let load_ret_annots pname =
match AttributesTable.load_attributes pname with
| Some attrs ->
let ret_annots, _ = attrs.ProcAttributes.method_annotation in
ret_annots
| None ->
Typ.item_annotation_empty
let execute_store ?(report_deref_errors=true) pname pdesc tenv lhs_exp typ rhs_exp loc prop_ =
let execute_store_ pdesc tenv rhs_exp acc_in iter =
let (lexp, strexp, typ, len, st, offlist) =
match Prop.prop_iter_current tenv iter with
| (Sil.Hpointsto(lexp, strexp, Exp.Sizeof (typ, len, st)), offlist) ->
(lexp, strexp, typ, len, st, offlist)
| _ -> assert false in
let p = Prop.prop_iter_to_prop tenv iter in
let new_ptsto, pred_insts_op =
ptsto_update pdesc tenv p (lexp, strexp, typ, len, st) offlist rhs_exp in
let update acc (pi, sigma) =
let sigma' = new_ptsto:: sigma in
let iter' = update_iter iter pi sigma' in
let prop' = Prop.prop_iter_to_prop tenv iter' in
prop' :: acc in
match pred_insts_op with
| None -> update acc_in ([],[])
| Some pred_insts -> IList.fold_left update acc_in pred_insts in
try
let n_lhs_exp, prop_' = check_arith_norm_exp tenv pname lhs_exp prop_ in
let n_rhs_exp, prop = check_arith_norm_exp tenv pname rhs_exp prop_' in
let prop = Attribute.replace_objc_null tenv prop n_lhs_exp n_rhs_exp in
let n_lhs_exp' = Prop.exp_collapse_consecutive_indices_prop typ n_lhs_exp in
let iter_list = Rearrange.rearrange ~report_deref_errors pdesc tenv n_lhs_exp' typ prop loc in
IList.rev (IList.fold_left (execute_store_ pdesc tenv n_rhs_exp) [] iter_list)
with Rearrange.ARRAY_ACCESS ->
if (Config.array_level = 0) then assert false
else [prop_]
let rec sym_exec tenv current_pdesc _instr (prop_: Prop.normal Prop.t) path
: (Prop.normal Prop.t * Paths.Path.t) list =
let current_pname = Cfg.Procdesc.get_proc_name current_pdesc in
mark prop , tenv , pdesc last seen
pay one symop
IList.map (fun p -> (p, path)) pl in
let instr = match _instr with
| Sil.Call (ret, exp, par, loc, call_flags) ->
let exp' = Prop.exp_normalize_prop tenv prop_ exp in
let instr' = match exp' with
| Exp.Closure c ->
let proc_exp = Exp.Const (Const.Cfun c.name) in
let proc_exp' = Prop.exp_normalize_prop tenv prop_ proc_exp in
let par' = IList.map (fun (id_exp, _, typ) -> (id_exp, typ)) c.captured_vars in
Sil.Call (ret, proc_exp', par' @ par, loc, call_flags)
| _ ->
Sil.Call (ret, exp', par, loc, call_flags) in
instr'
| _ -> _instr in
let skip_call ?(is_objc_instance_method=false) prop path callee_pname ret_annots loc ret_ids
ret_typ_opt actual_args =
let skip_res () =
let exn = Exceptions.Skip_function (Localise.desc_skip_function callee_pname) in
Reporting.log_info current_pname exn;
L.d_strln
("Undefined function " ^ Procname.to_string callee_pname
^ ", returning undefined value.");
(match Specs.get_summary current_pname with
| None -> ()
| Some summary ->
Specs.CallStats.trace
summary.Specs.stats.Specs.call_stats callee_pname loc
(Specs.CallStats.CR_skip) !Config.footprint);
unknown_or_scan_call ~is_scan:false ret_typ_opt ret_annots Builtin.{
pdesc= current_pdesc; instr; tenv; prop_= prop; path; ret_ids; args= actual_args;
proc_name= callee_pname; loc; } in
if is_objc_instance_method then
handle_objc_instance_method_call_or_skip tenv actual_args path callee_pname prop ret_ids skip_res
else skip_res () in
let call_args prop_ proc_name args ret_ids loc = {
Builtin.pdesc = current_pdesc; instr; tenv; prop_; path; ret_ids; args; proc_name; loc; } in
match instr with
| Sil.Load (id, rhs_exp, typ, loc) ->
execute_load current_pname current_pdesc tenv id rhs_exp typ loc prop_
|> ret_old_path
| Sil.Store (lhs_exp, typ, rhs_exp, loc) ->
execute_store current_pname current_pdesc tenv lhs_exp typ rhs_exp loc prop_
|> ret_old_path
| Sil.Prune (cond, loc, true_branch, ik) ->
let prop__ = Attribute.nullify_exp_with_objc_null tenv prop_ cond in
let check_condition_always_true_false () =
let report_condition_always_true_false i =
let skip_loop = match ik with
| Sil.Ik_while | Sil.Ik_for ->
skip wile(1 ) and for (; 1 ;)
| Sil.Ik_dowhile ->
| Sil.Ik_land_lor ->
| _ -> false in
true_branch && not skip_loop in
match Prop.exp_normalize_prop tenv Prop.prop_emp cond with
| Exp.Const (Const.Cint i) when report_condition_always_true_false i ->
let node = State.get_node () in
let desc = Errdesc.explain_condition_always_true_false tenv i cond node loc in
let exn =
Exceptions.Condition_always_true_false (desc, not (IntLit.iszero i), __POS__) in
let pre_opt = State.get_normalized_pre (Abs.abstract_no_symop current_pname) in
Reporting.log_warning current_pname ?pre:pre_opt exn
| _ -> () in
if not Config.report_runtime_exceptions then
check_already_dereferenced tenv current_pname cond prop__;
check_condition_always_true_false ();
let n_cond, prop = check_arith_norm_exp tenv current_pname cond prop__ in
ret_old_path (Propset.to_proplist (prune tenv ~positive:true n_cond prop))
| Sil.Call (ret_ids, Exp.Const (Const.Cfun callee_pname), args, loc, _)
when Builtin.is_registered callee_pname ->
let sym_exe_builtin = Builtin.get callee_pname in
sym_exe_builtin (call_args prop_ callee_pname args ret_ids loc)
| Sil.Call (ret_ids,
Exp.Const (Const.Cfun ((Procname.Java callee_pname_java) as callee_pname)),
actual_params, loc, call_flags)
when Config.lazy_dynamic_dispatch ->
let norm_prop, norm_args = normalize_params tenv current_pname prop_ actual_params in
let exec_skip_call skipped_pname ret_annots ret_type =
skip_call norm_prop path skipped_pname ret_annots loc ret_ids (Some ret_type) norm_args in
let resolved_pname, summary_opt =
resolve_and_analyze tenv current_pdesc norm_prop norm_args callee_pname call_flags in
begin
match summary_opt with
| None ->
let ret_typ = Typ.java_proc_return_typ callee_pname_java in
let ret_annots = load_ret_annots callee_pname in
exec_skip_call resolved_pname ret_annots ret_typ
| Some summary when call_should_be_skipped resolved_pname summary ->
let proc_attrs = summary.Specs.attributes in
let ret_annots, _ = proc_attrs.ProcAttributes.method_annotation in
exec_skip_call resolved_pname ret_annots proc_attrs.ProcAttributes.ret_type
| Some summary ->
proc_call summary (call_args prop_ callee_pname norm_args ret_ids loc)
end
| Sil.Call (ret_ids,
Exp.Const (Const.Cfun ((Procname.Java callee_pname_java) as callee_pname)),
actual_params, loc, call_flags) ->
do_error_checks tenv (Paths.Path.curr_node path) instr current_pname current_pdesc;
let norm_prop, norm_args = normalize_params tenv current_pname prop_ actual_params in
let url_handled_args =
call_constructor_url_update_args callee_pname norm_args in
let resolved_pnames =
resolve_virtual_pname tenv norm_prop url_handled_args callee_pname call_flags in
let exec_one_pname pname =
Ondemand.analyze_proc_name tenv ~propagate_exceptions:true current_pdesc pname;
let exec_skip_call ret_annots ret_type =
skip_call norm_prop path pname ret_annots loc ret_ids (Some ret_type) url_handled_args in
match Specs.get_summary pname with
| None ->
let ret_typ = Typ.java_proc_return_typ callee_pname_java in
let ret_annots = load_ret_annots callee_pname in
exec_skip_call ret_annots ret_typ
| Some summary when call_should_be_skipped pname summary ->
let proc_attrs = summary.Specs.attributes in
let ret_annots, _ = proc_attrs.ProcAttributes.method_annotation in
exec_skip_call ret_annots proc_attrs.ProcAttributes.ret_type
| Some summary ->
proc_call summary (call_args norm_prop pname url_handled_args ret_ids loc) in
IList.fold_left (fun acc pname -> exec_one_pname pname @ acc) [] resolved_pnames
| Sil.Call (ret_ids, Exp.Const (Const.Cfun callee_pname), actual_params, loc, call_flags) ->
Generic fun call with known name
let (prop_r, n_actual_params) = normalize_params tenv current_pname prop_ actual_params in
let resolved_pname =
match resolve_virtual_pname tenv prop_r n_actual_params callee_pname call_flags with
| resolved_pname :: _ -> resolved_pname
| [] -> callee_pname in
Ondemand.analyze_proc_name tenv ~propagate_exceptions:true current_pdesc resolved_pname;
let callee_pdesc_opt = Ondemand.get_proc_desc resolved_pname in
let ret_typ_opt = Option.map Cfg.Procdesc.get_ret_type callee_pdesc_opt in
let sentinel_result =
if !Config.curr_language = Config.Clang then
check_variadic_sentinel_if_present
(call_args prop_r callee_pname actual_params ret_ids loc)
else [(prop_r, path)] in
let do_call (prop, path) =
let summary = Specs.get_summary resolved_pname in
let should_skip resolved_pname summary =
match summary with
| None -> true
| Some summary -> call_should_be_skipped resolved_pname summary in
if should_skip resolved_pname summary then
let attrs_opt =
let attr_opt = Option.map Cfg.Procdesc.get_attributes callee_pdesc_opt in
match attr_opt, resolved_pname with
| Some attrs, Procname.ObjC_Cpp _ -> Some attrs
| None, Procname.ObjC_Cpp _ -> AttributesTable.load_attributes resolved_pname
| _ -> None in
let objc_property_accessor_ret_typ_opt =
match attrs_opt with
| Some attrs ->
(match attrs.ProcAttributes.objc_accessor with
| Some objc_accessor -> Some (objc_accessor, attrs.ProcAttributes.ret_type)
| None -> None)
| None -> None in
match objc_property_accessor_ret_typ_opt with
| Some (objc_property_accessor, ret_typ) ->
handle_objc_instance_method_call
n_actual_params n_actual_params prop tenv ret_ids
current_pdesc callee_pname loc path
(sym_exec_objc_accessor objc_property_accessor ret_typ)
| None ->
let ret_annots = match summary with
| Some summ ->
let ret_annots, _ = summ.Specs.attributes.ProcAttributes.method_annotation in
ret_annots
| None ->
load_ret_annots resolved_pname in
let is_objc_instance_method =
match attrs_opt with
| Some attrs -> attrs.ProcAttributes.is_objc_instance_method
| None -> false in
skip_call ~is_objc_instance_method prop path resolved_pname ret_annots loc ret_ids
ret_typ_opt n_actual_params
else
proc_call (Option.get summary)
(call_args prop resolved_pname n_actual_params ret_ids loc) in
IList.flatten (IList.map do_call sentinel_result)
let (prop_r, n_actual_params) = normalize_params tenv current_pname prop_ actual_params in
if call_flags.CallFlags.cf_is_objc_block then
Rearrange.check_call_to_objc_block_error tenv current_pdesc prop_r fun_exp loc;
Rearrange.check_dereference_error tenv current_pdesc prop_r fun_exp loc;
if call_flags.CallFlags.cf_noreturn then begin
L.d_str "Unknown function pointer with noreturn attribute ";
Sil.d_exp fun_exp; L.d_strln ", diverging.";
diverge prop_r path
end else begin
L.d_str "Unknown function pointer "; Sil.d_exp fun_exp;
L.d_strln ", returning undefined value.";
let callee_pname = Procname.from_string_c_fun "__function_pointer__" in
unknown_or_scan_call ~is_scan:false None Typ.item_annotation_empty Builtin.{
pdesc= current_pdesc; instr; tenv; prop_= prop_r; path; ret_ids; args= n_actual_params;
proc_name= callee_pname; loc; }
end
| Sil.Nullify (pvar, _) ->
begin
let eprop = Prop.expose prop_ in
match IList.partition
(function
| Sil.Hpointsto (Exp.Lvar pvar', _, _) -> Pvar.equal pvar pvar'
| _ -> false) eprop.Prop.sigma with
| [Sil.Hpointsto(e, se, typ)], sigma' ->
let sigma'' =
let se' = execute_nullify_se se in
Sil.Hpointsto(e, se', typ):: sigma' in
let eprop_res = Prop.set eprop ~sigma:sigma'' in
ret_old_path [Prop.normalize tenv eprop_res]
| [], _ ->
ret_old_path [prop_]
| _ ->
L.err "Pvar %a appears on the LHS of >1 heap predicate!@." (Pvar.pp pe_text) pvar;
assert false
end
| Sil.Abstract _ ->
let node = State.get_node () in
let blocks_nullified = get_blocks_nullified node in
IList.iter (check_block_retain_cycle tenv current_pname prop_) blocks_nullified;
if Prover.check_inconsistency tenv prop_
then
ret_old_path []
else
ret_old_path
[Abs.remove_redundant_array_elements current_pname tenv
(Abs.abstract current_pname tenv prop_)]
| Sil.Remove_temps (temps, _) ->
ret_old_path [Prop.exist_quantify tenv (Sil.fav_from_list temps) prop_]
| Sil.Declare_locals (ptl, _) ->
let sigma_locals =
let add_None (x, y) = (x, Exp.Sizeof (y, None, Subtype.exact), None) in
let sigma_locals () =
IList.map
(Prop.mk_ptsto_lvar tenv Prop.Fld_init Sil.inst_initial)
(IList.map add_None ptl) in
sigma_locals () in
let sigma' = prop_.Prop.sigma @ sigma_locals in
let prop' = Prop.normalize tenv (Prop.set prop_ ~sigma:sigma') in
ret_old_path [prop']
and diverge prop path =
[]
and instrs ?(mask_errors=false) tenv pdesc instrs ppl =
let exe_instr instr (p, path) =
L.d_str "Executing Generated Instruction "; Sil.d_instr instr; L.d_ln ();
try sym_exec tenv pdesc instr p path
with exn when SymOp.exn_not_failure exn && mask_errors ->
let err_name, _, ml_source, _ , _, _, _ = Exceptions.recognize_exception exn in
let loc = (match ml_source with
| Some ml_loc -> "at " ^ (L.ml_loc_to_string ml_loc)
| None -> "") in
L.d_warning
("Generated Instruction Failed with: " ^
(Localise.to_string err_name)^loc ); L.d_ln();
[(p, path)] in
let f plist instr = IList.flatten (IList.map (exe_instr instr) plist) in
IList.fold_left f ppl instrs
and add_constraints_on_actuals_by_ref tenv prop actuals_by_ref callee_pname callee_loc =
let replace_actual_hpred actual_var new_hpred prop =
let sigma' =
IList.map
(function
| Sil.Hpointsto (lhs, _, _) when Exp.equal lhs actual_var -> new_hpred
| hpred -> hpred)
prop.Prop.sigma in
Prop.normalize tenv (Prop.set prop ~sigma:sigma') in
let add_actual_by_ref_to_footprint prop (actual, actual_typ, _) =
match actual with
| Exp.Lvar actual_pv ->
let abduced_ref_pv =
Pvar.mk_abduced_ref_param callee_pname actual_pv callee_loc in
let already_has_abduced_retval p =
IList.exists
(fun hpred -> match hpred with
| Sil.Hpointsto (Exp.Lvar pv, _, _) -> Pvar.equal pv abduced_ref_pv
| _ -> false)
p.Prop.sigma_fp in
if already_has_abduced_retval prop then prop
else
if !Config.footprint then
let prop', abduced_strexp =
match actual_typ with
| Typ.Tptr ((Tstruct _) as typ, _) ->
add_struct_value_to_footprint tenv abduced_ref_pv typ prop
| Typ.Tptr (typ, _) ->
let (prop', fresh_fp_var) =
add_to_footprint tenv abduced_ref_pv typ prop in
prop', Sil.Eexp (fresh_fp_var, Sil.Inone)
| typ ->
failwith
("No need for abduction on non-pointer type " ^
(Typ.to_string typ)) in
let filtered_sigma =
IList.map
(function
| Sil.Hpointsto (lhs, _, typ_exp) when Exp.equal lhs actual ->
Sil.Hpointsto (lhs, abduced_strexp, typ_exp)
| hpred -> hpred)
prop'.Prop.sigma in
Prop.normalize tenv (Prop.set prop' ~sigma:filtered_sigma)
else
let prop' =
let filtered_sigma =
IList.filter
(function
| Sil.Hpointsto (lhs, _, _) when Exp.equal lhs actual ->
false
| _ -> true)
prop.Prop.sigma in
Prop.normalize tenv (Prop.set prop ~sigma:filtered_sigma) in
IList.fold_left
(fun p hpred ->
match hpred with
| Sil.Hpointsto (Exp.Lvar pv, rhs, texp) when Pvar.equal pv abduced_ref_pv ->
let new_hpred = Sil.Hpointsto (actual, rhs, texp) in
Prop.normalize tenv (Prop.set p ~sigma:(new_hpred :: prop'.Prop.sigma))
| _ -> p)
prop'
prop'.Prop.sigma
| _ -> assert false in
let havoc_actual_by_ref prop (actual, actual_typ, _) =
let actual_pt_havocd_var =
let havocd_var = Exp.Var (Ident.create_fresh Ident.kprimed) in
let sizeof_exp = Exp.Sizeof (Typ.strip_ptr actual_typ, None, Subtype.subtypes) in
Prop.mk_ptsto tenv actual (Sil.Eexp (havocd_var, Sil.Inone)) sizeof_exp in
replace_actual_hpred actual actual_pt_havocd_var prop in
let do_actual_by_ref =
if Config.angelic_execution then add_actual_by_ref_to_footprint
else havoc_actual_by_ref in
let non_const_actuals_by_ref =
let is_not_const (e, _, i) =
match AttributesTable.load_attributes callee_pname with
| Some attrs ->
let is_const = IList.mem int_equal i attrs.ProcAttributes.const_formals in
if is_const then (
L.d_str (Printf.sprintf "Not havocing const argument number %d: " i);
Sil.d_exp e;
L.d_ln ()
);
not is_const
| None ->
true in
IList.filter is_not_const actuals_by_ref in
IList.fold_left do_actual_by_ref prop non_const_actuals_by_ref
and check_untainted tenv exp taint_kind caller_pname callee_pname prop =
match Attribute.get_taint tenv prop exp with
| Some (Apred (Ataint taint_info, _)) ->
let err_desc =
Errdesc.explain_tainted_value_reaching_sensitive_function
prop
exp
taint_info
callee_pname
(State.get_loc ()) in
let exn =
Exceptions.Tainted_value_reaching_sensitive_function
(err_desc, __POS__) in
Reporting.log_warning caller_pname exn;
Attribute.add_or_replace tenv prop (Apred (Auntaint taint_info, [exp]))
| _ ->
if !Config.footprint then
let taint_info = { PredSymb.taint_source = callee_pname; taint_kind; } in
Attribute.add tenv ~footprint:true prop (Auntaint taint_info) [exp]
else prop
and unknown_or_scan_call ~is_scan ret_type_option ret_annots
{ Builtin.tenv; pdesc; prop_= pre; path; ret_ids;
args; proc_name= callee_pname; loc; instr; } =
let remove_file_attribute prop =
let do_exp p (e, _) =
let do_attribute q atom =
match atom with
| Sil.Apred ((Aresource {ra_res = Rfile} as res), _) -> Attribute.remove_for_attr tenv q res
| _ -> q in
IList.fold_left do_attribute p (Attribute.get_for_exp tenv p e) in
let filtered_args =
match args, instr with
| _:: other_args, Sil.Call (_, _, _, _, { CallFlags.cf_virtual }) when cf_virtual ->
other_args
| _ -> args in
IList.fold_left do_exp prop filtered_args in
let add_tainted_pre prop actuals caller_pname callee_pname =
if Config.taint_analysis then
match Taint.accepts_sensitive_params callee_pname None with
| [] -> prop
| param_nums ->
let check_taint_if_nums_match (prop_acc, param_num) (actual_exp, _actual_typ) =
let prop_acc' =
try
let _, taint_kind = IList.find (fun (num, _) -> num = param_num) param_nums in
check_untainted tenv actual_exp taint_kind caller_pname callee_pname prop_acc
with Not_found -> prop_acc in
prop_acc', param_num + 1 in
IList.fold_left
check_taint_if_nums_match
(prop, 0)
actuals
|> fst
else prop in
let actuals_by_ref =
IList.flatten_options (IList.mapi
(fun i actual -> match actual with
| (Exp.Lvar _ as e, (Typ.Tptr _ as t)) -> Some (e, t, i)
| _ -> None)
args) in
let has_nullable_annot = Annotations.ia_is_nullable ret_annots in
let pre_final =
in Java , assume that skip functions close resources passed as params
let pre_1 =
if Procname.is_java callee_pname
then remove_file_attribute pre
else pre in
let pre_2 = match ret_ids, ret_type_option with
| [ret_id], Some ret_typ ->
add_constraints_on_retval tenv
pdesc pre_1 (Exp.Var ret_id) ret_typ ~has_nullable_annot callee_pname loc
| _ ->
pre_1 in
let pre_3 = add_constraints_on_actuals_by_ref tenv pre_2 actuals_by_ref callee_pname loc in
let caller_pname = Cfg.Procdesc.get_proc_name pdesc in
add_tainted_pre pre_3 args caller_pname callee_pname in
then [(Tabulation.remove_constant_string_class tenv pre_final, path)]
else
let exps_to_mark =
let ret_exps = IList.map (fun ret_id -> Exp.Var ret_id) ret_ids in
IList.fold_left
(fun exps_to_mark (exp, _, _) -> exp :: exps_to_mark) ret_exps actuals_by_ref in
let prop_with_undef_attr =
let path_pos = State.get_path_pos () in
Attribute.mark_vars_as_undefined tenv
pre_final exps_to_mark callee_pname ret_annots loc path_pos in
[(prop_with_undef_attr, path)]
and check_variadic_sentinel
?(fails_on_nil = false) n_formals (sentinel, null_pos)
{ Builtin.pdesc; tenv; prop_; path; args; proc_name; loc; }
=
but the language forces you to have at least one .
let first_var_arg_pos = if null_pos > n_formals then 0 else n_formals - null_pos in
let nargs = IList.length args in
let sentinel_pos = nargs - sentinel - 1 in
let mk_non_terminal_argsi (acc, i) a =
if i < first_var_arg_pos || i >= sentinel_pos then (acc, i +1)
else ((a, i):: acc, i +1) in
let non_terminal_argsi = fst (IList.fold_left mk_non_terminal_argsi ([], 0) args) in
let check_allocated result ((lexp, typ), i) =
let tmp_id_deref = Ident.create_fresh Ident.kprimed in
let load_instr = Sil.Load (tmp_id_deref, lexp, typ, loc) in
try
instrs tenv pdesc [load_instr] result
with e when SymOp.exn_not_failure e ->
if not fails_on_nil then
let deref_str = Localise.deref_str_nil_argument_in_variadic_method proc_name nargs i in
let err_desc =
Errdesc.explain_dereference tenv ~use_buckets: true ~is_premature_nil: true
deref_str prop_ loc in
raise (Exceptions.Premature_nil_termination (err_desc, __POS__))
else
raise e in
error on the first premature nil argument
IList.fold_left check_allocated [(prop_, path)] non_terminal_argsi
and check_variadic_sentinel_if_present
({ Builtin.prop_; path; proc_name; } as builtin_args) =
match Specs.proc_resolve_attributes proc_name with
| None ->
[(prop_, path)]
| Some callee_attributes ->
match PredSymb.get_sentinel_func_attribute_value
callee_attributes.ProcAttributes.func_attributes with
| None -> [(prop_, path)]
| Some sentinel_arg ->
let formals = callee_attributes.ProcAttributes.formals in
check_variadic_sentinel (IList.length formals) sentinel_arg builtin_args
and sym_exec_objc_getter field_name ret_typ tenv ret_ids pdesc pname loc args prop =
L.d_strln ("No custom getter found. Executing the ObjC builtin getter with ivar "^
(Ident.fieldname_to_string field_name)^".");
let ret_id =
match ret_ids with
| [ret_id] -> ret_id
| _ -> assert false in
match args with
| [(lexp, (Typ.Tstruct _ as typ | Tptr (Tstruct _ as typ, _)))] ->
let field_access_exp = Exp.Lfield (lexp, field_name, typ) in
execute_load
~report_deref_errors:false pname pdesc tenv ret_id field_access_exp ret_typ loc prop
| _ -> raise (Exceptions.Wrong_argument_number __POS__)
and sym_exec_objc_setter field_name _ tenv _ pdesc pname loc args prop =
L.d_strln ("No custom setter found. Executing the ObjC builtin setter with ivar "^
(Ident.fieldname_to_string field_name)^".");
match args with
| (lexp1, (Typ.Tstruct _ as typ1 | Tptr (typ1, _))) :: (lexp2, typ2) :: _ ->
let field_access_exp = Exp.Lfield (lexp1, field_name, typ1) in
execute_store ~report_deref_errors:false pname pdesc tenv field_access_exp typ2 lexp2 loc prop
| _ -> raise (Exceptions.Wrong_argument_number __POS__)
and sym_exec_objc_accessor property_accesor ret_typ tenv ret_ids pdesc _ loc args prop path
: Builtin.ret_typ =
let f_accessor =
match property_accesor with
| ProcAttributes.Objc_getter field_name -> sym_exec_objc_getter field_name
| ProcAttributes.Objc_setter field_name -> sym_exec_objc_setter field_name in
let cur_pname = Cfg.Procdesc.get_proc_name pdesc in
f_accessor ret_typ tenv ret_ids pdesc cur_pname loc args prop
|> IList.map (fun p -> (p, path))
and proc_call summary {Builtin.pdesc; tenv; prop_= pre; path; ret_ids; args= actual_pars; loc; } =
let caller_pname = Cfg.Procdesc.get_proc_name pdesc in
let callee_pname = Specs.get_proc_name summary in
let ret_typ = Specs.get_ret_type summary in
let check_return_value_ignored () =
let is_ignored = match ret_typ, ret_ids with
| Typ.Tvoid, _ -> false
| Typ.Tint _, _ when not (proc_is_defined callee_pname) ->
if the proc returns and is not defined ,
false
| _, [] -> true
| _, [id] -> Errdesc.id_is_assigned_then_dead (State.get_node ()) id
| _ -> false in
if is_ignored
&& Specs.get_flag callee_pname proc_flag_ignore_return = None then
let err_desc = Localise.desc_return_value_ignored callee_pname loc in
let exn = (Exceptions.Return_value_ignored (err_desc, __POS__)) in
let pre_opt = State.get_normalized_pre (Abs.abstract_no_symop caller_pname) in
Reporting.log_warning caller_pname ?pre:pre_opt exn in
check_inherently_dangerous_function caller_pname callee_pname;
begin
let formal_types = IList.map (fun (_, typ) -> typ) (Specs.get_formals summary) in
let rec comb actual_pars formal_types =
match actual_pars, formal_types with
| [], [] -> actual_pars
| (e, t_e):: etl', _:: tl' ->
(e, t_e) :: comb etl' tl'
| _,[] ->
Errdesc.warning_err
(State.get_loc ())
"likely use of variable-arguments function, or function prototype missing@.";
L.d_warning
"likely use of variable-arguments function, or function prototype missing";
L.d_ln();
L.d_str "actual parameters: "; Sil.d_exp_list (IList.map fst actual_pars); L.d_ln ();
L.d_str "formal parameters: "; Typ.d_list formal_types; L.d_ln ();
actual_pars
| [], _ ->
L.d_str ("**** ERROR: Procedure " ^ Procname.to_string callee_pname);
L.d_strln (" mismatch in the number of parameters ****");
L.d_str "actual parameters: "; Sil.d_exp_list (IList.map fst actual_pars); L.d_ln ();
L.d_str "formal parameters: "; Typ.d_list formal_types; L.d_ln ();
raise (Exceptions.Wrong_argument_number __POS__) in
let actual_params = comb actual_pars formal_types in
check_return_value_ignored ();
were the receiver is null and the semantics of the call is nop
let callee_attrs = Specs.get_attributes summary in
if (!Config.curr_language <> Config.Java) &&
(Specs.get_attributes summary).ProcAttributes.is_objc_instance_method then
handle_objc_instance_method_call actual_pars actual_params pre tenv ret_ids pdesc
callee_pname loc path (Tabulation.exe_function_call callee_attrs)
Tabulation.exe_function_call
callee_attrs tenv ret_ids pdesc callee_pname loc actual_params pre path
end
and sym_exec_wrapper handle_exn tenv pdesc instr ((prop: Prop.normal Prop.t), path)
: Paths.PathSet.t =
let pname = Cfg.Procdesc.get_proc_name pdesc in
let fav = Prop.prop_fav p in
Sil.fav_filter_ident fav Ident.is_primed;
let ids_primed = Sil.fav_to_list fav in
let ids_primed_normal =
IList.map (fun id -> (id, Ident.create_fresh Ident.knormal)) ids_primed in
let ren_sub =
Sil.sub_of_list (IList.map
(fun (id1, id2) -> (id1, Exp.Var id2)) ids_primed_normal) in
let p' = Prop.normalize tenv (Prop.prop_sub ren_sub p) in
let fav_normal = Sil.fav_from_list (IList.map snd ids_primed_normal) in
p', fav_normal in
if Sil.fav_to_list fav_normal = [] then p
else Prop.exist_quantify tenv fav_normal p in
try
let pre_process_prop p =
let p', fav =
if Sil.instr_is_auxiliary instr
then p, Sil.fav_new ()
else prop_primed_to_normal p in
let p'' =
let vpath, _ = Errdesc.vpath_find tenv p' e in
{ ra with PredSymb.ra_vpath = vpath } in
Attribute.map_resource tenv p' map_res_action in
p'', fav in
let post_process_result fav_normal p path =
let p' = prop_normal_to_primed fav_normal p in
State.set_path path None;
let node_has_abstraction node =
let instr_is_abstraction = function
| Sil.Abstract _ -> true
| _ -> false in
IList.exists instr_is_abstraction (Cfg.Node.get_instrs node) in
let curr_node = State.get_node () in
match Cfg.Node.get_kind curr_node with
| Cfg.Node.Prune_node _ when not (node_has_abstraction curr_node) ->
p'
| _ ->
check_deallocate_static_memory (Abs.abstract_junk ~original_prop: p
pname tenv p') in
~~~~~~~~~~~~~~~~~~~FOOTPATCH START~~~~~~~~~~~~~~~~~~
L.d_str "Instruction ";
Sil.d_instr instr;
L.d_ln ();
let prop', fav_normal = pre_process_prop prop in
let res_list =
no exp abstraction during sym exe
Config.run_with_abs_val_equal_zero
(fun () -> sym_exec tenv pdesc instr prop' path)
()
in
let res_list_nojunk =
IList.map
(fun (p, path) -> (post_process_result fav_normal p path, path))
res_list
in
let results =
IList.map
(fun (p, path) -> (Prop.prop_rename_primed_footprint_vars tenv p, path))
res_list_nojunk in
L.d_strln "Instruction Returns";
let printenv = Utils.pe_text in
begin
match IList.map fst results with
| hd :: _ ->
let propgraph1 = Propgraph.from_prop prop in
let propgraph2 = Propgraph.from_prop hd in
let diff = Propgraph.compute_diff Blue propgraph1 propgraph2 in
let cmap_norm = Propgraph.diff_get_colormap false diff in
let cmap_fp = Propgraph.diff_get_colormap true diff in
let pi = hd.Prop.pi in
let sigma = hd.Prop.sigma in
let pi_fp = hd.Prop.pi_fp in
let sigma_fp = hd.Prop.sigma_fp in
let sigma_all = sigma @ sigma_fp in
let pi_all = pi @ pi_fp in
let f = Footpatch_utils.new_mem_predsymb in
let g = Footpatch_utils.exn_is_changed in
let open Footpatch_assert_spec in
let check_instantiate_fn_with_cmap fn cmap =
IList.iter
(fun v ->
match fn cmap v with
| Some pvar ->
begin
match
Footpatch_utils.lookup_hpred_typ_from_new_mem_pvar
pvar sigma
with
| Some typname ->
let curr_node = State.get_node () in
let c =
{ typ = Null_instantiate
; fixes_var_type =
Some
(Footpatch_utils.normalize_java_type_name @@
Typename.to_string typname)
; node = curr_node
; pvar = Some pvar
; insn = instr
}
in
Footpatch_assert_spec.save c
| None ->
let curr_node = State.get_node () in
let c =
{ typ = Null_instantiate
; fixes_var_type = None
; node = curr_node
; pvar = Some pvar
; insn = instr
}
in
Footpatch_assert_spec.save c
end
| None -> ()) pi_all in
check_instantiate_fn_with_cmap f cmap_norm;
check_instantiate_fn_with_cmap f cmap_fp;
let check_exn_fn_with_cmap fn cmap =
IList.iter (fun v ->
L.d_strln
@@ Format.sprintf "Checking %s"
@@ Utils.pp_to_string (Sil.pp_hpred printenv) v;
match fn cmap v with
| true ->
let curr_node = State.get_node () in
let c =
{ typ = Null_exn
; fixes_var_type = None
; node = curr_node
; pvar = None
; insn = instr
}
in
Footpatch_assert_spec.save c
| false -> ()) sigma_all in
check_exn_fn_with_cmap g cmap_norm;
check_exn_fn_with_cmap g cmap_fp
| _ -> ()
end;
begin
match instr with
| Sil.Call _ ->
let open Candidate.Top_down in
let c =
{ insn = instr
; pre = prop
; post = (IList.map fst results)
; loc = Sil.instr_get_loc instr
; f = None
; pname = Procname.to_string pname
}
in
L.d_strln @@ Candidate.Top_down.to_string c;
Candidate.Top_down.save c;
| Sil.Prune _ ->
begin
try
let pre = prop in
let post = IList.map fst results |> IList.hd in
let pvar, typ =
Footpatch_utils.assert_pvar_null pre post in
let p = { Footpatch_assert_spec.pvar; typ; insn = instr } in
Footpatch_assert_spec.save_prune p
with Failure _ -> ()
end
| _ -> ()
end;
~~~~~~~~~~~~~~~~~~~FOOTPATCH END~~~~~~~~~~~~~~~~~~~~~
State.mark_instr_ok ();
Paths.PathSet.from_renamed_list results
with exn when Exceptions.handle_exception exn && !Config.footprint ->
calls State.mark_instr_fail
if Config.nonstop
then
(Paths.PathSet.from_renamed_list [(prop, path)])
else
Paths.PathSet.empty
let node handle_exn tenv node (pset : Paths.PathSet.t) : Paths.PathSet.t =
let pdesc = Cfg.Node.get_proc_desc node in
let pname = Cfg.Procdesc.get_proc_name pdesc in
let exe_instr_prop instr p tr (pset1: Paths.PathSet.t) =
let pset2 =
if Tabulation.prop_is_exn pname p && not (Sil.instr_is_auxiliary instr)
&& Cfg.Node.get_kind node <> Cfg.Node.exn_handler_kind
then
begin
L.d_str "Skipping instr "; Sil.d_instr instr; L.d_strln " due to exception";
Paths.PathSet.from_renamed_list [(p, tr)]
end
else sym_exec_wrapper handle_exn tenv pdesc instr (p, tr) in
Paths.PathSet.union pset2 pset1 in
let exe_instr_pset pset instr =
Paths.PathSet.fold (exe_instr_prop instr) pset Paths.PathSet.empty in
IList.fold_left exe_instr_pset pset (Cfg.Node.get_instrs node)
|
a67dd19344d78df0520208c5b8c2584ddf360c6d13d13b0730df93616906a688 | hopbit/sonic-pi-snippets | mel_nem.sps | # key: mel nem
# point_line: 0
# point_index: 0
# --
# metallica - nothing else matters (24 beats)
melody = (ring :e5, :r, :g5, :r, :b5, :r, :e6, :r, :b5, :r, :g5, :r) * 2
##| melody = (ring :b6, :r, :b6, :r, :r, :r, :b6, :r, :e6, :r, :b6, :r)
##| melody += (ring :c7, :r, :b6, :r, :c7, :r, :b6, :c7)
| null | https://raw.githubusercontent.com/hopbit/sonic-pi-snippets/2232854ac9587fc2f9f684ba04d7476e2dbaa288/melodies/mel_nem.sps | scheme | # key: mel nem
# point_line: 0
# point_index: 0
# --
# metallica - nothing else matters (24 beats)
melody = (ring :e5, :r, :g5, :r, :b5, :r, :e6, :r, :b5, :r, :g5, :r) * 2
##| melody = (ring :b6, :r, :b6, :r, :r, :r, :b6, :r, :e6, :r, :b6, :r)
##| melody += (ring :c7, :r, :b6, :r, :c7, :r, :b6, :c7)
| |
e4aa4b40be5f3012f2f515262bad301d93e8ab037adea5392b35f8442013a938 | erlangonrails/devdb | email_msg.erl | %%
%% file: email_msg.erl
author : < >
%% description: a very simple module that creates a non-multipart
%% email message.
%% Doesn't support MIME or non-ascii characters
%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% Usage Example
%%
2 > c(email_msg ) .
%% {ok,email_msg}
3 > From = " " .
%% ""
4 > To = " " .
%% ""
5 > Subject = " Testing ! ! ! ! " .
%% "Testing !!!!"
6 > Content = " Hi , this is a test , bye " .
" Hi , this is a test , bye "
7 > Msg = email_msg : simp_msg(From , To , Subject , Content ) .
%% "from: \r\nto: \r\n
subject : Testi ng ! ! ! ! , this is a test , bye\r\n "
8 >
%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%
-module(email_msg).
-vsn('v1.0').
-export([simp_msg/4]).
simp_msg(From, To, Subject, Message) ->
FromStr = ["from: ", From, "\r\n"],
ToStr = ["to: ", To, "\r\n"],
SubjStr = ["subject: ", Subject, "\r\n"],
MsgStr = ["\r\n", Message],
lists:concat(lists:concat([FromStr, ToStr, SubjStr, MsgStr, ["\r\n"]])).
| null | https://raw.githubusercontent.com/erlangonrails/devdb/0e7eaa6bd810ec3892bfc3d933439560620d0941/dev/scalaris/contrib/log4erl/src/email_msg.erl | erlang |
file: email_msg.erl
description: a very simple module that creates a non-multipart
email message.
Doesn't support MIME or non-ascii characters
Usage Example
{ok,email_msg}
""
""
"Testing !!!!"
"from: \r\nto: \r\n
| author : < >
2 > c(email_msg ) .
3 > From = " " .
4 > To = " " .
5 > Subject = " Testing ! ! ! ! " .
6 > Content = " Hi , this is a test , bye " .
" Hi , this is a test , bye "
7 > Msg = email_msg : simp_msg(From , To , Subject , Content ) .
subject : Testi ng ! ! ! ! , this is a test , bye\r\n "
8 >
-module(email_msg).
-vsn('v1.0').
-export([simp_msg/4]).
simp_msg(From, To, Subject, Message) ->
FromStr = ["from: ", From, "\r\n"],
ToStr = ["to: ", To, "\r\n"],
SubjStr = ["subject: ", Subject, "\r\n"],
MsgStr = ["\r\n", Message],
lists:concat(lists:concat([FromStr, ToStr, SubjStr, MsgStr, ["\r\n"]])).
|
e1772f89ac036171dc891df209b50b12bd78832e7960fd3b7dadf080398ca309 | facebook/duckling | Core.hs | Copyright ( c ) 2016 - present , Facebook , Inc.
-- All rights reserved.
--
-- This source code is licensed under the BSD-style license found in the
-- LICENSE file in the root directory of this source tree.
# LANGUAGE NoRebindableSyntax #
-- | Everything needed to run Duckling.
module Duckling.Core
( Context(..)
, Dimension(..)
, Entity(..)
, Lang(..)
, Locale
, Node(..)
, Options(..)
, Range(..)
, Region(..)
, ResolvedVal(..)
, Seal(..)
, withSeal
, fromName
, makeLocale
, toJText
, toName
-- Duckling API
, parse
, supportedDimensions
, allLocales
-- Reference time builders
, currentReftime
, fromZonedTime
, makeReftime
) where
import Data.HashMap.Strict (HashMap)
import Data.Text (Text)
import Data.Time
import Data.Time.LocalTime.TimeZone.Series
import Prelude
import qualified Data.HashMap.Strict as HashMap
import Duckling.Api
import Duckling.Dimensions.Types
import Duckling.Locale
import Duckling.Resolve
import Duckling.Types
-- | Builds a `DucklingTime` for timezone `tz` at `utcTime`.
-- If no `series` found for `tz`, uses UTC.
makeReftime :: HashMap Text TimeZoneSeries -> Text -> UTCTime -> DucklingTime
makeReftime series tz utcTime = DucklingTime $ ZoneSeriesTime ducklingTime tzs
where
tzs = HashMap.lookupDefault (TimeZoneSeries utc []) tz series
ducklingTime = toUTC $ utcToLocalTime' tzs utcTime
-- | Builds a `DucklingTime` for timezone `tz` at current time.
-- If no `series` found for `tz`, uses UTC.
currentReftime :: HashMap Text TimeZoneSeries -> Text -> IO DucklingTime
currentReftime series tz = makeReftime series tz <$> getCurrentTime
| Builds a ` DucklingTime ` from a ` ZonedTime ` .
fromZonedTime :: ZonedTime -> DucklingTime
fromZonedTime (ZonedTime localTime timeZone) = DucklingTime $
ZoneSeriesTime (toUTC localTime) (TimeZoneSeries timeZone [])
| null | https://raw.githubusercontent.com/facebook/duckling/72f45e8e2c7385f41f2f8b1f063e7b5daa6dca94/Duckling/Core.hs | haskell | All rights reserved.
This source code is licensed under the BSD-style license found in the
LICENSE file in the root directory of this source tree.
| Everything needed to run Duckling.
Duckling API
Reference time builders
| Builds a `DucklingTime` for timezone `tz` at `utcTime`.
If no `series` found for `tz`, uses UTC.
| Builds a `DucklingTime` for timezone `tz` at current time.
If no `series` found for `tz`, uses UTC. | Copyright ( c ) 2016 - present , Facebook , Inc.
# LANGUAGE NoRebindableSyntax #
module Duckling.Core
( Context(..)
, Dimension(..)
, Entity(..)
, Lang(..)
, Locale
, Node(..)
, Options(..)
, Range(..)
, Region(..)
, ResolvedVal(..)
, Seal(..)
, withSeal
, fromName
, makeLocale
, toJText
, toName
, parse
, supportedDimensions
, allLocales
, currentReftime
, fromZonedTime
, makeReftime
) where
import Data.HashMap.Strict (HashMap)
import Data.Text (Text)
import Data.Time
import Data.Time.LocalTime.TimeZone.Series
import Prelude
import qualified Data.HashMap.Strict as HashMap
import Duckling.Api
import Duckling.Dimensions.Types
import Duckling.Locale
import Duckling.Resolve
import Duckling.Types
makeReftime :: HashMap Text TimeZoneSeries -> Text -> UTCTime -> DucklingTime
makeReftime series tz utcTime = DucklingTime $ ZoneSeriesTime ducklingTime tzs
where
tzs = HashMap.lookupDefault (TimeZoneSeries utc []) tz series
ducklingTime = toUTC $ utcToLocalTime' tzs utcTime
currentReftime :: HashMap Text TimeZoneSeries -> Text -> IO DucklingTime
currentReftime series tz = makeReftime series tz <$> getCurrentTime
| Builds a ` DucklingTime ` from a ` ZonedTime ` .
fromZonedTime :: ZonedTime -> DucklingTime
fromZonedTime (ZonedTime localTime timeZone) = DucklingTime $
ZoneSeriesTime (toUTC localTime) (TimeZoneSeries timeZone [])
|
0c4124f315857f509c719723ea01ef9ea24999a27ac802fae79f956e66500e3b | facebook/pyre-check | transform.mli |
* Copyright ( c ) Meta Platforms , Inc. and affiliates .
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree .
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*)
module type Transformer = sig
type t
val transform_expression_children : t -> Expression.t -> bool
val expression : t -> Expression.t -> Expression.t
val transform_children : t -> Statement.t -> t * bool
val statement : t -> Statement.t -> t * Statement.t list
end
module type StatementTransformer = sig
type t
val statement : t -> Statement.t -> t * Statement.t list
end
module Identity : sig
val transform_expression_children : 't -> Expression.t -> bool
val expression : 't -> Expression.t -> Expression.t
val transform_children : 't -> Statement.t -> 't * bool
val statement : 't -> Statement.t -> 't * Statement.t list
end
module Make (Transformer : Transformer) : sig
type result = {
state: Transformer.t;
source: Source.t;
}
val source : result -> Source.t
val transform : Transformer.t -> Source.t -> result
end
module MakeStatementTransformer (Transformer : StatementTransformer) : sig
type result = {
state: Transformer.t;
source: Source.t;
}
val source : result -> Source.t
val transform : Transformer.t -> Source.t -> result
end
val transform_in_statement
: transform:(Expression.expression -> Expression.expression) ->
Statement.statement ->
Statement.statement
val transform_in_expression
: transform:(Expression.expression -> Expression.expression) ->
Expression.t ->
Expression.t
val sanitize_expression : Expression.t -> Expression.t
val sanitize_statement : Statement.statement -> Statement.statement
val map_location : transform_location:(Location.t -> Location.t) -> Expression.t -> Expression.t
| null | https://raw.githubusercontent.com/facebook/pyre-check/7c76a295c577696b57cc7e9dacc19f043ba9daf5/source/ast/transform.mli | ocaml |
* Copyright ( c ) Meta Platforms , Inc. and affiliates .
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree .
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*)
module type Transformer = sig
type t
val transform_expression_children : t -> Expression.t -> bool
val expression : t -> Expression.t -> Expression.t
val transform_children : t -> Statement.t -> t * bool
val statement : t -> Statement.t -> t * Statement.t list
end
module type StatementTransformer = sig
type t
val statement : t -> Statement.t -> t * Statement.t list
end
module Identity : sig
val transform_expression_children : 't -> Expression.t -> bool
val expression : 't -> Expression.t -> Expression.t
val transform_children : 't -> Statement.t -> 't * bool
val statement : 't -> Statement.t -> 't * Statement.t list
end
module Make (Transformer : Transformer) : sig
type result = {
state: Transformer.t;
source: Source.t;
}
val source : result -> Source.t
val transform : Transformer.t -> Source.t -> result
end
module MakeStatementTransformer (Transformer : StatementTransformer) : sig
type result = {
state: Transformer.t;
source: Source.t;
}
val source : result -> Source.t
val transform : Transformer.t -> Source.t -> result
end
val transform_in_statement
: transform:(Expression.expression -> Expression.expression) ->
Statement.statement ->
Statement.statement
val transform_in_expression
: transform:(Expression.expression -> Expression.expression) ->
Expression.t ->
Expression.t
val sanitize_expression : Expression.t -> Expression.t
val sanitize_statement : Statement.statement -> Statement.statement
val map_location : transform_location:(Location.t -> Location.t) -> Expression.t -> Expression.t
| |
cb6720a5edad688b0544c55cc3b685146c54cf41a90616a5311a4a18aed0da04 | mbenelli/klio | fwsim.scm | ;; fwsim.scm - Simulator for fetch-write protocol
;;
Copyright ( c ) 2011 by < >
;; All Right Reserved.
;;
Author : < >
;;
The fecth - write protocol is used to communicate with Siemens S5 / S7 plcs .
;;
;;
;; TODO: check mutex
(##include "~~lib/gambit#.scm")
(##include "~/.klio/prelude#.scm")
(##namespace
("fetchwrite#" OK OPCODE-WRITE OPCODE-FETCH make-response-header))
(load "~/.klio/fetchwrite")
(define buffer (make-u8vector 1024))
(define sample-data
'#u8(
Measures [ 0 , 127 ]
66 242 4 108
67 159 74 131
0 0 0 0
0 0 0 0
0 0 0 0
0 0 0 0
64 224 0 0
65 166 149 142
0 0 0 0
0 0 0 0
0 0 0 0
0 0 0 0
0 0 0 0
0 0 0 0
65 1 213 9
0 0 0 0
66 242 4 108
0 0 0 0
0 0 0 0
0 0 0 0
0 0 0 0
0 0 0 0
0 0 0 0
0 0 0 0
0 0 0 0
0 0 0 0
66 242 4 119
0 0 0 0
0 0 0 0
65 152 0 0
0 0 0 0
0 0 0 0
Alarms [ 128 , 137 ]
0 0 0 0 0 0 0 0 0 0
; misc
channel enablings [ 138 ]
commands enablings [ 139 ]
special contacts enablings [ 140 , 141 ]
aux contacts enablings [ 142 , 143 ]
vacuum contacts enablings [ 144 , 145 ]
channel enablings [ 146 ]
commands enablings [ 147 ]
special contacts enablings [ 148 , 149 ]
aux contacts enabling [ 150 , 151 ]
vacuum contacts enablings [ 152 , 153 ]
67 22 0 0
0 0 0 0
64 64 0 0
66 72 0 0
0 0 0 0
0 0 0 0
0 0 0 0
0 0 0 0
0 0 0 0
0 0 0 0
0 0 0 0
0 0 0 0
0 0 0 0
0 0 0 0
0 0 0 0
0 0 0 0
0 0 0 0
0 0 0 0
0 0 0 0
0 0 0 0
0 0 0 0
0 0 0 0
0 0 0 0
0 0 0 0))
(define buffer-mutex (make-mutex))
(define (serve-request req p)
(let* ((opcode (u8vector-ref req 5))
(org-id (u8vector-ref req 8))
(db (u8vector-ref req 9))
(offset-high (u8vector-ref req 10))
(offset-low (u8vector-ref req 11))
(offset (bitwise-ior (arithmetic-shift offset-high 8) offset-low))
(len-high (u8vector-ref req 12))
(len-low (u8vector-ref req 13))
(len (bitwise-ior (arithmetic-shift len-high 8) len-low)))
(cond
((eqv? opcode OPCODE-WRITE)
(db-write org-id db offset len p))
((eqv? opcode OPCODE-FETCH)
(fetch org-id db offset len p))
(else (raise "Unknown opcode")))))
(define (db-write org-id db offset len
#!optional (p (current-output-port)))
(let ((data (make-u8vector len)))
(read-subu8vector data 0 len p)
(pp data)
(pp (subu8vector sample-data (* 2 offset) (* 2 (+ offset len))))
(with-input-from-u8vector
data
(lambda ()
(with-mutex buffer-mutex
(read-subu8vector sample-data (* 2 offset) (* 2 (+ offset len))))))
(pp (subu8vector sample-data (* 2 offset) (* 2 (+ offset len))))
(force-output (current-error-port))
(write-subu8vector (make-response-header OK) 0 16 p)
(force-output p)))
(define (fetch org-id db offset len #!optional (p (current-output-port)))
(write-subu8vector (make-response-header OK) 0 16 p)
(mutex-lock! buffer-mutex #f #f)
(write-subu8vector sample-data (* 2 offset) (* 2 (+ offset len)) p)
(force-output p)
(mutex-unlock! buffer-mutex))
(define (serve-connection p)
(let ((request (make-u8vector 16)))
(print (time->seconds (current-time)) " - Serving request ...")
(read-subu8vector request 0 16 p)
(serve-request request p)
(println "done.")
(serve-connection p)))
(define (srv s)
(let ((p (read s)))
(thread-start!
(make-thread
(lambda ()
(serve-connection p))))
(srv s)))
(define (simulator-start fetch-port write-port)
(let* ((fp (open-tcp-server fetch-port))
(wp (open-tcp-server write-port))
(ft (make-thread (lambda () (srv fp))))
(wt (make-thread (lambda () (srv wp)))))
(thread-start! ft)
(thread-start! wt)
(if (char=? (read-char) #\q)
(exit))))
(simulator-start 2000 2001)
| null | https://raw.githubusercontent.com/mbenelli/klio/33c11700d6080de44a22a27a5147f97899583f6e/examples/scada/fwsim.scm | scheme | fwsim.scm - Simulator for fetch-write protocol
All Right Reserved.
TODO: check mutex
misc | Copyright ( c ) 2011 by < >
Author : < >
The fecth - write protocol is used to communicate with Siemens S5 / S7 plcs .
(##include "~~lib/gambit#.scm")
(##include "~/.klio/prelude#.scm")
(##namespace
("fetchwrite#" OK OPCODE-WRITE OPCODE-FETCH make-response-header))
(load "~/.klio/fetchwrite")
(define buffer (make-u8vector 1024))
(define sample-data
'#u8(
Measures [ 0 , 127 ]
66 242 4 108
67 159 74 131
0 0 0 0
0 0 0 0
0 0 0 0
0 0 0 0
64 224 0 0
65 166 149 142
0 0 0 0
0 0 0 0
0 0 0 0
0 0 0 0
0 0 0 0
0 0 0 0
65 1 213 9
0 0 0 0
66 242 4 108
0 0 0 0
0 0 0 0
0 0 0 0
0 0 0 0
0 0 0 0
0 0 0 0
0 0 0 0
0 0 0 0
0 0 0 0
66 242 4 119
0 0 0 0
0 0 0 0
65 152 0 0
0 0 0 0
0 0 0 0
Alarms [ 128 , 137 ]
0 0 0 0 0 0 0 0 0 0
channel enablings [ 138 ]
commands enablings [ 139 ]
special contacts enablings [ 140 , 141 ]
aux contacts enablings [ 142 , 143 ]
vacuum contacts enablings [ 144 , 145 ]
channel enablings [ 146 ]
commands enablings [ 147 ]
special contacts enablings [ 148 , 149 ]
aux contacts enabling [ 150 , 151 ]
vacuum contacts enablings [ 152 , 153 ]
67 22 0 0
0 0 0 0
64 64 0 0
66 72 0 0
0 0 0 0
0 0 0 0
0 0 0 0
0 0 0 0
0 0 0 0
0 0 0 0
0 0 0 0
0 0 0 0
0 0 0 0
0 0 0 0
0 0 0 0
0 0 0 0
0 0 0 0
0 0 0 0
0 0 0 0
0 0 0 0
0 0 0 0
0 0 0 0
0 0 0 0
0 0 0 0))
(define buffer-mutex (make-mutex))
(define (serve-request req p)
(let* ((opcode (u8vector-ref req 5))
(org-id (u8vector-ref req 8))
(db (u8vector-ref req 9))
(offset-high (u8vector-ref req 10))
(offset-low (u8vector-ref req 11))
(offset (bitwise-ior (arithmetic-shift offset-high 8) offset-low))
(len-high (u8vector-ref req 12))
(len-low (u8vector-ref req 13))
(len (bitwise-ior (arithmetic-shift len-high 8) len-low)))
(cond
((eqv? opcode OPCODE-WRITE)
(db-write org-id db offset len p))
((eqv? opcode OPCODE-FETCH)
(fetch org-id db offset len p))
(else (raise "Unknown opcode")))))
(define (db-write org-id db offset len
#!optional (p (current-output-port)))
(let ((data (make-u8vector len)))
(read-subu8vector data 0 len p)
(pp data)
(pp (subu8vector sample-data (* 2 offset) (* 2 (+ offset len))))
(with-input-from-u8vector
data
(lambda ()
(with-mutex buffer-mutex
(read-subu8vector sample-data (* 2 offset) (* 2 (+ offset len))))))
(pp (subu8vector sample-data (* 2 offset) (* 2 (+ offset len))))
(force-output (current-error-port))
(write-subu8vector (make-response-header OK) 0 16 p)
(force-output p)))
(define (fetch org-id db offset len #!optional (p (current-output-port)))
(write-subu8vector (make-response-header OK) 0 16 p)
(mutex-lock! buffer-mutex #f #f)
(write-subu8vector sample-data (* 2 offset) (* 2 (+ offset len)) p)
(force-output p)
(mutex-unlock! buffer-mutex))
(define (serve-connection p)
(let ((request (make-u8vector 16)))
(print (time->seconds (current-time)) " - Serving request ...")
(read-subu8vector request 0 16 p)
(serve-request request p)
(println "done.")
(serve-connection p)))
(define (srv s)
(let ((p (read s)))
(thread-start!
(make-thread
(lambda ()
(serve-connection p))))
(srv s)))
(define (simulator-start fetch-port write-port)
(let* ((fp (open-tcp-server fetch-port))
(wp (open-tcp-server write-port))
(ft (make-thread (lambda () (srv fp))))
(wt (make-thread (lambda () (srv wp)))))
(thread-start! ft)
(thread-start! wt)
(if (char=? (read-char) #\q)
(exit))))
(simulator-start 2000 2001)
|
302602f8fd09e3934769adc58724a04585251018a580999a88d155f99153daca | zenspider/schemers | exercise.2.70.scm | #lang racket/base
(require "../lib/test.rkt")
(require "../lib/myutils.scm")
Exercise 2.70 :
The following eight - symbol alphabet with associated relative
frequencies was designed to efficiently encode the lyrics of 1950s
;; rock songs. (Note that the "symbols" of an "alphabet" need not be
;; individual letters.)
;;
A 2 NA 16
BOOM 1 SHA 3
GET 2 YIP 9
JOB 2 WAH 1
;;
Use ` generate - huffman - tree ' ( * Note Exercise 2 - 69 : :) to generate a
corresponding tree , and use ` encode ' ( * Note Exercise
2 - 68 : :) to encode the following message :
;;
;; Get a job
;; Sha na na na na na na na na
;; Get a job
;; Sha na na na na na na na na
;; Sha boom
;;
;; How many bits are required for the encoding? What is the smallest
;; number of bits that would be needed to encode this song if we used
a fixed - length code for the eight - symbol alphabet ?
( let ( ( input ' ( ( a 2 ) ( na 16 ) ( boom 1 ) ( sha 3 )
( get 2 ) ( yip 9 ) ( job 2 ) ( wah 1 ) ) ) )
;; (let ((tree (generate-huffman-tree input))
;; (song '(get a job
na na na na na na na na
;; get a job
na na na na na na na na
) ) )
;; (encode song tree)))
;; tree:
'((leaf na 16)
((leaf yip 9)
((((leaf boom 1) (leaf wah 1) (boom wah) 2) (leaf a 2) (boom wah a) 4)
((leaf sha 3) ((leaf get 2) (leaf job 2) (get job) 4) (sha get job) 7)
(boom wah a sha get job)
11)
(yip boom wah a sha get job)
20)
(na yip boom wah a sha get job)
36)
;; song:
'(1 1 1 1 0 1 1 0 1 1 1 1 1 1
1 1 1 0 0 0 0 0 0 0 0 0
1 1 1 1 0 1 1 0 1 1 1 1 1 1
1 1 1 0 0 0 0 0 0 0 0 0
1 1 0 0 1 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0
1 1 1 0 1 1 0 0 0)
(done)
| null | https://raw.githubusercontent.com/zenspider/schemers/2939ca553ac79013a4c3aaaec812c1bad3933b16/sicp/ch_2/exercise.2.70.scm | scheme | rock songs. (Note that the "symbols" of an "alphabet" need not be
individual letters.)
Get a job
Sha na na na na na na na na
Get a job
Sha na na na na na na na na
Sha boom
How many bits are required for the encoding? What is the smallest
number of bits that would be needed to encode this song if we used
(let ((tree (generate-huffman-tree input))
(song '(get a job
get a job
(encode song tree)))
tree:
song: | #lang racket/base
(require "../lib/test.rkt")
(require "../lib/myutils.scm")
Exercise 2.70 :
The following eight - symbol alphabet with associated relative
frequencies was designed to efficiently encode the lyrics of 1950s
A 2 NA 16
BOOM 1 SHA 3
GET 2 YIP 9
JOB 2 WAH 1
Use ` generate - huffman - tree ' ( * Note Exercise 2 - 69 : :) to generate a
corresponding tree , and use ` encode ' ( * Note Exercise
2 - 68 : :) to encode the following message :
a fixed - length code for the eight - symbol alphabet ?
( let ( ( input ' ( ( a 2 ) ( na 16 ) ( boom 1 ) ( sha 3 )
( get 2 ) ( yip 9 ) ( job 2 ) ( wah 1 ) ) ) )
na na na na na na na na
na na na na na na na na
) ) )
'((leaf na 16)
((leaf yip 9)
((((leaf boom 1) (leaf wah 1) (boom wah) 2) (leaf a 2) (boom wah a) 4)
((leaf sha 3) ((leaf get 2) (leaf job 2) (get job) 4) (sha get job) 7)
(boom wah a sha get job)
11)
(yip boom wah a sha get job)
20)
(na yip boom wah a sha get job)
36)
'(1 1 1 1 0 1 1 0 1 1 1 1 1 1
1 1 1 0 0 0 0 0 0 0 0 0
1 1 1 1 0 1 1 0 1 1 1 1 1 1
1 1 1 0 0 0 0 0 0 0 0 0
1 1 0 0 1 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0
1 1 1 0 1 1 0 0 0)
(done)
|
81618eb580e6bc12bceebdaf30bcaa3ffecd454cbc5e2e9c7580d96be3b2c86a | fused-effects/fused-effects-exceptions | Main.hs | {-# LANGUAGE ScopedTypeVariables, TypeApplications #-}
module Main where
import Prelude hiding (ioError)
import qualified Control.Carrier.State.IORef as IOState
import qualified Control.Carrier.State.Strict as State
import Control.Carrier.Lift (runM)
import Control.Effect.Exception
import Control.Effect.State
import qualified Test.Tasty as Tasty
import qualified Test.Tasty.HUnit as HUnit
problematic :: (Has (Lift IO) sig m, Has (State Char) sig m) => m ()
problematic =
let throws = modify @Char succ *> throwIO (userError "should explode") `finally` put @Char 'x'
in throws `catch` (\(_ :: IOException) -> pure ())
testStateDropsWrites :: Tasty.TestTree
testStateDropsWrites = HUnit.testCase "State.Strict drops writes" $ do
result <- State.execState 'a' problematic
result HUnit.@?= 'a' -- writes are lost
testIOStatePreservesWrites :: Tasty.TestTree
testIOStatePreservesWrites = HUnit.testCase "State.IORef preserves writes" $ do
result <- IOState.execState 'a' problematic
result HUnit.@?= 'x'
tests :: Tasty.TestTree
tests = Tasty.testGroup "Control.Carrier.Exception"
[ Tasty.testGroup "finally"
[ testStateDropsWrites
, testIOStatePreservesWrites
]
]
main :: IO ()
main = Tasty.defaultMain tests
| null | https://raw.githubusercontent.com/fused-effects/fused-effects-exceptions/7920fa7a96743b0c77897651707be09f31d4afbc/test/Main.hs | haskell | # LANGUAGE ScopedTypeVariables, TypeApplications #
writes are lost |
module Main where
import Prelude hiding (ioError)
import qualified Control.Carrier.State.IORef as IOState
import qualified Control.Carrier.State.Strict as State
import Control.Carrier.Lift (runM)
import Control.Effect.Exception
import Control.Effect.State
import qualified Test.Tasty as Tasty
import qualified Test.Tasty.HUnit as HUnit
problematic :: (Has (Lift IO) sig m, Has (State Char) sig m) => m ()
problematic =
let throws = modify @Char succ *> throwIO (userError "should explode") `finally` put @Char 'x'
in throws `catch` (\(_ :: IOException) -> pure ())
testStateDropsWrites :: Tasty.TestTree
testStateDropsWrites = HUnit.testCase "State.Strict drops writes" $ do
result <- State.execState 'a' problematic
testIOStatePreservesWrites :: Tasty.TestTree
testIOStatePreservesWrites = HUnit.testCase "State.IORef preserves writes" $ do
result <- IOState.execState 'a' problematic
result HUnit.@?= 'x'
tests :: Tasty.TestTree
tests = Tasty.testGroup "Control.Carrier.Exception"
[ Tasty.testGroup "finally"
[ testStateDropsWrites
, testIOStatePreservesWrites
]
]
main :: IO ()
main = Tasty.defaultMain tests
|
29f76fbf4ab2547ab14b03badf5aa221f1b9131f84b8714bf0d5c5bdda552bae | ParaPhrase/skel | sk_assembler.erl | %%%----------------------------------------------------------------------------
@author < >
2012 University of St Andrews ( See LICENCE )
@headerfile " skel.hrl "
%%%
%%% @doc This module takes a workflow specification, and converts it in into a
%%% set of (concurrent) running processes.
%%%
%%%
%%% @end
%%%----------------------------------------------------------------------------
-module(sk_assembler).
-export([
make/2
,make_hyb/4
,run/2
]).
-include("skel.hrl").
-ifdef(TEST).
-compile(export_all).
-endif.
-spec make(workflow(), pid() | module()) -> pid() .
%% @doc Function to produce a set of processes according to the given workflow
%% specification.
make(WorkFlow, EndModule) when is_atom(EndModule) ->
DrainPid = (sk_sink:make(EndModule))(self()),
make(WorkFlow, DrainPid);
make(WorkFlow, EndPid) when is_pid(EndPid) ->
MakeFns = [parse(Section) || Section <- WorkFlow],
lists:foldr(fun(MakeFn, Pid) -> MakeFn(Pid) end, EndPid, MakeFns).
-spec make_hyb(workflow(), pid(), pos_integer(), pos_integer()) -> pid().
make_hyb(WorkFlow, EndPid, NCPUWorkers, NGPUWorkers) when is_pid(EndPid) ->
MakeFns = [parse_hyb(Section, NCPUWorkers, NGPUWorkers) || Section <- WorkFlow],
lists:foldr(fun(MakeFn, Pid) -> MakeFn(Pid) end, EndPid, MakeFns).
-spec run(pid() | workflow(), input()) -> pid().
%% @doc Function to produce and start a set of processes according to the
%% given workflow specification and input.
run(WorkFlow, Input) when is_pid(WorkFlow) ->
Feeder = sk_source:make(Input),
Feeder(WorkFlow);
run(WorkFlow, Input) when is_list(WorkFlow) ->
DrainPid = (sk_sink:make())(self()),
AssembledWF = make(WorkFlow, DrainPid),
run(AssembledWF, Input).
parse_hyb(Section, NCPUWorkers, NGPUWorkers) ->
case Section of
{hyb_map, WorkFlowCPU, WorkFlowGPU} ->
parse({hyb_map, WorkFlowCPU, WorkFlowGPU, NCPUWorkers, NGPUWorkers});
Other -> parse(Other)
end.
-spec parse(wf_item()) -> maker_fun().
%% @doc Determines the course of action to be taken according to the type of
%% workflow specified. Constructs and starts specific skeleton instances.
parse(Fun) when is_function(Fun, 1) ->
parse({seq, Fun});
parse({seq, Fun}) when is_function(Fun, 1) ->
sk_seq:make(Fun);
parse({pipe, WorkFlow}) ->
sk_pipe:make(WorkFlow);
parse({ord, WorkFlow}) ->
sk_ord:make(WorkFlow);
parse({farm, WorkFlow, NWorkers}) ->
sk_farm:make(NWorkers, WorkFlow);
parse({hyb_farm, WorkFlowCPU, WorkFlowGPU, NCPUWorkers, NGPUWorkers}) ->
sk_farm:make_hyb(NCPUWorkers, NGPUWorkers, WorkFlowCPU, WorkFlowGPU);
parse({map, WorkFlow}) ->
sk_map:make(WorkFlow);
parse({map, WorkFlow, NWorkers}) ->
sk_map:make(WorkFlow, NWorkers);
parse({hyb_map, WorkFlowCPU, WorkFlowGPU}) ->
sk_map:make_hyb(WorkFlowCPU, WorkFlowGPU);
parse({hyb_map, WorkFlowCPU, WorkFlowGPU, NCPUWorkers, NGPUWorkers}) ->
sk_map:make_hyb(WorkFlowCPU, WorkFlowGPU, NCPUWorkers, NGPUWorkers);
parse({cluster, WorkFlow, Decomp, Recomp}) when is_function(Decomp, 1),
is_function(Recomp, 1) ->
sk_cluster:make(WorkFlow, Decomp, Recomp);
parse({hyb_cluster, WorkFlow, Decomp, Recomp, NCPUWorkers, NGPUWorkers}) when
is_function(Decomp, 1), is_function(Recomp, 1) ->
sk_cluster:make_hyb(WorkFlow, Decomp, Recomp, NCPUWorkers, NGPUWorkers);
parse({hyb_cluster, WorkFlow, TimeRatio, NCPUWorkers, NGPUWorkers}) ->
sk_cluster:make_hyb(WorkFlow, TimeRatio, NCPUWorkers, NGPUWorkers);
parse({hyb_cluster, WorkFlow, TimeRatio, StructSizeFun, MakeChunkFun, RecompFun, NCPUWorkers, NGPUWorkers}) ->
sk_cluster:make_hyb(WorkFlow, TimeRatio, StructSizeFun, MakeChunkFun, RecompFun, NCPUWorkers, NGPUWorkers);
parse({decomp , WorkFlow , Decomp , Recomp } ) when is_function(Decomp , 1 ) ,
is_function(Recomp , 1 ) - >
sk_decomp : make(WorkFlow , Decomp , Recomp ) ;
parse({map , WorkFlow , Decomp , Recomp } ) when is_function(Decomp , 1 ) ,
is_function(Recomp , 1 ) - >
sk_map : make(WorkFlow , Decomp , Recomp ) ;
parse({reduce, Reduce, Decomp}) when is_function(Reduce, 2),
is_function(Decomp, 1) ->
sk_reduce:make(Decomp, Reduce);
parse({feedback, WorkFlow, Filter}) when is_function(Filter, 1) ->
sk_feedback:make(WorkFlow, Filter).
| null | https://raw.githubusercontent.com/ParaPhrase/skel/bf55de94e64354592ea335f4375f4b40607baf43/src/sk_assembler.erl | erlang | ----------------------------------------------------------------------------
@doc This module takes a workflow specification, and converts it in into a
set of (concurrent) running processes.
@end
----------------------------------------------------------------------------
@doc Function to produce a set of processes according to the given workflow
specification.
@doc Function to produce and start a set of processes according to the
given workflow specification and input.
@doc Determines the course of action to be taken according to the type of
workflow specified. Constructs and starts specific skeleton instances. | @author < >
2012 University of St Andrews ( See LICENCE )
@headerfile " skel.hrl "
-module(sk_assembler).
-export([
make/2
,make_hyb/4
,run/2
]).
-include("skel.hrl").
-ifdef(TEST).
-compile(export_all).
-endif.
-spec make(workflow(), pid() | module()) -> pid() .
make(WorkFlow, EndModule) when is_atom(EndModule) ->
DrainPid = (sk_sink:make(EndModule))(self()),
make(WorkFlow, DrainPid);
make(WorkFlow, EndPid) when is_pid(EndPid) ->
MakeFns = [parse(Section) || Section <- WorkFlow],
lists:foldr(fun(MakeFn, Pid) -> MakeFn(Pid) end, EndPid, MakeFns).
-spec make_hyb(workflow(), pid(), pos_integer(), pos_integer()) -> pid().
make_hyb(WorkFlow, EndPid, NCPUWorkers, NGPUWorkers) when is_pid(EndPid) ->
MakeFns = [parse_hyb(Section, NCPUWorkers, NGPUWorkers) || Section <- WorkFlow],
lists:foldr(fun(MakeFn, Pid) -> MakeFn(Pid) end, EndPid, MakeFns).
-spec run(pid() | workflow(), input()) -> pid().
run(WorkFlow, Input) when is_pid(WorkFlow) ->
Feeder = sk_source:make(Input),
Feeder(WorkFlow);
run(WorkFlow, Input) when is_list(WorkFlow) ->
DrainPid = (sk_sink:make())(self()),
AssembledWF = make(WorkFlow, DrainPid),
run(AssembledWF, Input).
parse_hyb(Section, NCPUWorkers, NGPUWorkers) ->
case Section of
{hyb_map, WorkFlowCPU, WorkFlowGPU} ->
parse({hyb_map, WorkFlowCPU, WorkFlowGPU, NCPUWorkers, NGPUWorkers});
Other -> parse(Other)
end.
-spec parse(wf_item()) -> maker_fun().
parse(Fun) when is_function(Fun, 1) ->
parse({seq, Fun});
parse({seq, Fun}) when is_function(Fun, 1) ->
sk_seq:make(Fun);
parse({pipe, WorkFlow}) ->
sk_pipe:make(WorkFlow);
parse({ord, WorkFlow}) ->
sk_ord:make(WorkFlow);
parse({farm, WorkFlow, NWorkers}) ->
sk_farm:make(NWorkers, WorkFlow);
parse({hyb_farm, WorkFlowCPU, WorkFlowGPU, NCPUWorkers, NGPUWorkers}) ->
sk_farm:make_hyb(NCPUWorkers, NGPUWorkers, WorkFlowCPU, WorkFlowGPU);
parse({map, WorkFlow}) ->
sk_map:make(WorkFlow);
parse({map, WorkFlow, NWorkers}) ->
sk_map:make(WorkFlow, NWorkers);
parse({hyb_map, WorkFlowCPU, WorkFlowGPU}) ->
sk_map:make_hyb(WorkFlowCPU, WorkFlowGPU);
parse({hyb_map, WorkFlowCPU, WorkFlowGPU, NCPUWorkers, NGPUWorkers}) ->
sk_map:make_hyb(WorkFlowCPU, WorkFlowGPU, NCPUWorkers, NGPUWorkers);
parse({cluster, WorkFlow, Decomp, Recomp}) when is_function(Decomp, 1),
is_function(Recomp, 1) ->
sk_cluster:make(WorkFlow, Decomp, Recomp);
parse({hyb_cluster, WorkFlow, Decomp, Recomp, NCPUWorkers, NGPUWorkers}) when
is_function(Decomp, 1), is_function(Recomp, 1) ->
sk_cluster:make_hyb(WorkFlow, Decomp, Recomp, NCPUWorkers, NGPUWorkers);
parse({hyb_cluster, WorkFlow, TimeRatio, NCPUWorkers, NGPUWorkers}) ->
sk_cluster:make_hyb(WorkFlow, TimeRatio, NCPUWorkers, NGPUWorkers);
parse({hyb_cluster, WorkFlow, TimeRatio, StructSizeFun, MakeChunkFun, RecompFun, NCPUWorkers, NGPUWorkers}) ->
sk_cluster:make_hyb(WorkFlow, TimeRatio, StructSizeFun, MakeChunkFun, RecompFun, NCPUWorkers, NGPUWorkers);
parse({decomp , WorkFlow , Decomp , Recomp } ) when is_function(Decomp , 1 ) ,
is_function(Recomp , 1 ) - >
sk_decomp : make(WorkFlow , Decomp , Recomp ) ;
parse({map , WorkFlow , Decomp , Recomp } ) when is_function(Decomp , 1 ) ,
is_function(Recomp , 1 ) - >
sk_map : make(WorkFlow , Decomp , Recomp ) ;
parse({reduce, Reduce, Decomp}) when is_function(Reduce, 2),
is_function(Decomp, 1) ->
sk_reduce:make(Decomp, Reduce);
parse({feedback, WorkFlow, Filter}) when is_function(Filter, 1) ->
sk_feedback:make(WorkFlow, Filter).
|
ec34e0b2672499b079255b518bdeaa5c3a36b9964a7b0a4e1069d234c7ce6844 | chchen/comet | mapping.rkt | #lang rosette/safe
(require "../synth.rkt"
"../util.rkt"
"bitvector.rkt"
"symbolic.rkt"
"syntax.rkt"
(prefix-in unity: "../unity/semantics.rkt")
(prefix-in unity: "../unity/syntax.rkt")
rosette/lib/match
;; unsafe! only allowed for concrete evaluation
(only-in racket/base string->symbol))
(define max-pin-id
21)
The Arduino model admits four different sorts of mutable references : byte
;; variables, unsigned int variables, input pins, and output pins. Variables are
;; used for internal state, and pins are used for external state (input/output).
;;
;; The current strategy for showing equivalence is to translate a
;; UNITY context C_u into an Arduino context C_a, and to derive a mapping
from any Arduino state S_a that satisifes C_a to a UNITY state S_u
;; that satisifies C_u.
;;
We can show that two programs are equivalent by generating an Arduino
symbolic state S_a that satisifies C_a , mapping it to a symbolic UNITY state
;; S_a->S_u, symbolically interpreting the reference program against S_a->S_u
;; yielding a new symbolic state S_a->S_u', then finding an Arduino program P
;; such that interpreting P against S_a yields a state S_a' such that the
;; mapping into the UNITY state S_a'->S_u' is equivalent to S_a->S_u.
;;
;; This function takes a UNITY context and provides a corresponding synth-map.
;;
;; unity_context -> synth_map
(define (unity-context->synth-map unity-context)
;; num -> num (checking to see if we're within pin bounds)
(define (next-pin-id current)
(if (>= current max-pin-id)
current
(add1 current)))
;; create a new symbol according to format
(define (symbol-format fmt sym)
(string->symbol (format fmt sym)))
;; map: symbol to f: arduino_state -> unity_state ->
;; arduino_state ->
;; unity_state
;; (f: symbol -> (fn: arduino_state -> unity_val))
;; -> arduino_state
;; -> unity_state
(define (state-mapper state-map state)
(match state-map
['() '()]
[(cons (cons id fn) tail)
(cons (cons id (fn state))
(state-mapper tail state))]))
;; (f: symbol -> (fn: arduino_state -> unity_val))
;; -> unity_id
;; -> arduino_state
;; -> unity_val
(define (state-id-mapper state-map id state)
(let ([id-fn (get-mapping id state-map)])
(if (null? id-fn)
'()
(id-fn state))))
(define (target-id-writable? id cxt)
(match (get-mapping id cxt)
['byte #t]
['unsigned-int #t]
['pin-out #t]
[_ #f]))
(define (helper working-unity-cxt arduino-cxt state-map inv-map current-pin)
(match working-unity-cxt
['() (synth-map (unity:context->external-vars unity-context)
(unity:context->internal-vars unity-context)
arduino-cxt
(symbolic-state arduino-cxt)
(lambda (id) (target-id-writable? id arduino-cxt))
(lambda (st) (state-mapper state-map st))
(lambda (id st) (state-id-mapper state-map id st))
(lambda (id) (get-mapping id inv-map)))]
[(cons (cons id 'boolean) tail)
(helper tail
(cons (cons id 'unsigned-int)
arduino-cxt)
(cons (cons id
(lambda (st)
(bitvector->bool (get-mapping id st))))
state-map)
(cons (cons id (list id))
inv-map)
current-pin)]
[(cons (cons id 'natural) tail)
(helper tail
(cons (cons id 'unsigned-int)
arduino-cxt)
(cons (cons id
(lambda (st)
(bitvector->natural (get-mapping id st))))
state-map)
(cons (cons id (list id))
inv-map)
current-pin)]
[(cons (cons id 'recv-channel) tail)
(let* ([req-pin current-pin]
[ack-pin (next-pin-id req-pin)]
[val-pin (next-pin-id ack-pin)]
[req-id (symbol-format "d~a" req-pin)]
[ack-id (symbol-format "d~a" ack-pin)]
[val-id (symbol-format "d~a" val-pin)])
(helper tail
(append (list (cons req-id 'pin-in)
(cons ack-id 'pin-out)
(cons val-id 'pin-in))
arduino-cxt)
(cons (cons id
(lambda (st)
(let ([req-v (get-mapping req-id st)]
[ack-v (get-mapping ack-id st)]
[val-v (get-mapping val-id st)])
(if (xor req-v ack-v)
(unity:channel* #t val-v)
(unity:channel* #f null)))))
state-map)
(cons (cons id (list req-id ack-id val-id))
inv-map)
(next-pin-id val-pin)))]
[(cons (cons id 'send-channel) tail)
(let* ([req-pin current-pin]
[ack-pin (next-pin-id req-pin)]
[val-pin (next-pin-id ack-pin)]
[req-id (symbol-format "d~a" req-pin)]
[ack-id (symbol-format "d~a" ack-pin)]
[val-id (symbol-format "d~a" val-pin)])
(helper tail
(append (list (cons req-id 'pin-out)
(cons ack-id 'pin-in)
(cons val-id 'pin-out))
arduino-cxt)
(cons (cons id
(lambda (st)
(let ([req-v (get-mapping req-id st)]
[ack-v (get-mapping ack-id st)]
[val-v (get-mapping val-id st)])
(if (xor req-v ack-v)
(unity:channel* #t val-v)
(unity:channel* #f null)))))
state-map)
(cons (cons id (list req-id ack-id val-id))
inv-map)
(next-pin-id val-pin)))]
[(cons (cons id 'recv-buf) tail)
(let ([rcvd-id (symbol-format "~a_rcvd" id)]
[vals-id (symbol-format "~a_vals" id)])
(helper tail
(append (list (cons rcvd-id 'unsigned-int)
(cons vals-id 'unsigned-int))
arduino-cxt)
(cons (cons id
(lambda (st)
(let ([rcvd-val (get-mapping rcvd-id st)]
[vals-val (get-mapping vals-id st)])
(unity:buffer* (bitvector->natural rcvd-val)
(map bitvector->bool
(bitvector->bits vals-val))))))
state-map)
(cons (cons id (list rcvd-id vals-id))
inv-map)
current-pin))]
[(cons (cons id 'send-buf) tail)
(let ([sent-id (symbol-format "~a_sent" id)]
[vals-id (symbol-format "~a_vals" id)])
(helper tail
(append (list (cons sent-id 'unsigned-int)
(cons vals-id 'unsigned-int))
arduino-cxt)
(cons (cons id
(lambda (st)
(let ([sent-val (get-mapping sent-id st)]
[vals-val (get-mapping vals-id st)])
(unity:buffer* (bitvector->natural sent-val)
(map bitvector->bool
(bitvector->bits vals-val))))))
state-map)
(cons (cons id (list sent-id vals-id))
inv-map)
current-pin))]))
(helper unity-context '() '() '() 0))
(define (unity-prog->synth-map unity-prog)
(match unity-prog
[(unity:unity*
(unity:declare* unity-cxt)
initially
assign)
(unity-context->synth-map unity-cxt)]))
(provide unity-prog->synth-map)
| null | https://raw.githubusercontent.com/chchen/comet/005477b761f4d35c9fce175738f4dcbb805909e7/unity-synthesis/arduino/mapping.rkt | racket | unsafe! only allowed for concrete evaluation
variables, unsigned int variables, input pins, and output pins. Variables are
used for internal state, and pins are used for external state (input/output).
The current strategy for showing equivalence is to translate a
UNITY context C_u into an Arduino context C_a, and to derive a mapping
that satisifies C_u.
S_a->S_u, symbolically interpreting the reference program against S_a->S_u
yielding a new symbolic state S_a->S_u', then finding an Arduino program P
such that interpreting P against S_a yields a state S_a' such that the
mapping into the UNITY state S_a'->S_u' is equivalent to S_a->S_u.
This function takes a UNITY context and provides a corresponding synth-map.
unity_context -> synth_map
num -> num (checking to see if we're within pin bounds)
create a new symbol according to format
map: symbol to f: arduino_state -> unity_state ->
arduino_state ->
unity_state
(f: symbol -> (fn: arduino_state -> unity_val))
-> arduino_state
-> unity_state
(f: symbol -> (fn: arduino_state -> unity_val))
-> unity_id
-> arduino_state
-> unity_val | #lang rosette/safe
(require "../synth.rkt"
"../util.rkt"
"bitvector.rkt"
"symbolic.rkt"
"syntax.rkt"
(prefix-in unity: "../unity/semantics.rkt")
(prefix-in unity: "../unity/syntax.rkt")
rosette/lib/match
(only-in racket/base string->symbol))
(define max-pin-id
21)
The Arduino model admits four different sorts of mutable references : byte
from any Arduino state S_a that satisifes C_a to a UNITY state S_u
We can show that two programs are equivalent by generating an Arduino
symbolic state S_a that satisifies C_a , mapping it to a symbolic UNITY state
(define (unity-context->synth-map unity-context)
(define (next-pin-id current)
(if (>= current max-pin-id)
current
(add1 current)))
(define (symbol-format fmt sym)
(string->symbol (format fmt sym)))
(define (state-mapper state-map state)
(match state-map
['() '()]
[(cons (cons id fn) tail)
(cons (cons id (fn state))
(state-mapper tail state))]))
(define (state-id-mapper state-map id state)
(let ([id-fn (get-mapping id state-map)])
(if (null? id-fn)
'()
(id-fn state))))
(define (target-id-writable? id cxt)
(match (get-mapping id cxt)
['byte #t]
['unsigned-int #t]
['pin-out #t]
[_ #f]))
(define (helper working-unity-cxt arduino-cxt state-map inv-map current-pin)
(match working-unity-cxt
['() (synth-map (unity:context->external-vars unity-context)
(unity:context->internal-vars unity-context)
arduino-cxt
(symbolic-state arduino-cxt)
(lambda (id) (target-id-writable? id arduino-cxt))
(lambda (st) (state-mapper state-map st))
(lambda (id st) (state-id-mapper state-map id st))
(lambda (id) (get-mapping id inv-map)))]
[(cons (cons id 'boolean) tail)
(helper tail
(cons (cons id 'unsigned-int)
arduino-cxt)
(cons (cons id
(lambda (st)
(bitvector->bool (get-mapping id st))))
state-map)
(cons (cons id (list id))
inv-map)
current-pin)]
[(cons (cons id 'natural) tail)
(helper tail
(cons (cons id 'unsigned-int)
arduino-cxt)
(cons (cons id
(lambda (st)
(bitvector->natural (get-mapping id st))))
state-map)
(cons (cons id (list id))
inv-map)
current-pin)]
[(cons (cons id 'recv-channel) tail)
(let* ([req-pin current-pin]
[ack-pin (next-pin-id req-pin)]
[val-pin (next-pin-id ack-pin)]
[req-id (symbol-format "d~a" req-pin)]
[ack-id (symbol-format "d~a" ack-pin)]
[val-id (symbol-format "d~a" val-pin)])
(helper tail
(append (list (cons req-id 'pin-in)
(cons ack-id 'pin-out)
(cons val-id 'pin-in))
arduino-cxt)
(cons (cons id
(lambda (st)
(let ([req-v (get-mapping req-id st)]
[ack-v (get-mapping ack-id st)]
[val-v (get-mapping val-id st)])
(if (xor req-v ack-v)
(unity:channel* #t val-v)
(unity:channel* #f null)))))
state-map)
(cons (cons id (list req-id ack-id val-id))
inv-map)
(next-pin-id val-pin)))]
[(cons (cons id 'send-channel) tail)
(let* ([req-pin current-pin]
[ack-pin (next-pin-id req-pin)]
[val-pin (next-pin-id ack-pin)]
[req-id (symbol-format "d~a" req-pin)]
[ack-id (symbol-format "d~a" ack-pin)]
[val-id (symbol-format "d~a" val-pin)])
(helper tail
(append (list (cons req-id 'pin-out)
(cons ack-id 'pin-in)
(cons val-id 'pin-out))
arduino-cxt)
(cons (cons id
(lambda (st)
(let ([req-v (get-mapping req-id st)]
[ack-v (get-mapping ack-id st)]
[val-v (get-mapping val-id st)])
(if (xor req-v ack-v)
(unity:channel* #t val-v)
(unity:channel* #f null)))))
state-map)
(cons (cons id (list req-id ack-id val-id))
inv-map)
(next-pin-id val-pin)))]
[(cons (cons id 'recv-buf) tail)
(let ([rcvd-id (symbol-format "~a_rcvd" id)]
[vals-id (symbol-format "~a_vals" id)])
(helper tail
(append (list (cons rcvd-id 'unsigned-int)
(cons vals-id 'unsigned-int))
arduino-cxt)
(cons (cons id
(lambda (st)
(let ([rcvd-val (get-mapping rcvd-id st)]
[vals-val (get-mapping vals-id st)])
(unity:buffer* (bitvector->natural rcvd-val)
(map bitvector->bool
(bitvector->bits vals-val))))))
state-map)
(cons (cons id (list rcvd-id vals-id))
inv-map)
current-pin))]
[(cons (cons id 'send-buf) tail)
(let ([sent-id (symbol-format "~a_sent" id)]
[vals-id (symbol-format "~a_vals" id)])
(helper tail
(append (list (cons sent-id 'unsigned-int)
(cons vals-id 'unsigned-int))
arduino-cxt)
(cons (cons id
(lambda (st)
(let ([sent-val (get-mapping sent-id st)]
[vals-val (get-mapping vals-id st)])
(unity:buffer* (bitvector->natural sent-val)
(map bitvector->bool
(bitvector->bits vals-val))))))
state-map)
(cons (cons id (list sent-id vals-id))
inv-map)
current-pin))]))
(helper unity-context '() '() '() 0))
(define (unity-prog->synth-map unity-prog)
(match unity-prog
[(unity:unity*
(unity:declare* unity-cxt)
initially
assign)
(unity-context->synth-map unity-cxt)]))
(provide unity-prog->synth-map)
|
718f41be6ddee0a27cc92491223b523111d2e00b9c37b21ae97dfe59db31c530 | spurious/snd-mirror | rgb.scm | ;;; X11 color names converted to Snd colors
(provide 'snd-rgb.scm)
(define *rgb*
(let ((snow (make-color 1.00 0.98 0.98))
(ghost-white (make-color 0.97 0.97 1.00))
(white-smoke (make-color 0.96 0.96 0.96))
(gainsboro (make-color 0.86 0.86 0.86))
(floral-white (make-color 1.00 0.98 0.94))
(old-lace (make-color 0.99 0.96 0.90))
(linen (make-color 0.98 0.94 0.90))
(antique-white (make-color 0.98 0.92 0.84))
(papaya-whip (make-color 1.00 0.93 0.83))
(blanched-almond (make-color 1.00 0.92 0.80))
(bisque (make-color 1.00 0.89 0.77))
(peach-puff (make-color 1.00 0.85 0.72))
(navajo-white (make-color 1.00 0.87 0.68))
(moccasin (make-color 1.00 0.89 0.71))
(cornsilk (make-color 1.00 0.97 0.86))
(ivory (make-color 1.00 1.00 0.94))
(lemon-chiffon (make-color 1.00 0.98 0.80))
(seashell (make-color 1.00 0.96 0.93))
(honeydew (make-color 0.94 1.00 0.94))
(mint-cream (make-color 0.96 1.00 0.98))
(azure (make-color 0.94 1.00 1.00))
(alice-blue (make-color 0.94 0.97 1.00))
(lavender (make-color 0.90 0.90 0.98))
(lavender-blush (make-color 1.00 0.94 0.96))
(misty-rose (make-color 1.00 0.89 0.88))
(white (make-color 1.00 1.00 1.00))
(black (make-color 0.00 0.00 0.00))
(dark-slate-gray (make-color 0.18 0.31 0.31))
(dark-slate-grey (make-color 0.18 0.31 0.31))
(dim-gray (make-color 0.41 0.41 0.41))
(dim-grey (make-color 0.41 0.41 0.41))
(slate-gray (make-color 0.44 0.50 0.56))
(slate-grey (make-color 0.44 0.50 0.56))
(light-slate-gray (make-color 0.46 0.53 0.60))
(light-slate-grey (make-color 0.46 0.53 0.60))
(gray (make-color 0.74 0.74 0.74))
(grey (make-color 0.74 0.74 0.74))
(light-grey (make-color 0.82 0.82 0.82))
(light-gray (make-color 0.82 0.82 0.82))
(midnight-blue (make-color 0.10 0.10 0.44))
(navy (make-color 0.00 0.00 0.50))
(navy-blue (make-color 0.00 0.00 0.50))
(cornflower-blue (make-color 0.39 0.58 0.93))
(dark-slate-blue (make-color 0.28 0.24 0.54))
(slate-blue (make-color 0.41 0.35 0.80))
(medium-slate-blue (make-color 0.48 0.41 0.93))
(light-slate-blue (make-color 0.52 0.44 1.00))
(medium-blue (make-color 0.00 0.00 0.80))
(royal-blue (make-color 0.25 0.41 0.88))
(blue (make-color 0.00 0.00 1.00))
(dodger-blue (make-color 0.12 0.56 1.00))
(deep-sky-blue (make-color 0.00 0.75 1.00))
(sky-blue (make-color 0.53 0.80 0.92))
(light-sky-blue (make-color 0.53 0.80 0.98))
(steel-blue (make-color 0.27 0.51 0.70))
(light-steel-blue (make-color 0.69 0.77 0.87))
(light-blue (make-color 0.68 0.84 0.90))
(powder-blue (make-color 0.69 0.87 0.90))
(pale-turquoise (make-color 0.68 0.93 0.93))
(dark-turquoise (make-color 0.00 0.80 0.82))
(medium-turquoise (make-color 0.28 0.82 0.80))
(turquoise (make-color 0.25 0.87 0.81))
(cyan (make-color 0.00 1.00 1.00))
(light-cyan (make-color 0.87 1.00 1.00))
(cadet-blue (make-color 0.37 0.62 0.62))
(medium-aquamarine (make-color 0.40 0.80 0.66))
(aquamarine (make-color 0.50 1.00 0.83))
(dark-green (make-color 0.00 0.39 0.00))
(dark-olive-green (make-color 0.33 0.42 0.18))
(dark-sea-green (make-color 0.56 0.73 0.56))
(sea-green (make-color 0.18 0.54 0.34))
(medium-sea-green (make-color 0.23 0.70 0.44))
(light-sea-green (make-color 0.12 0.70 0.66))
(pale-green (make-color 0.59 0.98 0.59))
(spring-green (make-color 0.00 1.00 0.50))
(lawn-green (make-color 0.48 0.98 0.00))
(green (make-color 0.00 1.00 0.00))
(chartreuse (make-color 0.50 1.00 0.00))
(medium-spring-green (make-color 0.00 0.98 0.60))
(green-yellow (make-color 0.68 1.00 0.18))
(lime-green (make-color 0.20 0.80 0.20))
(yellow-green (make-color 0.60 0.80 0.20))
(forest-green (make-color 0.13 0.54 0.13))
(olive-drab (make-color 0.42 0.55 0.14))
(dark-khaki (make-color 0.74 0.71 0.42))
(khaki (make-color 0.94 0.90 0.55))
(pale-goldenrod (make-color 0.93 0.91 0.66))
(light-goldenrod-yellow (make-color 0.98 0.98 0.82))
(light-yellow (make-color 1.00 1.00 0.87))
(yellow (make-color 1.00 1.00 0.00))
(gold (make-color 1.00 0.84 0.00))
(light-goldenrod (make-color 0.93 0.86 0.51))
(goldenrod (make-color 0.85 0.64 0.12))
(dark-goldenrod (make-color 0.72 0.52 0.04))
(rosy-brown (make-color 0.73 0.56 0.56))
(indian-red (make-color 0.80 0.36 0.36))
(saddle-brown (make-color 0.54 0.27 0.07))
(sienna (make-color 0.62 0.32 0.18))
(peru (make-color 0.80 0.52 0.25))
(burlywood (make-color 0.87 0.72 0.53))
(beige (make-color 0.96 0.96 0.86))
(wheat (make-color 0.96 0.87 0.70))
(sandy-brown (make-color 0.95 0.64 0.37))
tan collides with Scheme built - in -- tawny suggested by
(chocolate (make-color 0.82 0.41 0.12))
(firebrick (make-color 0.70 0.13 0.13))
(brown (make-color 0.64 0.16 0.16))
(dark-salmon (make-color 0.91 0.59 0.48))
(salmon (make-color 0.98 0.50 0.45))
(light-salmon (make-color 1.00 0.62 0.48))
(orange (make-color 1.00 0.64 0.00))
(dark-orange (make-color 1.00 0.55 0.00))
(coral (make-color 1.00 0.50 0.31))
(light-coral (make-color 0.94 0.50 0.50))
(tomato (make-color 1.00 0.39 0.28))
(orange-red (make-color 1.00 0.27 0.00))
(red (make-color 1.00 0.00 0.00))
(hot-pink (make-color 1.00 0.41 0.70))
(deep-pink (make-color 1.00 0.08 0.57))
(pink (make-color 1.00 0.75 0.79))
(light-pink (make-color 1.00 0.71 0.75))
(pale-violet-red (make-color 0.86 0.44 0.57))
(maroon (make-color 0.69 0.19 0.37))
(medium-violet-red (make-color 0.78 0.08 0.52))
(violet-red (make-color 0.81 0.12 0.56))
(magenta (make-color 1.00 0.00 1.00))
(violet (make-color 0.93 0.51 0.93))
(plum (make-color 0.86 0.62 0.86))
(orchid (make-color 0.85 0.44 0.84))
(medium-orchid (make-color 0.73 0.33 0.82))
(dark-orchid (make-color 0.60 0.20 0.80))
(dark-violet (make-color 0.58 0.00 0.82))
(blue-violet (make-color 0.54 0.17 0.88))
(purple (make-color 0.62 0.12 0.94))
(medium-purple (make-color 0.57 0.44 0.86))
(thistle (make-color 0.84 0.75 0.84))
(snow1 (make-color 1.00 0.98 0.98))
(snow2 (make-color 0.93 0.91 0.91))
(snow3 (make-color 0.80 0.79 0.79))
(snow4 (make-color 0.54 0.54 0.54))
(seashell1 (make-color 1.00 0.96 0.93))
(seashell2 (make-color 0.93 0.89 0.87))
(seashell3 (make-color 0.80 0.77 0.75))
(seashell4 (make-color 0.54 0.52 0.51))
(antiquewhite1 (make-color 1.00 0.93 0.86))
(antiquewhite2 (make-color 0.93 0.87 0.80))
(antiquewhite3 (make-color 0.80 0.75 0.69))
(antiquewhite4 (make-color 0.54 0.51 0.47))
(bisque1 (make-color 1.00 0.89 0.77))
(bisque2 (make-color 0.93 0.83 0.71))
(bisque3 (make-color 0.80 0.71 0.62))
(bisque4 (make-color 0.54 0.49 0.42))
(peachpuff1 (make-color 1.00 0.85 0.72))
(peachpuff2 (make-color 0.93 0.79 0.68))
(peachpuff3 (make-color 0.80 0.68 0.58))
(peachpuff4 (make-color 0.54 0.46 0.39))
(navajowhite1 (make-color 1.00 0.87 0.68))
(navajowhite2 (make-color 0.93 0.81 0.63))
(navajowhite3 (make-color 0.80 0.70 0.54))
(navajowhite4 (make-color 0.54 0.47 0.37))
(lemonchiffon1 (make-color 1.00 0.98 0.80))
(lemonchiffon2 (make-color 0.93 0.91 0.75))
(lemonchiffon3 (make-color 0.80 0.79 0.64))
(lemonchiffon4 (make-color 0.54 0.54 0.44))
(cornsilk1 (make-color 1.00 0.97 0.86))
(cornsilk2 (make-color 0.93 0.91 0.80))
(cornsilk3 (make-color 0.80 0.78 0.69))
(cornsilk4 (make-color 0.54 0.53 0.47))
(ivory1 (make-color 1.00 1.00 0.94))
(ivory2 (make-color 0.93 0.93 0.87))
(ivory3 (make-color 0.80 0.80 0.75))
(ivory4 (make-color 0.54 0.54 0.51))
(honeydew1 (make-color 0.94 1.00 0.94))
(honeydew2 (make-color 0.87 0.93 0.87))
(honeydew3 (make-color 0.75 0.80 0.75))
(honeydew4 (make-color 0.51 0.54 0.51))
(lavenderblush1 (make-color 1.00 0.94 0.96))
(lavenderblush2 (make-color 0.93 0.87 0.89))
(lavenderblush3 (make-color 0.80 0.75 0.77))
(lavenderblush4 (make-color 0.54 0.51 0.52))
(mistyrose1 (make-color 1.00 0.89 0.88))
(mistyrose2 (make-color 0.93 0.83 0.82))
(mistyrose3 (make-color 0.80 0.71 0.71))
(mistyrose4 (make-color 0.54 0.49 0.48))
(azure1 (make-color 0.94 1.00 1.00))
(azure2 (make-color 0.87 0.93 0.93))
(azure3 (make-color 0.75 0.80 0.80))
(azure4 (make-color 0.51 0.54 0.54))
(slateblue1 (make-color 0.51 0.43 1.00))
(slateblue2 (make-color 0.48 0.40 0.93))
(slateblue3 (make-color 0.41 0.35 0.80))
(slateblue4 (make-color 0.28 0.23 0.54))
(royalblue1 (make-color 0.28 0.46 1.00))
(royalblue2 (make-color 0.26 0.43 0.93))
(royalblue3 (make-color 0.23 0.37 0.80))
(royalblue4 (make-color 0.15 0.25 0.54))
(blue1 (make-color 0.00 0.00 1.00))
(blue2 (make-color 0.00 0.00 0.93))
(blue3 (make-color 0.00 0.00 0.80))
(blue4 (make-color 0.00 0.00 0.54))
(dodgerblue1 (make-color 0.12 0.56 1.00))
(dodgerblue2 (make-color 0.11 0.52 0.93))
(dodgerblue3 (make-color 0.09 0.45 0.80))
(dodgerblue4 (make-color 0.06 0.30 0.54))
(steelblue1 (make-color 0.39 0.72 1.00))
(steelblue2 (make-color 0.36 0.67 0.93))
(steelblue3 (make-color 0.31 0.58 0.80))
(steelblue4 (make-color 0.21 0.39 0.54))
(deepskyblue1 (make-color 0.00 0.75 1.00))
(deepskyblue2 (make-color 0.00 0.70 0.93))
(deepskyblue3 (make-color 0.00 0.60 0.80))
(deepskyblue4 (make-color 0.00 0.41 0.54))
(skyblue1 (make-color 0.53 0.80 1.00))
(skyblue2 (make-color 0.49 0.75 0.93))
(skyblue3 (make-color 0.42 0.65 0.80))
(skyblue4 (make-color 0.29 0.44 0.54))
(lightskyblue1 (make-color 0.69 0.88 1.00))
(lightskyblue2 (make-color 0.64 0.82 0.93))
(lightskyblue3 (make-color 0.55 0.71 0.80))
(lightskyblue4 (make-color 0.37 0.48 0.54))
(slategray1 (make-color 0.77 0.88 1.00))
(slategray2 (make-color 0.72 0.82 0.93))
(slategray3 (make-color 0.62 0.71 0.80))
(slategray4 (make-color 0.42 0.48 0.54))
(lightsteelblue1 (make-color 0.79 0.88 1.00))
(lightsteelblue2 (make-color 0.73 0.82 0.93))
(lightsteelblue3 (make-color 0.63 0.71 0.80))
(lightsteelblue4 (make-color 0.43 0.48 0.54))
(lightblue1 (make-color 0.75 0.93 1.00))
(lightblue2 (make-color 0.70 0.87 0.93))
(lightblue3 (make-color 0.60 0.75 0.80))
(lightblue4 (make-color 0.41 0.51 0.54))
(lightcyan1 (make-color 0.87 1.00 1.00))
(lightcyan2 (make-color 0.82 0.93 0.93))
(lightcyan3 (make-color 0.70 0.80 0.80))
(lightcyan4 (make-color 0.48 0.54 0.54))
(paleturquoise1 (make-color 0.73 1.00 1.00))
(paleturquoise2 (make-color 0.68 0.93 0.93))
(paleturquoise3 (make-color 0.59 0.80 0.80))
(paleturquoise4 (make-color 0.40 0.54 0.54))
(cadetblue1 (make-color 0.59 0.96 1.00))
(cadetblue2 (make-color 0.55 0.89 0.93))
(cadetblue3 (make-color 0.48 0.77 0.80))
(cadetblue4 (make-color 0.32 0.52 0.54))
(turquoise1 (make-color 0.00 0.96 1.00))
(turquoise2 (make-color 0.00 0.89 0.93))
(turquoise3 (make-color 0.00 0.77 0.80))
(turquoise4 (make-color 0.00 0.52 0.54))
(cyan1 (make-color 0.00 1.00 1.00))
(cyan2 (make-color 0.00 0.93 0.93))
(cyan3 (make-color 0.00 0.80 0.80))
(cyan4 (make-color 0.00 0.54 0.54))
(darkslategray1 (make-color 0.59 1.00 1.00))
(darkslategray2 (make-color 0.55 0.93 0.93))
(darkslategray3 (make-color 0.47 0.80 0.80))
(darkslategray4 (make-color 0.32 0.54 0.54))
(aquamarine1 (make-color 0.50 1.00 0.83))
(aquamarine2 (make-color 0.46 0.93 0.77))
(aquamarine3 (make-color 0.40 0.80 0.66))
(aquamarine4 (make-color 0.27 0.54 0.45))
(darkseagreen1 (make-color 0.75 1.00 0.75))
(darkseagreen2 (make-color 0.70 0.93 0.70))
(darkseagreen3 (make-color 0.61 0.80 0.61))
(darkseagreen4 (make-color 0.41 0.54 0.41))
(seagreen1 (make-color 0.33 1.00 0.62))
(seagreen2 (make-color 0.30 0.93 0.58))
(seagreen3 (make-color 0.26 0.80 0.50))
(seagreen4 (make-color 0.18 0.54 0.34))
(palegreen1 (make-color 0.60 1.00 0.60))
(palegreen2 (make-color 0.56 0.93 0.56))
(palegreen3 (make-color 0.48 0.80 0.48))
(palegreen4 (make-color 0.33 0.54 0.33))
(springgreen1 (make-color 0.00 1.00 0.50))
(springgreen2 (make-color 0.00 0.93 0.46))
(springgreen3 (make-color 0.00 0.80 0.40))
(springgreen4 (make-color 0.00 0.54 0.27))
(green1 (make-color 0.00 1.00 0.00))
(green2 (make-color 0.00 0.93 0.00))
(green3 (make-color 0.00 0.80 0.00))
(green4 (make-color 0.00 0.54 0.00))
(chartreuse1 (make-color 0.50 1.00 0.00))
(chartreuse2 (make-color 0.46 0.93 0.00))
(chartreuse3 (make-color 0.40 0.80 0.00))
(chartreuse4 (make-color 0.27 0.54 0.00))
(olivedrab1 (make-color 0.75 1.00 0.24))
(olivedrab2 (make-color 0.70 0.93 0.23))
(olivedrab3 (make-color 0.60 0.80 0.20))
(olivedrab4 (make-color 0.41 0.54 0.13))
(darkolivegreen1 (make-color 0.79 1.00 0.44))
(darkolivegreen2 (make-color 0.73 0.93 0.41))
(darkolivegreen3 (make-color 0.63 0.80 0.35))
(darkolivegreen4 (make-color 0.43 0.54 0.24))
(khaki1 (make-color 1.00 0.96 0.56))
(khaki2 (make-color 0.93 0.90 0.52))
(khaki3 (make-color 0.80 0.77 0.45))
(khaki4 (make-color 0.54 0.52 0.30))
(lightgoldenrod1 (make-color 1.00 0.92 0.54))
(lightgoldenrod2 (make-color 0.93 0.86 0.51))
(lightgoldenrod3 (make-color 0.80 0.74 0.44))
(lightgoldenrod4 (make-color 0.54 0.50 0.30))
(lightyellow1 (make-color 1.00 1.00 0.87))
(lightyellow2 (make-color 0.93 0.93 0.82))
(lightyellow3 (make-color 0.80 0.80 0.70))
(lightyellow4 (make-color 0.54 0.54 0.48))
(yellow1 (make-color 1.00 1.00 0.00))
(yellow2 (make-color 0.93 0.93 0.00))
(yellow3 (make-color 0.80 0.80 0.00))
(yellow4 (make-color 0.54 0.54 0.00))
(gold1 (make-color 1.00 0.84 0.00))
(gold2 (make-color 0.93 0.79 0.00))
(gold3 (make-color 0.80 0.68 0.00))
(gold4 (make-color 0.54 0.46 0.00))
(goldenrod1 (make-color 1.00 0.75 0.14))
(goldenrod2 (make-color 0.93 0.70 0.13))
(goldenrod3 (make-color 0.80 0.61 0.11))
(goldenrod4 (make-color 0.54 0.41 0.08))
(darkgoldenrod1 (make-color 1.00 0.72 0.06))
(darkgoldenrod2 (make-color 0.93 0.68 0.05))
(darkgoldenrod3 (make-color 0.80 0.58 0.05))
(darkgoldenrod4 (make-color 0.54 0.39 0.03))
(rosybrown1 (make-color 1.00 0.75 0.75))
(rosybrown2 (make-color 0.93 0.70 0.70))
(rosybrown3 (make-color 0.80 0.61 0.61))
(rosybrown4 (make-color 0.54 0.41 0.41))
(indianred1 (make-color 1.00 0.41 0.41))
(indianred2 (make-color 0.93 0.39 0.39))
(indianred3 (make-color 0.80 0.33 0.33))
(indianred4 (make-color 0.54 0.23 0.23))
(sienna1 (make-color 1.00 0.51 0.28))
(sienna2 (make-color 0.93 0.47 0.26))
(sienna3 (make-color 0.80 0.41 0.22))
(sienna4 (make-color 0.54 0.28 0.15))
(burlywood1 (make-color 1.00 0.82 0.61))
(burlywood2 (make-color 0.93 0.77 0.57))
(burlywood3 (make-color 0.80 0.66 0.49))
(burlywood4 (make-color 0.54 0.45 0.33))
(wheat1 (make-color 1.00 0.90 0.73))
(wheat2 (make-color 0.93 0.84 0.68))
(wheat3 (make-color 0.80 0.73 0.59))
(wheat4 (make-color 0.54 0.49 0.40))
(tan1 (make-color 1.00 0.64 0.31))
(tan2 (make-color 0.93 0.60 0.29))
(tan3 (make-color 0.80 0.52 0.25))
(tan4 (make-color 0.54 0.35 0.17))
(chocolate1 (make-color 1.00 0.50 0.14))
(chocolate2 (make-color 0.93 0.46 0.13))
(chocolate3 (make-color 0.80 0.40 0.11))
(chocolate4 (make-color 0.54 0.27 0.07))
(firebrick1 (make-color 1.00 0.19 0.19))
(firebrick2 (make-color 0.93 0.17 0.17))
(firebrick3 (make-color 0.80 0.15 0.15))
(firebrick4 (make-color 0.54 0.10 0.10))
(brown1 (make-color 1.00 0.25 0.25))
(brown2 (make-color 0.93 0.23 0.23))
(brown3 (make-color 0.80 0.20 0.20))
(brown4 (make-color 0.54 0.14 0.14))
(salmon1 (make-color 1.00 0.55 0.41))
(salmon2 (make-color 0.93 0.51 0.38))
(salmon3 (make-color 0.80 0.44 0.33))
(salmon4 (make-color 0.54 0.30 0.22))
(lightsalmon1 (make-color 1.00 0.62 0.48))
(lightsalmon2 (make-color 0.93 0.58 0.45))
(lightsalmon3 (make-color 0.80 0.50 0.38))
(lightsalmon4 (make-color 0.54 0.34 0.26))
(orange1 (make-color 1.00 0.64 0.00))
(orange2 (make-color 0.93 0.60 0.00))
(orange3 (make-color 0.80 0.52 0.00))
(orange4 (make-color 0.54 0.35 0.00))
(darkorange1 (make-color 1.00 0.50 0.00))
(darkorange2 (make-color 0.93 0.46 0.00))
(darkorange3 (make-color 0.80 0.40 0.00))
(darkorange4 (make-color 0.54 0.27 0.00))
(coral1 (make-color 1.00 0.45 0.34))
(coral2 (make-color 0.93 0.41 0.31))
(coral3 (make-color 0.80 0.36 0.27))
(coral4 (make-color 0.54 0.24 0.18))
(tomato1 (make-color 1.00 0.39 0.28))
(tomato2 (make-color 0.93 0.36 0.26))
(tomato3 (make-color 0.80 0.31 0.22))
(tomato4 (make-color 0.54 0.21 0.15))
(orangered1 (make-color 1.00 0.27 0.00))
(orangered2 (make-color 0.93 0.25 0.00))
(orangered3 (make-color 0.80 0.21 0.00))
(orangered4 (make-color 0.54 0.14 0.00))
(red1 (make-color 1.00 0.00 0.00))
(red2 (make-color 0.93 0.00 0.00))
(red3 (make-color 0.80 0.00 0.00))
(red4 (make-color 0.54 0.00 0.00))
(deeppink1 (make-color 1.00 0.08 0.57))
(deeppink2 (make-color 0.93 0.07 0.54))
(deeppink3 (make-color 0.80 0.06 0.46))
(deeppink4 (make-color 0.54 0.04 0.31))
(hotpink1 (make-color 1.00 0.43 0.70))
(hotpink2 (make-color 0.93 0.41 0.65))
(hotpink3 (make-color 0.80 0.37 0.56))
(hotpink4 (make-color 0.54 0.23 0.38))
(pink1 (make-color 1.00 0.71 0.77))
(pink2 (make-color 0.93 0.66 0.72))
(pink3 (make-color 0.80 0.57 0.62))
(pink4 (make-color 0.54 0.39 0.42))
(lightpink1 (make-color 1.00 0.68 0.72))
(lightpink2 (make-color 0.93 0.63 0.68))
(lightpink3 (make-color 0.80 0.55 0.58))
(lightpink4 (make-color 0.54 0.37 0.39))
(palevioletred1 (make-color 1.00 0.51 0.67))
(palevioletred2 (make-color 0.93 0.47 0.62))
(palevioletred3 (make-color 0.80 0.41 0.54))
(palevioletred4 (make-color 0.54 0.28 0.36))
(maroon1 (make-color 1.00 0.20 0.70))
(maroon2 (make-color 0.93 0.19 0.65))
(maroon3 (make-color 0.80 0.16 0.56))
(maroon4 (make-color 0.54 0.11 0.38))
(violetred1 (make-color 1.00 0.24 0.59))
(violetred2 (make-color 0.93 0.23 0.55))
(violetred3 (make-color 0.80 0.20 0.47))
(violetred4 (make-color 0.54 0.13 0.32))
(magenta1 (make-color 1.00 0.00 1.00))
(magenta2 (make-color 0.93 0.00 0.93))
(magenta3 (make-color 0.80 0.00 0.80))
(magenta4 (make-color 0.54 0.00 0.54))
(orchid1 (make-color 1.00 0.51 0.98))
(orchid2 (make-color 0.93 0.48 0.91))
(orchid3 (make-color 0.80 0.41 0.79))
(orchid4 (make-color 0.54 0.28 0.54))
(plum1 (make-color 1.00 0.73 1.00))
(plum2 (make-color 0.93 0.68 0.93))
(plum3 (make-color 0.80 0.59 0.80))
(plum4 (make-color 0.54 0.40 0.54))
(mediumorchid1 (make-color 0.87 0.40 1.00))
(mediumorchid2 (make-color 0.82 0.37 0.93))
(mediumorchid3 (make-color 0.70 0.32 0.80))
(mediumorchid4 (make-color 0.48 0.21 0.54))
(darkorchid1 (make-color 0.75 0.24 1.00))
(darkorchid2 (make-color 0.70 0.23 0.93))
(darkorchid3 (make-color 0.60 0.20 0.80))
(darkorchid4 (make-color 0.41 0.13 0.54))
(purple1 (make-color 0.61 0.19 1.00))
(purple2 (make-color 0.57 0.17 0.93))
(purple3 (make-color 0.49 0.15 0.80))
(purple4 (make-color 0.33 0.10 0.54))
(mediumpurple1 (make-color 0.67 0.51 1.00))
(mediumpurple2 (make-color 0.62 0.47 0.93))
(mediumpurple3 (make-color 0.54 0.41 0.80))
(mediumpurple4 (make-color 0.36 0.28 0.54))
(thistle1 (make-color 1.00 0.88 1.00))
(thistle2 (make-color 0.93 0.82 0.93))
(thistle3 (make-color 0.80 0.71 0.80))
(thistle4 (make-color 0.54 0.48 0.54))
(gray0 (make-color 0.00 0.00 0.00))
(grey0 (make-color 0.00 0.00 0.00))
(gray1 (make-color 0.01 0.01 0.01))
(grey1 (make-color 0.01 0.01 0.01))
(gray2 (make-color 0.02 0.02 0.02))
(grey2 (make-color 0.02 0.02 0.02))
(gray3 (make-color 0.03 0.03 0.03))
(grey3 (make-color 0.03 0.03 0.03))
(gray4 (make-color 0.04 0.04 0.04))
(grey4 (make-color 0.04 0.04 0.04))
(gray5 (make-color 0.05 0.05 0.05))
(grey5 (make-color 0.05 0.05 0.05))
(gray6 (make-color 0.06 0.06 0.06))
(grey6 (make-color 0.06 0.06 0.06))
(gray7 (make-color 0.07 0.07 0.07))
(grey7 (make-color 0.07 0.07 0.07))
(gray8 (make-color 0.08 0.08 0.08))
(grey8 (make-color 0.08 0.08 0.08))
(gray9 (make-color 0.09 0.09 0.09))
(grey9 (make-color 0.09 0.09 0.09))
(gray10 (make-color 0.10 0.10 0.10))
(grey10 (make-color 0.10 0.10 0.10))
(gray11 (make-color 0.11 0.11 0.11))
(grey11 (make-color 0.11 0.11 0.11))
(gray12 (make-color 0.12 0.12 0.12))
(grey12 (make-color 0.12 0.12 0.12))
(gray13 (make-color 0.13 0.13 0.13))
(grey13 (make-color 0.13 0.13 0.13))
(gray14 (make-color 0.14 0.14 0.14))
(grey14 (make-color 0.14 0.14 0.14))
(gray15 (make-color 0.15 0.15 0.15))
(grey15 (make-color 0.15 0.15 0.15))
(gray16 (make-color 0.16 0.16 0.16))
(grey16 (make-color 0.16 0.16 0.16))
(gray17 (make-color 0.17 0.17 0.17))
(grey17 (make-color 0.17 0.17 0.17))
(gray18 (make-color 0.18 0.18 0.18))
(grey18 (make-color 0.18 0.18 0.18))
(gray19 (make-color 0.19 0.19 0.19))
(grey19 (make-color 0.19 0.19 0.19))
(gray20 (make-color 0.20 0.20 0.20))
(grey20 (make-color 0.20 0.20 0.20))
(gray21 (make-color 0.21 0.21 0.21))
(grey21 (make-color 0.21 0.21 0.21))
(gray22 (make-color 0.22 0.22 0.22))
(grey22 (make-color 0.22 0.22 0.22))
(gray23 (make-color 0.23 0.23 0.23))
(grey23 (make-color 0.23 0.23 0.23))
(gray24 (make-color 0.24 0.24 0.24))
(grey24 (make-color 0.24 0.24 0.24))
(gray25 (make-color 0.25 0.25 0.25))
(grey25 (make-color 0.25 0.25 0.25))
(gray26 (make-color 0.26 0.26 0.26))
(grey26 (make-color 0.26 0.26 0.26))
(gray27 (make-color 0.27 0.27 0.27))
(grey27 (make-color 0.27 0.27 0.27))
(gray28 (make-color 0.28 0.28 0.28))
(grey28 (make-color 0.28 0.28 0.28))
(gray29 (make-color 0.29 0.29 0.29))
(grey29 (make-color 0.29 0.29 0.29))
(gray30 (make-color 0.30 0.30 0.30))
(grey30 (make-color 0.30 0.30 0.30))
(gray31 (make-color 0.31 0.31 0.31))
(grey31 (make-color 0.31 0.31 0.31))
(gray32 (make-color 0.32 0.32 0.32))
(grey32 (make-color 0.32 0.32 0.32))
(gray33 (make-color 0.33 0.33 0.33))
(grey33 (make-color 0.33 0.33 0.33))
(gray34 (make-color 0.34 0.34 0.34))
(grey34 (make-color 0.34 0.34 0.34))
(gray35 (make-color 0.35 0.35 0.35))
(grey35 (make-color 0.35 0.35 0.35))
(gray36 (make-color 0.36 0.36 0.36))
(grey36 (make-color 0.36 0.36 0.36))
(gray37 (make-color 0.37 0.37 0.37))
(grey37 (make-color 0.37 0.37 0.37))
(gray38 (make-color 0.38 0.38 0.38))
(grey38 (make-color 0.38 0.38 0.38))
(gray39 (make-color 0.39 0.39 0.39))
(grey39 (make-color 0.39 0.39 0.39))
(gray40 (make-color 0.40 0.40 0.40))
(grey40 (make-color 0.40 0.40 0.40))
(gray41 (make-color 0.41 0.41 0.41))
(grey41 (make-color 0.41 0.41 0.41))
(gray42 (make-color 0.42 0.42 0.42))
(grey42 (make-color 0.42 0.42 0.42))
(gray43 (make-color 0.43 0.43 0.43))
(grey43 (make-color 0.43 0.43 0.43))
(gray44 (make-color 0.44 0.44 0.44))
(grey44 (make-color 0.44 0.44 0.44))
(gray45 (make-color 0.45 0.45 0.45))
(grey45 (make-color 0.45 0.45 0.45))
(gray46 (make-color 0.46 0.46 0.46))
(grey46 (make-color 0.46 0.46 0.46))
(gray47 (make-color 0.47 0.47 0.47))
(grey47 (make-color 0.47 0.47 0.47))
(gray48 (make-color 0.48 0.48 0.48))
(grey48 (make-color 0.48 0.48 0.48))
(gray49 (make-color 0.49 0.49 0.49))
(grey49 (make-color 0.49 0.49 0.49))
(gray50 (make-color 0.50 0.50 0.50))
(grey50 (make-color 0.50 0.50 0.50))
(gray51 (make-color 0.51 0.51 0.51))
(grey51 (make-color 0.51 0.51 0.51))
(gray52 (make-color 0.52 0.52 0.52))
(grey52 (make-color 0.52 0.52 0.52))
(gray53 (make-color 0.53 0.53 0.53))
(grey53 (make-color 0.53 0.53 0.53))
(gray54 (make-color 0.54 0.54 0.54))
(grey54 (make-color 0.54 0.54 0.54))
(gray55 (make-color 0.55 0.55 0.55))
(grey55 (make-color 0.55 0.55 0.55))
(gray56 (make-color 0.56 0.56 0.56))
(grey56 (make-color 0.56 0.56 0.56))
(gray57 (make-color 0.57 0.57 0.57))
(grey57 (make-color 0.57 0.57 0.57))
(gray58 (make-color 0.58 0.58 0.58))
(grey58 (make-color 0.58 0.58 0.58))
(gray59 (make-color 0.59 0.59 0.59))
(grey59 (make-color 0.59 0.59 0.59))
(gray60 (make-color 0.60 0.60 0.60))
(grey60 (make-color 0.60 0.60 0.60))
(gray61 (make-color 0.61 0.61 0.61))
(grey61 (make-color 0.61 0.61 0.61))
(gray62 (make-color 0.62 0.62 0.62))
(grey62 (make-color 0.62 0.62 0.62))
(gray63 (make-color 0.63 0.63 0.63))
(grey63 (make-color 0.63 0.63 0.63))
(gray64 (make-color 0.64 0.64 0.64))
(grey64 (make-color 0.64 0.64 0.64))
(gray65 (make-color 0.65 0.65 0.65))
(grey65 (make-color 0.65 0.65 0.65))
(gray66 (make-color 0.66 0.66 0.66))
(grey66 (make-color 0.66 0.66 0.66))
(gray67 (make-color 0.67 0.67 0.67))
(grey67 (make-color 0.67 0.67 0.67))
(gray68 (make-color 0.68 0.68 0.68))
(grey68 (make-color 0.68 0.68 0.68))
(gray69 (make-color 0.69 0.69 0.69))
(grey69 (make-color 0.69 0.69 0.69))
(gray70 (make-color 0.70 0.70 0.70))
(grey70 (make-color 0.70 0.70 0.70))
(gray71 (make-color 0.71 0.71 0.71))
(grey71 (make-color 0.71 0.71 0.71))
(gray72 (make-color 0.72 0.72 0.72))
(grey72 (make-color 0.72 0.72 0.72))
(gray73 (make-color 0.73 0.73 0.73))
(grey73 (make-color 0.73 0.73 0.73))
(gray74 (make-color 0.74 0.74 0.74))
(grey74 (make-color 0.74 0.74 0.74))
(gray75 (make-color 0.75 0.75 0.75))
(grey75 (make-color 0.75 0.75 0.75))
(gray76 (make-color 0.76 0.76 0.76))
(grey76 (make-color 0.76 0.76 0.76))
(gray77 (make-color 0.77 0.77 0.77))
(grey77 (make-color 0.77 0.77 0.77))
(gray78 (make-color 0.78 0.78 0.78))
(grey78 (make-color 0.78 0.78 0.78))
(gray79 (make-color 0.79 0.79 0.79))
(grey79 (make-color 0.79 0.79 0.79))
(gray80 (make-color 0.80 0.80 0.80))
(grey80 (make-color 0.80 0.80 0.80))
(gray81 (make-color 0.81 0.81 0.81))
(grey81 (make-color 0.81 0.81 0.81))
(gray82 (make-color 0.82 0.82 0.82))
(grey82 (make-color 0.82 0.82 0.82))
(gray83 (make-color 0.83 0.83 0.83))
(grey83 (make-color 0.83 0.83 0.83))
(gray84 (make-color 0.84 0.84 0.84))
(grey84 (make-color 0.84 0.84 0.84))
(gray85 (make-color 0.85 0.85 0.85))
(grey85 (make-color 0.85 0.85 0.85))
(gray86 (make-color 0.86 0.86 0.86))
(grey86 (make-color 0.86 0.86 0.86))
(gray87 (make-color 0.87 0.87 0.87))
(grey87 (make-color 0.87 0.87 0.87))
(gray88 (make-color 0.87 0.87 0.87))
(grey88 (make-color 0.87 0.87 0.87))
(gray89 (make-color 0.89 0.89 0.89))
(grey89 (make-color 0.89 0.89 0.89))
(gray90 (make-color 0.89 0.89 0.89))
(grey90 (make-color 0.89 0.89 0.89))
(gray91 (make-color 0.91 0.91 0.91))
(grey91 (make-color 0.91 0.91 0.91))
(gray92 (make-color 0.92 0.92 0.92))
(grey92 (make-color 0.92 0.92 0.92))
(gray93 (make-color 0.93 0.93 0.93))
(grey93 (make-color 0.93 0.93 0.93))
(gray94 (make-color 0.94 0.94 0.94))
(grey94 (make-color 0.94 0.94 0.94))
(gray95 (make-color 0.95 0.95 0.95))
(grey95 (make-color 0.95 0.95 0.95))
(gray96 (make-color 0.96 0.96 0.96))
(grey96 (make-color 0.96 0.96 0.96))
(gray97 (make-color 0.96 0.96 0.96))
(grey97 (make-color 0.96 0.96 0.96))
(gray98 (make-color 0.98 0.98 0.98))
(grey98 (make-color 0.98 0.98 0.98))
(gray99 (make-color 0.98 0.98 0.98))
(grey99 (make-color 0.98 0.98 0.98))
(gray100 (make-color 1.00 1.00 1.00))
(grey100 (make-color 1.00 1.00 1.00))
(dark-grey (make-color 0.66 0.66 0.66))
(dark-gray (make-color 0.66 0.66 0.66))
(dark-blue (make-color 0.00 0.00 0.54))
(dark-cyan (make-color 0.00 0.54 0.54))
(dark-magenta (make-color 0.54 0.00 0.54))
(dark-red (make-color 0.54 0.00 0.00))
(light-green (make-color 0.56 0.93 0.56)))
(curlet)))
| null | https://raw.githubusercontent.com/spurious/snd-mirror/8e7a643c840592797c29384ffe07c87ba5c0a3eb/rgb.scm | scheme | X11 color names converted to Snd colors |
(provide 'snd-rgb.scm)
(define *rgb*
(let ((snow (make-color 1.00 0.98 0.98))
(ghost-white (make-color 0.97 0.97 1.00))
(white-smoke (make-color 0.96 0.96 0.96))
(gainsboro (make-color 0.86 0.86 0.86))
(floral-white (make-color 1.00 0.98 0.94))
(old-lace (make-color 0.99 0.96 0.90))
(linen (make-color 0.98 0.94 0.90))
(antique-white (make-color 0.98 0.92 0.84))
(papaya-whip (make-color 1.00 0.93 0.83))
(blanched-almond (make-color 1.00 0.92 0.80))
(bisque (make-color 1.00 0.89 0.77))
(peach-puff (make-color 1.00 0.85 0.72))
(navajo-white (make-color 1.00 0.87 0.68))
(moccasin (make-color 1.00 0.89 0.71))
(cornsilk (make-color 1.00 0.97 0.86))
(ivory (make-color 1.00 1.00 0.94))
(lemon-chiffon (make-color 1.00 0.98 0.80))
(seashell (make-color 1.00 0.96 0.93))
(honeydew (make-color 0.94 1.00 0.94))
(mint-cream (make-color 0.96 1.00 0.98))
(azure (make-color 0.94 1.00 1.00))
(alice-blue (make-color 0.94 0.97 1.00))
(lavender (make-color 0.90 0.90 0.98))
(lavender-blush (make-color 1.00 0.94 0.96))
(misty-rose (make-color 1.00 0.89 0.88))
(white (make-color 1.00 1.00 1.00))
(black (make-color 0.00 0.00 0.00))
(dark-slate-gray (make-color 0.18 0.31 0.31))
(dark-slate-grey (make-color 0.18 0.31 0.31))
(dim-gray (make-color 0.41 0.41 0.41))
(dim-grey (make-color 0.41 0.41 0.41))
(slate-gray (make-color 0.44 0.50 0.56))
(slate-grey (make-color 0.44 0.50 0.56))
(light-slate-gray (make-color 0.46 0.53 0.60))
(light-slate-grey (make-color 0.46 0.53 0.60))
(gray (make-color 0.74 0.74 0.74))
(grey (make-color 0.74 0.74 0.74))
(light-grey (make-color 0.82 0.82 0.82))
(light-gray (make-color 0.82 0.82 0.82))
(midnight-blue (make-color 0.10 0.10 0.44))
(navy (make-color 0.00 0.00 0.50))
(navy-blue (make-color 0.00 0.00 0.50))
(cornflower-blue (make-color 0.39 0.58 0.93))
(dark-slate-blue (make-color 0.28 0.24 0.54))
(slate-blue (make-color 0.41 0.35 0.80))
(medium-slate-blue (make-color 0.48 0.41 0.93))
(light-slate-blue (make-color 0.52 0.44 1.00))
(medium-blue (make-color 0.00 0.00 0.80))
(royal-blue (make-color 0.25 0.41 0.88))
(blue (make-color 0.00 0.00 1.00))
(dodger-blue (make-color 0.12 0.56 1.00))
(deep-sky-blue (make-color 0.00 0.75 1.00))
(sky-blue (make-color 0.53 0.80 0.92))
(light-sky-blue (make-color 0.53 0.80 0.98))
(steel-blue (make-color 0.27 0.51 0.70))
(light-steel-blue (make-color 0.69 0.77 0.87))
(light-blue (make-color 0.68 0.84 0.90))
(powder-blue (make-color 0.69 0.87 0.90))
(pale-turquoise (make-color 0.68 0.93 0.93))
(dark-turquoise (make-color 0.00 0.80 0.82))
(medium-turquoise (make-color 0.28 0.82 0.80))
(turquoise (make-color 0.25 0.87 0.81))
(cyan (make-color 0.00 1.00 1.00))
(light-cyan (make-color 0.87 1.00 1.00))
(cadet-blue (make-color 0.37 0.62 0.62))
(medium-aquamarine (make-color 0.40 0.80 0.66))
(aquamarine (make-color 0.50 1.00 0.83))
(dark-green (make-color 0.00 0.39 0.00))
(dark-olive-green (make-color 0.33 0.42 0.18))
(dark-sea-green (make-color 0.56 0.73 0.56))
(sea-green (make-color 0.18 0.54 0.34))
(medium-sea-green (make-color 0.23 0.70 0.44))
(light-sea-green (make-color 0.12 0.70 0.66))
(pale-green (make-color 0.59 0.98 0.59))
(spring-green (make-color 0.00 1.00 0.50))
(lawn-green (make-color 0.48 0.98 0.00))
(green (make-color 0.00 1.00 0.00))
(chartreuse (make-color 0.50 1.00 0.00))
(medium-spring-green (make-color 0.00 0.98 0.60))
(green-yellow (make-color 0.68 1.00 0.18))
(lime-green (make-color 0.20 0.80 0.20))
(yellow-green (make-color 0.60 0.80 0.20))
(forest-green (make-color 0.13 0.54 0.13))
(olive-drab (make-color 0.42 0.55 0.14))
(dark-khaki (make-color 0.74 0.71 0.42))
(khaki (make-color 0.94 0.90 0.55))
(pale-goldenrod (make-color 0.93 0.91 0.66))
(light-goldenrod-yellow (make-color 0.98 0.98 0.82))
(light-yellow (make-color 1.00 1.00 0.87))
(yellow (make-color 1.00 1.00 0.00))
(gold (make-color 1.00 0.84 0.00))
(light-goldenrod (make-color 0.93 0.86 0.51))
(goldenrod (make-color 0.85 0.64 0.12))
(dark-goldenrod (make-color 0.72 0.52 0.04))
(rosy-brown (make-color 0.73 0.56 0.56))
(indian-red (make-color 0.80 0.36 0.36))
(saddle-brown (make-color 0.54 0.27 0.07))
(sienna (make-color 0.62 0.32 0.18))
(peru (make-color 0.80 0.52 0.25))
(burlywood (make-color 0.87 0.72 0.53))
(beige (make-color 0.96 0.96 0.86))
(wheat (make-color 0.96 0.87 0.70))
(sandy-brown (make-color 0.95 0.64 0.37))
tan collides with Scheme built - in -- tawny suggested by
(chocolate (make-color 0.82 0.41 0.12))
(firebrick (make-color 0.70 0.13 0.13))
(brown (make-color 0.64 0.16 0.16))
(dark-salmon (make-color 0.91 0.59 0.48))
(salmon (make-color 0.98 0.50 0.45))
(light-salmon (make-color 1.00 0.62 0.48))
(orange (make-color 1.00 0.64 0.00))
(dark-orange (make-color 1.00 0.55 0.00))
(coral (make-color 1.00 0.50 0.31))
(light-coral (make-color 0.94 0.50 0.50))
(tomato (make-color 1.00 0.39 0.28))
(orange-red (make-color 1.00 0.27 0.00))
(red (make-color 1.00 0.00 0.00))
(hot-pink (make-color 1.00 0.41 0.70))
(deep-pink (make-color 1.00 0.08 0.57))
(pink (make-color 1.00 0.75 0.79))
(light-pink (make-color 1.00 0.71 0.75))
(pale-violet-red (make-color 0.86 0.44 0.57))
(maroon (make-color 0.69 0.19 0.37))
(medium-violet-red (make-color 0.78 0.08 0.52))
(violet-red (make-color 0.81 0.12 0.56))
(magenta (make-color 1.00 0.00 1.00))
(violet (make-color 0.93 0.51 0.93))
(plum (make-color 0.86 0.62 0.86))
(orchid (make-color 0.85 0.44 0.84))
(medium-orchid (make-color 0.73 0.33 0.82))
(dark-orchid (make-color 0.60 0.20 0.80))
(dark-violet (make-color 0.58 0.00 0.82))
(blue-violet (make-color 0.54 0.17 0.88))
(purple (make-color 0.62 0.12 0.94))
(medium-purple (make-color 0.57 0.44 0.86))
(thistle (make-color 0.84 0.75 0.84))
(snow1 (make-color 1.00 0.98 0.98))
(snow2 (make-color 0.93 0.91 0.91))
(snow3 (make-color 0.80 0.79 0.79))
(snow4 (make-color 0.54 0.54 0.54))
(seashell1 (make-color 1.00 0.96 0.93))
(seashell2 (make-color 0.93 0.89 0.87))
(seashell3 (make-color 0.80 0.77 0.75))
(seashell4 (make-color 0.54 0.52 0.51))
(antiquewhite1 (make-color 1.00 0.93 0.86))
(antiquewhite2 (make-color 0.93 0.87 0.80))
(antiquewhite3 (make-color 0.80 0.75 0.69))
(antiquewhite4 (make-color 0.54 0.51 0.47))
(bisque1 (make-color 1.00 0.89 0.77))
(bisque2 (make-color 0.93 0.83 0.71))
(bisque3 (make-color 0.80 0.71 0.62))
(bisque4 (make-color 0.54 0.49 0.42))
(peachpuff1 (make-color 1.00 0.85 0.72))
(peachpuff2 (make-color 0.93 0.79 0.68))
(peachpuff3 (make-color 0.80 0.68 0.58))
(peachpuff4 (make-color 0.54 0.46 0.39))
(navajowhite1 (make-color 1.00 0.87 0.68))
(navajowhite2 (make-color 0.93 0.81 0.63))
(navajowhite3 (make-color 0.80 0.70 0.54))
(navajowhite4 (make-color 0.54 0.47 0.37))
(lemonchiffon1 (make-color 1.00 0.98 0.80))
(lemonchiffon2 (make-color 0.93 0.91 0.75))
(lemonchiffon3 (make-color 0.80 0.79 0.64))
(lemonchiffon4 (make-color 0.54 0.54 0.44))
(cornsilk1 (make-color 1.00 0.97 0.86))
(cornsilk2 (make-color 0.93 0.91 0.80))
(cornsilk3 (make-color 0.80 0.78 0.69))
(cornsilk4 (make-color 0.54 0.53 0.47))
(ivory1 (make-color 1.00 1.00 0.94))
(ivory2 (make-color 0.93 0.93 0.87))
(ivory3 (make-color 0.80 0.80 0.75))
(ivory4 (make-color 0.54 0.54 0.51))
(honeydew1 (make-color 0.94 1.00 0.94))
(honeydew2 (make-color 0.87 0.93 0.87))
(honeydew3 (make-color 0.75 0.80 0.75))
(honeydew4 (make-color 0.51 0.54 0.51))
(lavenderblush1 (make-color 1.00 0.94 0.96))
(lavenderblush2 (make-color 0.93 0.87 0.89))
(lavenderblush3 (make-color 0.80 0.75 0.77))
(lavenderblush4 (make-color 0.54 0.51 0.52))
(mistyrose1 (make-color 1.00 0.89 0.88))
(mistyrose2 (make-color 0.93 0.83 0.82))
(mistyrose3 (make-color 0.80 0.71 0.71))
(mistyrose4 (make-color 0.54 0.49 0.48))
(azure1 (make-color 0.94 1.00 1.00))
(azure2 (make-color 0.87 0.93 0.93))
(azure3 (make-color 0.75 0.80 0.80))
(azure4 (make-color 0.51 0.54 0.54))
(slateblue1 (make-color 0.51 0.43 1.00))
(slateblue2 (make-color 0.48 0.40 0.93))
(slateblue3 (make-color 0.41 0.35 0.80))
(slateblue4 (make-color 0.28 0.23 0.54))
(royalblue1 (make-color 0.28 0.46 1.00))
(royalblue2 (make-color 0.26 0.43 0.93))
(royalblue3 (make-color 0.23 0.37 0.80))
(royalblue4 (make-color 0.15 0.25 0.54))
(blue1 (make-color 0.00 0.00 1.00))
(blue2 (make-color 0.00 0.00 0.93))
(blue3 (make-color 0.00 0.00 0.80))
(blue4 (make-color 0.00 0.00 0.54))
(dodgerblue1 (make-color 0.12 0.56 1.00))
(dodgerblue2 (make-color 0.11 0.52 0.93))
(dodgerblue3 (make-color 0.09 0.45 0.80))
(dodgerblue4 (make-color 0.06 0.30 0.54))
(steelblue1 (make-color 0.39 0.72 1.00))
(steelblue2 (make-color 0.36 0.67 0.93))
(steelblue3 (make-color 0.31 0.58 0.80))
(steelblue4 (make-color 0.21 0.39 0.54))
(deepskyblue1 (make-color 0.00 0.75 1.00))
(deepskyblue2 (make-color 0.00 0.70 0.93))
(deepskyblue3 (make-color 0.00 0.60 0.80))
(deepskyblue4 (make-color 0.00 0.41 0.54))
(skyblue1 (make-color 0.53 0.80 1.00))
(skyblue2 (make-color 0.49 0.75 0.93))
(skyblue3 (make-color 0.42 0.65 0.80))
(skyblue4 (make-color 0.29 0.44 0.54))
(lightskyblue1 (make-color 0.69 0.88 1.00))
(lightskyblue2 (make-color 0.64 0.82 0.93))
(lightskyblue3 (make-color 0.55 0.71 0.80))
(lightskyblue4 (make-color 0.37 0.48 0.54))
(slategray1 (make-color 0.77 0.88 1.00))
(slategray2 (make-color 0.72 0.82 0.93))
(slategray3 (make-color 0.62 0.71 0.80))
(slategray4 (make-color 0.42 0.48 0.54))
(lightsteelblue1 (make-color 0.79 0.88 1.00))
(lightsteelblue2 (make-color 0.73 0.82 0.93))
(lightsteelblue3 (make-color 0.63 0.71 0.80))
(lightsteelblue4 (make-color 0.43 0.48 0.54))
(lightblue1 (make-color 0.75 0.93 1.00))
(lightblue2 (make-color 0.70 0.87 0.93))
(lightblue3 (make-color 0.60 0.75 0.80))
(lightblue4 (make-color 0.41 0.51 0.54))
(lightcyan1 (make-color 0.87 1.00 1.00))
(lightcyan2 (make-color 0.82 0.93 0.93))
(lightcyan3 (make-color 0.70 0.80 0.80))
(lightcyan4 (make-color 0.48 0.54 0.54))
(paleturquoise1 (make-color 0.73 1.00 1.00))
(paleturquoise2 (make-color 0.68 0.93 0.93))
(paleturquoise3 (make-color 0.59 0.80 0.80))
(paleturquoise4 (make-color 0.40 0.54 0.54))
(cadetblue1 (make-color 0.59 0.96 1.00))
(cadetblue2 (make-color 0.55 0.89 0.93))
(cadetblue3 (make-color 0.48 0.77 0.80))
(cadetblue4 (make-color 0.32 0.52 0.54))
(turquoise1 (make-color 0.00 0.96 1.00))
(turquoise2 (make-color 0.00 0.89 0.93))
(turquoise3 (make-color 0.00 0.77 0.80))
(turquoise4 (make-color 0.00 0.52 0.54))
(cyan1 (make-color 0.00 1.00 1.00))
(cyan2 (make-color 0.00 0.93 0.93))
(cyan3 (make-color 0.00 0.80 0.80))
(cyan4 (make-color 0.00 0.54 0.54))
(darkslategray1 (make-color 0.59 1.00 1.00))
(darkslategray2 (make-color 0.55 0.93 0.93))
(darkslategray3 (make-color 0.47 0.80 0.80))
(darkslategray4 (make-color 0.32 0.54 0.54))
(aquamarine1 (make-color 0.50 1.00 0.83))
(aquamarine2 (make-color 0.46 0.93 0.77))
(aquamarine3 (make-color 0.40 0.80 0.66))
(aquamarine4 (make-color 0.27 0.54 0.45))
(darkseagreen1 (make-color 0.75 1.00 0.75))
(darkseagreen2 (make-color 0.70 0.93 0.70))
(darkseagreen3 (make-color 0.61 0.80 0.61))
(darkseagreen4 (make-color 0.41 0.54 0.41))
(seagreen1 (make-color 0.33 1.00 0.62))
(seagreen2 (make-color 0.30 0.93 0.58))
(seagreen3 (make-color 0.26 0.80 0.50))
(seagreen4 (make-color 0.18 0.54 0.34))
(palegreen1 (make-color 0.60 1.00 0.60))
(palegreen2 (make-color 0.56 0.93 0.56))
(palegreen3 (make-color 0.48 0.80 0.48))
(palegreen4 (make-color 0.33 0.54 0.33))
(springgreen1 (make-color 0.00 1.00 0.50))
(springgreen2 (make-color 0.00 0.93 0.46))
(springgreen3 (make-color 0.00 0.80 0.40))
(springgreen4 (make-color 0.00 0.54 0.27))
(green1 (make-color 0.00 1.00 0.00))
(green2 (make-color 0.00 0.93 0.00))
(green3 (make-color 0.00 0.80 0.00))
(green4 (make-color 0.00 0.54 0.00))
(chartreuse1 (make-color 0.50 1.00 0.00))
(chartreuse2 (make-color 0.46 0.93 0.00))
(chartreuse3 (make-color 0.40 0.80 0.00))
(chartreuse4 (make-color 0.27 0.54 0.00))
(olivedrab1 (make-color 0.75 1.00 0.24))
(olivedrab2 (make-color 0.70 0.93 0.23))
(olivedrab3 (make-color 0.60 0.80 0.20))
(olivedrab4 (make-color 0.41 0.54 0.13))
(darkolivegreen1 (make-color 0.79 1.00 0.44))
(darkolivegreen2 (make-color 0.73 0.93 0.41))
(darkolivegreen3 (make-color 0.63 0.80 0.35))
(darkolivegreen4 (make-color 0.43 0.54 0.24))
(khaki1 (make-color 1.00 0.96 0.56))
(khaki2 (make-color 0.93 0.90 0.52))
(khaki3 (make-color 0.80 0.77 0.45))
(khaki4 (make-color 0.54 0.52 0.30))
(lightgoldenrod1 (make-color 1.00 0.92 0.54))
(lightgoldenrod2 (make-color 0.93 0.86 0.51))
(lightgoldenrod3 (make-color 0.80 0.74 0.44))
(lightgoldenrod4 (make-color 0.54 0.50 0.30))
(lightyellow1 (make-color 1.00 1.00 0.87))
(lightyellow2 (make-color 0.93 0.93 0.82))
(lightyellow3 (make-color 0.80 0.80 0.70))
(lightyellow4 (make-color 0.54 0.54 0.48))
(yellow1 (make-color 1.00 1.00 0.00))
(yellow2 (make-color 0.93 0.93 0.00))
(yellow3 (make-color 0.80 0.80 0.00))
(yellow4 (make-color 0.54 0.54 0.00))
(gold1 (make-color 1.00 0.84 0.00))
(gold2 (make-color 0.93 0.79 0.00))
(gold3 (make-color 0.80 0.68 0.00))
(gold4 (make-color 0.54 0.46 0.00))
(goldenrod1 (make-color 1.00 0.75 0.14))
(goldenrod2 (make-color 0.93 0.70 0.13))
(goldenrod3 (make-color 0.80 0.61 0.11))
(goldenrod4 (make-color 0.54 0.41 0.08))
(darkgoldenrod1 (make-color 1.00 0.72 0.06))
(darkgoldenrod2 (make-color 0.93 0.68 0.05))
(darkgoldenrod3 (make-color 0.80 0.58 0.05))
(darkgoldenrod4 (make-color 0.54 0.39 0.03))
(rosybrown1 (make-color 1.00 0.75 0.75))
(rosybrown2 (make-color 0.93 0.70 0.70))
(rosybrown3 (make-color 0.80 0.61 0.61))
(rosybrown4 (make-color 0.54 0.41 0.41))
(indianred1 (make-color 1.00 0.41 0.41))
(indianred2 (make-color 0.93 0.39 0.39))
(indianred3 (make-color 0.80 0.33 0.33))
(indianred4 (make-color 0.54 0.23 0.23))
(sienna1 (make-color 1.00 0.51 0.28))
(sienna2 (make-color 0.93 0.47 0.26))
(sienna3 (make-color 0.80 0.41 0.22))
(sienna4 (make-color 0.54 0.28 0.15))
(burlywood1 (make-color 1.00 0.82 0.61))
(burlywood2 (make-color 0.93 0.77 0.57))
(burlywood3 (make-color 0.80 0.66 0.49))
(burlywood4 (make-color 0.54 0.45 0.33))
(wheat1 (make-color 1.00 0.90 0.73))
(wheat2 (make-color 0.93 0.84 0.68))
(wheat3 (make-color 0.80 0.73 0.59))
(wheat4 (make-color 0.54 0.49 0.40))
(tan1 (make-color 1.00 0.64 0.31))
(tan2 (make-color 0.93 0.60 0.29))
(tan3 (make-color 0.80 0.52 0.25))
(tan4 (make-color 0.54 0.35 0.17))
(chocolate1 (make-color 1.00 0.50 0.14))
(chocolate2 (make-color 0.93 0.46 0.13))
(chocolate3 (make-color 0.80 0.40 0.11))
(chocolate4 (make-color 0.54 0.27 0.07))
(firebrick1 (make-color 1.00 0.19 0.19))
(firebrick2 (make-color 0.93 0.17 0.17))
(firebrick3 (make-color 0.80 0.15 0.15))
(firebrick4 (make-color 0.54 0.10 0.10))
(brown1 (make-color 1.00 0.25 0.25))
(brown2 (make-color 0.93 0.23 0.23))
(brown3 (make-color 0.80 0.20 0.20))
(brown4 (make-color 0.54 0.14 0.14))
(salmon1 (make-color 1.00 0.55 0.41))
(salmon2 (make-color 0.93 0.51 0.38))
(salmon3 (make-color 0.80 0.44 0.33))
(salmon4 (make-color 0.54 0.30 0.22))
(lightsalmon1 (make-color 1.00 0.62 0.48))
(lightsalmon2 (make-color 0.93 0.58 0.45))
(lightsalmon3 (make-color 0.80 0.50 0.38))
(lightsalmon4 (make-color 0.54 0.34 0.26))
(orange1 (make-color 1.00 0.64 0.00))
(orange2 (make-color 0.93 0.60 0.00))
(orange3 (make-color 0.80 0.52 0.00))
(orange4 (make-color 0.54 0.35 0.00))
(darkorange1 (make-color 1.00 0.50 0.00))
(darkorange2 (make-color 0.93 0.46 0.00))
(darkorange3 (make-color 0.80 0.40 0.00))
(darkorange4 (make-color 0.54 0.27 0.00))
(coral1 (make-color 1.00 0.45 0.34))
(coral2 (make-color 0.93 0.41 0.31))
(coral3 (make-color 0.80 0.36 0.27))
(coral4 (make-color 0.54 0.24 0.18))
(tomato1 (make-color 1.00 0.39 0.28))
(tomato2 (make-color 0.93 0.36 0.26))
(tomato3 (make-color 0.80 0.31 0.22))
(tomato4 (make-color 0.54 0.21 0.15))
(orangered1 (make-color 1.00 0.27 0.00))
(orangered2 (make-color 0.93 0.25 0.00))
(orangered3 (make-color 0.80 0.21 0.00))
(orangered4 (make-color 0.54 0.14 0.00))
(red1 (make-color 1.00 0.00 0.00))
(red2 (make-color 0.93 0.00 0.00))
(red3 (make-color 0.80 0.00 0.00))
(red4 (make-color 0.54 0.00 0.00))
(deeppink1 (make-color 1.00 0.08 0.57))
(deeppink2 (make-color 0.93 0.07 0.54))
(deeppink3 (make-color 0.80 0.06 0.46))
(deeppink4 (make-color 0.54 0.04 0.31))
(hotpink1 (make-color 1.00 0.43 0.70))
(hotpink2 (make-color 0.93 0.41 0.65))
(hotpink3 (make-color 0.80 0.37 0.56))
(hotpink4 (make-color 0.54 0.23 0.38))
(pink1 (make-color 1.00 0.71 0.77))
(pink2 (make-color 0.93 0.66 0.72))
(pink3 (make-color 0.80 0.57 0.62))
(pink4 (make-color 0.54 0.39 0.42))
(lightpink1 (make-color 1.00 0.68 0.72))
(lightpink2 (make-color 0.93 0.63 0.68))
(lightpink3 (make-color 0.80 0.55 0.58))
(lightpink4 (make-color 0.54 0.37 0.39))
(palevioletred1 (make-color 1.00 0.51 0.67))
(palevioletred2 (make-color 0.93 0.47 0.62))
(palevioletred3 (make-color 0.80 0.41 0.54))
(palevioletred4 (make-color 0.54 0.28 0.36))
(maroon1 (make-color 1.00 0.20 0.70))
(maroon2 (make-color 0.93 0.19 0.65))
(maroon3 (make-color 0.80 0.16 0.56))
(maroon4 (make-color 0.54 0.11 0.38))
(violetred1 (make-color 1.00 0.24 0.59))
(violetred2 (make-color 0.93 0.23 0.55))
(violetred3 (make-color 0.80 0.20 0.47))
(violetred4 (make-color 0.54 0.13 0.32))
(magenta1 (make-color 1.00 0.00 1.00))
(magenta2 (make-color 0.93 0.00 0.93))
(magenta3 (make-color 0.80 0.00 0.80))
(magenta4 (make-color 0.54 0.00 0.54))
(orchid1 (make-color 1.00 0.51 0.98))
(orchid2 (make-color 0.93 0.48 0.91))
(orchid3 (make-color 0.80 0.41 0.79))
(orchid4 (make-color 0.54 0.28 0.54))
(plum1 (make-color 1.00 0.73 1.00))
(plum2 (make-color 0.93 0.68 0.93))
(plum3 (make-color 0.80 0.59 0.80))
(plum4 (make-color 0.54 0.40 0.54))
(mediumorchid1 (make-color 0.87 0.40 1.00))
(mediumorchid2 (make-color 0.82 0.37 0.93))
(mediumorchid3 (make-color 0.70 0.32 0.80))
(mediumorchid4 (make-color 0.48 0.21 0.54))
(darkorchid1 (make-color 0.75 0.24 1.00))
(darkorchid2 (make-color 0.70 0.23 0.93))
(darkorchid3 (make-color 0.60 0.20 0.80))
(darkorchid4 (make-color 0.41 0.13 0.54))
(purple1 (make-color 0.61 0.19 1.00))
(purple2 (make-color 0.57 0.17 0.93))
(purple3 (make-color 0.49 0.15 0.80))
(purple4 (make-color 0.33 0.10 0.54))
(mediumpurple1 (make-color 0.67 0.51 1.00))
(mediumpurple2 (make-color 0.62 0.47 0.93))
(mediumpurple3 (make-color 0.54 0.41 0.80))
(mediumpurple4 (make-color 0.36 0.28 0.54))
(thistle1 (make-color 1.00 0.88 1.00))
(thistle2 (make-color 0.93 0.82 0.93))
(thistle3 (make-color 0.80 0.71 0.80))
(thistle4 (make-color 0.54 0.48 0.54))
(gray0 (make-color 0.00 0.00 0.00))
(grey0 (make-color 0.00 0.00 0.00))
(gray1 (make-color 0.01 0.01 0.01))
(grey1 (make-color 0.01 0.01 0.01))
(gray2 (make-color 0.02 0.02 0.02))
(grey2 (make-color 0.02 0.02 0.02))
(gray3 (make-color 0.03 0.03 0.03))
(grey3 (make-color 0.03 0.03 0.03))
(gray4 (make-color 0.04 0.04 0.04))
(grey4 (make-color 0.04 0.04 0.04))
(gray5 (make-color 0.05 0.05 0.05))
(grey5 (make-color 0.05 0.05 0.05))
(gray6 (make-color 0.06 0.06 0.06))
(grey6 (make-color 0.06 0.06 0.06))
(gray7 (make-color 0.07 0.07 0.07))
(grey7 (make-color 0.07 0.07 0.07))
(gray8 (make-color 0.08 0.08 0.08))
(grey8 (make-color 0.08 0.08 0.08))
(gray9 (make-color 0.09 0.09 0.09))
(grey9 (make-color 0.09 0.09 0.09))
(gray10 (make-color 0.10 0.10 0.10))
(grey10 (make-color 0.10 0.10 0.10))
(gray11 (make-color 0.11 0.11 0.11))
(grey11 (make-color 0.11 0.11 0.11))
(gray12 (make-color 0.12 0.12 0.12))
(grey12 (make-color 0.12 0.12 0.12))
(gray13 (make-color 0.13 0.13 0.13))
(grey13 (make-color 0.13 0.13 0.13))
(gray14 (make-color 0.14 0.14 0.14))
(grey14 (make-color 0.14 0.14 0.14))
(gray15 (make-color 0.15 0.15 0.15))
(grey15 (make-color 0.15 0.15 0.15))
(gray16 (make-color 0.16 0.16 0.16))
(grey16 (make-color 0.16 0.16 0.16))
(gray17 (make-color 0.17 0.17 0.17))
(grey17 (make-color 0.17 0.17 0.17))
(gray18 (make-color 0.18 0.18 0.18))
(grey18 (make-color 0.18 0.18 0.18))
(gray19 (make-color 0.19 0.19 0.19))
(grey19 (make-color 0.19 0.19 0.19))
(gray20 (make-color 0.20 0.20 0.20))
(grey20 (make-color 0.20 0.20 0.20))
(gray21 (make-color 0.21 0.21 0.21))
(grey21 (make-color 0.21 0.21 0.21))
(gray22 (make-color 0.22 0.22 0.22))
(grey22 (make-color 0.22 0.22 0.22))
(gray23 (make-color 0.23 0.23 0.23))
(grey23 (make-color 0.23 0.23 0.23))
(gray24 (make-color 0.24 0.24 0.24))
(grey24 (make-color 0.24 0.24 0.24))
(gray25 (make-color 0.25 0.25 0.25))
(grey25 (make-color 0.25 0.25 0.25))
(gray26 (make-color 0.26 0.26 0.26))
(grey26 (make-color 0.26 0.26 0.26))
(gray27 (make-color 0.27 0.27 0.27))
(grey27 (make-color 0.27 0.27 0.27))
(gray28 (make-color 0.28 0.28 0.28))
(grey28 (make-color 0.28 0.28 0.28))
(gray29 (make-color 0.29 0.29 0.29))
(grey29 (make-color 0.29 0.29 0.29))
(gray30 (make-color 0.30 0.30 0.30))
(grey30 (make-color 0.30 0.30 0.30))
(gray31 (make-color 0.31 0.31 0.31))
(grey31 (make-color 0.31 0.31 0.31))
(gray32 (make-color 0.32 0.32 0.32))
(grey32 (make-color 0.32 0.32 0.32))
(gray33 (make-color 0.33 0.33 0.33))
(grey33 (make-color 0.33 0.33 0.33))
(gray34 (make-color 0.34 0.34 0.34))
(grey34 (make-color 0.34 0.34 0.34))
(gray35 (make-color 0.35 0.35 0.35))
(grey35 (make-color 0.35 0.35 0.35))
(gray36 (make-color 0.36 0.36 0.36))
(grey36 (make-color 0.36 0.36 0.36))
(gray37 (make-color 0.37 0.37 0.37))
(grey37 (make-color 0.37 0.37 0.37))
(gray38 (make-color 0.38 0.38 0.38))
(grey38 (make-color 0.38 0.38 0.38))
(gray39 (make-color 0.39 0.39 0.39))
(grey39 (make-color 0.39 0.39 0.39))
(gray40 (make-color 0.40 0.40 0.40))
(grey40 (make-color 0.40 0.40 0.40))
(gray41 (make-color 0.41 0.41 0.41))
(grey41 (make-color 0.41 0.41 0.41))
(gray42 (make-color 0.42 0.42 0.42))
(grey42 (make-color 0.42 0.42 0.42))
(gray43 (make-color 0.43 0.43 0.43))
(grey43 (make-color 0.43 0.43 0.43))
(gray44 (make-color 0.44 0.44 0.44))
(grey44 (make-color 0.44 0.44 0.44))
(gray45 (make-color 0.45 0.45 0.45))
(grey45 (make-color 0.45 0.45 0.45))
(gray46 (make-color 0.46 0.46 0.46))
(grey46 (make-color 0.46 0.46 0.46))
(gray47 (make-color 0.47 0.47 0.47))
(grey47 (make-color 0.47 0.47 0.47))
(gray48 (make-color 0.48 0.48 0.48))
(grey48 (make-color 0.48 0.48 0.48))
(gray49 (make-color 0.49 0.49 0.49))
(grey49 (make-color 0.49 0.49 0.49))
(gray50 (make-color 0.50 0.50 0.50))
(grey50 (make-color 0.50 0.50 0.50))
(gray51 (make-color 0.51 0.51 0.51))
(grey51 (make-color 0.51 0.51 0.51))
(gray52 (make-color 0.52 0.52 0.52))
(grey52 (make-color 0.52 0.52 0.52))
(gray53 (make-color 0.53 0.53 0.53))
(grey53 (make-color 0.53 0.53 0.53))
(gray54 (make-color 0.54 0.54 0.54))
(grey54 (make-color 0.54 0.54 0.54))
(gray55 (make-color 0.55 0.55 0.55))
(grey55 (make-color 0.55 0.55 0.55))
(gray56 (make-color 0.56 0.56 0.56))
(grey56 (make-color 0.56 0.56 0.56))
(gray57 (make-color 0.57 0.57 0.57))
(grey57 (make-color 0.57 0.57 0.57))
(gray58 (make-color 0.58 0.58 0.58))
(grey58 (make-color 0.58 0.58 0.58))
(gray59 (make-color 0.59 0.59 0.59))
(grey59 (make-color 0.59 0.59 0.59))
(gray60 (make-color 0.60 0.60 0.60))
(grey60 (make-color 0.60 0.60 0.60))
(gray61 (make-color 0.61 0.61 0.61))
(grey61 (make-color 0.61 0.61 0.61))
(gray62 (make-color 0.62 0.62 0.62))
(grey62 (make-color 0.62 0.62 0.62))
(gray63 (make-color 0.63 0.63 0.63))
(grey63 (make-color 0.63 0.63 0.63))
(gray64 (make-color 0.64 0.64 0.64))
(grey64 (make-color 0.64 0.64 0.64))
(gray65 (make-color 0.65 0.65 0.65))
(grey65 (make-color 0.65 0.65 0.65))
(gray66 (make-color 0.66 0.66 0.66))
(grey66 (make-color 0.66 0.66 0.66))
(gray67 (make-color 0.67 0.67 0.67))
(grey67 (make-color 0.67 0.67 0.67))
(gray68 (make-color 0.68 0.68 0.68))
(grey68 (make-color 0.68 0.68 0.68))
(gray69 (make-color 0.69 0.69 0.69))
(grey69 (make-color 0.69 0.69 0.69))
(gray70 (make-color 0.70 0.70 0.70))
(grey70 (make-color 0.70 0.70 0.70))
(gray71 (make-color 0.71 0.71 0.71))
(grey71 (make-color 0.71 0.71 0.71))
(gray72 (make-color 0.72 0.72 0.72))
(grey72 (make-color 0.72 0.72 0.72))
(gray73 (make-color 0.73 0.73 0.73))
(grey73 (make-color 0.73 0.73 0.73))
(gray74 (make-color 0.74 0.74 0.74))
(grey74 (make-color 0.74 0.74 0.74))
(gray75 (make-color 0.75 0.75 0.75))
(grey75 (make-color 0.75 0.75 0.75))
(gray76 (make-color 0.76 0.76 0.76))
(grey76 (make-color 0.76 0.76 0.76))
(gray77 (make-color 0.77 0.77 0.77))
(grey77 (make-color 0.77 0.77 0.77))
(gray78 (make-color 0.78 0.78 0.78))
(grey78 (make-color 0.78 0.78 0.78))
(gray79 (make-color 0.79 0.79 0.79))
(grey79 (make-color 0.79 0.79 0.79))
(gray80 (make-color 0.80 0.80 0.80))
(grey80 (make-color 0.80 0.80 0.80))
(gray81 (make-color 0.81 0.81 0.81))
(grey81 (make-color 0.81 0.81 0.81))
(gray82 (make-color 0.82 0.82 0.82))
(grey82 (make-color 0.82 0.82 0.82))
(gray83 (make-color 0.83 0.83 0.83))
(grey83 (make-color 0.83 0.83 0.83))
(gray84 (make-color 0.84 0.84 0.84))
(grey84 (make-color 0.84 0.84 0.84))
(gray85 (make-color 0.85 0.85 0.85))
(grey85 (make-color 0.85 0.85 0.85))
(gray86 (make-color 0.86 0.86 0.86))
(grey86 (make-color 0.86 0.86 0.86))
(gray87 (make-color 0.87 0.87 0.87))
(grey87 (make-color 0.87 0.87 0.87))
(gray88 (make-color 0.87 0.87 0.87))
(grey88 (make-color 0.87 0.87 0.87))
(gray89 (make-color 0.89 0.89 0.89))
(grey89 (make-color 0.89 0.89 0.89))
(gray90 (make-color 0.89 0.89 0.89))
(grey90 (make-color 0.89 0.89 0.89))
(gray91 (make-color 0.91 0.91 0.91))
(grey91 (make-color 0.91 0.91 0.91))
(gray92 (make-color 0.92 0.92 0.92))
(grey92 (make-color 0.92 0.92 0.92))
(gray93 (make-color 0.93 0.93 0.93))
(grey93 (make-color 0.93 0.93 0.93))
(gray94 (make-color 0.94 0.94 0.94))
(grey94 (make-color 0.94 0.94 0.94))
(gray95 (make-color 0.95 0.95 0.95))
(grey95 (make-color 0.95 0.95 0.95))
(gray96 (make-color 0.96 0.96 0.96))
(grey96 (make-color 0.96 0.96 0.96))
(gray97 (make-color 0.96 0.96 0.96))
(grey97 (make-color 0.96 0.96 0.96))
(gray98 (make-color 0.98 0.98 0.98))
(grey98 (make-color 0.98 0.98 0.98))
(gray99 (make-color 0.98 0.98 0.98))
(grey99 (make-color 0.98 0.98 0.98))
(gray100 (make-color 1.00 1.00 1.00))
(grey100 (make-color 1.00 1.00 1.00))
(dark-grey (make-color 0.66 0.66 0.66))
(dark-gray (make-color 0.66 0.66 0.66))
(dark-blue (make-color 0.00 0.00 0.54))
(dark-cyan (make-color 0.00 0.54 0.54))
(dark-magenta (make-color 0.54 0.00 0.54))
(dark-red (make-color 0.54 0.00 0.00))
(light-green (make-color 0.56 0.93 0.56)))
(curlet)))
|
8105174464d310b05831332367e1905a27c646ad12b32fd9ca6ec1eaead13862 | facebook/duckling | Rules.hs | Copyright ( c ) 2016 - present , Facebook , Inc.
-- All rights reserved.
--
-- This source code is licensed under the BSD-style license found in the
-- LICENSE file in the root directory of this source tree.
{-# LANGUAGE OverloadedStrings #-}
module Duckling.TimeGrain.FR.Rules
( rules ) where
import Data.Text (Text)
import Prelude
import Data.String
import Duckling.Dimensions.Types
import qualified Duckling.TimeGrain.Types as TG
import Duckling.Types
grains :: [(Text, String, TG.Grain)]
grains = [ ("seconde (grain)", "sec(onde)?s?", TG.Second)
, ("minute (grain)", "min(ute)?s?", TG.Minute)
, ("heure (grain)", "heures?", TG.Hour)
, ("jour (grain)", "jour(n(e|é)e?)?s?", TG.Day)
, ("semaine (grain)", "semaines?", TG.Week)
, ("mois (grain)", "mois", TG.Month)
, ("trimestre (grain)", "trimestres?", TG.Quarter)
, ("année (grain)", "an(n(e|é)e?)?s?", TG.Year)
]
rules :: [Rule]
rules = map go grains
where
go (name, regexPattern, grain) = Rule
{ name = name
, pattern = [regex regexPattern]
, prod = \_ -> Just $ Token TimeGrain grain
}
| null | https://raw.githubusercontent.com/facebook/duckling/72f45e8e2c7385f41f2f8b1f063e7b5daa6dca94/Duckling/TimeGrain/FR/Rules.hs | haskell | All rights reserved.
This source code is licensed under the BSD-style license found in the
LICENSE file in the root directory of this source tree.
# LANGUAGE OverloadedStrings # | Copyright ( c ) 2016 - present , Facebook , Inc.
module Duckling.TimeGrain.FR.Rules
( rules ) where
import Data.Text (Text)
import Prelude
import Data.String
import Duckling.Dimensions.Types
import qualified Duckling.TimeGrain.Types as TG
import Duckling.Types
grains :: [(Text, String, TG.Grain)]
grains = [ ("seconde (grain)", "sec(onde)?s?", TG.Second)
, ("minute (grain)", "min(ute)?s?", TG.Minute)
, ("heure (grain)", "heures?", TG.Hour)
, ("jour (grain)", "jour(n(e|é)e?)?s?", TG.Day)
, ("semaine (grain)", "semaines?", TG.Week)
, ("mois (grain)", "mois", TG.Month)
, ("trimestre (grain)", "trimestres?", TG.Quarter)
, ("année (grain)", "an(n(e|é)e?)?s?", TG.Year)
]
rules :: [Rule]
rules = map go grains
where
go (name, regexPattern, grain) = Rule
{ name = name
, pattern = [regex regexPattern]
, prod = \_ -> Just $ Token TimeGrain grain
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.