_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 |
|---|---|---|---|---|---|---|---|---|
cab8e764cc9400f7bf09703ca76d9c2ace352b6622ad53fa8b1242e20ac90a8f | scalaris-team/scalaris | lb_active_directories.erl | 2014 - 2015 Zuse Institute Berlin
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.
@author < >
%% @doc Implementation of a modified version of the paper below. This implementation
%% doesn't use virtual servers but can still benefit from the load balancing
%% algorithm's attributes, respectively the load directories and the emergency
%% transfer of load.
%%
%% Many-to-Many scheme
%% @end
, , , , and
%% "Load balancing in dynamic structured peer-to-peer systems"
Performance Evaluation , vol . 63 , no . 3 , pp . 217 - 240 , 2006 .
%%
%% @version $Id$
-module(lb_active_directories).
-author('').
-vsn('$Id$').
-behaviour(lb_active_beh).
%% implements
-export([init/0, check_config/0]).
-export([handle_msg/2, handle_dht_msg/2]).
-export([get_web_debug_kv/1]).
-include("scalaris.hrl").
-include("record_helpers.hrl").
%% Defines the number of directories
e.g. 1 implies a central directory
-define(NUM_DIRECTORIES, 2).
-define(TRACE(X,Y), ok).
%-define(TRACE(X,Y), io:format(X,Y)).
-type directory_name() :: string().
-record(directory, {name = ?required(directory, name) :: directory_name(),
pool = gb_sets:new() :: gb_sets:set(lb_info:lb_info()),
num_reported = 0 :: non_neg_integer()
}).
-record(reassign, {light = ?required(reassign, from) :: lb_info:lb_info(),
heavy = ?required(reassign, to) :: lb_info:lb_info()
}).
-type reassign() :: #reassign{}.
-type schedule() :: [reassign()].
-record(state, {my_dirs = [] :: [directory_name()],
threshold_periodic = 0.5 , % % k_p = ( 1 + average directory utilization ) / 2
threshold_emergency = 1.0 , % % k_e
schedule = [] :: schedule()
}).
-type directory() :: #directory{}.
-type state() :: #state{}.
-type trigger() :: publish_trigger | directory_trigger.
-type message() :: {publish_trigger} |
{post_load, lb_info:lb_info()} |
{directory_trigger} |
{get_state_response, intervals:interval()}.
-type dht_message() :: {lb_active, request_load, pid()} |
{lb_active, before_jump,
HeavyNode::lb_info:lb_info(), LightNode::lb_info:lb_info()}.
%%%%%%%%%%%%%%%% Initialization %%%%%%%%%%%%%%%%%%%%%%%
-spec init() -> state().
init() ->
%% post load to random directory
request_dht_load(),
trigger(publish_trigger),
trigger(directory_trigger),
request_dht_range(),
This = comm:this(),
rm_loop:subscribe(
self(), ?MODULE, fun rm_loop:subscribe_dneighbor_change_slide_filter/3,
fun(_,_,_,_,_) -> comm:send_local(self(), {get_state, This, my_range}) end, inf),
#state{}.
%%%%%%%%%%%%%%%% Process Messages %%%%%%%%%%%%%%%%%%%%%%%
-spec handle_msg(message(), state()) -> state().
handle_msg({publish_trigger}, State) ->
trigger(publish_trigger),
case emergency of %% emergency when load(node) > k_e
% true ->
%post_load(),
%get && perform_transfer()
State ;
_ ->
get & & perform transfer ( ) without overloading
Schedule = State#state.schedule,
%% transfer (balance) up to MaxTransfer nodes
MaxTransfer = config:read(lb_active_directories_max_transfer),
perform_transfer(Schedule, 0, MaxTransfer),
% post_load()
request load to post it in the directory afterwards
request_dht_load(),
State#state{schedule = []}
end;
%% we received load because of publish load trigger or emergency
handle_msg({post_load, LoadInfo}, State) ->
?TRACE("Posting load ~p~n", [LoadInfo]),
Directory = get_random_directory(),
DirKey = Directory#directory.name,
post_load_to_directory(LoadInfo, DirKey, 0),
%% TODO Emergency Threshold has been already checked at the node overloaded...
EmergencyThreshold = State#state.threshold_emergency ,
case lb_info : ) > EmergencyThreshold of
%% true ->
%% ?TRACE("Emergency in post_load~n", []),
MySchedule = State#state.schedule ,
Schedule = directory_routine(DirKey , emergency , MySchedule ) ,
%% perform_transfer(Schedule);
%% false -> ok
%% end,
State;
handle_msg({directory_trigger}, State) ->
trigger(directory_trigger),
?TRACE("~p My Directories: ~p~n", [self(), State#state.my_dirs]),
Threshold k_p = Average laod in directory
Threshold k_e = 1 meaning full capacity
%% Upon receipt of load information:
%% add_to_directory(load_information),
%% case node_overloaded of
%% true -> compute_reassign(directory_load, node, k_e);
%% _ -> compute_reassign(directory_load, node, k_p),
%% clear_directory()
%% end
%% compute_reassign:
%% for every node from heavist to lightest in directory
if l_n / c_n > k
balance such that ( l_n + l_x ) / c_n gets minimized
%% return assignment
MyDirKeys = State#state.my_dirs,
NewSchedule = manage_directories(MyDirKeys),
State#state{schedule = NewSchedule};
handle_msg({get_state_response, MyRange}, State) ->
Directories = get_all_directory_keys(),
MyDirectories = [int_to_str(Dir) || Dir <- Directories, intervals:in(Dir, MyRange)],
?TRACE("~p: I am responsible for ~p~n", [self(), MyDirectories]),
State#state{my_dirs = MyDirectories, schedule = []};
handle_msg(_Msg, State) ->
?TRACE("Unknown message: ~p~n", [_Msg]),
State.
%%%%%%%%%%%%%%%%%% DHT Node interaction %%%%%%%%%%%%%%%%%%%%%%%
@doc Load balancing messages received by the node .
-spec handle_dht_msg(dht_message(), dht_node_state:state()) -> dht_node_state:state().
handle_dht_msg({lb_active, request_load, ReplyPid}, DhtState) ->
NodeDetails = dht_node_state:details(DhtState),
LoadInfo = lb_info:new(NodeDetails),
case lb_info:is_valid(LoadInfo) of
true -> comm:send_local(ReplyPid, {post_load, LoadInfo});
_ -> ok
end,
DhtState;
%% This handler is for requesting load information from the succ of
%% the light node in case of a jump (we are the succ of the light node).
handle_dht_msg({lb_active, before_jump, HeavyNode, LightNode}, DhtState) ->
NodeDetails = dht_node_state:details(DhtState),
LightNodeSucc = lb_info:new(NodeDetails),
case lb_info:is_valid(LightNodeSucc) of
true -> lb_active:balance_nodes(HeavyNode, LightNode, LightNodeSucc, []);
_ -> ok
end,
DhtState;
handle_dht_msg(_Msg, DhtState) ->
?TRACE("Unknown message: ~p~n", [_Msg]),
DhtState.
%%%%%%%%%%%%%%%%% Directory Management %%%%%%%%%%%%%%%
manage_directories(DirKeys) ->
manage_directories(DirKeys, []).
manage_directories([], Schedule) ->
Schedule;
manage_directories([DirKey | Other], Schedule) ->
DirSchedule = directory_routine(DirKey, periodic, Schedule),
manage_directories(Other, Schedule ++ DirSchedule).
-spec directory_routine(directory_name(), periodic | emergency, schedule()) -> schedule().
directory_routine(DirKey, _Type, Schedule) ->
%% Because of the lack of virtual servers/nodes, the load
%% balancing is differs from the paper here. We try to
%% balance the most loaded node with the least loaded
%% node.
%% TODO Some preference should be given to neighboring
%% nodes to avoid too many jumps.
{_TLog, Directory} = get_directory(DirKey),
clear_directory(Directory, 0),
case dir_is_empty(Directory) of
true -> Schedule;
false ->
Pool = Directory#directory.pool,
ScheduleNew = find_matches(Pool),
?TRACE("New schedule: ~p~n", [ScheduleNew]),
ScheduleNew
end.
-spec find_matches(gb_sets:set(lb_info:lb_info())) -> schedule().
find_matches(Nodes) ->
case gb_sets:size(Nodes) >= 2 of
true ->
{LightNode, NodesNew} = gb_sets:take_smallest(Nodes),
{HeavyNode, NodesNew2} = gb_sets:take_largest(NodesNew),
Epsilon = 0.24,
case lb_info:get_load(LightNode) =< Epsilon * lb_info:get_load(HeavyNode) of
true ->
[#reassign{light = LightNode, heavy = HeavyNode} | find_matches(NodesNew2)];
_ ->
find_matches(NodesNew2)
end;
false ->
return the result with the best match first
[]
end.
-spec get_all_directory_keys() -> [?RT:key()].
get_all_directory_keys() ->
[get_directory_key_by_number(N) || N <- lists:seq(1, ?NUM_DIRECTORIES)].
-spec get_random_directory_key() -> ?RT:key().
get_random_directory_key() ->
Rand = randoms:rand_uniform(1, ?NUM_DIRECTORIES+1),
get_directory_key_by_number(Rand).
-spec get_directory_key_by_number(pos_integer()) -> ?RT:key().
get_directory_key_by_number(N) when N > 0 ->
?RT:hash_key("lb_active_dir" ++ int_to_str(N)).
selects two directories at random and returns the one which least nodes reported to
get_random_directory() ->
{_TLog1, RandDir1} = get_directory(int_to_str(get_random_directory_key())),
{_TLog2, RandDir2} = get_directory(int_to_str(get_random_directory_key())),
case RandDir1#directory.num_reported >= RandDir2#directory.num_reported of
true -> RandDir1;
_ -> RandDir2
end.
-spec post_load_to_directory(lb_info:lb_info(), directory_name(), non_neg_integer()) -> ok.
post_load_to_directory(Load, DirKey, Retries) ->
{TLog, Dir} = get_directory(DirKey),
DirNew = dir_add_load(Load, Dir),
case set_directory(TLog, DirNew) of
ok -> ok;
failed ->
if Retries < 5 ->
wait_randomly(),
post_load_to_directory(Load, DirKey, Retries + 1);
true -> ok
end
end.
-spec clear_directory(directory(), non_neg_integer()) -> ok.
clear_directory(Directory, Retries) ->
DirNew = dir_clear_load(Directory),
case set_directory(api_tx:new_tlog(), DirNew) of
ok -> ok;
failed ->
if Retries < 5 ->
wait_randomly(),
clear_directory(Directory, Retries + 1);
true -> ok
end
end.
-spec get_directory(directory_name()) -> {tx_tlog:tlog(), directory()}.
get_directory(DirKey) ->
TLog = api_tx:new_tlog(),
case api_tx:read(TLog, DirKey) of
{TLog2, {ok, Directory}} ->
%?TRACE("~p: Got directory: ~p~n", [?MODULE, Directory]),
{TLog2, Directory};
{TLog2, {fail, not_found}} ->
log:log(warn, "~p: Directory not found: ~p", [?MODULE, DirKey]),
{TLog2, #directory{name = DirKey}}
end.
-spec set_directory(tx_tlog:tlog(), directory()) -> ok | failed.
set_directory(TLog, Directory) ->
DirKey = Directory#directory.name,
case api_tx:req_list(TLog, [{write, DirKey, Directory}, {commit}]) of
{[], [{ok}, {ok}]} ->
ok;
Error ->
log:log(warn, "~p: Failed to save directory ~p because of failed transaction: ~p", [?MODULE, DirKey, Error]),
failed
end.
Directory record % % % % % % % % % % % % % % % % % % % % % %
-spec dir_add_load(lb_info:lb_info(), directory()) -> directory().
dir_add_load(Load, Directory) ->
Pool = Directory#directory.pool,
PoolNew = gb_sets:add(Load, Pool),
NumReported = Directory#directory.num_reported,
Directory#directory{pool = PoolNew, num_reported = NumReported + 1}.
-spec dir_clear_load(directory()) -> directory().
dir_clear_load(Directory) ->
Directory#directory{pool = gb_sets:new(), num_reported = 0}.
%% dir_set_schedule(Schedule, Directory) ->
%% Directory#directory{schedule = Schedule}.
-spec dir_is_empty(directory()) -> boolean().
dir_is_empty(Directory) ->
Pool = Directory#directory.pool,
gb_sets:is_empty(Pool).
%%%%%%%%%%%%%% Reassignments %%%%%%%%%%%%%%%%%%%%%
-spec perform_transfer(schedule(), non_neg_integer(), pos_integer()) -> ok.
perform_transfer([], _, _) ->
ok;
perform_transfer(_, MaxTransfer, MaxTransfer) ->
ok;
perform_transfer([#reassign{light = LightNode, heavy = HeavyNode} | Other], Transferred, MaxTransfer) ->
?TRACE("~p: Reassigning ~p (light: ~p) and ~p (heavy: ~p)~n", [?MODULE, lb_info:get_node(LightNode), lb_info:get_load(LightNode), lb_info:get_node(HeavyNode), lb_info:get_load(HeavyNode)]),
case lb_info:neighbors(HeavyNode, LightNode) of
true ->
lb_active:balance_nodes(HeavyNode, LightNode, []);
send message to succ of to get his load
LightNodeSucc = lb_info:get_succ(LightNode),
comm:send(node:pidX(LightNodeSucc), {lb_active, before_jump, HeavyNode, LightNode})
end,
perform_transfer(Other, Transferred + 1, MaxTransfer).
%%%%%%%%%%%%
%% Helpers
%%
-spec request_dht_range() -> ok.
request_dht_range() ->
MyDHT = pid_groups:get_my(dht_node),
comm:send_local(MyDHT, {get_state, comm:this(), my_range}).
-spec request_dht_load() -> ok.
request_dht_load() ->
MyDHT = pid_groups:find_a(dht_node),
comm:send_local(MyDHT, {lb_active, request_load, self()}).
-spec int_to_str(integer()) -> string().
int_to_str(N) ->
erlang:integer_to_list(N).
-spec wait_randomly() -> ok.
wait_randomly() ->
timer:sleep(randoms:rand_uniform(1, 50)).
-spec trigger(trigger()) -> ok.
trigger(Trigger) ->
Interval =
case Trigger of
publish_trigger -> config:read(lb_active_directories_publish_interval);
directory_trigger -> config:read(lb_active_directories_directory_interval)
end,
msg_delay:send_trigger(Interval div 1000, {Trigger}).
-spec get_web_debug_kv(state()) -> [{string(), string()}].
get_web_debug_kv(State) ->
[{"state", webhelpers:html_pre("~p", [State])}].
-spec check_config() -> boolean().
check_config() ->
config:cfg_is_integer(lb_active_directories_publish_interval) and
config:cfg_is_greater_than(lb_active_directories_publish_interval, 1000) and
config:cfg_is_integer(lb_active_directories_directory_interval) and
config:cfg_is_greater_than(lb_active_directories_directory_interval, 1000) and
config:cfg_is_integer(lb_active_directories_max_transfer) and
config:cfg_is_greater_than(lb_active_directories_max_transfer, 0).
| null | https://raw.githubusercontent.com/scalaris-team/scalaris/feb894d54e642bb3530e709e730156b0ecc1635f/src/lb_active_directories.erl | erlang | you may not use this file except in compliance with the License.
You may obtain a copy of the License at
-2.0
Unless required by applicable law or agreed to in writing, software
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
@doc Implementation of a modified version of the paper below. This implementation
doesn't use virtual servers but can still benefit from the load balancing
algorithm's attributes, respectively the load directories and the emergency
transfer of load.
Many-to-Many scheme
@end
"Load balancing in dynamic structured peer-to-peer systems"
@version $Id$
implements
Defines the number of directories
-define(TRACE(X,Y), io:format(X,Y)).
% k_p = ( 1 + average directory utilization ) / 2
% k_e
Initialization %%%%%%%%%%%%%%%%%%%%%%%
post load to random directory
Process Messages %%%%%%%%%%%%%%%%%%%%%%%
emergency when load(node) > k_e
true ->
post_load(),
get && perform_transfer()
transfer (balance) up to MaxTransfer nodes
post_load()
we received load because of publish load trigger or emergency
TODO Emergency Threshold has been already checked at the node overloaded...
true ->
?TRACE("Emergency in post_load~n", []),
perform_transfer(Schedule);
false -> ok
end,
Upon receipt of load information:
add_to_directory(load_information),
case node_overloaded of
true -> compute_reassign(directory_load, node, k_e);
_ -> compute_reassign(directory_load, node, k_p),
clear_directory()
end
compute_reassign:
for every node from heavist to lightest in directory
return assignment
DHT Node interaction %%%%%%%%%%%%%%%%%%%%%%%
This handler is for requesting load information from the succ of
the light node in case of a jump (we are the succ of the light node).
Directory Management %%%%%%%%%%%%%%%
Because of the lack of virtual servers/nodes, the load
balancing is differs from the paper here. We try to
balance the most loaded node with the least loaded
node.
TODO Some preference should be given to neighboring
nodes to avoid too many jumps.
?TRACE("~p: Got directory: ~p~n", [?MODULE, Directory]),
% % % % % % % % % % % % % % % % % % % % %
dir_set_schedule(Schedule, Directory) ->
Directory#directory{schedule = Schedule}.
Reassignments %%%%%%%%%%%%%%%%%%%%%
Helpers
| 2014 - 2015 Zuse Institute Berlin
Licensed under the Apache License , Version 2.0 ( the " License " ) ;
distributed under the License is distributed on an " AS IS " BASIS ,
@author < >
, , , , and
Performance Evaluation , vol . 63 , no . 3 , pp . 217 - 240 , 2006 .
-module(lb_active_directories).
-author('').
-vsn('$Id$').
-behaviour(lb_active_beh).
-export([init/0, check_config/0]).
-export([handle_msg/2, handle_dht_msg/2]).
-export([get_web_debug_kv/1]).
-include("scalaris.hrl").
-include("record_helpers.hrl").
e.g. 1 implies a central directory
-define(NUM_DIRECTORIES, 2).
-define(TRACE(X,Y), ok).
-type directory_name() :: string().
-record(directory, {name = ?required(directory, name) :: directory_name(),
pool = gb_sets:new() :: gb_sets:set(lb_info:lb_info()),
num_reported = 0 :: non_neg_integer()
}).
-record(reassign, {light = ?required(reassign, from) :: lb_info:lb_info(),
heavy = ?required(reassign, to) :: lb_info:lb_info()
}).
-type reassign() :: #reassign{}.
-type schedule() :: [reassign()].
-record(state, {my_dirs = [] :: [directory_name()],
schedule = [] :: schedule()
}).
-type directory() :: #directory{}.
-type state() :: #state{}.
-type trigger() :: publish_trigger | directory_trigger.
-type message() :: {publish_trigger} |
{post_load, lb_info:lb_info()} |
{directory_trigger} |
{get_state_response, intervals:interval()}.
-type dht_message() :: {lb_active, request_load, pid()} |
{lb_active, before_jump,
HeavyNode::lb_info:lb_info(), LightNode::lb_info:lb_info()}.
-spec init() -> state().
init() ->
request_dht_load(),
trigger(publish_trigger),
trigger(directory_trigger),
request_dht_range(),
This = comm:this(),
rm_loop:subscribe(
self(), ?MODULE, fun rm_loop:subscribe_dneighbor_change_slide_filter/3,
fun(_,_,_,_,_) -> comm:send_local(self(), {get_state, This, my_range}) end, inf),
#state{}.
-spec handle_msg(message(), state()) -> state().
handle_msg({publish_trigger}, State) ->
trigger(publish_trigger),
State ;
_ ->
get & & perform transfer ( ) without overloading
Schedule = State#state.schedule,
MaxTransfer = config:read(lb_active_directories_max_transfer),
perform_transfer(Schedule, 0, MaxTransfer),
request load to post it in the directory afterwards
request_dht_load(),
State#state{schedule = []}
end;
handle_msg({post_load, LoadInfo}, State) ->
?TRACE("Posting load ~p~n", [LoadInfo]),
Directory = get_random_directory(),
DirKey = Directory#directory.name,
post_load_to_directory(LoadInfo, DirKey, 0),
EmergencyThreshold = State#state.threshold_emergency ,
case lb_info : ) > EmergencyThreshold of
MySchedule = State#state.schedule ,
Schedule = directory_routine(DirKey , emergency , MySchedule ) ,
State;
handle_msg({directory_trigger}, State) ->
trigger(directory_trigger),
?TRACE("~p My Directories: ~p~n", [self(), State#state.my_dirs]),
Threshold k_p = Average laod in directory
Threshold k_e = 1 meaning full capacity
if l_n / c_n > k
balance such that ( l_n + l_x ) / c_n gets minimized
MyDirKeys = State#state.my_dirs,
NewSchedule = manage_directories(MyDirKeys),
State#state{schedule = NewSchedule};
handle_msg({get_state_response, MyRange}, State) ->
Directories = get_all_directory_keys(),
MyDirectories = [int_to_str(Dir) || Dir <- Directories, intervals:in(Dir, MyRange)],
?TRACE("~p: I am responsible for ~p~n", [self(), MyDirectories]),
State#state{my_dirs = MyDirectories, schedule = []};
handle_msg(_Msg, State) ->
?TRACE("Unknown message: ~p~n", [_Msg]),
State.
@doc Load balancing messages received by the node .
-spec handle_dht_msg(dht_message(), dht_node_state:state()) -> dht_node_state:state().
handle_dht_msg({lb_active, request_load, ReplyPid}, DhtState) ->
NodeDetails = dht_node_state:details(DhtState),
LoadInfo = lb_info:new(NodeDetails),
case lb_info:is_valid(LoadInfo) of
true -> comm:send_local(ReplyPid, {post_load, LoadInfo});
_ -> ok
end,
DhtState;
handle_dht_msg({lb_active, before_jump, HeavyNode, LightNode}, DhtState) ->
NodeDetails = dht_node_state:details(DhtState),
LightNodeSucc = lb_info:new(NodeDetails),
case lb_info:is_valid(LightNodeSucc) of
true -> lb_active:balance_nodes(HeavyNode, LightNode, LightNodeSucc, []);
_ -> ok
end,
DhtState;
handle_dht_msg(_Msg, DhtState) ->
?TRACE("Unknown message: ~p~n", [_Msg]),
DhtState.
manage_directories(DirKeys) ->
manage_directories(DirKeys, []).
manage_directories([], Schedule) ->
Schedule;
manage_directories([DirKey | Other], Schedule) ->
DirSchedule = directory_routine(DirKey, periodic, Schedule),
manage_directories(Other, Schedule ++ DirSchedule).
-spec directory_routine(directory_name(), periodic | emergency, schedule()) -> schedule().
directory_routine(DirKey, _Type, Schedule) ->
{_TLog, Directory} = get_directory(DirKey),
clear_directory(Directory, 0),
case dir_is_empty(Directory) of
true -> Schedule;
false ->
Pool = Directory#directory.pool,
ScheduleNew = find_matches(Pool),
?TRACE("New schedule: ~p~n", [ScheduleNew]),
ScheduleNew
end.
-spec find_matches(gb_sets:set(lb_info:lb_info())) -> schedule().
find_matches(Nodes) ->
case gb_sets:size(Nodes) >= 2 of
true ->
{LightNode, NodesNew} = gb_sets:take_smallest(Nodes),
{HeavyNode, NodesNew2} = gb_sets:take_largest(NodesNew),
Epsilon = 0.24,
case lb_info:get_load(LightNode) =< Epsilon * lb_info:get_load(HeavyNode) of
true ->
[#reassign{light = LightNode, heavy = HeavyNode} | find_matches(NodesNew2)];
_ ->
find_matches(NodesNew2)
end;
false ->
return the result with the best match first
[]
end.
-spec get_all_directory_keys() -> [?RT:key()].
get_all_directory_keys() ->
[get_directory_key_by_number(N) || N <- lists:seq(1, ?NUM_DIRECTORIES)].
-spec get_random_directory_key() -> ?RT:key().
get_random_directory_key() ->
Rand = randoms:rand_uniform(1, ?NUM_DIRECTORIES+1),
get_directory_key_by_number(Rand).
-spec get_directory_key_by_number(pos_integer()) -> ?RT:key().
get_directory_key_by_number(N) when N > 0 ->
?RT:hash_key("lb_active_dir" ++ int_to_str(N)).
selects two directories at random and returns the one which least nodes reported to
get_random_directory() ->
{_TLog1, RandDir1} = get_directory(int_to_str(get_random_directory_key())),
{_TLog2, RandDir2} = get_directory(int_to_str(get_random_directory_key())),
case RandDir1#directory.num_reported >= RandDir2#directory.num_reported of
true -> RandDir1;
_ -> RandDir2
end.
-spec post_load_to_directory(lb_info:lb_info(), directory_name(), non_neg_integer()) -> ok.
post_load_to_directory(Load, DirKey, Retries) ->
{TLog, Dir} = get_directory(DirKey),
DirNew = dir_add_load(Load, Dir),
case set_directory(TLog, DirNew) of
ok -> ok;
failed ->
if Retries < 5 ->
wait_randomly(),
post_load_to_directory(Load, DirKey, Retries + 1);
true -> ok
end
end.
-spec clear_directory(directory(), non_neg_integer()) -> ok.
clear_directory(Directory, Retries) ->
DirNew = dir_clear_load(Directory),
case set_directory(api_tx:new_tlog(), DirNew) of
ok -> ok;
failed ->
if Retries < 5 ->
wait_randomly(),
clear_directory(Directory, Retries + 1);
true -> ok
end
end.
-spec get_directory(directory_name()) -> {tx_tlog:tlog(), directory()}.
get_directory(DirKey) ->
TLog = api_tx:new_tlog(),
case api_tx:read(TLog, DirKey) of
{TLog2, {ok, Directory}} ->
{TLog2, Directory};
{TLog2, {fail, not_found}} ->
log:log(warn, "~p: Directory not found: ~p", [?MODULE, DirKey]),
{TLog2, #directory{name = DirKey}}
end.
-spec set_directory(tx_tlog:tlog(), directory()) -> ok | failed.
set_directory(TLog, Directory) ->
DirKey = Directory#directory.name,
case api_tx:req_list(TLog, [{write, DirKey, Directory}, {commit}]) of
{[], [{ok}, {ok}]} ->
ok;
Error ->
log:log(warn, "~p: Failed to save directory ~p because of failed transaction: ~p", [?MODULE, DirKey, Error]),
failed
end.
-spec dir_add_load(lb_info:lb_info(), directory()) -> directory().
dir_add_load(Load, Directory) ->
Pool = Directory#directory.pool,
PoolNew = gb_sets:add(Load, Pool),
NumReported = Directory#directory.num_reported,
Directory#directory{pool = PoolNew, num_reported = NumReported + 1}.
-spec dir_clear_load(directory()) -> directory().
dir_clear_load(Directory) ->
Directory#directory{pool = gb_sets:new(), num_reported = 0}.
-spec dir_is_empty(directory()) -> boolean().
dir_is_empty(Directory) ->
Pool = Directory#directory.pool,
gb_sets:is_empty(Pool).
-spec perform_transfer(schedule(), non_neg_integer(), pos_integer()) -> ok.
perform_transfer([], _, _) ->
ok;
perform_transfer(_, MaxTransfer, MaxTransfer) ->
ok;
perform_transfer([#reassign{light = LightNode, heavy = HeavyNode} | Other], Transferred, MaxTransfer) ->
?TRACE("~p: Reassigning ~p (light: ~p) and ~p (heavy: ~p)~n", [?MODULE, lb_info:get_node(LightNode), lb_info:get_load(LightNode), lb_info:get_node(HeavyNode), lb_info:get_load(HeavyNode)]),
case lb_info:neighbors(HeavyNode, LightNode) of
true ->
lb_active:balance_nodes(HeavyNode, LightNode, []);
send message to succ of to get his load
LightNodeSucc = lb_info:get_succ(LightNode),
comm:send(node:pidX(LightNodeSucc), {lb_active, before_jump, HeavyNode, LightNode})
end,
perform_transfer(Other, Transferred + 1, MaxTransfer).
-spec request_dht_range() -> ok.
request_dht_range() ->
MyDHT = pid_groups:get_my(dht_node),
comm:send_local(MyDHT, {get_state, comm:this(), my_range}).
-spec request_dht_load() -> ok.
request_dht_load() ->
MyDHT = pid_groups:find_a(dht_node),
comm:send_local(MyDHT, {lb_active, request_load, self()}).
-spec int_to_str(integer()) -> string().
int_to_str(N) ->
erlang:integer_to_list(N).
-spec wait_randomly() -> ok.
wait_randomly() ->
timer:sleep(randoms:rand_uniform(1, 50)).
-spec trigger(trigger()) -> ok.
trigger(Trigger) ->
Interval =
case Trigger of
publish_trigger -> config:read(lb_active_directories_publish_interval);
directory_trigger -> config:read(lb_active_directories_directory_interval)
end,
msg_delay:send_trigger(Interval div 1000, {Trigger}).
-spec get_web_debug_kv(state()) -> [{string(), string()}].
get_web_debug_kv(State) ->
[{"state", webhelpers:html_pre("~p", [State])}].
-spec check_config() -> boolean().
check_config() ->
config:cfg_is_integer(lb_active_directories_publish_interval) and
config:cfg_is_greater_than(lb_active_directories_publish_interval, 1000) and
config:cfg_is_integer(lb_active_directories_directory_interval) and
config:cfg_is_greater_than(lb_active_directories_directory_interval, 1000) and
config:cfg_is_integer(lb_active_directories_max_transfer) and
config:cfg_is_greater_than(lb_active_directories_max_transfer, 0).
|
76f39cde0d889c61d6d86b2dfdbc0262bd1bf7e3cedd59da93ff52afa677f40c | openweb-nl/open-bank-mark | postgres_db.clj | (ns nl.openweb.graphql-endpoint.postgres-db
(:require [com.stuartsierra.component :as component]
[hikari-cp.core :as h]
[nl.openweb.topology.clients :as clients]))
(def db-port (read-string (or (System/getenv "DB_PORT") "5432")))
(def db-hostname (or (System/getenv "DB_HOSTNAME") "localhost"))
(def db-password (or (System/getenv "DB_PASSWORD") "open-bank"))
(defn datasource-options
[db-port db-hostname db-password]
{:auto-commit true
:read-only false
:connection-timeout 30000
:validation-timeout 5000
:idle-timeout 600000
:max-lifetime 1800000
:minimum-idle 10
:maximum-pool-size 10
:pool-name "db-pool"
:adapter "postgresql"
:username "clojure_ge"
:password db-password
:database-name "transactiondb"
:server-name db-hostname
:port-number db-port
:register-mbeans false})
(defrecord PostgresDatabase []
component/Lifecycle
(start [this]
(let [datasource (h/make-datasource (datasource-options db-port db-hostname db-password))]
(assoc this :datasource datasource)))
(stop [this]
(h/close-datasource (:datasource this))
(assoc this :datasource nil)))
(defn new-db
[]
{:db (map->PostgresDatabase {})})
| null | https://raw.githubusercontent.com/openweb-nl/open-bank-mark/786c940dafb39c36fdbcae736fe893af9c00ef17/graphql-endpoint/src/nl/openweb/graphql_endpoint/postgres_db.clj | clojure | (ns nl.openweb.graphql-endpoint.postgres-db
(:require [com.stuartsierra.component :as component]
[hikari-cp.core :as h]
[nl.openweb.topology.clients :as clients]))
(def db-port (read-string (or (System/getenv "DB_PORT") "5432")))
(def db-hostname (or (System/getenv "DB_HOSTNAME") "localhost"))
(def db-password (or (System/getenv "DB_PASSWORD") "open-bank"))
(defn datasource-options
[db-port db-hostname db-password]
{:auto-commit true
:read-only false
:connection-timeout 30000
:validation-timeout 5000
:idle-timeout 600000
:max-lifetime 1800000
:minimum-idle 10
:maximum-pool-size 10
:pool-name "db-pool"
:adapter "postgresql"
:username "clojure_ge"
:password db-password
:database-name "transactiondb"
:server-name db-hostname
:port-number db-port
:register-mbeans false})
(defrecord PostgresDatabase []
component/Lifecycle
(start [this]
(let [datasource (h/make-datasource (datasource-options db-port db-hostname db-password))]
(assoc this :datasource datasource)))
(stop [this]
(h/close-datasource (:datasource this))
(assoc this :datasource nil)))
(defn new-db
[]
{:db (map->PostgresDatabase {})})
| |
1cbecf8c060cb626066afb9c0d11154a3e066fe0c23d4d6fcb018d7725b6b499 | ghc/ghc | Decls.hs |
{-# LANGUAGE ConstraintKinds #-}
{-# LANGUAGE DeriveDataTypeable #-}
# LANGUAGE FlexibleContexts #
# LANGUAGE FlexibleInstances #
# LANGUAGE ScopedTypeVariables #
# LANGUAGE TypeApplications #
# LANGUAGE TypeFamilies #
# LANGUAGE UndecidableInstances #
in module Language . Haskell . Syntax . Extension
# OPTIONS_GHC -Wno - orphans #
( c ) The University of Glasgow 2006
( c ) The GRASP / AQUA Project , Glasgow University , 1992 - 1998
(c) The University of Glasgow 2006
(c) The GRASP/AQUA Project, Glasgow University, 1992-1998
-}
-- | Abstract syntax of global declarations.
--
-- Definitions for: @SynDecl@ and @ConDecl@, @ClassDecl@,
-- @InstDecl@, @DefaultDecl@ and @ForeignDecl@.
module GHC.Hs.Decls (
* Toplevel declarations
HsDecl(..), LHsDecl, HsDataDefn(..), HsDeriving, LHsFunDep,
HsDerivingClause(..), LHsDerivingClause, DerivClauseTys(..), LDerivClauseTys,
NewOrData, newOrDataToFlavour, anyLConIsGadt,
StandaloneKindSig(..), LStandaloneKindSig, standaloneKindSigName,
-- ** Class or type declarations
TyClDecl(..), LTyClDecl, DataDeclRn(..),
TyClGroup(..),
tyClGroupTyClDecls, tyClGroupInstDecls, tyClGroupRoleDecls,
tyClGroupKindSigs,
isClassDecl, isDataDecl, isSynDecl, tcdName,
isFamilyDecl, isTypeFamilyDecl, isDataFamilyDecl,
isOpenTypeFamilyInfo, isClosedTypeFamilyInfo,
tyFamInstDeclName, tyFamInstDeclLName,
countTyClDecls, pprTyClDeclFlavour,
tyClDeclLName, tyClDeclTyVars,
hsDeclHasCusk, famResultKindSignature,
FamilyDecl(..), LFamilyDecl,
FunDep(..), ppDataDefnHeader,
pp_vanilla_decl_head,
-- ** Instance declarations
InstDecl(..), LInstDecl, FamilyInfo(..),
TyFamInstDecl(..), LTyFamInstDecl, instDeclDataFamInsts,
TyFamDefltDecl, LTyFamDefltDecl,
DataFamInstDecl(..), LDataFamInstDecl,
pprDataFamInstFlavour, pprTyFamInstDecl, pprHsFamInstLHS,
FamEqn(..), TyFamInstEqn, LTyFamInstEqn, HsTyPats,
LClsInstDecl, ClsInstDecl(..),
-- ** Standalone deriving declarations
DerivDecl(..), LDerivDecl,
-- ** Deriving strategies
DerivStrategy(..), LDerivStrategy,
derivStrategyName, foldDerivStrategy, mapDerivStrategy,
XViaStrategyPs(..),
* * declarations
LRuleDecls,RuleDecls(..),RuleDecl(..),LRuleDecl,HsRuleRn(..),
HsRuleAnn(..),
RuleBndr(..),LRuleBndr,
collectRuleBndrSigTys,
flattenRuleDecls, pprFullRuleName,
-- ** @default@ declarations
DefaultDecl(..), LDefaultDecl,
-- ** Template haskell declaration splice
SpliceDecoration(..),
SpliceDecl(..), LSpliceDecl,
-- ** Foreign function interface declarations
ForeignDecl(..), LForeignDecl, ForeignImport(..), ForeignExport(..),
CImportSpec(..),
-- ** Data-constructor declarations
ConDecl(..), LConDecl,
HsConDeclH98Details, HsConDeclGADTDetails(..), hsConDeclTheta,
getConNames, getRecConArgs_maybe,
-- ** Document comments
DocDecl(..), LDocDecl, docDeclDoc,
* *
WarnDecl(..), LWarnDecl,
WarnDecls(..), LWarnDecls,
-- ** Annotations
AnnDecl(..), LAnnDecl,
AnnProvenance(..), annProvenanceName_maybe,
-- ** Role annotations
RoleAnnotDecl(..), LRoleAnnotDecl, roleAnnotDeclName,
-- ** Injective type families
FamilyResultSig(..), LFamilyResultSig, InjectivityAnn(..), LInjectivityAnn,
resultVariableName, familyDeclLName, familyDeclName,
-- * Grouping
HsGroup(..), emptyRdrGroup, emptyRnGroup, appendGroups, hsGroupInstDecls,
hsGroupTopLevelFixitySigs,
partitionBindsAndSigs,
) where
-- friends:
import GHC.Prelude
import Language.Haskell.Syntax.Decls
import {-# SOURCE #-} GHC.Hs.Expr ( pprExpr, pprUntypedSplice )
Because imports Decls via HsBracket
import GHC.Hs.Binds
import GHC.Hs.Type
import GHC.Hs.Doc
import GHC.Types.Basic
import GHC.Core.Coercion
import Language.Haskell.Syntax.Extension
import GHC.Hs.Extension
import GHC.Parser.Annotation
import GHC.Types.Name
import GHC.Types.Name.Set
import GHC.Types.Fixity
-- others:
import GHC.Utils.Misc (count)
import GHC.Utils.Outputable
import GHC.Utils.Panic
import GHC.Types.SrcLoc
import GHC.Types.SourceText
import GHC.Core.Type
import GHC.Core.TyCon (TyConFlavour(NewtypeFlavour,DataTypeFlavour))
import GHC.Types.ForeignCall
import GHC.Data.Bag
import GHC.Data.Maybe
import Data.Data (Data)
import Data.Foldable (toList)
{-
************************************************************************
* *
\subsection[HsDecl]{Declarations}
* *
************************************************************************
-}
type instance XTyClD (GhcPass _) = NoExtField
type instance XInstD (GhcPass _) = NoExtField
type instance XDerivD (GhcPass _) = NoExtField
type instance XValD (GhcPass _) = NoExtField
type instance XSigD (GhcPass _) = NoExtField
type instance XKindSigD (GhcPass _) = NoExtField
type instance XDefD (GhcPass _) = NoExtField
type instance XForD (GhcPass _) = NoExtField
type instance XWarningD (GhcPass _) = NoExtField
type instance XAnnD (GhcPass _) = NoExtField
type instance XRuleD (GhcPass _) = NoExtField
type instance XSpliceD (GhcPass _) = NoExtField
type instance XDocD (GhcPass _) = NoExtField
type instance XRoleAnnotD (GhcPass _) = NoExtField
type instance XXHsDecl (GhcPass _) = DataConCantHappen
| Partition a list of into function / pattern bindings , signatures ,
-- type family declarations, type family instances, and documentation comments.
--
-- Panics when given a declaration that cannot be put into any of the output
-- groups.
--
-- The primary use of this function is to implement
' GHC.Parser . PostProcess.cvBindsAndSigs ' .
partitionBindsAndSigs
:: [LHsDecl GhcPs]
-> (LHsBinds GhcPs, [LSig GhcPs], [LFamilyDecl GhcPs],
[LTyFamInstDecl GhcPs], [LDataFamInstDecl GhcPs], [LDocDecl GhcPs])
partitionBindsAndSigs = go
where
go [] = (emptyBag, [], [], [], [], [])
go ((L l decl) : ds) =
let (bs, ss, ts, tfis, dfis, docs) = go ds in
case decl of
ValD _ b
-> (L l b `consBag` bs, ss, ts, tfis, dfis, docs)
SigD _ s
-> (bs, L l s : ss, ts, tfis, dfis, docs)
TyClD _ (FamDecl _ t)
-> (bs, ss, L l t : ts, tfis, dfis, docs)
InstD _ (TyFamInstD { tfid_inst = tfi })
-> (bs, ss, ts, L l tfi : tfis, dfis, docs)
InstD _ (DataFamInstD { dfid_inst = dfi })
-> (bs, ss, ts, tfis, L l dfi : dfis, docs)
DocD _ d
-> (bs, ss, ts, tfis, dfis, L l d : docs)
_ -> pprPanic "partitionBindsAndSigs" (ppr decl)
-- Okay, I need to reconstruct the document comments, but for now:
instance Outputable (DocDecl name) where
ppr _ = text "<document comment>"
type instance XCHsGroup (GhcPass _) = NoExtField
type instance XXHsGroup (GhcPass _) = DataConCantHappen
emptyGroup, emptyRdrGroup, emptyRnGroup :: HsGroup (GhcPass p)
emptyRdrGroup = emptyGroup { hs_valds = emptyValBindsIn }
emptyRnGroup = emptyGroup { hs_valds = emptyValBindsOut }
emptyGroup = HsGroup { hs_ext = noExtField,
hs_tyclds = [],
hs_derivds = [],
hs_fixds = [], hs_defds = [], hs_annds = [],
hs_fords = [], hs_warnds = [], hs_ruleds = [],
hs_valds = error "emptyGroup hs_valds: Can't happen",
hs_splcds = [],
hs_docs = [] }
-- | The fixity signatures for each top-level declaration and class method
-- in an 'HsGroup'.
-- See Note [Top-level fixity signatures in an HsGroup]
hsGroupTopLevelFixitySigs :: HsGroup (GhcPass p) -> [LFixitySig (GhcPass p)]
hsGroupTopLevelFixitySigs (HsGroup{ hs_fixds = fixds, hs_tyclds = tyclds }) =
fixds ++ cls_fixds
where
cls_fixds = [ L loc sig
| L _ ClassDecl{tcdSigs = sigs} <- tyClGroupTyClDecls tyclds
, L loc (FixSig _ sig) <- sigs
]
appendGroups :: HsGroup (GhcPass p) -> HsGroup (GhcPass p)
-> HsGroup (GhcPass p)
appendGroups
HsGroup {
hs_valds = val_groups1,
hs_splcds = spliceds1,
hs_tyclds = tyclds1,
hs_derivds = derivds1,
hs_fixds = fixds1,
hs_defds = defds1,
hs_annds = annds1,
hs_fords = fords1,
hs_warnds = warnds1,
hs_ruleds = rulds1,
hs_docs = docs1 }
HsGroup {
hs_valds = val_groups2,
hs_splcds = spliceds2,
hs_tyclds = tyclds2,
hs_derivds = derivds2,
hs_fixds = fixds2,
hs_defds = defds2,
hs_annds = annds2,
hs_fords = fords2,
hs_warnds = warnds2,
hs_ruleds = rulds2,
hs_docs = docs2 }
=
HsGroup {
hs_ext = noExtField,
hs_valds = val_groups1 `plusHsValBinds` val_groups2,
hs_splcds = spliceds1 ++ spliceds2,
hs_tyclds = tyclds1 ++ tyclds2,
hs_derivds = derivds1 ++ derivds2,
hs_fixds = fixds1 ++ fixds2,
hs_annds = annds1 ++ annds2,
hs_defds = defds1 ++ defds2,
hs_fords = fords1 ++ fords2,
hs_warnds = warnds1 ++ warnds2,
hs_ruleds = rulds1 ++ rulds2,
hs_docs = docs1 ++ docs2 }
instance (OutputableBndrId p) => Outputable (HsDecl (GhcPass p)) where
ppr (TyClD _ dcl) = ppr dcl
ppr (ValD _ binds) = ppr binds
ppr (DefD _ def) = ppr def
ppr (InstD _ inst) = ppr inst
ppr (DerivD _ deriv) = ppr deriv
ppr (ForD _ fd) = ppr fd
ppr (SigD _ sd) = ppr sd
ppr (KindSigD _ ksd) = ppr ksd
ppr (RuleD _ rd) = ppr rd
ppr (WarningD _ wd) = ppr wd
ppr (AnnD _ ad) = ppr ad
ppr (SpliceD _ dd) = ppr dd
ppr (DocD _ doc) = ppr doc
ppr (RoleAnnotD _ ra) = ppr ra
instance (OutputableBndrId p) => Outputable (HsGroup (GhcPass p)) where
ppr (HsGroup { hs_valds = val_decls,
hs_tyclds = tycl_decls,
hs_derivds = deriv_decls,
hs_fixds = fix_decls,
hs_warnds = deprec_decls,
hs_annds = ann_decls,
hs_fords = foreign_decls,
hs_defds = default_decls,
hs_ruleds = rule_decls })
= vcat_mb empty
[ppr_ds fix_decls, ppr_ds default_decls,
ppr_ds deprec_decls, ppr_ds ann_decls,
ppr_ds rule_decls,
if isEmptyValBinds val_decls
then Nothing
else Just (ppr val_decls),
ppr_ds (tyClGroupRoleDecls tycl_decls),
ppr_ds (tyClGroupKindSigs tycl_decls),
ppr_ds (tyClGroupTyClDecls tycl_decls),
ppr_ds (tyClGroupInstDecls tycl_decls),
ppr_ds deriv_decls,
ppr_ds foreign_decls]
where
ppr_ds :: Outputable a => [a] -> Maybe SDoc
ppr_ds [] = Nothing
ppr_ds ds = Just (vcat (map ppr ds))
vcat_mb :: SDoc -> [Maybe SDoc] -> SDoc
vertically with white - space between non - blanks
vcat_mb _ [] = empty
vcat_mb gap (Nothing : ds) = vcat_mb gap ds
vcat_mb gap (Just d : ds) = gap $$ d $$ vcat_mb blankLine ds
type instance XSpliceDecl (GhcPass _) = NoExtField
type instance XXSpliceDecl (GhcPass _) = DataConCantHappen
instance OutputableBndrId p
=> Outputable (SpliceDecl (GhcPass p)) where
ppr (SpliceDecl _ (L _ e) DollarSplice) = pprUntypedSplice True Nothing e
ppr (SpliceDecl _ (L _ e) BareSplice) = pprUntypedSplice False Nothing e
instance Outputable SpliceDecoration where
ppr x = text $ show x
{-
************************************************************************
* *
Type and class declarations
* *
************************************************************************
-}
type instance XFamDecl (GhcPass _) = NoExtField
type instance XSynDecl GhcPs = EpAnn [AddEpAnn]
FVs
FVs
type instance XDataDecl GhcPs = EpAnn [AddEpAnn]
type instance XDataDecl GhcRn = DataDeclRn
type instance XDataDecl GhcTc = DataDeclRn
data DataDeclRn = DataDeclRn
{ tcdDataCusk :: Bool -- ^ does this have a CUSK?
-- See Note [CUSKs: complete user-supplied kind signatures]
, tcdFVs :: NameSet }
deriving Data
type instance XClassDecl GhcPs = (EpAnn [AddEpAnn], AnnSortKey)
TODO : AZ : tidy up AnnSortKey above
FVs
FVs
type instance XXTyClDecl (GhcPass _) = DataConCantHappen
type instance XCTyFamInstDecl (GhcPass _) = EpAnn [AddEpAnn]
type instance XXTyFamInstDecl (GhcPass _) = DataConCantHappen
----------- Pretty printing FamilyDecls -----------
pprFlavour :: FamilyInfo pass -> SDoc
pprFlavour DataFamily = text "data"
pprFlavour OpenTypeFamily = text "type"
pprFlavour (ClosedTypeFamily {}) = text "type"
instance Outputable (FamilyInfo pass) where
ppr info = pprFlavour info <+> text "family"
-- Dealing with names
tyFamInstDeclName :: Anno (IdGhcP p) ~ SrcSpanAnnN
=> TyFamInstDecl (GhcPass p) -> IdP (GhcPass p)
tyFamInstDeclName = unLoc . tyFamInstDeclLName
tyFamInstDeclLName :: Anno (IdGhcP p) ~ SrcSpanAnnN
=> TyFamInstDecl (GhcPass p) -> LocatedN (IdP (GhcPass p))
tyFamInstDeclLName (TyFamInstDecl { tfid_eqn = FamEqn { feqn_tycon = ln }})
= ln
tyClDeclLName :: Anno (IdGhcP p) ~ SrcSpanAnnN
=> TyClDecl (GhcPass p) -> LocatedN (IdP (GhcPass p))
tyClDeclLName (FamDecl { tcdFam = fd }) = familyDeclLName fd
tyClDeclLName (SynDecl { tcdLName = ln }) = ln
tyClDeclLName (DataDecl { tcdLName = ln }) = ln
tyClDeclLName (ClassDecl { tcdLName = ln }) = ln
countTyClDecls :: [TyClDecl pass] -> (Int, Int, Int, Int, Int)
-- class, synonym decls, data, newtype, family decls
countTyClDecls decls
= (count isClassDecl decls,
count isSynDecl decls, -- excluding...
count isDataTy decls, -- ...family...
count isNewTy decls, -- ...instances
count isFamilyDecl decls)
where
isDataTy DataDecl{ tcdDataDefn = HsDataDefn { dd_cons = DataTypeCons _ _ } } = True
isDataTy _ = False
isNewTy DataDecl{ tcdDataDefn = HsDataDefn { dd_cons = NewTypeCon _ } } = True
isNewTy _ = False
FIXME : tcdName is commonly used by both GHC and third - party tools , so it
-- needs to be polymorphic in the pass
tcdName :: Anno (IdGhcP p) ~ SrcSpanAnnN
=> TyClDecl (GhcPass p) -> IdP (GhcPass p)
tcdName = unLoc . tyClDeclLName
-- | Does this declaration have a complete, user-supplied kind signature?
-- See Note [CUSKs: complete user-supplied kind signatures]
hsDeclHasCusk :: TyClDecl GhcRn -> Bool
hsDeclHasCusk (FamDecl { tcdFam =
FamilyDecl { fdInfo = fam_info
, fdTyVars = tyvars
, fdResultSig = L _ resultSig } }) =
case fam_info of
ClosedTypeFamily {} -> hsTvbAllKinded tyvars
&& isJust (famResultKindSignature resultSig)
Un - associated open type / data families have CUSKs
hsDeclHasCusk (SynDecl { tcdTyVars = tyvars, tcdRhs = rhs })
= hsTvbAllKinded tyvars && isJust (hsTyKindSig rhs)
hsDeclHasCusk (DataDecl { tcdDExt = DataDeclRn { tcdDataCusk = cusk }}) = cusk
hsDeclHasCusk (ClassDecl { tcdTyVars = tyvars }) = hsTvbAllKinded tyvars
-- Pretty-printing TyClDecl
-- ~~~~~~~~~~~~~~~~~~~~~~~~
instance (OutputableBndrId p) => Outputable (TyClDecl (GhcPass p)) where
ppr (FamDecl { tcdFam = decl }) = ppr decl
ppr (SynDecl { tcdLName = ltycon, tcdTyVars = tyvars, tcdFixity = fixity
, tcdRhs = rhs })
= hang (text "type" <+>
pp_vanilla_decl_head ltycon tyvars fixity Nothing <+> equals)
4 (ppr rhs)
ppr (DataDecl { tcdLName = ltycon, tcdTyVars = tyvars, tcdFixity = fixity
, tcdDataDefn = defn })
= pp_data_defn (pp_vanilla_decl_head ltycon tyvars fixity) defn
ppr (ClassDecl {tcdCtxt = context, tcdLName = lclas, tcdTyVars = tyvars,
tcdFixity = fixity,
tcdFDs = fds,
tcdSigs = sigs, tcdMeths = methods,
tcdATs = ats, tcdATDefs = at_defs})
| null sigs && isEmptyBag methods && null ats && null at_defs -- No "where" part
= top_matter
| otherwise -- Laid out
= vcat [ top_matter <+> text "where"
, nest 2 $ pprDeclList (map (ppr . unLoc) ats ++
map (pprTyFamDefltDecl . unLoc) at_defs ++
pprLHsBindsForUser methods sigs) ]
where
top_matter = text "class"
<+> pp_vanilla_decl_head lclas tyvars fixity context
<+> pprFundeps (map unLoc fds)
instance OutputableBndrId p
=> Outputable (TyClGroup (GhcPass p)) where
ppr (TyClGroup { group_tyclds = tyclds
, group_roles = roles
, group_kisigs = kisigs
, group_instds = instds
}
)
= hang (text "TyClGroup") 2 $
ppr kisigs $$
ppr tyclds $$
ppr roles $$
ppr instds
pp_vanilla_decl_head :: (OutputableBndrId p)
=> XRec (GhcPass p) (IdP (GhcPass p))
-> LHsQTyVars (GhcPass p)
-> LexicalFixity
-> Maybe (LHsContext (GhcPass p))
-> SDoc
pp_vanilla_decl_head thing (HsQTvs { hsq_explicit = tyvars }) fixity context
= hsep [pprLHsContext context, pp_tyvars tyvars]
where
pp_tyvars (varl:varsr)
| fixity == Infix, varr:varsr'@(_:_) <- varsr
If varsr has at least 2 elements , parenthesize .
= hsep [char '(',ppr (unLoc varl), pprInfixOcc (unLoc thing)
, (ppr.unLoc) varr, char ')'
, hsep (map (ppr.unLoc) varsr')]
| fixity == Infix
= hsep [ppr (unLoc varl), pprInfixOcc (unLoc thing)
, hsep (map (ppr.unLoc) varsr)]
| otherwise = hsep [ pprPrefixOcc (unLoc thing)
, hsep (map (ppr.unLoc) (varl:varsr))]
pp_tyvars [] = pprPrefixOcc (unLoc thing)
pprTyClDeclFlavour :: TyClDecl (GhcPass p) -> SDoc
pprTyClDeclFlavour (ClassDecl {}) = text "class"
pprTyClDeclFlavour (SynDecl {}) = text "type"
pprTyClDeclFlavour (FamDecl { tcdFam = FamilyDecl { fdInfo = info }})
= pprFlavour info <+> text "family"
pprTyClDeclFlavour (DataDecl { tcdDataDefn = HsDataDefn { dd_cons = nd } })
= ppr (dataDefnConsNewOrData nd)
instance OutputableBndrId p => Outputable (FunDep (GhcPass p)) where
ppr = pprFunDep
type instance XCFunDep (GhcPass _) = EpAnn [AddEpAnn]
type instance XXFunDep (GhcPass _) = DataConCantHappen
pprFundeps :: OutputableBndrId p => [FunDep (GhcPass p)] -> SDoc
pprFundeps [] = empty
pprFundeps fds = hsep (vbar : punctuate comma (map pprFunDep fds))
pprFunDep :: OutputableBndrId p => FunDep (GhcPass p) -> SDoc
pprFunDep (FunDep _ us vs) = hsep [interppSP us, arrow, interppSP vs]
{- *********************************************************************
* *
TyClGroup
Strongly connected components of
type, class, instance, and role declarations
* *
********************************************************************* -}
type instance XCTyClGroup (GhcPass _) = NoExtField
type instance XXTyClGroup (GhcPass _) = DataConCantHappen
{- *********************************************************************
* *
Data and type family declarations
* *
********************************************************************* -}
type instance XNoSig (GhcPass _) = NoExtField
type instance XCKindSig (GhcPass _) = NoExtField
type instance XTyVarSig (GhcPass _) = NoExtField
type instance XXFamilyResultSig (GhcPass _) = DataConCantHappen
type instance XCFamilyDecl (GhcPass _) = EpAnn [AddEpAnn]
type instance XXFamilyDecl (GhcPass _) = DataConCantHappen
----------- Functions over FamilyDecls -----------
familyDeclLName :: FamilyDecl (GhcPass p) -> XRec (GhcPass p) (IdP (GhcPass p))
familyDeclLName (FamilyDecl { fdLName = n }) = n
familyDeclName :: FamilyDecl (GhcPass p) -> IdP (GhcPass p)
familyDeclName = unLoc . familyDeclLName
famResultKindSignature :: FamilyResultSig (GhcPass p) -> Maybe (LHsKind (GhcPass p))
famResultKindSignature (NoSig _) = Nothing
famResultKindSignature (KindSig _ ki) = Just ki
famResultKindSignature (TyVarSig _ bndr) =
case unLoc bndr of
UserTyVar _ _ _ -> Nothing
KindedTyVar _ _ _ ki -> Just ki
-- | Maybe return name of the result type variable
resultVariableName :: FamilyResultSig (GhcPass a) -> Maybe (IdP (GhcPass a))
resultVariableName (TyVarSig _ sig) = Just $ hsLTyVarName sig
resultVariableName _ = Nothing
----------- Pretty printing FamilyDecls -----------
type instance XCInjectivityAnn (GhcPass _) = EpAnn [AddEpAnn]
type instance XXInjectivityAnn (GhcPass _) = DataConCantHappen
instance OutputableBndrId p
=> Outputable (FamilyDecl (GhcPass p)) where
ppr (FamilyDecl { fdInfo = info, fdLName = ltycon
, fdTopLevel = top_level
, fdTyVars = tyvars
, fdFixity = fixity
, fdResultSig = L _ result
, fdInjectivityAnn = mb_inj })
= vcat [ pprFlavour info <+> pp_top_level <+>
pp_vanilla_decl_head ltycon tyvars fixity Nothing <+>
pp_kind <+> pp_inj <+> pp_where
, nest 2 $ pp_eqns ]
where
pp_top_level = case top_level of
TopLevel -> text "family"
NotTopLevel -> empty
pp_kind = case result of
NoSig _ -> empty
KindSig _ kind -> dcolon <+> ppr kind
TyVarSig _ tv_bndr -> text "=" <+> ppr tv_bndr
pp_inj = case mb_inj of
Just (L _ (InjectivityAnn _ lhs rhs)) ->
hsep [ vbar, ppr lhs, text "->", hsep (map ppr rhs) ]
Nothing -> empty
(pp_where, pp_eqns) = case info of
ClosedTypeFamily mb_eqns ->
( text "where"
, case mb_eqns of
Nothing -> text ".."
Just eqns -> vcat $ map (ppr_fam_inst_eqn . unLoc) eqns )
_ -> (empty, empty)
{- *********************************************************************
* *
Data types and data constructors
* *
********************************************************************* -}
type instance XCHsDataDefn (GhcPass _) = NoExtField
type instance XXHsDataDefn (GhcPass _) = DataConCantHappen
type instance XCHsDerivingClause (GhcPass _) = EpAnn [AddEpAnn]
type instance XXHsDerivingClause (GhcPass _) = DataConCantHappen
instance OutputableBndrId p
=> Outputable (HsDerivingClause (GhcPass p)) where
ppr (HsDerivingClause { deriv_clause_strategy = dcs
, deriv_clause_tys = L _ dct })
= hsep [ text "deriving"
, pp_strat_before
, ppr dct
, pp_strat_after ]
where
@via@ is unique in that in comes /after/ the class being derived ,
-- so we must special-case it.
(pp_strat_before, pp_strat_after) =
case dcs of
Just (L _ via@ViaStrategy{}) -> (empty, ppr via)
_ -> (ppDerivStrategy dcs, empty)
| A short description of a @DerivStrategy'@.
derivStrategyName :: DerivStrategy a -> SDoc
derivStrategyName = text . go
where
go StockStrategy {} = "stock"
go AnyclassStrategy {} = "anyclass"
go NewtypeStrategy {} = "newtype"
go ViaStrategy {} = "via"
type instance XDctSingle (GhcPass _) = NoExtField
type instance XDctMulti (GhcPass _) = NoExtField
type instance XXDerivClauseTys (GhcPass _) = DataConCantHappen
instance OutputableBndrId p => Outputable (DerivClauseTys (GhcPass p)) where
ppr (DctSingle _ ty) = ppr ty
ppr (DctMulti _ tys) = parens (interpp'SP tys)
type instance XStandaloneKindSig GhcPs = EpAnn [AddEpAnn]
type instance XStandaloneKindSig GhcRn = NoExtField
type instance XStandaloneKindSig GhcTc = NoExtField
type instance XXStandaloneKindSig (GhcPass p) = DataConCantHappen
standaloneKindSigName :: StandaloneKindSig (GhcPass p) -> IdP (GhcPass p)
standaloneKindSigName (StandaloneKindSig _ lname _) = unLoc lname
type instance XConDeclGADT (GhcPass _) = EpAnn [AddEpAnn]
type instance XConDeclH98 (GhcPass _) = EpAnn [AddEpAnn]
type instance XXConDecl (GhcPass _) = DataConCantHappen
Codomain could be ' NonEmpty ' , but at the moment all users need a list .
getConNames :: ConDecl GhcRn -> [LocatedN Name]
getConNames ConDeclH98 {con_name = name} = [name]
getConNames ConDeclGADT {con_names = names} = toList names
-- | Return @'Just' fields@ if a data constructor declaration uses record
syntax ( i.e. , ' RecCon ' ) , where @fields@ are the field selectors .
-- Otherwise, return 'Nothing'.
getRecConArgs_maybe :: ConDecl GhcRn -> Maybe (LocatedL [LConDeclField GhcRn])
getRecConArgs_maybe (ConDeclH98{con_args = args}) = case args of
PrefixCon{} -> Nothing
RecCon flds -> Just flds
InfixCon{} -> Nothing
getRecConArgs_maybe (ConDeclGADT{con_g_args = args}) = case args of
PrefixConGADT{} -> Nothing
RecConGADT flds _ -> Just flds
hsConDeclTheta :: Maybe (LHsContext (GhcPass p)) -> [LHsType (GhcPass p)]
hsConDeclTheta Nothing = []
hsConDeclTheta (Just (L _ theta)) = theta
ppDataDefnHeader
:: (OutputableBndrId p)
=> (Maybe (LHsContext (GhcPass p)) -> SDoc) -- Printing the header
-> HsDataDefn (GhcPass p)
-> SDoc
ppDataDefnHeader pp_hdr HsDataDefn
{ dd_ctxt = context
, dd_cType = mb_ct
, dd_kindSig = mb_sig
, dd_cons = condecls }
= pp_type <+> ppr (dataDefnConsNewOrData condecls) <+> pp_ct <+> pp_hdr context <+> pp_sig
where
pp_type
| isTypeDataDefnCons condecls = text "type"
| otherwise = empty
pp_ct = case mb_ct of
Nothing -> empty
Just ct -> ppr ct
pp_sig = case mb_sig of
Nothing -> empty
Just kind -> dcolon <+> ppr kind
pp_data_defn :: (OutputableBndrId p)
=> (Maybe (LHsContext (GhcPass p)) -> SDoc) -- Printing the header
-> HsDataDefn (GhcPass p)
-> SDoc
pp_data_defn pp_hdr defn@HsDataDefn
{ dd_cons = condecls
, dd_derivs = derivings }
| null condecls
= ppDataDefnHeader pp_hdr defn <+> pp_derivings derivings
| otherwise
= hang (ppDataDefnHeader pp_hdr defn) 2 (pp_condecls (toList condecls) $$ pp_derivings derivings)
where
pp_derivings ds = vcat (map ppr ds)
instance OutputableBndrId p
=> Outputable (HsDataDefn (GhcPass p)) where
ppr d = pp_data_defn (\_ -> text "Naked HsDataDefn") d
instance OutputableBndrId p
=> Outputable (StandaloneKindSig (GhcPass p)) where
ppr (StandaloneKindSig _ v ki)
= text "type" <+> pprPrefixOcc (unLoc v) <+> text "::" <+> ppr ki
pp_condecls :: forall p. OutputableBndrId p => [LConDecl (GhcPass p)] -> SDoc
pp_condecls cs
In GADT syntax
= hang (text "where") 2 (vcat (map ppr cs))
| otherwise -- In H98 syntax
= equals <+> sep (punctuate (text " |") (map ppr cs))
instance (OutputableBndrId p) => Outputable (ConDecl (GhcPass p)) where
ppr = pprConDecl
pprConDecl :: forall p. OutputableBndrId p => ConDecl (GhcPass p) -> SDoc
pprConDecl (ConDeclH98 { con_name = L _ con
, con_ex_tvs = ex_tvs
, con_mb_cxt = mcxt
, con_args = args
, con_doc = doc })
= pprMaybeWithDoc doc $
sep [ pprHsForAll (mkHsForAllInvisTele noAnn ex_tvs) mcxt
, ppr_details args ]
where
In ppr_details : let 's not print the multiplicities ( they are always 1 , by
-- definition) as they do not appear in an actual declaration.
ppr_details (InfixCon t1 t2) = hsep [ppr (hsScaledThing t1),
pprInfixOcc con,
ppr (hsScaledThing t2)]
ppr_details (PrefixCon _ tys) = hsep (pprPrefixOcc con
: map (pprHsType . unLoc . hsScaledThing) tys)
ppr_details (RecCon fields) = pprPrefixOcc con
<+> pprConDeclFields (unLoc fields)
pprConDecl (ConDeclGADT { con_names = cons, con_bndrs = L _ outer_bndrs
, con_mb_cxt = mcxt, con_g_args = args
, con_res_ty = res_ty, con_doc = doc })
= pprMaybeWithDoc doc $ ppr_con_names (toList cons) <+> dcolon
<+> (sep [pprHsOuterSigTyVarBndrs outer_bndrs <+> pprLHsContext mcxt,
sep (ppr_args args ++ [ppr res_ty]) ])
where
ppr_args (PrefixConGADT args) = map (\(HsScaled arr t) -> ppr t <+> ppr_arr arr) args
ppr_args (RecConGADT fields _) = [pprConDeclFields (unLoc fields) <+> arrow]
-- Display linear arrows as unrestricted with -XNoLinearTypes
( cf . dataConDisplayType in Note [ Displaying linear fields ] in GHC.Core . DataCon )
ppr_arr (HsLinearArrow _) = sdocOption sdocLinearTypes $ \show_linear_types ->
if show_linear_types then lollipop else arrow
ppr_arr arr = pprHsArrow arr
ppr_con_names :: (OutputableBndr a) => [GenLocated l a] -> SDoc
ppr_con_names = pprWithCommas (pprPrefixOcc . unLoc)
{-
************************************************************************
* *
Instance declarations
* *
************************************************************************
-}
type instance XCFamEqn (GhcPass _) r = EpAnn [AddEpAnn]
type instance XXFamEqn (GhcPass _) r = DataConCantHappen
type instance Anno (FamEqn (GhcPass p) _) = SrcSpanAnnA
----------------- Class instances -------------
TODO : AZ : tidy up
type instance XCClsInstDecl GhcRn = NoExtField
type instance XCClsInstDecl GhcTc = NoExtField
type instance XXClsInstDecl (GhcPass _) = DataConCantHappen
----------------- Instances of all kinds -------------
type instance XClsInstD (GhcPass _) = NoExtField
type instance XDataFamInstD (GhcPass _) = NoExtField
type instance XTyFamInstD GhcPs = NoExtField
type instance XTyFamInstD GhcRn = NoExtField
type instance XTyFamInstD GhcTc = NoExtField
type instance XXInstDecl (GhcPass _) = DataConCantHappen
instance OutputableBndrId p
=> Outputable (TyFamInstDecl (GhcPass p)) where
ppr = pprTyFamInstDecl TopLevel
pprTyFamInstDecl :: (OutputableBndrId p)
=> TopLevelFlag -> TyFamInstDecl (GhcPass p) -> SDoc
pprTyFamInstDecl top_lvl (TyFamInstDecl { tfid_eqn = eqn })
= text "type" <+> ppr_instance_keyword top_lvl <+> ppr_fam_inst_eqn eqn
ppr_instance_keyword :: TopLevelFlag -> SDoc
ppr_instance_keyword TopLevel = text "instance"
ppr_instance_keyword NotTopLevel = empty
pprTyFamDefltDecl :: (OutputableBndrId p)
=> TyFamDefltDecl (GhcPass p) -> SDoc
pprTyFamDefltDecl = pprTyFamInstDecl NotTopLevel
ppr_fam_inst_eqn :: (OutputableBndrId p)
=> TyFamInstEqn (GhcPass p) -> SDoc
ppr_fam_inst_eqn (FamEqn { feqn_tycon = L _ tycon
, feqn_bndrs = bndrs
, feqn_pats = pats
, feqn_fixity = fixity
, feqn_rhs = rhs })
= pprHsFamInstLHS tycon bndrs pats fixity Nothing <+> equals <+> ppr rhs
instance OutputableBndrId p
=> Outputable (DataFamInstDecl (GhcPass p)) where
ppr = pprDataFamInstDecl TopLevel
pprDataFamInstDecl :: (OutputableBndrId p)
=> TopLevelFlag -> DataFamInstDecl (GhcPass p) -> SDoc
pprDataFamInstDecl top_lvl (DataFamInstDecl { dfid_eqn =
(FamEqn { feqn_tycon = L _ tycon
, feqn_bndrs = bndrs
, feqn_pats = pats
, feqn_fixity = fixity
, feqn_rhs = defn })})
= pp_data_defn pp_hdr defn
where
pp_hdr mctxt = ppr_instance_keyword top_lvl
<+> pprHsFamInstLHS tycon bndrs pats fixity mctxt
pp_data_defn pretty - prints the kind sig . See # 14817 .
pprDataFamInstFlavour :: DataFamInstDecl (GhcPass p) -> SDoc
pprDataFamInstFlavour DataFamInstDecl
{ dfid_eqn = FamEqn { feqn_rhs = HsDataDefn { dd_cons = cons }}}
= ppr (dataDefnConsNewOrData cons)
pprHsFamInstLHS :: (OutputableBndrId p)
=> IdP (GhcPass p)
-> HsOuterFamEqnTyVarBndrs (GhcPass p)
-> HsTyPats (GhcPass p)
-> LexicalFixity
-> Maybe (LHsContext (GhcPass p))
-> SDoc
pprHsFamInstLHS thing bndrs typats fixity mb_ctxt
= hsep [ pprHsOuterFamEqnTyVarBndrs bndrs
, pprLHsContext mb_ctxt
, pprHsArgsApp thing fixity typats ]
instance OutputableBndrId p
=> Outputable (ClsInstDecl (GhcPass p)) where
ppr (ClsInstDecl { cid_poly_ty = inst_ty, cid_binds = binds
, cid_sigs = sigs, cid_tyfam_insts = ats
, cid_overlap_mode = mbOverlap
, cid_datafam_insts = adts })
| null sigs, null ats, null adts, isEmptyBag binds -- No "where" part
= top_matter
| otherwise -- Laid out
= vcat [ top_matter <+> text "where"
, nest 2 $ pprDeclList $
map (pprTyFamInstDecl NotTopLevel . unLoc) ats ++
map (pprDataFamInstDecl NotTopLevel . unLoc) adts ++
pprLHsBindsForUser binds sigs ]
where
top_matter = text "instance" <+> ppOverlapPragma mbOverlap
<+> ppr inst_ty
ppDerivStrategy :: OutputableBndrId p
=> Maybe (LDerivStrategy (GhcPass p)) -> SDoc
ppDerivStrategy mb =
case mb of
Nothing -> empty
Just (L _ ds) -> ppr ds
ppOverlapPragma :: Maybe (LocatedP OverlapMode) -> SDoc
ppOverlapPragma mb =
case mb of
Nothing -> empty
Just (L _ (NoOverlap s)) -> maybe_stext s "{-# NO_OVERLAP #-}"
Just (L _ (Overlappable s)) -> maybe_stext s "{-# OVERLAPPABLE #-}"
Just (L _ (Overlapping s)) -> maybe_stext s "{-# OVERLAPPING #-}"
Just (L _ (Overlaps s)) -> maybe_stext s "{-# OVERLAPS #-}"
Just (L _ (Incoherent s)) -> maybe_stext s "{-# INCOHERENT #-}"
where
maybe_stext NoSourceText alt = text alt
maybe_stext (SourceText src) _ = text src <+> text "#-}"
instance (OutputableBndrId p) => Outputable (InstDecl (GhcPass p)) where
ppr (ClsInstD { cid_inst = decl }) = ppr decl
ppr (TyFamInstD { tfid_inst = decl }) = ppr decl
ppr (DataFamInstD { dfid_inst = decl }) = ppr decl
-- Extract the declarations of associated data types from an instance
instDeclDataFamInsts :: [LInstDecl (GhcPass p)] -> [DataFamInstDecl (GhcPass p)]
instDeclDataFamInsts inst_decls
= concatMap do_one inst_decls
where
do_one :: LInstDecl (GhcPass p) -> [DataFamInstDecl (GhcPass p)]
do_one (L _ (ClsInstD { cid_inst = ClsInstDecl { cid_datafam_insts = fam_insts } }))
= map unLoc fam_insts
do_one (L _ (DataFamInstD { dfid_inst = fam_inst })) = [fam_inst]
do_one (L _ (TyFamInstD {})) = []
-- | Convert a 'NewOrData' to a 'TyConFlavour'
newOrDataToFlavour :: NewOrData -> TyConFlavour
newOrDataToFlavour NewType = NewtypeFlavour
newOrDataToFlavour DataType = DataTypeFlavour
instance Outputable NewOrData where
ppr NewType = text "newtype"
ppr DataType = text "data"
At the moment we only call this with @f = ' [ ] ' @ and = ' DataDefnCons'@.
anyLConIsGadt :: Foldable f => f (GenLocated l (ConDecl pass)) -> Bool
anyLConIsGadt xs = case toList xs of
L _ ConDeclGADT {} : _ -> True
_ -> False
# SPECIALIZE anyLConIsGadt : : [ GenLocated l ( ConDecl pass ) ] - > Bool #
# SPECIALIZE anyLConIsGadt : : DataDefnCons ( GenLocated l ( ConDecl pass ) ) - > Bool #
{-
************************************************************************
* *
\subsection[DerivDecl]{A stand-alone instance deriving declaration}
* *
************************************************************************
-}
type instance XCDerivDecl (GhcPass _) = EpAnn [AddEpAnn]
type instance XXDerivDecl (GhcPass _) = DataConCantHappen
type instance Anno OverlapMode = SrcSpanAnnP
instance OutputableBndrId p
=> Outputable (DerivDecl (GhcPass p)) where
ppr (DerivDecl { deriv_type = ty
, deriv_strategy = ds
, deriv_overlap_mode = o })
= hsep [ text "deriving"
, ppDerivStrategy ds
, text "instance"
, ppOverlapPragma o
, ppr ty ]
{-
************************************************************************
* *
Deriving strategies
* *
************************************************************************
-}
type instance XStockStrategy GhcPs = EpAnn [AddEpAnn]
type instance XStockStrategy GhcRn = NoExtField
type instance XStockStrategy GhcTc = NoExtField
type instance XAnyClassStrategy GhcPs = EpAnn [AddEpAnn]
type instance XAnyClassStrategy GhcRn = NoExtField
type instance XAnyClassStrategy GhcTc = NoExtField
type instance XNewtypeStrategy GhcPs = EpAnn [AddEpAnn]
type instance XNewtypeStrategy GhcRn = NoExtField
type instance XNewtypeStrategy GhcTc = NoExtField
type instance XViaStrategy GhcPs = XViaStrategyPs
type instance XViaStrategy GhcRn = LHsSigType GhcRn
type instance XViaStrategy GhcTc = Type
data XViaStrategyPs = XViaStrategyPs (EpAnn [AddEpAnn]) (LHsSigType GhcPs)
instance OutputableBndrId p
=> Outputable (DerivStrategy (GhcPass p)) where
ppr (StockStrategy _) = text "stock"
ppr (AnyclassStrategy _) = text "anyclass"
ppr (NewtypeStrategy _) = text "newtype"
ppr (ViaStrategy ty) = text "via" <+> case ghcPass @p of
GhcPs -> ppr ty
GhcRn -> ppr ty
GhcTc -> ppr ty
instance Outputable XViaStrategyPs where
ppr (XViaStrategyPs _ t) = ppr t
-- | Eliminate a 'DerivStrategy'.
foldDerivStrategy :: (p ~ GhcPass pass)
=> r -> (XViaStrategy p -> r) -> DerivStrategy p -> r
foldDerivStrategy other _ (StockStrategy _) = other
foldDerivStrategy other _ (AnyclassStrategy _) = other
foldDerivStrategy other _ (NewtypeStrategy _) = other
foldDerivStrategy _ via (ViaStrategy t) = via t
| Map over the @via@ type if dealing with ' ViaStrategy ' . Otherwise ,
-- return the 'DerivStrategy' unchanged.
mapDerivStrategy :: (p ~ GhcPass pass)
=> (XViaStrategy p -> XViaStrategy p)
-> DerivStrategy p -> DerivStrategy p
mapDerivStrategy f ds = foldDerivStrategy ds (ViaStrategy . f) ds
{-
************************************************************************
* *
\subsection[DefaultDecl]{A @default@ declaration}
* *
************************************************************************
-}
type instance XCDefaultDecl GhcPs = EpAnn [AddEpAnn]
type instance XCDefaultDecl GhcRn = NoExtField
type instance XCDefaultDecl GhcTc = NoExtField
type instance XXDefaultDecl (GhcPass _) = DataConCantHappen
instance OutputableBndrId p
=> Outputable (DefaultDecl (GhcPass p)) where
ppr (DefaultDecl _ tys)
= text "default" <+> parens (interpp'SP tys)
{-
************************************************************************
* *
\subsection{Foreign function interface declaration}
* *
************************************************************************
-}
type instance XForeignImport GhcPs = EpAnn [AddEpAnn]
type instance XForeignImport GhcRn = NoExtField
type instance XForeignImport GhcTc = Coercion
type instance XForeignExport GhcPs = EpAnn [AddEpAnn]
type instance XForeignExport GhcRn = NoExtField
type instance XForeignExport GhcTc = Coercion
type instance XXForeignDecl (GhcPass _) = DataConCantHappen
type instance XCImport (GhcPass _) = Located SourceText -- original source text for the C entity
type instance XXForeignImport (GhcPass _) = DataConCantHappen
type instance XCExport (GhcPass _) = Located SourceText -- original source text for the C entity
type instance XXForeignExport (GhcPass _) = DataConCantHappen
-- pretty printing of foreign declarations
instance OutputableBndrId p
=> Outputable (ForeignDecl (GhcPass p)) where
ppr (ForeignImport { fd_name = n, fd_sig_ty = ty, fd_fi = fimport })
= hang (text "foreign import" <+> ppr fimport <+> ppr n)
2 (dcolon <+> ppr ty)
ppr (ForeignExport { fd_name = n, fd_sig_ty = ty, fd_fe = fexport }) =
hang (text "foreign export" <+> ppr fexport <+> ppr n)
2 (dcolon <+> ppr ty)
instance OutputableBndrId p
=> Outputable (ForeignImport (GhcPass p)) where
ppr (CImport (L _ srcText) cconv safety mHeader spec) =
ppr cconv <+> ppr safety
<+> pprWithSourceText srcText (pprCEntity spec "")
where
pp_hdr = case mHeader of
Nothing -> empty
Just (Header _ header) -> ftext header
pprCEntity (CLabel lbl) _ =
doubleQuotes $ text "static" <+> pp_hdr <+> char '&' <> ppr lbl
pprCEntity (CFunction (StaticTarget st _lbl _ isFun)) src =
if dqNeeded then doubleQuotes ce else empty
where
dqNeeded = (take 6 src == "static")
|| isJust mHeader
|| not isFun
|| st /= NoSourceText
ce =
We may need to drop leading spaces first
(if take 6 src == "static" then text "static" else empty)
<+> pp_hdr
<+> (if isFun then empty else text "value")
<+> (pprWithSourceText st empty)
pprCEntity (CFunction DynamicTarget) _ =
doubleQuotes $ text "dynamic"
pprCEntity CWrapper _ = doubleQuotes $ text "wrapper"
instance OutputableBndrId p
=> Outputable (ForeignExport (GhcPass p)) where
ppr (CExport _ (L _ (CExportStatic _ lbl cconv))) =
ppr cconv <+> char '"' <> ppr lbl <> char '"'
{-
************************************************************************
* *
\subsection{Rewrite rules}
* *
************************************************************************
-}
type instance XCRuleDecls GhcPs = (EpAnn [AddEpAnn], SourceText)
type instance XCRuleDecls GhcRn = SourceText
type instance XCRuleDecls GhcTc = SourceText
type instance XXRuleDecls (GhcPass _) = DataConCantHappen
type instance XHsRule GhcPs = (EpAnn HsRuleAnn, SourceText)
type instance XHsRule GhcRn = (HsRuleRn, SourceText)
type instance XHsRule GhcTc = (HsRuleRn, SourceText)
Free - vars from the LHS and RHS
deriving Data
type instance XXRuleDecl (GhcPass _) = DataConCantHappen
data HsRuleAnn
= HsRuleAnn
{ ra_tyanns :: Maybe (AddEpAnn, AddEpAnn)
-- ^ The locations of 'forall' and '.' for forall'd type vars
-- Using AddEpAnn to capture possible unicode variants
, ra_tmanns :: Maybe (AddEpAnn, AddEpAnn)
-- ^ The locations of 'forall' and '.' for forall'd term vars
-- Using AddEpAnn to capture possible unicode variants
, ra_rest :: [AddEpAnn]
} deriving (Data, Eq)
flattenRuleDecls :: [LRuleDecls (GhcPass p)] -> [LRuleDecl (GhcPass p)]
flattenRuleDecls decls = concatMap (rds_rules . unLoc) decls
type instance XCRuleBndr (GhcPass _) = EpAnn [AddEpAnn]
type instance XRuleBndrSig (GhcPass _) = EpAnn [AddEpAnn]
type instance XXRuleBndr (GhcPass _) = DataConCantHappen
instance (OutputableBndrId p) => Outputable (RuleDecls (GhcPass p)) where
ppr (HsRules { rds_ext = ext
, rds_rules = rules })
= pprWithSourceText st (text "{-# RULES")
<+> vcat (punctuate semi (map ppr rules)) <+> text "#-}"
where st = case ghcPass @p of
GhcPs | (_, st) <- ext -> st
GhcRn -> ext
GhcTc -> ext
instance (OutputableBndrId p) => Outputable (RuleDecl (GhcPass p)) where
ppr (HsRule { rd_ext = ext
, rd_name = name
, rd_act = act
, rd_tyvs = tys
, rd_tmvs = tms
, rd_lhs = lhs
, rd_rhs = rhs })
= sep [pprFullRuleName st name <+> ppr act,
nest 4 (pp_forall_ty tys <+> pp_forall_tm tys
<+> pprExpr (unLoc lhs)),
nest 6 (equals <+> pprExpr (unLoc rhs)) ]
where
pp_forall_ty Nothing = empty
pp_forall_ty (Just qtvs) = forAllLit <+> fsep (map ppr qtvs) <> dot
pp_forall_tm Nothing | null tms = empty
pp_forall_tm _ = forAllLit <+> fsep (map ppr tms) <> dot
st = case ghcPass @p of
GhcPs | (_, st) <- ext -> st
GhcRn | (_, st) <- ext -> st
GhcTc | (_, st) <- ext -> st
instance (OutputableBndrId p) => Outputable (RuleBndr (GhcPass p)) where
ppr (RuleBndr _ name) = ppr name
ppr (RuleBndrSig _ name ty) = parens (ppr name <> dcolon <> ppr ty)
pprFullRuleName :: SourceText -> GenLocated a (RuleName) -> SDoc
pprFullRuleName st (L _ n) = pprWithSourceText st (doubleQuotes $ ftext n)
{-
************************************************************************
* *
\subsection[DeprecDecl]{Deprecations}
* *
************************************************************************
-}
type instance XWarnings GhcPs = (EpAnn [AddEpAnn], SourceText)
type instance XWarnings GhcRn = SourceText
type instance XWarnings GhcTc = SourceText
type instance XXWarnDecls (GhcPass _) = DataConCantHappen
type instance XWarning (GhcPass _) = EpAnn [AddEpAnn]
type instance XXWarnDecl (GhcPass _) = DataConCantHappen
instance OutputableBndrId p
=> Outputable (WarnDecls (GhcPass p)) where
ppr (Warnings ext decls)
= text src <+> vcat (punctuate comma (map ppr decls)) <+> text "#-}"
where src = case ghcPass @p of
GhcPs | (_, SourceText src) <- ext -> src
GhcRn | SourceText src <- ext -> src
GhcTc | SourceText src <- ext -> src
_ -> panic "WarnDecls"
instance OutputableBndrId p
=> Outputable (WarnDecl (GhcPass p)) where
ppr (Warning _ thing txt)
= hsep ( punctuate comma (map ppr thing))
<+> ppr txt
{-
************************************************************************
* *
\subsection[AnnDecl]{Annotations}
* *
************************************************************************
-}
type instance XHsAnnotation (GhcPass _) = (EpAnn AnnPragma, SourceText)
type instance XXAnnDecl (GhcPass _) = DataConCantHappen
instance (OutputableBndrId p) => Outputable (AnnDecl (GhcPass p)) where
ppr (HsAnnotation _ provenance expr)
= hsep [text "{-#", pprAnnProvenance provenance, pprExpr (unLoc expr), text "#-}"]
pprAnnProvenance :: OutputableBndrId p => AnnProvenance (GhcPass p) -> SDoc
pprAnnProvenance ModuleAnnProvenance = text "ANN module"
pprAnnProvenance (ValueAnnProvenance (L _ name))
= text "ANN" <+> ppr name
pprAnnProvenance (TypeAnnProvenance (L _ name))
= text "ANN type" <+> ppr name
{-
************************************************************************
* *
\subsection[RoleAnnot]{Role annotations}
* *
************************************************************************
-}
type instance XCRoleAnnotDecl GhcPs = EpAnn [AddEpAnn]
type instance XCRoleAnnotDecl GhcRn = NoExtField
type instance XCRoleAnnotDecl GhcTc = NoExtField
type instance XXRoleAnnotDecl (GhcPass _) = DataConCantHappen
type instance Anno (Maybe Role) = SrcAnn NoEpAnns
instance OutputableBndr (IdP (GhcPass p))
=> Outputable (RoleAnnotDecl (GhcPass p)) where
ppr (RoleAnnotDecl _ ltycon roles)
= text "type role" <+> pprPrefixOcc (unLoc ltycon) <+>
hsep (map (pp_role . unLoc) roles)
where
pp_role Nothing = underscore
pp_role (Just r) = ppr r
roleAnnotDeclName :: RoleAnnotDecl (GhcPass p) -> IdP (GhcPass p)
roleAnnotDeclName (RoleAnnotDecl _ (L _ name) _) = name
{-
************************************************************************
* *
\subsection{Anno instances}
* *
************************************************************************
-}
type instance Anno (HsDecl (GhcPass _)) = SrcSpanAnnA
type instance Anno (SpliceDecl (GhcPass p)) = SrcSpanAnnA
type instance Anno (TyClDecl (GhcPass p)) = SrcSpanAnnA
type instance Anno (FunDep (GhcPass p)) = SrcSpanAnnA
type instance Anno (FamilyResultSig (GhcPass p)) = SrcAnn NoEpAnns
type instance Anno (FamilyDecl (GhcPass p)) = SrcSpanAnnA
type instance Anno (InjectivityAnn (GhcPass p)) = SrcAnn NoEpAnns
type instance Anno CType = SrcSpanAnnP
type instance Anno (HsDerivingClause (GhcPass p)) = SrcAnn NoEpAnns
type instance Anno (DerivClauseTys (GhcPass _)) = SrcSpanAnnC
type instance Anno (StandaloneKindSig (GhcPass p)) = SrcSpanAnnA
type instance Anno (ConDecl (GhcPass p)) = SrcSpanAnnA
type instance Anno Bool = SrcAnn NoEpAnns
type instance Anno [LocatedA (ConDeclField (GhcPass _))] = SrcSpanAnnL
type instance Anno (FamEqn p (LocatedA (HsType p))) = SrcSpanAnnA
type instance Anno (TyFamInstDecl (GhcPass p)) = SrcSpanAnnA
type instance Anno (DataFamInstDecl (GhcPass p)) = SrcSpanAnnA
type instance Anno (FamEqn (GhcPass p) _) = SrcSpanAnnA
type instance Anno (ClsInstDecl (GhcPass p)) = SrcSpanAnnA
type instance Anno (InstDecl (GhcPass p)) = SrcSpanAnnA
type instance Anno (DocDecl (GhcPass p)) = SrcSpanAnnA
type instance Anno (DerivDecl (GhcPass p)) = SrcSpanAnnA
type instance Anno OverlapMode = SrcSpanAnnP
type instance Anno (DerivStrategy (GhcPass p)) = SrcAnn NoEpAnns
type instance Anno (DefaultDecl (GhcPass p)) = SrcSpanAnnA
type instance Anno (ForeignDecl (GhcPass p)) = SrcSpanAnnA
type instance Anno (RuleDecls (GhcPass p)) = SrcSpanAnnA
type instance Anno (RuleDecl (GhcPass p)) = SrcSpanAnnA
type instance Anno (SourceText, RuleName) = SrcAnn NoEpAnns
type instance Anno (RuleBndr (GhcPass p)) = SrcAnn NoEpAnns
type instance Anno (WarnDecls (GhcPass p)) = SrcSpanAnnA
type instance Anno (WarnDecl (GhcPass p)) = SrcSpanAnnA
type instance Anno (AnnDecl (GhcPass p)) = SrcSpanAnnA
type instance Anno (RoleAnnotDecl (GhcPass p)) = SrcSpanAnnA
type instance Anno (Maybe Role) = SrcAnn NoEpAnns
type instance Anno CCallConv = SrcSpan
type instance Anno Safety = SrcSpan
type instance Anno CExportSpec = SrcSpan
| null | https://raw.githubusercontent.com/ghc/ghc/178c1fd830c78377ef5d338406a41e1d8eb5f0da/compiler/GHC/Hs/Decls.hs | haskell | # LANGUAGE ConstraintKinds #
# LANGUAGE DeriveDataTypeable #
| Abstract syntax of global declarations.
Definitions for: @SynDecl@ and @ConDecl@, @ClassDecl@,
@InstDecl@, @DefaultDecl@ and @ForeignDecl@.
** Class or type declarations
** Instance declarations
** Standalone deriving declarations
** Deriving strategies
** @default@ declarations
** Template haskell declaration splice
** Foreign function interface declarations
** Data-constructor declarations
** Document comments
** Annotations
** Role annotations
** Injective type families
* Grouping
friends:
# SOURCE #
others:
************************************************************************
* *
\subsection[HsDecl]{Declarations}
* *
************************************************************************
type family declarations, type family instances, and documentation comments.
Panics when given a declaration that cannot be put into any of the output
groups.
The primary use of this function is to implement
Okay, I need to reconstruct the document comments, but for now:
| The fixity signatures for each top-level declaration and class method
in an 'HsGroup'.
See Note [Top-level fixity signatures in an HsGroup]
************************************************************************
* *
Type and class declarations
* *
************************************************************************
^ does this have a CUSK?
See Note [CUSKs: complete user-supplied kind signatures]
--------- Pretty printing FamilyDecls -----------
Dealing with names
class, synonym decls, data, newtype, family decls
excluding...
...family...
...instances
needs to be polymorphic in the pass
| Does this declaration have a complete, user-supplied kind signature?
See Note [CUSKs: complete user-supplied kind signatures]
Pretty-printing TyClDecl
~~~~~~~~~~~~~~~~~~~~~~~~
No "where" part
Laid out
*********************************************************************
* *
TyClGroup
Strongly connected components of
type, class, instance, and role declarations
* *
*********************************************************************
*********************************************************************
* *
Data and type family declarations
* *
*********************************************************************
--------- Functions over FamilyDecls -----------
| Maybe return name of the result type variable
--------- Pretty printing FamilyDecls -----------
*********************************************************************
* *
Data types and data constructors
* *
*********************************************************************
so we must special-case it.
| Return @'Just' fields@ if a data constructor declaration uses record
Otherwise, return 'Nothing'.
Printing the header
Printing the header
In H98 syntax
definition) as they do not appear in an actual declaration.
Display linear arrows as unrestricted with -XNoLinearTypes
************************************************************************
* *
Instance declarations
* *
************************************************************************
--------------- Class instances -------------
--------------- Instances of all kinds -------------
No "where" part
Laid out
Extract the declarations of associated data types from an instance
| Convert a 'NewOrData' to a 'TyConFlavour'
************************************************************************
* *
\subsection[DerivDecl]{A stand-alone instance deriving declaration}
* *
************************************************************************
************************************************************************
* *
Deriving strategies
* *
************************************************************************
| Eliminate a 'DerivStrategy'.
return the 'DerivStrategy' unchanged.
************************************************************************
* *
\subsection[DefaultDecl]{A @default@ declaration}
* *
************************************************************************
************************************************************************
* *
\subsection{Foreign function interface declaration}
* *
************************************************************************
original source text for the C entity
original source text for the C entity
pretty printing of foreign declarations
************************************************************************
* *
\subsection{Rewrite rules}
* *
************************************************************************
^ The locations of 'forall' and '.' for forall'd type vars
Using AddEpAnn to capture possible unicode variants
^ The locations of 'forall' and '.' for forall'd term vars
Using AddEpAnn to capture possible unicode variants
************************************************************************
* *
\subsection[DeprecDecl]{Deprecations}
* *
************************************************************************
************************************************************************
* *
\subsection[AnnDecl]{Annotations}
* *
************************************************************************
************************************************************************
* *
\subsection[RoleAnnot]{Role annotations}
* *
************************************************************************
************************************************************************
* *
\subsection{Anno instances}
* *
************************************************************************
|
# LANGUAGE FlexibleContexts #
# LANGUAGE FlexibleInstances #
# LANGUAGE ScopedTypeVariables #
# LANGUAGE TypeApplications #
# LANGUAGE TypeFamilies #
# LANGUAGE UndecidableInstances #
in module Language . Haskell . Syntax . Extension
# OPTIONS_GHC -Wno - orphans #
( c ) The University of Glasgow 2006
( c ) The GRASP / AQUA Project , Glasgow University , 1992 - 1998
(c) The University of Glasgow 2006
(c) The GRASP/AQUA Project, Glasgow University, 1992-1998
-}
module GHC.Hs.Decls (
* Toplevel declarations
HsDecl(..), LHsDecl, HsDataDefn(..), HsDeriving, LHsFunDep,
HsDerivingClause(..), LHsDerivingClause, DerivClauseTys(..), LDerivClauseTys,
NewOrData, newOrDataToFlavour, anyLConIsGadt,
StandaloneKindSig(..), LStandaloneKindSig, standaloneKindSigName,
TyClDecl(..), LTyClDecl, DataDeclRn(..),
TyClGroup(..),
tyClGroupTyClDecls, tyClGroupInstDecls, tyClGroupRoleDecls,
tyClGroupKindSigs,
isClassDecl, isDataDecl, isSynDecl, tcdName,
isFamilyDecl, isTypeFamilyDecl, isDataFamilyDecl,
isOpenTypeFamilyInfo, isClosedTypeFamilyInfo,
tyFamInstDeclName, tyFamInstDeclLName,
countTyClDecls, pprTyClDeclFlavour,
tyClDeclLName, tyClDeclTyVars,
hsDeclHasCusk, famResultKindSignature,
FamilyDecl(..), LFamilyDecl,
FunDep(..), ppDataDefnHeader,
pp_vanilla_decl_head,
InstDecl(..), LInstDecl, FamilyInfo(..),
TyFamInstDecl(..), LTyFamInstDecl, instDeclDataFamInsts,
TyFamDefltDecl, LTyFamDefltDecl,
DataFamInstDecl(..), LDataFamInstDecl,
pprDataFamInstFlavour, pprTyFamInstDecl, pprHsFamInstLHS,
FamEqn(..), TyFamInstEqn, LTyFamInstEqn, HsTyPats,
LClsInstDecl, ClsInstDecl(..),
DerivDecl(..), LDerivDecl,
DerivStrategy(..), LDerivStrategy,
derivStrategyName, foldDerivStrategy, mapDerivStrategy,
XViaStrategyPs(..),
* * declarations
LRuleDecls,RuleDecls(..),RuleDecl(..),LRuleDecl,HsRuleRn(..),
HsRuleAnn(..),
RuleBndr(..),LRuleBndr,
collectRuleBndrSigTys,
flattenRuleDecls, pprFullRuleName,
DefaultDecl(..), LDefaultDecl,
SpliceDecoration(..),
SpliceDecl(..), LSpliceDecl,
ForeignDecl(..), LForeignDecl, ForeignImport(..), ForeignExport(..),
CImportSpec(..),
ConDecl(..), LConDecl,
HsConDeclH98Details, HsConDeclGADTDetails(..), hsConDeclTheta,
getConNames, getRecConArgs_maybe,
DocDecl(..), LDocDecl, docDeclDoc,
* *
WarnDecl(..), LWarnDecl,
WarnDecls(..), LWarnDecls,
AnnDecl(..), LAnnDecl,
AnnProvenance(..), annProvenanceName_maybe,
RoleAnnotDecl(..), LRoleAnnotDecl, roleAnnotDeclName,
FamilyResultSig(..), LFamilyResultSig, InjectivityAnn(..), LInjectivityAnn,
resultVariableName, familyDeclLName, familyDeclName,
HsGroup(..), emptyRdrGroup, emptyRnGroup, appendGroups, hsGroupInstDecls,
hsGroupTopLevelFixitySigs,
partitionBindsAndSigs,
) where
import GHC.Prelude
import Language.Haskell.Syntax.Decls
Because imports Decls via HsBracket
import GHC.Hs.Binds
import GHC.Hs.Type
import GHC.Hs.Doc
import GHC.Types.Basic
import GHC.Core.Coercion
import Language.Haskell.Syntax.Extension
import GHC.Hs.Extension
import GHC.Parser.Annotation
import GHC.Types.Name
import GHC.Types.Name.Set
import GHC.Types.Fixity
import GHC.Utils.Misc (count)
import GHC.Utils.Outputable
import GHC.Utils.Panic
import GHC.Types.SrcLoc
import GHC.Types.SourceText
import GHC.Core.Type
import GHC.Core.TyCon (TyConFlavour(NewtypeFlavour,DataTypeFlavour))
import GHC.Types.ForeignCall
import GHC.Data.Bag
import GHC.Data.Maybe
import Data.Data (Data)
import Data.Foldable (toList)
type instance XTyClD (GhcPass _) = NoExtField
type instance XInstD (GhcPass _) = NoExtField
type instance XDerivD (GhcPass _) = NoExtField
type instance XValD (GhcPass _) = NoExtField
type instance XSigD (GhcPass _) = NoExtField
type instance XKindSigD (GhcPass _) = NoExtField
type instance XDefD (GhcPass _) = NoExtField
type instance XForD (GhcPass _) = NoExtField
type instance XWarningD (GhcPass _) = NoExtField
type instance XAnnD (GhcPass _) = NoExtField
type instance XRuleD (GhcPass _) = NoExtField
type instance XSpliceD (GhcPass _) = NoExtField
type instance XDocD (GhcPass _) = NoExtField
type instance XRoleAnnotD (GhcPass _) = NoExtField
type instance XXHsDecl (GhcPass _) = DataConCantHappen
| Partition a list of into function / pattern bindings , signatures ,
' GHC.Parser . PostProcess.cvBindsAndSigs ' .
partitionBindsAndSigs
:: [LHsDecl GhcPs]
-> (LHsBinds GhcPs, [LSig GhcPs], [LFamilyDecl GhcPs],
[LTyFamInstDecl GhcPs], [LDataFamInstDecl GhcPs], [LDocDecl GhcPs])
partitionBindsAndSigs = go
where
go [] = (emptyBag, [], [], [], [], [])
go ((L l decl) : ds) =
let (bs, ss, ts, tfis, dfis, docs) = go ds in
case decl of
ValD _ b
-> (L l b `consBag` bs, ss, ts, tfis, dfis, docs)
SigD _ s
-> (bs, L l s : ss, ts, tfis, dfis, docs)
TyClD _ (FamDecl _ t)
-> (bs, ss, L l t : ts, tfis, dfis, docs)
InstD _ (TyFamInstD { tfid_inst = tfi })
-> (bs, ss, ts, L l tfi : tfis, dfis, docs)
InstD _ (DataFamInstD { dfid_inst = dfi })
-> (bs, ss, ts, tfis, L l dfi : dfis, docs)
DocD _ d
-> (bs, ss, ts, tfis, dfis, L l d : docs)
_ -> pprPanic "partitionBindsAndSigs" (ppr decl)
instance Outputable (DocDecl name) where
ppr _ = text "<document comment>"
type instance XCHsGroup (GhcPass _) = NoExtField
type instance XXHsGroup (GhcPass _) = DataConCantHappen
emptyGroup, emptyRdrGroup, emptyRnGroup :: HsGroup (GhcPass p)
emptyRdrGroup = emptyGroup { hs_valds = emptyValBindsIn }
emptyRnGroup = emptyGroup { hs_valds = emptyValBindsOut }
emptyGroup = HsGroup { hs_ext = noExtField,
hs_tyclds = [],
hs_derivds = [],
hs_fixds = [], hs_defds = [], hs_annds = [],
hs_fords = [], hs_warnds = [], hs_ruleds = [],
hs_valds = error "emptyGroup hs_valds: Can't happen",
hs_splcds = [],
hs_docs = [] }
hsGroupTopLevelFixitySigs :: HsGroup (GhcPass p) -> [LFixitySig (GhcPass p)]
hsGroupTopLevelFixitySigs (HsGroup{ hs_fixds = fixds, hs_tyclds = tyclds }) =
fixds ++ cls_fixds
where
cls_fixds = [ L loc sig
| L _ ClassDecl{tcdSigs = sigs} <- tyClGroupTyClDecls tyclds
, L loc (FixSig _ sig) <- sigs
]
appendGroups :: HsGroup (GhcPass p) -> HsGroup (GhcPass p)
-> HsGroup (GhcPass p)
appendGroups
HsGroup {
hs_valds = val_groups1,
hs_splcds = spliceds1,
hs_tyclds = tyclds1,
hs_derivds = derivds1,
hs_fixds = fixds1,
hs_defds = defds1,
hs_annds = annds1,
hs_fords = fords1,
hs_warnds = warnds1,
hs_ruleds = rulds1,
hs_docs = docs1 }
HsGroup {
hs_valds = val_groups2,
hs_splcds = spliceds2,
hs_tyclds = tyclds2,
hs_derivds = derivds2,
hs_fixds = fixds2,
hs_defds = defds2,
hs_annds = annds2,
hs_fords = fords2,
hs_warnds = warnds2,
hs_ruleds = rulds2,
hs_docs = docs2 }
=
HsGroup {
hs_ext = noExtField,
hs_valds = val_groups1 `plusHsValBinds` val_groups2,
hs_splcds = spliceds1 ++ spliceds2,
hs_tyclds = tyclds1 ++ tyclds2,
hs_derivds = derivds1 ++ derivds2,
hs_fixds = fixds1 ++ fixds2,
hs_annds = annds1 ++ annds2,
hs_defds = defds1 ++ defds2,
hs_fords = fords1 ++ fords2,
hs_warnds = warnds1 ++ warnds2,
hs_ruleds = rulds1 ++ rulds2,
hs_docs = docs1 ++ docs2 }
instance (OutputableBndrId p) => Outputable (HsDecl (GhcPass p)) where
ppr (TyClD _ dcl) = ppr dcl
ppr (ValD _ binds) = ppr binds
ppr (DefD _ def) = ppr def
ppr (InstD _ inst) = ppr inst
ppr (DerivD _ deriv) = ppr deriv
ppr (ForD _ fd) = ppr fd
ppr (SigD _ sd) = ppr sd
ppr (KindSigD _ ksd) = ppr ksd
ppr (RuleD _ rd) = ppr rd
ppr (WarningD _ wd) = ppr wd
ppr (AnnD _ ad) = ppr ad
ppr (SpliceD _ dd) = ppr dd
ppr (DocD _ doc) = ppr doc
ppr (RoleAnnotD _ ra) = ppr ra
instance (OutputableBndrId p) => Outputable (HsGroup (GhcPass p)) where
ppr (HsGroup { hs_valds = val_decls,
hs_tyclds = tycl_decls,
hs_derivds = deriv_decls,
hs_fixds = fix_decls,
hs_warnds = deprec_decls,
hs_annds = ann_decls,
hs_fords = foreign_decls,
hs_defds = default_decls,
hs_ruleds = rule_decls })
= vcat_mb empty
[ppr_ds fix_decls, ppr_ds default_decls,
ppr_ds deprec_decls, ppr_ds ann_decls,
ppr_ds rule_decls,
if isEmptyValBinds val_decls
then Nothing
else Just (ppr val_decls),
ppr_ds (tyClGroupRoleDecls tycl_decls),
ppr_ds (tyClGroupKindSigs tycl_decls),
ppr_ds (tyClGroupTyClDecls tycl_decls),
ppr_ds (tyClGroupInstDecls tycl_decls),
ppr_ds deriv_decls,
ppr_ds foreign_decls]
where
ppr_ds :: Outputable a => [a] -> Maybe SDoc
ppr_ds [] = Nothing
ppr_ds ds = Just (vcat (map ppr ds))
vcat_mb :: SDoc -> [Maybe SDoc] -> SDoc
vertically with white - space between non - blanks
vcat_mb _ [] = empty
vcat_mb gap (Nothing : ds) = vcat_mb gap ds
vcat_mb gap (Just d : ds) = gap $$ d $$ vcat_mb blankLine ds
type instance XSpliceDecl (GhcPass _) = NoExtField
type instance XXSpliceDecl (GhcPass _) = DataConCantHappen
instance OutputableBndrId p
=> Outputable (SpliceDecl (GhcPass p)) where
ppr (SpliceDecl _ (L _ e) DollarSplice) = pprUntypedSplice True Nothing e
ppr (SpliceDecl _ (L _ e) BareSplice) = pprUntypedSplice False Nothing e
instance Outputable SpliceDecoration where
ppr x = text $ show x
type instance XFamDecl (GhcPass _) = NoExtField
type instance XSynDecl GhcPs = EpAnn [AddEpAnn]
FVs
FVs
type instance XDataDecl GhcPs = EpAnn [AddEpAnn]
type instance XDataDecl GhcRn = DataDeclRn
type instance XDataDecl GhcTc = DataDeclRn
data DataDeclRn = DataDeclRn
, tcdFVs :: NameSet }
deriving Data
type instance XClassDecl GhcPs = (EpAnn [AddEpAnn], AnnSortKey)
TODO : AZ : tidy up AnnSortKey above
FVs
FVs
type instance XXTyClDecl (GhcPass _) = DataConCantHappen
type instance XCTyFamInstDecl (GhcPass _) = EpAnn [AddEpAnn]
type instance XXTyFamInstDecl (GhcPass _) = DataConCantHappen
pprFlavour :: FamilyInfo pass -> SDoc
pprFlavour DataFamily = text "data"
pprFlavour OpenTypeFamily = text "type"
pprFlavour (ClosedTypeFamily {}) = text "type"
instance Outputable (FamilyInfo pass) where
ppr info = pprFlavour info <+> text "family"
tyFamInstDeclName :: Anno (IdGhcP p) ~ SrcSpanAnnN
=> TyFamInstDecl (GhcPass p) -> IdP (GhcPass p)
tyFamInstDeclName = unLoc . tyFamInstDeclLName
tyFamInstDeclLName :: Anno (IdGhcP p) ~ SrcSpanAnnN
=> TyFamInstDecl (GhcPass p) -> LocatedN (IdP (GhcPass p))
tyFamInstDeclLName (TyFamInstDecl { tfid_eqn = FamEqn { feqn_tycon = ln }})
= ln
tyClDeclLName :: Anno (IdGhcP p) ~ SrcSpanAnnN
=> TyClDecl (GhcPass p) -> LocatedN (IdP (GhcPass p))
tyClDeclLName (FamDecl { tcdFam = fd }) = familyDeclLName fd
tyClDeclLName (SynDecl { tcdLName = ln }) = ln
tyClDeclLName (DataDecl { tcdLName = ln }) = ln
tyClDeclLName (ClassDecl { tcdLName = ln }) = ln
countTyClDecls :: [TyClDecl pass] -> (Int, Int, Int, Int, Int)
countTyClDecls decls
= (count isClassDecl decls,
count isFamilyDecl decls)
where
isDataTy DataDecl{ tcdDataDefn = HsDataDefn { dd_cons = DataTypeCons _ _ } } = True
isDataTy _ = False
isNewTy DataDecl{ tcdDataDefn = HsDataDefn { dd_cons = NewTypeCon _ } } = True
isNewTy _ = False
FIXME : tcdName is commonly used by both GHC and third - party tools , so it
tcdName :: Anno (IdGhcP p) ~ SrcSpanAnnN
=> TyClDecl (GhcPass p) -> IdP (GhcPass p)
tcdName = unLoc . tyClDeclLName
hsDeclHasCusk :: TyClDecl GhcRn -> Bool
hsDeclHasCusk (FamDecl { tcdFam =
FamilyDecl { fdInfo = fam_info
, fdTyVars = tyvars
, fdResultSig = L _ resultSig } }) =
case fam_info of
ClosedTypeFamily {} -> hsTvbAllKinded tyvars
&& isJust (famResultKindSignature resultSig)
Un - associated open type / data families have CUSKs
hsDeclHasCusk (SynDecl { tcdTyVars = tyvars, tcdRhs = rhs })
= hsTvbAllKinded tyvars && isJust (hsTyKindSig rhs)
hsDeclHasCusk (DataDecl { tcdDExt = DataDeclRn { tcdDataCusk = cusk }}) = cusk
hsDeclHasCusk (ClassDecl { tcdTyVars = tyvars }) = hsTvbAllKinded tyvars
instance (OutputableBndrId p) => Outputable (TyClDecl (GhcPass p)) where
ppr (FamDecl { tcdFam = decl }) = ppr decl
ppr (SynDecl { tcdLName = ltycon, tcdTyVars = tyvars, tcdFixity = fixity
, tcdRhs = rhs })
= hang (text "type" <+>
pp_vanilla_decl_head ltycon tyvars fixity Nothing <+> equals)
4 (ppr rhs)
ppr (DataDecl { tcdLName = ltycon, tcdTyVars = tyvars, tcdFixity = fixity
, tcdDataDefn = defn })
= pp_data_defn (pp_vanilla_decl_head ltycon tyvars fixity) defn
ppr (ClassDecl {tcdCtxt = context, tcdLName = lclas, tcdTyVars = tyvars,
tcdFixity = fixity,
tcdFDs = fds,
tcdSigs = sigs, tcdMeths = methods,
tcdATs = ats, tcdATDefs = at_defs})
= top_matter
= vcat [ top_matter <+> text "where"
, nest 2 $ pprDeclList (map (ppr . unLoc) ats ++
map (pprTyFamDefltDecl . unLoc) at_defs ++
pprLHsBindsForUser methods sigs) ]
where
top_matter = text "class"
<+> pp_vanilla_decl_head lclas tyvars fixity context
<+> pprFundeps (map unLoc fds)
instance OutputableBndrId p
=> Outputable (TyClGroup (GhcPass p)) where
ppr (TyClGroup { group_tyclds = tyclds
, group_roles = roles
, group_kisigs = kisigs
, group_instds = instds
}
)
= hang (text "TyClGroup") 2 $
ppr kisigs $$
ppr tyclds $$
ppr roles $$
ppr instds
pp_vanilla_decl_head :: (OutputableBndrId p)
=> XRec (GhcPass p) (IdP (GhcPass p))
-> LHsQTyVars (GhcPass p)
-> LexicalFixity
-> Maybe (LHsContext (GhcPass p))
-> SDoc
pp_vanilla_decl_head thing (HsQTvs { hsq_explicit = tyvars }) fixity context
= hsep [pprLHsContext context, pp_tyvars tyvars]
where
pp_tyvars (varl:varsr)
| fixity == Infix, varr:varsr'@(_:_) <- varsr
If varsr has at least 2 elements , parenthesize .
= hsep [char '(',ppr (unLoc varl), pprInfixOcc (unLoc thing)
, (ppr.unLoc) varr, char ')'
, hsep (map (ppr.unLoc) varsr')]
| fixity == Infix
= hsep [ppr (unLoc varl), pprInfixOcc (unLoc thing)
, hsep (map (ppr.unLoc) varsr)]
| otherwise = hsep [ pprPrefixOcc (unLoc thing)
, hsep (map (ppr.unLoc) (varl:varsr))]
pp_tyvars [] = pprPrefixOcc (unLoc thing)
pprTyClDeclFlavour :: TyClDecl (GhcPass p) -> SDoc
pprTyClDeclFlavour (ClassDecl {}) = text "class"
pprTyClDeclFlavour (SynDecl {}) = text "type"
pprTyClDeclFlavour (FamDecl { tcdFam = FamilyDecl { fdInfo = info }})
= pprFlavour info <+> text "family"
pprTyClDeclFlavour (DataDecl { tcdDataDefn = HsDataDefn { dd_cons = nd } })
= ppr (dataDefnConsNewOrData nd)
instance OutputableBndrId p => Outputable (FunDep (GhcPass p)) where
ppr = pprFunDep
type instance XCFunDep (GhcPass _) = EpAnn [AddEpAnn]
type instance XXFunDep (GhcPass _) = DataConCantHappen
pprFundeps :: OutputableBndrId p => [FunDep (GhcPass p)] -> SDoc
pprFundeps [] = empty
pprFundeps fds = hsep (vbar : punctuate comma (map pprFunDep fds))
pprFunDep :: OutputableBndrId p => FunDep (GhcPass p) -> SDoc
pprFunDep (FunDep _ us vs) = hsep [interppSP us, arrow, interppSP vs]
type instance XCTyClGroup (GhcPass _) = NoExtField
type instance XXTyClGroup (GhcPass _) = DataConCantHappen
type instance XNoSig (GhcPass _) = NoExtField
type instance XCKindSig (GhcPass _) = NoExtField
type instance XTyVarSig (GhcPass _) = NoExtField
type instance XXFamilyResultSig (GhcPass _) = DataConCantHappen
type instance XCFamilyDecl (GhcPass _) = EpAnn [AddEpAnn]
type instance XXFamilyDecl (GhcPass _) = DataConCantHappen
familyDeclLName :: FamilyDecl (GhcPass p) -> XRec (GhcPass p) (IdP (GhcPass p))
familyDeclLName (FamilyDecl { fdLName = n }) = n
familyDeclName :: FamilyDecl (GhcPass p) -> IdP (GhcPass p)
familyDeclName = unLoc . familyDeclLName
famResultKindSignature :: FamilyResultSig (GhcPass p) -> Maybe (LHsKind (GhcPass p))
famResultKindSignature (NoSig _) = Nothing
famResultKindSignature (KindSig _ ki) = Just ki
famResultKindSignature (TyVarSig _ bndr) =
case unLoc bndr of
UserTyVar _ _ _ -> Nothing
KindedTyVar _ _ _ ki -> Just ki
resultVariableName :: FamilyResultSig (GhcPass a) -> Maybe (IdP (GhcPass a))
resultVariableName (TyVarSig _ sig) = Just $ hsLTyVarName sig
resultVariableName _ = Nothing
type instance XCInjectivityAnn (GhcPass _) = EpAnn [AddEpAnn]
type instance XXInjectivityAnn (GhcPass _) = DataConCantHappen
instance OutputableBndrId p
=> Outputable (FamilyDecl (GhcPass p)) where
ppr (FamilyDecl { fdInfo = info, fdLName = ltycon
, fdTopLevel = top_level
, fdTyVars = tyvars
, fdFixity = fixity
, fdResultSig = L _ result
, fdInjectivityAnn = mb_inj })
= vcat [ pprFlavour info <+> pp_top_level <+>
pp_vanilla_decl_head ltycon tyvars fixity Nothing <+>
pp_kind <+> pp_inj <+> pp_where
, nest 2 $ pp_eqns ]
where
pp_top_level = case top_level of
TopLevel -> text "family"
NotTopLevel -> empty
pp_kind = case result of
NoSig _ -> empty
KindSig _ kind -> dcolon <+> ppr kind
TyVarSig _ tv_bndr -> text "=" <+> ppr tv_bndr
pp_inj = case mb_inj of
Just (L _ (InjectivityAnn _ lhs rhs)) ->
hsep [ vbar, ppr lhs, text "->", hsep (map ppr rhs) ]
Nothing -> empty
(pp_where, pp_eqns) = case info of
ClosedTypeFamily mb_eqns ->
( text "where"
, case mb_eqns of
Nothing -> text ".."
Just eqns -> vcat $ map (ppr_fam_inst_eqn . unLoc) eqns )
_ -> (empty, empty)
type instance XCHsDataDefn (GhcPass _) = NoExtField
type instance XXHsDataDefn (GhcPass _) = DataConCantHappen
type instance XCHsDerivingClause (GhcPass _) = EpAnn [AddEpAnn]
type instance XXHsDerivingClause (GhcPass _) = DataConCantHappen
instance OutputableBndrId p
=> Outputable (HsDerivingClause (GhcPass p)) where
ppr (HsDerivingClause { deriv_clause_strategy = dcs
, deriv_clause_tys = L _ dct })
= hsep [ text "deriving"
, pp_strat_before
, ppr dct
, pp_strat_after ]
where
@via@ is unique in that in comes /after/ the class being derived ,
(pp_strat_before, pp_strat_after) =
case dcs of
Just (L _ via@ViaStrategy{}) -> (empty, ppr via)
_ -> (ppDerivStrategy dcs, empty)
| A short description of a @DerivStrategy'@.
derivStrategyName :: DerivStrategy a -> SDoc
derivStrategyName = text . go
where
go StockStrategy {} = "stock"
go AnyclassStrategy {} = "anyclass"
go NewtypeStrategy {} = "newtype"
go ViaStrategy {} = "via"
type instance XDctSingle (GhcPass _) = NoExtField
type instance XDctMulti (GhcPass _) = NoExtField
type instance XXDerivClauseTys (GhcPass _) = DataConCantHappen
instance OutputableBndrId p => Outputable (DerivClauseTys (GhcPass p)) where
ppr (DctSingle _ ty) = ppr ty
ppr (DctMulti _ tys) = parens (interpp'SP tys)
type instance XStandaloneKindSig GhcPs = EpAnn [AddEpAnn]
type instance XStandaloneKindSig GhcRn = NoExtField
type instance XStandaloneKindSig GhcTc = NoExtField
type instance XXStandaloneKindSig (GhcPass p) = DataConCantHappen
standaloneKindSigName :: StandaloneKindSig (GhcPass p) -> IdP (GhcPass p)
standaloneKindSigName (StandaloneKindSig _ lname _) = unLoc lname
type instance XConDeclGADT (GhcPass _) = EpAnn [AddEpAnn]
type instance XConDeclH98 (GhcPass _) = EpAnn [AddEpAnn]
type instance XXConDecl (GhcPass _) = DataConCantHappen
Codomain could be ' NonEmpty ' , but at the moment all users need a list .
getConNames :: ConDecl GhcRn -> [LocatedN Name]
getConNames ConDeclH98 {con_name = name} = [name]
getConNames ConDeclGADT {con_names = names} = toList names
syntax ( i.e. , ' RecCon ' ) , where @fields@ are the field selectors .
getRecConArgs_maybe :: ConDecl GhcRn -> Maybe (LocatedL [LConDeclField GhcRn])
getRecConArgs_maybe (ConDeclH98{con_args = args}) = case args of
PrefixCon{} -> Nothing
RecCon flds -> Just flds
InfixCon{} -> Nothing
getRecConArgs_maybe (ConDeclGADT{con_g_args = args}) = case args of
PrefixConGADT{} -> Nothing
RecConGADT flds _ -> Just flds
hsConDeclTheta :: Maybe (LHsContext (GhcPass p)) -> [LHsType (GhcPass p)]
hsConDeclTheta Nothing = []
hsConDeclTheta (Just (L _ theta)) = theta
ppDataDefnHeader
:: (OutputableBndrId p)
-> HsDataDefn (GhcPass p)
-> SDoc
ppDataDefnHeader pp_hdr HsDataDefn
{ dd_ctxt = context
, dd_cType = mb_ct
, dd_kindSig = mb_sig
, dd_cons = condecls }
= pp_type <+> ppr (dataDefnConsNewOrData condecls) <+> pp_ct <+> pp_hdr context <+> pp_sig
where
pp_type
| isTypeDataDefnCons condecls = text "type"
| otherwise = empty
pp_ct = case mb_ct of
Nothing -> empty
Just ct -> ppr ct
pp_sig = case mb_sig of
Nothing -> empty
Just kind -> dcolon <+> ppr kind
pp_data_defn :: (OutputableBndrId p)
-> HsDataDefn (GhcPass p)
-> SDoc
pp_data_defn pp_hdr defn@HsDataDefn
{ dd_cons = condecls
, dd_derivs = derivings }
| null condecls
= ppDataDefnHeader pp_hdr defn <+> pp_derivings derivings
| otherwise
= hang (ppDataDefnHeader pp_hdr defn) 2 (pp_condecls (toList condecls) $$ pp_derivings derivings)
where
pp_derivings ds = vcat (map ppr ds)
instance OutputableBndrId p
=> Outputable (HsDataDefn (GhcPass p)) where
ppr d = pp_data_defn (\_ -> text "Naked HsDataDefn") d
instance OutputableBndrId p
=> Outputable (StandaloneKindSig (GhcPass p)) where
ppr (StandaloneKindSig _ v ki)
= text "type" <+> pprPrefixOcc (unLoc v) <+> text "::" <+> ppr ki
pp_condecls :: forall p. OutputableBndrId p => [LConDecl (GhcPass p)] -> SDoc
pp_condecls cs
In GADT syntax
= hang (text "where") 2 (vcat (map ppr cs))
= equals <+> sep (punctuate (text " |") (map ppr cs))
instance (OutputableBndrId p) => Outputable (ConDecl (GhcPass p)) where
ppr = pprConDecl
pprConDecl :: forall p. OutputableBndrId p => ConDecl (GhcPass p) -> SDoc
pprConDecl (ConDeclH98 { con_name = L _ con
, con_ex_tvs = ex_tvs
, con_mb_cxt = mcxt
, con_args = args
, con_doc = doc })
= pprMaybeWithDoc doc $
sep [ pprHsForAll (mkHsForAllInvisTele noAnn ex_tvs) mcxt
, ppr_details args ]
where
In ppr_details : let 's not print the multiplicities ( they are always 1 , by
ppr_details (InfixCon t1 t2) = hsep [ppr (hsScaledThing t1),
pprInfixOcc con,
ppr (hsScaledThing t2)]
ppr_details (PrefixCon _ tys) = hsep (pprPrefixOcc con
: map (pprHsType . unLoc . hsScaledThing) tys)
ppr_details (RecCon fields) = pprPrefixOcc con
<+> pprConDeclFields (unLoc fields)
pprConDecl (ConDeclGADT { con_names = cons, con_bndrs = L _ outer_bndrs
, con_mb_cxt = mcxt, con_g_args = args
, con_res_ty = res_ty, con_doc = doc })
= pprMaybeWithDoc doc $ ppr_con_names (toList cons) <+> dcolon
<+> (sep [pprHsOuterSigTyVarBndrs outer_bndrs <+> pprLHsContext mcxt,
sep (ppr_args args ++ [ppr res_ty]) ])
where
ppr_args (PrefixConGADT args) = map (\(HsScaled arr t) -> ppr t <+> ppr_arr arr) args
ppr_args (RecConGADT fields _) = [pprConDeclFields (unLoc fields) <+> arrow]
( cf . dataConDisplayType in Note [ Displaying linear fields ] in GHC.Core . DataCon )
ppr_arr (HsLinearArrow _) = sdocOption sdocLinearTypes $ \show_linear_types ->
if show_linear_types then lollipop else arrow
ppr_arr arr = pprHsArrow arr
ppr_con_names :: (OutputableBndr a) => [GenLocated l a] -> SDoc
ppr_con_names = pprWithCommas (pprPrefixOcc . unLoc)
type instance XCFamEqn (GhcPass _) r = EpAnn [AddEpAnn]
type instance XXFamEqn (GhcPass _) r = DataConCantHappen
type instance Anno (FamEqn (GhcPass p) _) = SrcSpanAnnA
TODO : AZ : tidy up
type instance XCClsInstDecl GhcRn = NoExtField
type instance XCClsInstDecl GhcTc = NoExtField
type instance XXClsInstDecl (GhcPass _) = DataConCantHappen
type instance XClsInstD (GhcPass _) = NoExtField
type instance XDataFamInstD (GhcPass _) = NoExtField
type instance XTyFamInstD GhcPs = NoExtField
type instance XTyFamInstD GhcRn = NoExtField
type instance XTyFamInstD GhcTc = NoExtField
type instance XXInstDecl (GhcPass _) = DataConCantHappen
instance OutputableBndrId p
=> Outputable (TyFamInstDecl (GhcPass p)) where
ppr = pprTyFamInstDecl TopLevel
pprTyFamInstDecl :: (OutputableBndrId p)
=> TopLevelFlag -> TyFamInstDecl (GhcPass p) -> SDoc
pprTyFamInstDecl top_lvl (TyFamInstDecl { tfid_eqn = eqn })
= text "type" <+> ppr_instance_keyword top_lvl <+> ppr_fam_inst_eqn eqn
ppr_instance_keyword :: TopLevelFlag -> SDoc
ppr_instance_keyword TopLevel = text "instance"
ppr_instance_keyword NotTopLevel = empty
pprTyFamDefltDecl :: (OutputableBndrId p)
=> TyFamDefltDecl (GhcPass p) -> SDoc
pprTyFamDefltDecl = pprTyFamInstDecl NotTopLevel
ppr_fam_inst_eqn :: (OutputableBndrId p)
=> TyFamInstEqn (GhcPass p) -> SDoc
ppr_fam_inst_eqn (FamEqn { feqn_tycon = L _ tycon
, feqn_bndrs = bndrs
, feqn_pats = pats
, feqn_fixity = fixity
, feqn_rhs = rhs })
= pprHsFamInstLHS tycon bndrs pats fixity Nothing <+> equals <+> ppr rhs
instance OutputableBndrId p
=> Outputable (DataFamInstDecl (GhcPass p)) where
ppr = pprDataFamInstDecl TopLevel
pprDataFamInstDecl :: (OutputableBndrId p)
=> TopLevelFlag -> DataFamInstDecl (GhcPass p) -> SDoc
pprDataFamInstDecl top_lvl (DataFamInstDecl { dfid_eqn =
(FamEqn { feqn_tycon = L _ tycon
, feqn_bndrs = bndrs
, feqn_pats = pats
, feqn_fixity = fixity
, feqn_rhs = defn })})
= pp_data_defn pp_hdr defn
where
pp_hdr mctxt = ppr_instance_keyword top_lvl
<+> pprHsFamInstLHS tycon bndrs pats fixity mctxt
pp_data_defn pretty - prints the kind sig . See # 14817 .
pprDataFamInstFlavour :: DataFamInstDecl (GhcPass p) -> SDoc
pprDataFamInstFlavour DataFamInstDecl
{ dfid_eqn = FamEqn { feqn_rhs = HsDataDefn { dd_cons = cons }}}
= ppr (dataDefnConsNewOrData cons)
pprHsFamInstLHS :: (OutputableBndrId p)
=> IdP (GhcPass p)
-> HsOuterFamEqnTyVarBndrs (GhcPass p)
-> HsTyPats (GhcPass p)
-> LexicalFixity
-> Maybe (LHsContext (GhcPass p))
-> SDoc
pprHsFamInstLHS thing bndrs typats fixity mb_ctxt
= hsep [ pprHsOuterFamEqnTyVarBndrs bndrs
, pprLHsContext mb_ctxt
, pprHsArgsApp thing fixity typats ]
instance OutputableBndrId p
=> Outputable (ClsInstDecl (GhcPass p)) where
ppr (ClsInstDecl { cid_poly_ty = inst_ty, cid_binds = binds
, cid_sigs = sigs, cid_tyfam_insts = ats
, cid_overlap_mode = mbOverlap
, cid_datafam_insts = adts })
= top_matter
= vcat [ top_matter <+> text "where"
, nest 2 $ pprDeclList $
map (pprTyFamInstDecl NotTopLevel . unLoc) ats ++
map (pprDataFamInstDecl NotTopLevel . unLoc) adts ++
pprLHsBindsForUser binds sigs ]
where
top_matter = text "instance" <+> ppOverlapPragma mbOverlap
<+> ppr inst_ty
ppDerivStrategy :: OutputableBndrId p
=> Maybe (LDerivStrategy (GhcPass p)) -> SDoc
ppDerivStrategy mb =
case mb of
Nothing -> empty
Just (L _ ds) -> ppr ds
ppOverlapPragma :: Maybe (LocatedP OverlapMode) -> SDoc
ppOverlapPragma mb =
case mb of
Nothing -> empty
Just (L _ (NoOverlap s)) -> maybe_stext s "{-# NO_OVERLAP #-}"
Just (L _ (Overlappable s)) -> maybe_stext s "{-# OVERLAPPABLE #-}"
Just (L _ (Overlapping s)) -> maybe_stext s "{-# OVERLAPPING #-}"
Just (L _ (Overlaps s)) -> maybe_stext s "{-# OVERLAPS #-}"
Just (L _ (Incoherent s)) -> maybe_stext s "{-# INCOHERENT #-}"
where
maybe_stext NoSourceText alt = text alt
maybe_stext (SourceText src) _ = text src <+> text "#-}"
instance (OutputableBndrId p) => Outputable (InstDecl (GhcPass p)) where
ppr (ClsInstD { cid_inst = decl }) = ppr decl
ppr (TyFamInstD { tfid_inst = decl }) = ppr decl
ppr (DataFamInstD { dfid_inst = decl }) = ppr decl
instDeclDataFamInsts :: [LInstDecl (GhcPass p)] -> [DataFamInstDecl (GhcPass p)]
instDeclDataFamInsts inst_decls
= concatMap do_one inst_decls
where
do_one :: LInstDecl (GhcPass p) -> [DataFamInstDecl (GhcPass p)]
do_one (L _ (ClsInstD { cid_inst = ClsInstDecl { cid_datafam_insts = fam_insts } }))
= map unLoc fam_insts
do_one (L _ (DataFamInstD { dfid_inst = fam_inst })) = [fam_inst]
do_one (L _ (TyFamInstD {})) = []
newOrDataToFlavour :: NewOrData -> TyConFlavour
newOrDataToFlavour NewType = NewtypeFlavour
newOrDataToFlavour DataType = DataTypeFlavour
instance Outputable NewOrData where
ppr NewType = text "newtype"
ppr DataType = text "data"
At the moment we only call this with @f = ' [ ] ' @ and = ' DataDefnCons'@.
anyLConIsGadt :: Foldable f => f (GenLocated l (ConDecl pass)) -> Bool
anyLConIsGadt xs = case toList xs of
L _ ConDeclGADT {} : _ -> True
_ -> False
# SPECIALIZE anyLConIsGadt : : [ GenLocated l ( ConDecl pass ) ] - > Bool #
# SPECIALIZE anyLConIsGadt : : DataDefnCons ( GenLocated l ( ConDecl pass ) ) - > Bool #
type instance XCDerivDecl (GhcPass _) = EpAnn [AddEpAnn]
type instance XXDerivDecl (GhcPass _) = DataConCantHappen
type instance Anno OverlapMode = SrcSpanAnnP
instance OutputableBndrId p
=> Outputable (DerivDecl (GhcPass p)) where
ppr (DerivDecl { deriv_type = ty
, deriv_strategy = ds
, deriv_overlap_mode = o })
= hsep [ text "deriving"
, ppDerivStrategy ds
, text "instance"
, ppOverlapPragma o
, ppr ty ]
type instance XStockStrategy GhcPs = EpAnn [AddEpAnn]
type instance XStockStrategy GhcRn = NoExtField
type instance XStockStrategy GhcTc = NoExtField
type instance XAnyClassStrategy GhcPs = EpAnn [AddEpAnn]
type instance XAnyClassStrategy GhcRn = NoExtField
type instance XAnyClassStrategy GhcTc = NoExtField
type instance XNewtypeStrategy GhcPs = EpAnn [AddEpAnn]
type instance XNewtypeStrategy GhcRn = NoExtField
type instance XNewtypeStrategy GhcTc = NoExtField
type instance XViaStrategy GhcPs = XViaStrategyPs
type instance XViaStrategy GhcRn = LHsSigType GhcRn
type instance XViaStrategy GhcTc = Type
data XViaStrategyPs = XViaStrategyPs (EpAnn [AddEpAnn]) (LHsSigType GhcPs)
instance OutputableBndrId p
=> Outputable (DerivStrategy (GhcPass p)) where
ppr (StockStrategy _) = text "stock"
ppr (AnyclassStrategy _) = text "anyclass"
ppr (NewtypeStrategy _) = text "newtype"
ppr (ViaStrategy ty) = text "via" <+> case ghcPass @p of
GhcPs -> ppr ty
GhcRn -> ppr ty
GhcTc -> ppr ty
instance Outputable XViaStrategyPs where
ppr (XViaStrategyPs _ t) = ppr t
foldDerivStrategy :: (p ~ GhcPass pass)
=> r -> (XViaStrategy p -> r) -> DerivStrategy p -> r
foldDerivStrategy other _ (StockStrategy _) = other
foldDerivStrategy other _ (AnyclassStrategy _) = other
foldDerivStrategy other _ (NewtypeStrategy _) = other
foldDerivStrategy _ via (ViaStrategy t) = via t
| Map over the @via@ type if dealing with ' ViaStrategy ' . Otherwise ,
mapDerivStrategy :: (p ~ GhcPass pass)
=> (XViaStrategy p -> XViaStrategy p)
-> DerivStrategy p -> DerivStrategy p
mapDerivStrategy f ds = foldDerivStrategy ds (ViaStrategy . f) ds
type instance XCDefaultDecl GhcPs = EpAnn [AddEpAnn]
type instance XCDefaultDecl GhcRn = NoExtField
type instance XCDefaultDecl GhcTc = NoExtField
type instance XXDefaultDecl (GhcPass _) = DataConCantHappen
instance OutputableBndrId p
=> Outputable (DefaultDecl (GhcPass p)) where
ppr (DefaultDecl _ tys)
= text "default" <+> parens (interpp'SP tys)
type instance XForeignImport GhcPs = EpAnn [AddEpAnn]
type instance XForeignImport GhcRn = NoExtField
type instance XForeignImport GhcTc = Coercion
type instance XForeignExport GhcPs = EpAnn [AddEpAnn]
type instance XForeignExport GhcRn = NoExtField
type instance XForeignExport GhcTc = Coercion
type instance XXForeignDecl (GhcPass _) = DataConCantHappen
type instance XXForeignImport (GhcPass _) = DataConCantHappen
type instance XXForeignExport (GhcPass _) = DataConCantHappen
instance OutputableBndrId p
=> Outputable (ForeignDecl (GhcPass p)) where
ppr (ForeignImport { fd_name = n, fd_sig_ty = ty, fd_fi = fimport })
= hang (text "foreign import" <+> ppr fimport <+> ppr n)
2 (dcolon <+> ppr ty)
ppr (ForeignExport { fd_name = n, fd_sig_ty = ty, fd_fe = fexport }) =
hang (text "foreign export" <+> ppr fexport <+> ppr n)
2 (dcolon <+> ppr ty)
instance OutputableBndrId p
=> Outputable (ForeignImport (GhcPass p)) where
ppr (CImport (L _ srcText) cconv safety mHeader spec) =
ppr cconv <+> ppr safety
<+> pprWithSourceText srcText (pprCEntity spec "")
where
pp_hdr = case mHeader of
Nothing -> empty
Just (Header _ header) -> ftext header
pprCEntity (CLabel lbl) _ =
doubleQuotes $ text "static" <+> pp_hdr <+> char '&' <> ppr lbl
pprCEntity (CFunction (StaticTarget st _lbl _ isFun)) src =
if dqNeeded then doubleQuotes ce else empty
where
dqNeeded = (take 6 src == "static")
|| isJust mHeader
|| not isFun
|| st /= NoSourceText
ce =
We may need to drop leading spaces first
(if take 6 src == "static" then text "static" else empty)
<+> pp_hdr
<+> (if isFun then empty else text "value")
<+> (pprWithSourceText st empty)
pprCEntity (CFunction DynamicTarget) _ =
doubleQuotes $ text "dynamic"
pprCEntity CWrapper _ = doubleQuotes $ text "wrapper"
instance OutputableBndrId p
=> Outputable (ForeignExport (GhcPass p)) where
ppr (CExport _ (L _ (CExportStatic _ lbl cconv))) =
ppr cconv <+> char '"' <> ppr lbl <> char '"'
type instance XCRuleDecls GhcPs = (EpAnn [AddEpAnn], SourceText)
type instance XCRuleDecls GhcRn = SourceText
type instance XCRuleDecls GhcTc = SourceText
type instance XXRuleDecls (GhcPass _) = DataConCantHappen
type instance XHsRule GhcPs = (EpAnn HsRuleAnn, SourceText)
type instance XHsRule GhcRn = (HsRuleRn, SourceText)
type instance XHsRule GhcTc = (HsRuleRn, SourceText)
Free - vars from the LHS and RHS
deriving Data
type instance XXRuleDecl (GhcPass _) = DataConCantHappen
data HsRuleAnn
= HsRuleAnn
{ ra_tyanns :: Maybe (AddEpAnn, AddEpAnn)
, ra_tmanns :: Maybe (AddEpAnn, AddEpAnn)
, ra_rest :: [AddEpAnn]
} deriving (Data, Eq)
flattenRuleDecls :: [LRuleDecls (GhcPass p)] -> [LRuleDecl (GhcPass p)]
flattenRuleDecls decls = concatMap (rds_rules . unLoc) decls
type instance XCRuleBndr (GhcPass _) = EpAnn [AddEpAnn]
type instance XRuleBndrSig (GhcPass _) = EpAnn [AddEpAnn]
type instance XXRuleBndr (GhcPass _) = DataConCantHappen
instance (OutputableBndrId p) => Outputable (RuleDecls (GhcPass p)) where
ppr (HsRules { rds_ext = ext
, rds_rules = rules })
= pprWithSourceText st (text "{-# RULES")
<+> vcat (punctuate semi (map ppr rules)) <+> text "#-}"
where st = case ghcPass @p of
GhcPs | (_, st) <- ext -> st
GhcRn -> ext
GhcTc -> ext
instance (OutputableBndrId p) => Outputable (RuleDecl (GhcPass p)) where
ppr (HsRule { rd_ext = ext
, rd_name = name
, rd_act = act
, rd_tyvs = tys
, rd_tmvs = tms
, rd_lhs = lhs
, rd_rhs = rhs })
= sep [pprFullRuleName st name <+> ppr act,
nest 4 (pp_forall_ty tys <+> pp_forall_tm tys
<+> pprExpr (unLoc lhs)),
nest 6 (equals <+> pprExpr (unLoc rhs)) ]
where
pp_forall_ty Nothing = empty
pp_forall_ty (Just qtvs) = forAllLit <+> fsep (map ppr qtvs) <> dot
pp_forall_tm Nothing | null tms = empty
pp_forall_tm _ = forAllLit <+> fsep (map ppr tms) <> dot
st = case ghcPass @p of
GhcPs | (_, st) <- ext -> st
GhcRn | (_, st) <- ext -> st
GhcTc | (_, st) <- ext -> st
instance (OutputableBndrId p) => Outputable (RuleBndr (GhcPass p)) where
ppr (RuleBndr _ name) = ppr name
ppr (RuleBndrSig _ name ty) = parens (ppr name <> dcolon <> ppr ty)
pprFullRuleName :: SourceText -> GenLocated a (RuleName) -> SDoc
pprFullRuleName st (L _ n) = pprWithSourceText st (doubleQuotes $ ftext n)
type instance XWarnings GhcPs = (EpAnn [AddEpAnn], SourceText)
type instance XWarnings GhcRn = SourceText
type instance XWarnings GhcTc = SourceText
type instance XXWarnDecls (GhcPass _) = DataConCantHappen
type instance XWarning (GhcPass _) = EpAnn [AddEpAnn]
type instance XXWarnDecl (GhcPass _) = DataConCantHappen
instance OutputableBndrId p
=> Outputable (WarnDecls (GhcPass p)) where
ppr (Warnings ext decls)
= text src <+> vcat (punctuate comma (map ppr decls)) <+> text "#-}"
where src = case ghcPass @p of
GhcPs | (_, SourceText src) <- ext -> src
GhcRn | SourceText src <- ext -> src
GhcTc | SourceText src <- ext -> src
_ -> panic "WarnDecls"
instance OutputableBndrId p
=> Outputable (WarnDecl (GhcPass p)) where
ppr (Warning _ thing txt)
= hsep ( punctuate comma (map ppr thing))
<+> ppr txt
type instance XHsAnnotation (GhcPass _) = (EpAnn AnnPragma, SourceText)
type instance XXAnnDecl (GhcPass _) = DataConCantHappen
instance (OutputableBndrId p) => Outputable (AnnDecl (GhcPass p)) where
ppr (HsAnnotation _ provenance expr)
= hsep [text "{-#", pprAnnProvenance provenance, pprExpr (unLoc expr), text "#-}"]
pprAnnProvenance :: OutputableBndrId p => AnnProvenance (GhcPass p) -> SDoc
pprAnnProvenance ModuleAnnProvenance = text "ANN module"
pprAnnProvenance (ValueAnnProvenance (L _ name))
= text "ANN" <+> ppr name
pprAnnProvenance (TypeAnnProvenance (L _ name))
= text "ANN type" <+> ppr name
type instance XCRoleAnnotDecl GhcPs = EpAnn [AddEpAnn]
type instance XCRoleAnnotDecl GhcRn = NoExtField
type instance XCRoleAnnotDecl GhcTc = NoExtField
type instance XXRoleAnnotDecl (GhcPass _) = DataConCantHappen
type instance Anno (Maybe Role) = SrcAnn NoEpAnns
instance OutputableBndr (IdP (GhcPass p))
=> Outputable (RoleAnnotDecl (GhcPass p)) where
ppr (RoleAnnotDecl _ ltycon roles)
= text "type role" <+> pprPrefixOcc (unLoc ltycon) <+>
hsep (map (pp_role . unLoc) roles)
where
pp_role Nothing = underscore
pp_role (Just r) = ppr r
roleAnnotDeclName :: RoleAnnotDecl (GhcPass p) -> IdP (GhcPass p)
roleAnnotDeclName (RoleAnnotDecl _ (L _ name) _) = name
type instance Anno (HsDecl (GhcPass _)) = SrcSpanAnnA
type instance Anno (SpliceDecl (GhcPass p)) = SrcSpanAnnA
type instance Anno (TyClDecl (GhcPass p)) = SrcSpanAnnA
type instance Anno (FunDep (GhcPass p)) = SrcSpanAnnA
type instance Anno (FamilyResultSig (GhcPass p)) = SrcAnn NoEpAnns
type instance Anno (FamilyDecl (GhcPass p)) = SrcSpanAnnA
type instance Anno (InjectivityAnn (GhcPass p)) = SrcAnn NoEpAnns
type instance Anno CType = SrcSpanAnnP
type instance Anno (HsDerivingClause (GhcPass p)) = SrcAnn NoEpAnns
type instance Anno (DerivClauseTys (GhcPass _)) = SrcSpanAnnC
type instance Anno (StandaloneKindSig (GhcPass p)) = SrcSpanAnnA
type instance Anno (ConDecl (GhcPass p)) = SrcSpanAnnA
type instance Anno Bool = SrcAnn NoEpAnns
type instance Anno [LocatedA (ConDeclField (GhcPass _))] = SrcSpanAnnL
type instance Anno (FamEqn p (LocatedA (HsType p))) = SrcSpanAnnA
type instance Anno (TyFamInstDecl (GhcPass p)) = SrcSpanAnnA
type instance Anno (DataFamInstDecl (GhcPass p)) = SrcSpanAnnA
type instance Anno (FamEqn (GhcPass p) _) = SrcSpanAnnA
type instance Anno (ClsInstDecl (GhcPass p)) = SrcSpanAnnA
type instance Anno (InstDecl (GhcPass p)) = SrcSpanAnnA
type instance Anno (DocDecl (GhcPass p)) = SrcSpanAnnA
type instance Anno (DerivDecl (GhcPass p)) = SrcSpanAnnA
type instance Anno OverlapMode = SrcSpanAnnP
type instance Anno (DerivStrategy (GhcPass p)) = SrcAnn NoEpAnns
type instance Anno (DefaultDecl (GhcPass p)) = SrcSpanAnnA
type instance Anno (ForeignDecl (GhcPass p)) = SrcSpanAnnA
type instance Anno (RuleDecls (GhcPass p)) = SrcSpanAnnA
type instance Anno (RuleDecl (GhcPass p)) = SrcSpanAnnA
type instance Anno (SourceText, RuleName) = SrcAnn NoEpAnns
type instance Anno (RuleBndr (GhcPass p)) = SrcAnn NoEpAnns
type instance Anno (WarnDecls (GhcPass p)) = SrcSpanAnnA
type instance Anno (WarnDecl (GhcPass p)) = SrcSpanAnnA
type instance Anno (AnnDecl (GhcPass p)) = SrcSpanAnnA
type instance Anno (RoleAnnotDecl (GhcPass p)) = SrcSpanAnnA
type instance Anno (Maybe Role) = SrcAnn NoEpAnns
type instance Anno CCallConv = SrcSpan
type instance Anno Safety = SrcSpan
type instance Anno CExportSpec = SrcSpan
|
e80069dca2d80a954b6362e3e9edf0aa1240b3332f4bb23c5d964ddab66e1b09 | morphismtech/squeal | Parameter.hs | |
Module : Squeal . PostgreSQL.Expression . Parameter
Description : out - of - line parameters
Copyright : ( c ) , 2019
Maintainer :
Stability : experimental
out - of - line parameters
Module: Squeal.PostgreSQL.Expression.Parameter
Description: out-of-line parameters
Copyright: (c) Eitan Chatav, 2019
Maintainer:
Stability: experimental
out-of-line parameters
-}
# LANGUAGE
AllowAmbiguousTypes
, , FlexibleContexts
, FlexibleInstances
, FunctionalDependencies
, GADTs
, , MultiParamTypeClasses
, OverloadedStrings
, RankNTypes
, ScopedTypeVariables
, TypeApplications
, TypeFamilies
, TypeOperators
, UndecidableInstances
#
AllowAmbiguousTypes
, DataKinds
, FlexibleContexts
, FlexibleInstances
, FunctionalDependencies
, GADTs
, KindSignatures
, MultiParamTypeClasses
, OverloadedStrings
, RankNTypes
, ScopedTypeVariables
, TypeApplications
, TypeFamilies
, TypeOperators
, UndecidableInstances
#-}
module Squeal.PostgreSQL.Expression.Parameter
( -- * Parameter
HasParameter (parameter)
, param
-- * Parameter Internals
, HasParameter'
, ParamOutOfBoundsError
, ParamTypeMismatchError
) where
import Data.Kind (Constraint)
import GHC.Exts (Any)
import GHC.TypeLits
import Squeal.PostgreSQL.Expression
import Squeal.PostgreSQL.Expression.Type
import Squeal.PostgreSQL.Render
import Squeal.PostgreSQL.Type.Schema
-- $setup
-- >>> import Squeal.PostgreSQL
| A ` HasParameter ` constraint is used to indicate a value that is
supplied externally to a SQL statement .
` Squeal . PostgreSQL.Session.manipulateParams ` ,
` Squeal . PostgreSQL.Session.queryParams ` and
` Squeal . PostgreSQL.Session.traversePrepared ` support specifying data values
separately from the SQL command string , in which case ` param`s are used to
refer to the out - of - line data values .
supplied externally to a SQL statement.
`Squeal.PostgreSQL.Session.manipulateParams`,
`Squeal.PostgreSQL.Session.queryParams` and
`Squeal.PostgreSQL.Session.traversePrepared` support specifying data values
separately from the SQL command string, in which case `param`s are used to
refer to the out-of-line data values.
-}
class KnownNat ix => HasParameter
(ix :: Nat)
(params :: [NullType])
(ty :: NullType)
| ix params -> ty where
| ` parameter ` takes a ` Nat ` using type application and a ` TypeExpression ` .
--
-- >>> printSQL (parameter @1 int4)
( $ 1 : : int4 )
parameter
:: TypeExpression db ty
-> Expression grp lat with db params from ty
parameter ty = UnsafeExpression $ parenthesized $
"$" <> renderNat @ix <+> "::"
<+> renderSQL ty
we could do the check for 0 in @HasParameter'@ , but this way forces checking ' ix ' before delegating ,
which has the nice effect of ambiguous ' ix ' errors mentioning ' HasParameter ' instead of @HasParameter'@
instance {-# OVERLAPS #-} (TypeError ('Text "Tried to get the param at index 0, but params are 1-indexed"), x ~ Any) => HasParameter 0 params x
instance {-# OVERLAPS #-} (KnownNat ix, HasParameter' ix params ix params x) => HasParameter ix params x
| @HasParameter'@ is an implementation detail of ' HasParameter ' allowing us to
-- include the full parameter list in our errors.
class KnownNat ix => HasParameter'
(originalIx :: Nat)
(allParams :: [NullType])
(ix :: Nat)
(params :: [NullType])
(ty :: NullType)
| ix params -> ty where
instance {-# OVERLAPS #-}
( params ~ (y ': xs)
, y ~ x -- having a separate 'y' type variable is required for 'ParamTypeMismatchError'
, ParamOutOfBoundsError originalIx allParams params
, ParamTypeMismatchError originalIx allParams x y
) => HasParameter' originalIx allParams 1 params x
instance {-# OVERLAPS #-}
( KnownNat ix
, HasParameter' originalIx allParams (ix-1) xs x
, params ~ (y ': xs)
, ParamOutOfBoundsError originalIx allParams params
)
=> HasParameter' originalIx allParams ix params x
-- | @ParamOutOfBoundsError@ reports a nicer error with more context when we try to do an out-of-bounds lookup successfully do a lookup but
-- find a different field than we expected, or when we find ourself out of bounds
type family ParamOutOfBoundsError (originalIx :: Nat) (allParams :: [NullType]) (params :: [NullType]) :: Constraint where
ParamOutOfBoundsError originalIx allParams '[] = TypeError
('Text "Index " ':<>: 'ShowType originalIx ':<>: 'Text " is out of bounds in 1-indexed parameter list:" ':$$: 'ShowType allParams)
ParamOutOfBoundsError _ _ _ = ()
| @ParamTypeMismatchError@ reports a nicer error with more context when we successfully do a lookup but
-- find a different field than we expected, or when we find ourself out of bounds
type family ParamTypeMismatchError (originalIx :: Nat) (allParams :: [NullType]) (found :: NullType) (expected :: NullType) :: Constraint where
ParamTypeMismatchError _ _ found found = ()
ParamTypeMismatchError originalIx allParams found expected = TypeError
( 'Text "Type mismatch when looking up param at index " ':<>: 'ShowType originalIx
':$$: 'Text "in 1-indexed parameter list:"
':$$: 'Text " " ':<>: 'ShowType allParams
':$$: 'Text ""
':$$: 'Text "Expected: " ':<>: 'ShowType expected
':$$: 'Text "But found: " ':<>: 'ShowType found
':$$: 'Text ""
)
| ` param ` takes a ` Nat ` using type application and for basic types ,
-- infers a `TypeExpression`.
--
-- >>> printSQL (param @1 @('Null 'PGint4))
( $ 1 : : int4 )
param
:: forall n ty lat with db params from grp
. (NullTyped db ty, HasParameter n params ty)
=> Expression grp lat with db params from ty -- ^ param
param = parameter @n (nulltype @db)
| null | https://raw.githubusercontent.com/morphismtech/squeal/599ebb9a0036ac7e5627be980a2a8de1a38ea4f0/squeal-postgresql/src/Squeal/PostgreSQL/Expression/Parameter.hs | haskell | * Parameter
* Parameter Internals
$setup
>>> import Squeal.PostgreSQL
>>> printSQL (parameter @1 int4)
# OVERLAPS #
# OVERLAPS #
include the full parameter list in our errors.
# OVERLAPS #
having a separate 'y' type variable is required for 'ParamTypeMismatchError'
# OVERLAPS #
| @ParamOutOfBoundsError@ reports a nicer error with more context when we try to do an out-of-bounds lookup successfully do a lookup but
find a different field than we expected, or when we find ourself out of bounds
find a different field than we expected, or when we find ourself out of bounds
infers a `TypeExpression`.
>>> printSQL (param @1 @('Null 'PGint4))
^ param | |
Module : Squeal . PostgreSQL.Expression . Parameter
Description : out - of - line parameters
Copyright : ( c ) , 2019
Maintainer :
Stability : experimental
out - of - line parameters
Module: Squeal.PostgreSQL.Expression.Parameter
Description: out-of-line parameters
Copyright: (c) Eitan Chatav, 2019
Maintainer:
Stability: experimental
out-of-line parameters
-}
# LANGUAGE
AllowAmbiguousTypes
, , FlexibleContexts
, FlexibleInstances
, FunctionalDependencies
, GADTs
, , MultiParamTypeClasses
, OverloadedStrings
, RankNTypes
, ScopedTypeVariables
, TypeApplications
, TypeFamilies
, TypeOperators
, UndecidableInstances
#
AllowAmbiguousTypes
, DataKinds
, FlexibleContexts
, FlexibleInstances
, FunctionalDependencies
, GADTs
, KindSignatures
, MultiParamTypeClasses
, OverloadedStrings
, RankNTypes
, ScopedTypeVariables
, TypeApplications
, TypeFamilies
, TypeOperators
, UndecidableInstances
#-}
module Squeal.PostgreSQL.Expression.Parameter
HasParameter (parameter)
, param
, HasParameter'
, ParamOutOfBoundsError
, ParamTypeMismatchError
) where
import Data.Kind (Constraint)
import GHC.Exts (Any)
import GHC.TypeLits
import Squeal.PostgreSQL.Expression
import Squeal.PostgreSQL.Expression.Type
import Squeal.PostgreSQL.Render
import Squeal.PostgreSQL.Type.Schema
| A ` HasParameter ` constraint is used to indicate a value that is
supplied externally to a SQL statement .
` Squeal . PostgreSQL.Session.manipulateParams ` ,
` Squeal . PostgreSQL.Session.queryParams ` and
` Squeal . PostgreSQL.Session.traversePrepared ` support specifying data values
separately from the SQL command string , in which case ` param`s are used to
refer to the out - of - line data values .
supplied externally to a SQL statement.
`Squeal.PostgreSQL.Session.manipulateParams`,
`Squeal.PostgreSQL.Session.queryParams` and
`Squeal.PostgreSQL.Session.traversePrepared` support specifying data values
separately from the SQL command string, in which case `param`s are used to
refer to the out-of-line data values.
-}
class KnownNat ix => HasParameter
(ix :: Nat)
(params :: [NullType])
(ty :: NullType)
| ix params -> ty where
| ` parameter ` takes a ` Nat ` using type application and a ` TypeExpression ` .
( $ 1 : : int4 )
parameter
:: TypeExpression db ty
-> Expression grp lat with db params from ty
parameter ty = UnsafeExpression $ parenthesized $
"$" <> renderNat @ix <+> "::"
<+> renderSQL ty
we could do the check for 0 in @HasParameter'@ , but this way forces checking ' ix ' before delegating ,
which has the nice effect of ambiguous ' ix ' errors mentioning ' HasParameter ' instead of @HasParameter'@
| @HasParameter'@ is an implementation detail of ' HasParameter ' allowing us to
class KnownNat ix => HasParameter'
(originalIx :: Nat)
(allParams :: [NullType])
(ix :: Nat)
(params :: [NullType])
(ty :: NullType)
| ix params -> ty where
( params ~ (y ': xs)
, ParamOutOfBoundsError originalIx allParams params
, ParamTypeMismatchError originalIx allParams x y
) => HasParameter' originalIx allParams 1 params x
( KnownNat ix
, HasParameter' originalIx allParams (ix-1) xs x
, params ~ (y ': xs)
, ParamOutOfBoundsError originalIx allParams params
)
=> HasParameter' originalIx allParams ix params x
type family ParamOutOfBoundsError (originalIx :: Nat) (allParams :: [NullType]) (params :: [NullType]) :: Constraint where
ParamOutOfBoundsError originalIx allParams '[] = TypeError
('Text "Index " ':<>: 'ShowType originalIx ':<>: 'Text " is out of bounds in 1-indexed parameter list:" ':$$: 'ShowType allParams)
ParamOutOfBoundsError _ _ _ = ()
| @ParamTypeMismatchError@ reports a nicer error with more context when we successfully do a lookup but
type family ParamTypeMismatchError (originalIx :: Nat) (allParams :: [NullType]) (found :: NullType) (expected :: NullType) :: Constraint where
ParamTypeMismatchError _ _ found found = ()
ParamTypeMismatchError originalIx allParams found expected = TypeError
( 'Text "Type mismatch when looking up param at index " ':<>: 'ShowType originalIx
':$$: 'Text "in 1-indexed parameter list:"
':$$: 'Text " " ':<>: 'ShowType allParams
':$$: 'Text ""
':$$: 'Text "Expected: " ':<>: 'ShowType expected
':$$: 'Text "But found: " ':<>: 'ShowType found
':$$: 'Text ""
)
| ` param ` takes a ` Nat ` using type application and for basic types ,
( $ 1 : : int4 )
param
:: forall n ty lat with db params from grp
. (NullTyped db ty, HasParameter n params ty)
param = parameter @n (nulltype @db)
|
04d71ae14b69c30aef46937610bd1adebf62818673a40d2e6b46211eeae4577d | ghc/packages-Cabal | setup.test.hs | import Test.Cabal.Prelude
main = setupAndCabalTest $ do
skipUnless =<< ghcVersionIs (>= mkVersion [8,1])
setup "configure" []
setup "build" []
| null | https://raw.githubusercontent.com/ghc/packages-Cabal/6f22f2a789fa23edb210a2591d74ea6a5f767872/cabal-testsuite/PackageTests/Backpack/T5634/setup.test.hs | haskell | import Test.Cabal.Prelude
main = setupAndCabalTest $ do
skipUnless =<< ghcVersionIs (>= mkVersion [8,1])
setup "configure" []
setup "build" []
| |
73b043148391f5c92b94c52e006e5002095a4e23b2f1f25325215b0669810bcb | tezos/tezos-mirror | test_scenario.ml | open Mockup_simulator
let bootstrap1 = Tezos_crypto.Signature.V0.Public_key.hash bootstrap1
let bootstrap2 = Tezos_crypto.Signature.V0.Public_key.hash bootstrap2
let bootstrap3 = Tezos_crypto.Signature.V0.Public_key.hash bootstrap3
let bootstrap4 = Tezos_crypto.Signature.V0.Public_key.hash bootstrap4
let bootstrap5 = Tezos_crypto.Signature.V0.Public_key.hash bootstrap5
let some_seed s = Some (Protocol.State_hash.of_b58check_exn s)
Test that the chain reaches the 5th level .
Test that the chain reaches the 5th level.
*)
let test_level_5 () =
let level_to_reach = 5l in
let module Hooks : Hooks = struct
include Default_hooks
let stop_on_event = function
| Baking_state.New_proposal {block; _} ->
(* Stop the node as soon as we receive a proposal with a level
higher than [level_to_reach]. *)
block.shell.level > level_to_reach
| _ -> false
let check_chain_on_success ~chain =
Make sure that all decided blocks have been decided at round 0 .
let round_is_zero block =
let level = block.rpc_context.block_header.level in
get_block_round block >>=? fun round ->
if Int32.equal round 0l then return ()
else failwith "block at level %ld was selected at round %ld" level round
in
List.iter_es round_is_zero chain
end in
Here we start two bakers , one with 3 delegates ( bootstrap1 , bootstrap2 ,
bootstrap3 ) and the other with 2 delegates ( bootstrap4 , ) .
The simulation continues till both nodes stop , see [ stop_on_event ]
above .
bootstrap3) and the other with 2 delegates (bootstrap4, bootstrap5).
The simulation continues till both nodes stop, see [stop_on_event]
above. *)
let config =
{
default_config with
timeout = Int32.to_int level_to_reach * 3 * 2;
round0 = 2L;
round1 = 3L;
}
in
run ~config [(3, (module Hooks)); (2, (module Hooks))]
Scenario T1
1 . Node A proposes at the round 0 .
2 . Both node A and node B preendorse .
3 . Node A stops .
4 . Node B endorses in the round 0 and locks . No decision is taken at the
round 0 because A did not endorse .
5 . We check that in round 1 ( the next slot for B ) , B proposes the same
value as A proposed in the round 0 , not a new proposal .
Scenario T1
1. Node A proposes at the round 0.
2. Both node A and node B preendorse.
3. Node A stops.
4. Node B endorses in the round 0 and locks. No decision is taken at the
round 0 because A did not endorse.
5. We check that in round 1 (the next slot for B), B proposes the same
value as A proposed in the round 0, not a new proposal.
*)
let test_scenario_t1 () =
let original_proposal = ref None in
let a_preendorsed = ref false in
let b_preendorsed = ref false in
let b_endorsed = ref false in
let b_reproposed = ref false in
(* Here we use custom hooks to make each node/baker behave according to
its role in the scenario. *)
let module Node_a_hooks : Hooks = struct
include Default_hooks
let check_mempool_after_processing ~mempool =
mempool_has_op_ref
~mempool
~predicate:
(op_is_both
(op_is_signed_by ~public_key:Mockup_simulator.bootstrap1)
(op_is_preendorsement ~level:1l ~round:0l))
~var:a_preendorsed
let stop_on_event _ = !a_preendorsed
end in
let module Node_b_hooks : Hooks = struct
include Default_hooks
let check_block_before_processing ~level ~round ~block_hash ~block_header
~(protocol_data : Protocol.Alpha_context.Block_header.protocol_data) =
(match (!b_endorsed, level, round) with
| false, 1l, 0l ->
(* If any of the checks fails the whole scenario will fail. *)
check_block_signature
~block_hash
~block_header
~public_key:Mockup_simulator.bootstrap1
>>=? fun () ->
save_proposal_payload ~protocol_data ~var:original_proposal
| true, 1l, 1l ->
check_block_signature
~block_hash
~block_header
~public_key:Mockup_simulator.bootstrap2
>>=? fun () ->
verify_payload_hash
~protocol_data
~original_proposal
~message:"a new block proposed instead of reproposal"
>>=? fun () ->
b_reproposed := true ;
return_unit
| _ -> failwith "unexpected level = %ld / round = %ld" level round)
>>=? fun () -> return_unit
let check_mempool_after_processing ~mempool =
mempool_has_op_ref
~mempool
~predicate:
(op_is_both
(op_is_signed_by ~public_key:Mockup_simulator.bootstrap2)
(op_is_preendorsement ~level:1l ~round:0l))
~var:b_preendorsed
>>=? fun () ->
mempool_has_op_ref
~mempool
~predicate:
(op_is_both
(op_is_signed_by ~public_key:Mockup_simulator.bootstrap2)
(op_is_preendorsement ~level:1l ~round:0l))
~var:b_endorsed
let stop_on_event _ = !b_reproposed
end in
let config =
{
default_config with
initial_seed = None;
delegate_selection = [(1l, [(0l, bootstrap1); (1l, bootstrap2)])];
}
in
run ~config [(1, (module Node_a_hooks)); (1, (module Node_b_hooks))]
Scenario T2
1 . Node A should propose at the round 0 , but it is dead .
2 . Node B waits til it has its proposal slot at round 1 and proposes then .
Scenario T2
1. Node A should propose at the round 0, but it is dead.
2. Node B waits til it has its proposal slot at round 1 and proposes then.
*)
let test_scenario_t2 () =
let b_proposed = ref false in
let module Node_a_hooks : Hooks = struct
include Default_hooks
let stop_on_event _ = true (* Node A stops immediately. *)
end in
let module Node_b_hooks : Hooks = struct
include Default_hooks
let check_block_before_processing ~level ~round ~block_hash ~block_header
~protocol_data:_ =
Here we test that the only block that B observes is its own
proposal for level 1 at round 1 .
proposal for level 1 at round 1. *)
match (level, round) with
| 1l, 1l ->
check_block_signature
~block_hash
~block_header
~public_key:Mockup_simulator.bootstrap2
>>=? fun () ->
b_proposed := true ;
return_unit
| _ -> failwith "unexpected level = %ld / round = %ld" level round
let stop_on_event _ =
(* Stop as soon as B has proposed. This ends the test. *)
!b_proposed
end in
let config =
{
default_config with
initial_seed = None;
delegate_selection = [(1l, [(0l, bootstrap1); (1l, bootstrap2)])];
}
in
run ~config [(1, (module Node_a_hooks)); (1, (module Node_b_hooks))]
Scenario T3
1 . There are four nodes : A , B , C , and D.
2 . C is the proposer at the round 0 . It sends the proposal , which is
received by all bakers except for D.
3 . Due to how the messages propagate , only B sees 3 preendorsements . It
endorses and locks . Other nodes all see fewer than 3 preendorsements .
A - > A and B
B - > B
C - > C and B
4 . D proposes at the round 1 . Its message reaches 3 nodes , including B.
D - > D , B , C
5 . B does not preendorse because it is locked .
6 . No decision is taken at the round 1 .
7 . B proposes at the round 2 . There are no more problems with propagation of
messages , so a decision is reached .
Scenario T3
1. There are four nodes: A, B, C, and D.
2. C is the proposer at the round 0. It sends the proposal, which is
received by all bakers except for D.
3. Due to how the messages propagate, only B sees 3 preendorsements. It
endorses and locks. Other nodes all see fewer than 3 preendorsements.
A -> A and B
B -> B
C -> C and B
4. D proposes at the round 1. Its message reaches 3 nodes, including B.
D -> D, B, C
5. B does not preendorse because it is locked.
6. No decision is taken at the round 1.
7. B proposes at the round 2. There are no more problems with propagation of
messages, so a decision is reached.
*)
let test_scenario_t3 () =
let b_observed_pqc = ref false in
let original_proposal = ref None in
let we_are_done = ref false in
let stop_on_event0 _ = !we_are_done in
let module Node_a_hooks : Hooks = struct
include Default_hooks
let on_inject_operation ~op_hash ~op =
if !b_observed_pqc then return (op_hash, op, [Pass; Pass; Pass; Pass])
else
op_is_preendorsement ~level:1l ~round:0l op_hash op
>>=? fun is_preendorsement ->
if is_preendorsement then
return (op_hash, op, [Pass; Pass; Block; Block])
else failwith "unexpected operation from the node D"
let stop_on_event = stop_on_event0
end in
let module Node_b_hooks : Hooks = struct
include Default_hooks
let on_inject_block ~level ~round ~block_hash ~block_header ~operations
~(protocol_data : Protocol.Alpha_context.Block_header.protocol_data) =
match (level, round) with
| 1l, 2l ->
check_block_signature
~block_hash
~block_header
~public_key:Mockup_simulator.bootstrap2
>>=? fun () ->
we_are_done := true ;
verify_payload_hash
~protocol_data
~original_proposal
~message:"a new block proposed instead of reproposal"
>>=? fun () ->
return (block_hash, block_header, operations, [Pass; Pass; Pass; Pass])
| _ ->
failwith
"unexpected injection on the node B, level = %ld / round = %ld"
level
round
let on_inject_operation ~op_hash ~op =
if !b_observed_pqc then return (op_hash, op, [Pass; Pass; Pass; Pass])
else
op_is_preendorsement ~level:1l ~round:0l op_hash op
>>=? fun is_preendorsement ->
if is_preendorsement then
return (op_hash, op, [Block; Pass; Block; Block])
else failwith "unexpected operation from the node B"
let check_mempool_after_processing ~mempool =
let predicate op_hash op =
op_is_preendorsement ~level:1l ~round:0l op_hash op
in
mempool_count_ops ~mempool ~predicate >>=? fun n ->
if n > 3 then
failwith "B received too many preendorsements, expected to see only 3"
else if n = 3 then (
b_observed_pqc := true ;
return_unit)
else return_unit
let stop_on_event = stop_on_event0
end in
let module Node_c_hooks : Hooks = struct
include Default_hooks
let on_inject_block ~level ~round ~block_hash ~block_header ~operations
~(protocol_data : Protocol.Alpha_context.Block_header.protocol_data) =
match (level, round) with
| 1l, 0l ->
check_block_signature
~block_hash
~block_header
~public_key:Mockup_simulator.bootstrap3
>>=? fun () ->
save_proposal_payload ~protocol_data ~var:original_proposal
>>=? fun () ->
return
(block_hash, block_header, operations, [Pass; Pass; Pass; Block])
| _ ->
failwith
"unexpected injection on the node C, level = %ld / round = %ld"
level
round
let on_inject_operation ~op_hash ~op =
if !b_observed_pqc then return (op_hash, op, [Pass; Pass; Pass; Pass])
else
op_is_preendorsement ~level:1l ~round:0l op_hash op
>>=? fun is_preendorsement ->
if is_preendorsement then
return (op_hash, op, [Block; Pass; Pass; Block])
else failwith "unexpected operation from the node C"
let stop_on_event = stop_on_event0
end in
let module Node_d_hooks : Hooks = struct
include Default_hooks
let on_inject_block ~level ~round ~block_hash ~block_header ~operations
~protocol_data:_ =
match (level, round) with
| 1l, 1l ->
return
(block_hash, block_header, operations, [Block; Pass; Pass; Pass])
| _ ->
failwith
"unexpected injection on the node D, level = %ld / round = %ld"
level
round
let on_inject_operation ~op_hash ~op =
if !b_observed_pqc then return (op_hash, op, [Pass; Pass; Pass; Pass])
else return (op_hash, op, [Block; Block; Block; Block])
let stop_on_event = stop_on_event0
end in
let config =
{
default_config with
initial_seed =
some_seed "rngFtAUcm1EneHCCrxxSWAaxSukwEhSPvpTnFjVdKLEjgkapUy1pP";
delegate_selection =
[
( 1l,
[
(0l, bootstrap3);
(1l, bootstrap4);
(2l, bootstrap2);
(3l, bootstrap1);
] );
( 2l,
[
(0l, bootstrap1);
(1l, bootstrap2);
(2l, bootstrap3);
(3l, bootstrap4);
] );
];
}
in
run
~config
[
(1, (module Node_a_hooks));
(1, (module Node_b_hooks));
(1, (module Node_c_hooks));
(1, (module Node_d_hooks));
]
Scenario F1
1 . Node C ( bootstrap3 ) proposes at level 1 round 0 , its proposal reaches all
nodes .
2 . Propagation of preendorsements happens in such a way that only Node A
( bootstrap1 ) observes :
A - > A
B - > B and A
C - > C and A
D - > D and A
Node A locks .
3 . At the level 1 round 1 node D ( bootstrap4 ) proposes . Propagation of
messages is normal .
4 . Node A ( bootstrap1 ) should propose at level 2 round 0 .
Scenario F1
1. Node C (bootstrap3) proposes at level 1 round 0, its proposal reaches all
nodes.
2. Propagation of preendorsements happens in such a way that only Node A
(bootstrap1) observes PQC:
A -> A
B -> B and A
C -> C and A
D -> D and A
Node A locks.
3. At the level 1 round 1 node D (bootstrap4) proposes. Propagation of
messages is normal.
4. Node A (bootstrap1) should propose at level 2 round 0.
*)
let test_scenario_f1 () =
let c_proposed_l1_r0 = ref false in
let d_proposed_l1_r1 = ref false in
let a_proposed_l2_r0 = ref false in
let stop_on_event0 _ = !a_proposed_l2_r0 in
let module Node_a_hooks : Hooks = struct
include Default_hooks
let on_inject_block ~level ~round ~block_hash ~block_header ~operations
~protocol_data:_ =
match (!c_proposed_l1_r0, !d_proposed_l1_r1, level, round) with
| true, true, 2l, 0l ->
check_block_signature
~block_hash
~block_header
~public_key:Mockup_simulator.bootstrap1
>>=? fun () ->
(a_proposed_l2_r0 := true ;
return_unit)
>>=? fun () ->
return (block_hash, block_header, operations, [Pass; Pass; Pass; Pass])
| _ ->
failwith
"unexpected injection on the node A, level = %ld / round = %ld"
level
round
let on_inject_operation ~op_hash ~op =
match (!c_proposed_l1_r0, !d_proposed_l1_r1) with
| true, false -> return (op_hash, op, [Pass; Block; Block; Block])
| _ -> return (op_hash, op, [Pass; Pass; Pass; Pass])
let stop_on_event = stop_on_event0
end in
let module Node_b_hooks : Hooks = struct
include Default_hooks
let on_inject_operation ~op_hash ~op =
match (!c_proposed_l1_r0, !d_proposed_l1_r1) with
| true, false -> return (op_hash, op, [Pass; Pass; Block; Block])
| _ -> return (op_hash, op, [Pass; Pass; Pass; Pass])
let stop_on_event = stop_on_event0
end in
let module Node_c_hooks : Hooks = struct
include Default_hooks
let on_inject_block ~level ~round ~block_hash ~block_header ~operations
~protocol_data:_ =
match (!c_proposed_l1_r0, !d_proposed_l1_r1, level, round) with
| false, false, 1l, 0l ->
check_block_signature
~block_hash
~block_header
~public_key:Mockup_simulator.bootstrap3
>>=? fun () ->
(c_proposed_l1_r0 := true ;
return_unit)
>>=? fun () ->
return (block_hash, block_header, operations, [Pass; Pass; Pass; Pass])
| _ ->
failwith
"unexpected injection on the node C, level = %ld / round = %ld"
level
round
let on_inject_operation ~op_hash ~op =
match (!c_proposed_l1_r0, !d_proposed_l1_r1) with
| true, false -> return (op_hash, op, [Pass; Block; Pass; Block])
| _ -> return (op_hash, op, [Pass; Pass; Pass; Pass])
let stop_on_event = stop_on_event0
end in
let module Node_d_hooks : Hooks = struct
include Default_hooks
let on_inject_block ~level ~round ~block_hash ~block_header ~operations
~protocol_data:_ =
match (!d_proposed_l1_r1, level, round) with
| false, 1l, 1l ->
check_block_signature
~block_hash
~block_header
~public_key:Mockup_simulator.bootstrap4
>>=? fun () ->
(d_proposed_l1_r1 := true ;
return_unit)
>>=? fun () ->
return (block_hash, block_header, operations, [Pass; Pass; Pass; Pass])
| _ ->
failwith
"unexpected injection on the node D, level = %ld / round = %ld"
level
round
let on_inject_operation ~op_hash ~op =
match (!c_proposed_l1_r0, !d_proposed_l1_r1) with
| true, false -> return (op_hash, op, [Pass; Block; Block; Pass])
| _ -> return (op_hash, op, [Pass; Pass; Pass; Pass])
let stop_on_event = stop_on_event0
end in
let config =
{
default_config with
initial_seed =
some_seed "rngGohKUZjXzv69sxvDqAYRd4XPDQSxDoEpP72znu2jduBuhcYiSE";
delegate_selection =
[
( 1l,
[
(0l, bootstrap3);
(1l, bootstrap4);
(2l, bootstrap1);
(3l, bootstrap2);
] );
( 2l,
[
(0l, bootstrap1);
(1l, bootstrap4);
(2l, bootstrap2);
(3l, bootstrap3);
] );
];
timeout = 60;
}
in
run
~config
[
(1, (module Node_a_hooks));
(1, (module Node_b_hooks));
(1, (module Node_c_hooks));
(1, (module Node_d_hooks));
]
Scenario F2
1 . There are four nodes : A , B , C , and D.
2 . A proposes at 1.0 and observes EQC .
3 . A has the slot at 2.0 but somehow it does n't propose or its proposal is lost .
4 . B , C , and D have the rounds 1 , 2 , and 3 respectively , but they also do not propose .
5 . A should still propose at 2.4 .
Scenario F2
1. There are four nodes: A, B, C, and D.
2. A proposes at 1.0 and observes EQC.
3. A has the slot at 2.0 but somehow it doesn't propose or its proposal is lost.
4. B, C, and D have the rounds 1, 2, and 3 respectively, but they also do not propose.
5. A should still propose at 2.4.
*)
let test_scenario_f2 () =
let proposal_2_4_observed = ref false in
let module Hooks : Hooks = struct
include Default_hooks
let on_inject_block ~level ~round ~block_hash ~block_header ~operations
~protocol_data:_ =
let propagation_vector =
match (level, round) with
| 1l, 0l -> [Pass; Pass; Pass; Pass]
| 2l, 0l -> [Pass; Block; Block; Block]
| 2l, 4l ->
proposal_2_4_observed := true ;
[Pass; Pass; Pass; Pass]
| _ -> [Block; Block; Block; Block]
in
return (block_hash, block_header, operations, propagation_vector)
let stop_on_event _ = !proposal_2_4_observed
end in
let config =
{
default_config with
initial_seed =
some_seed "rngGPSm87ZqWxJmZu7rewiLiyKY72ffCQQvxDuWmFBw59dWAL5VTB";
delegate_selection =
[
(1l, [(0l, bootstrap1)]);
( 2l,
[
(0l, bootstrap1);
(1l, bootstrap2);
(2l, bootstrap3);
(3l, bootstrap4);
(4l, bootstrap1);
] );
];
timeout = 60;
round0 = 2L;
round1 = 3L;
}
in
run
~config
[
(1, (module Hooks));
(1, (module Hooks));
(1, (module Hooks));
(1, (module Hooks));
]
Scenario M1
1 . Four nodes start , each with 1 delegate .
2 . As soon as 2nd level is proposed all communication between nodes becomes
impossible .
3 . The situation continues for 5 seconds .
4 . After communication is resumed the bakers must continue making progress .
Scenario M1
1. Four nodes start, each with 1 delegate.
2. As soon as 2nd level is proposed all communication between nodes becomes
impossible.
3. The situation continues for 5 seconds.
4. After communication is resumed the bakers must continue making progress.
*)
let test_scenario_m1 () =
let observed_level2_timestamp = ref None in
let network_down_sec = 5. in
let module Hooks : Hooks = struct
include Default_hooks
let on_inject_block ~level ~round:_ ~block_hash ~block_header ~operations
~protocol_data:_ =
let propagation_vector =
match !observed_level2_timestamp with
| None ->
if Compare.Int32.(level >= 2l) then (
observed_level2_timestamp := Some (Unix.time ()) ;
[Pass; Pass; Pass; Pass])
else [Pass; Pass; Pass; Pass]
| Some level2_observed ->
if Unix.time () -. level2_observed < network_down_sec then
[Block; Block; Block; Block]
else [Pass; Pass; Pass; Pass]
in
return (block_hash, block_header, operations, propagation_vector)
let on_inject_operation ~op_hash ~op =
let propagation_vector =
match !observed_level2_timestamp with
| None -> [Pass; Pass; Pass; Pass]
| Some level2_observed ->
if Unix.time () -. level2_observed < network_down_sec then
[Block; Block; Block; Block]
else [Pass; Pass; Pass; Pass]
in
return (op_hash, op, propagation_vector)
let stop_on_event = function
| Baking_state.New_proposal {block; _} -> block.shell.level > 4l
| _ -> false
end in
let config = {default_config with timeout = 60} in
run
~config
[
(1, (module Hooks));
(1, (module Hooks));
(1, (module Hooks));
(1, (module Hooks));
]
Scenario M2
1 . Five nodes start ( single delegate per node ) .
2 . They decide level 1 .
3 . However , the node that has the slot for level 2 round 0 is not there
to participate .
4 . We check that the chain continues advancing despite that .
Scenario M2
1. Five nodes start (single delegate per node).
2. They decide level 1.
3. However, the node that has the slot for level 2 round 0 is not there
to participate.
4. We check that the chain continues advancing despite that.
*)
let test_scenario_m2 () =
let module Normal_node : Hooks = struct
include Default_hooks
let stop_on_event = function
| Baking_state.New_proposal {block; _} -> block.shell.level > 5l
| _ -> false
end in
let module Missing_node : Hooks = struct
include Default_hooks
let stop_on_event _ = true (* stop immediately *)
end in
let config =
{
default_config with
initial_seed =
some_seed "rngGo77zNC59bYiQMk2M14aDZZu4KXG8BV1C8pi7afjJ7cXyqB3M1";
delegate_selection =
[
( 1l,
[
(0l, bootstrap1);
(1l, bootstrap2);
(2l, bootstrap3);
(3l, bootstrap4);
] );
( 2l,
[
(0l, bootstrap5);
(1l, bootstrap1);
(2l, bootstrap2);
(3l, bootstrap3);
(4l, bootstrap4);
] );
];
round0 = 2L;
round1 = 3L;
timeout = 60;
}
in
run
~config
[
(1, (module Normal_node));
(1, (module Normal_node));
(1, (module Normal_node));
(1, (module Normal_node));
(1, (module Missing_node));
]
Scenario M3
1 . There are four nodes : A , B , C , and D.
2 . A and B propose in turns . Messages from A reach every node , but messages
from other nodes only go to A.
3 . The chain should not make progress . Since we have both bootstrap1 and
bootstrap2 in delegate selection they have equal voting power . Therefore
it is necessary to have 2 votes for pre - quorums ( which is achieved when A
is proposing ) and 2 votes for quorums ( impossible because B has no way to
obtain PQC and thus can not send endorsements ) .
Scenario M3
1. There are four nodes: A, B, C, and D.
2. A and B propose in turns. Messages from A reach every node, but messages
from other nodes only go to A.
3. The chain should not make progress. Since we have both bootstrap1 and
bootstrap2 in delegate selection they have equal voting power. Therefore
it is necessary to have 2 votes for pre-quorums (which is achieved when A
is proposing) and 2 votes for quorums (impossible because B has no way to
obtain PQC and thus cannot send endorsements).
*)
let test_scenario_m3 () =
let stop_on_event0 = function
| Baking_state.New_proposal {block; _} ->
block.shell.level = 1l
&& Protocol.Alpha_context.Round.to_int32 block.round = 6l
| _ -> false
in
let module Node_a_hooks : Hooks = struct
include Default_hooks
let stop_on_event = stop_on_event0
end in
let module Other_hooks : Hooks = struct
include Default_hooks
let on_inject_block ~level:_ ~round:_ ~block_hash ~block_header ~operations
~protocol_data:_ =
return (block_hash, block_header, operations, [Pass; Block; Block; Block])
let on_inject_operation ~op_hash ~op =
return (op_hash, op, [Pass; Block; Block; Block])
let stop_on_event = stop_on_event0
end in
let config =
{
default_config with
initial_seed =
some_seed "rngGaxNJcwEVJLgQXmnN8KN5skn6fhU4Awtu8zVDKViTd5gsfT51M";
delegate_selection =
[
( 1l,
[
(0l, bootstrap1);
(1l, bootstrap2);
(2l, bootstrap1);
(3l, bootstrap2);
(4l, bootstrap1);
(5l, bootstrap2);
(6l, bootstrap1);
] );
];
round0 = 2L;
round1 = 3L;
timeout = 60;
}
in
run
~config
[
(1, (module Node_a_hooks));
(1, (module Other_hooks));
(1, (module Other_hooks));
(1, (module Other_hooks));
]
Scenario M4
1 . There are four bakers : A , B , C , and D.
2 . A proposes at level 1 round 0 . Its proposal reaches A , B , C , and D , but
with a delay of 0.5 seconds .
3 . 3 votes are enough for consensus , because voting powers of all delegates
are equal . Preendorsements propagate freely , however endorsements from C
are blocked .
4 . Check that at level 1 round 0 quorum is reached ( from the point of view
of A ) . This means that D sends an endorsement despite receiving
preendorsements before the proposal .
Scenario M4
1. There are four bakers: A, B, C, and D.
2. A proposes at level 1 round 0. Its proposal reaches A, B, C, and D, but
with a delay of 0.5 seconds.
3. 3 votes are enough for consensus, because voting powers of all delegates
are equal. Preendorsements propagate freely, however endorsements from C
are blocked.
4. Check that at level 1 round 0 quorum is reached (from the point of view
of A). This means that D sends an endorsement despite receiving
preendorsements before the proposal.
*)
let test_scenario_m4 () =
let a_observed_qc = ref false in
let stop_on_event0 _ = !a_observed_qc in
let module Node_a_hooks : Hooks = struct
include Default_hooks
let on_inject_block ~level ~round ~block_hash ~block_header ~operations
~protocol_data:_ =
match (level, round) with
| 1l, 0l ->
check_block_signature
~block_hash
~block_header
~public_key:Mockup_simulator.bootstrap1
>>=? fun () ->
return
(block_hash, block_header, operations, [Pass; Pass; Pass; Delay 0.5])
| _ ->
failwith
"unexpected injection on the node A, level = %ld / round = %ld"
level
round
let check_mempool_after_processing ~mempool =
let predicate op_hash op =
op_is_endorsement ~level:1l ~round:0l op_hash op
in
mempool_count_ops ~mempool ~predicate >>=? fun n ->
if n > 3 then
failwith "A received too many endorsements, expected to see only 3"
else if n = 3 then (
a_observed_qc := true ;
return_unit)
else return_unit
let stop_on_event = stop_on_event0
end in
let module Node_b_hooks : Hooks = struct
include Default_hooks
let stop_on_event = stop_on_event0
end in
let module Node_c_hooks : Hooks = struct
include Default_hooks
let on_inject_operation ~op_hash ~op =
op_is_endorsement ~level:1l ~round:0l op_hash op
>>=? fun is_endorsement ->
return
( op_hash,
op,
if is_endorsement then [Block; Block; Block; Block]
else [Pass; Pass; Pass; Pass] )
let stop_on_event = stop_on_event0
end in
let module Node_d_hooks : Hooks = struct
include Default_hooks
let stop_on_event = stop_on_event0
end in
let config =
{
default_config with
initial_seed =
some_seed "rngGJmwLi7kPvGwV2LR3kjNQ6xamGPCZ9ooep9QcafbqRXZhYEciT";
delegate_selection =
[
( 1l,
[
(0l, bootstrap1);
(1l, bootstrap2);
(2l, bootstrap3);
(3l, bootstrap4);
] );
];
}
in
run
~config
[
(1, (module Node_a_hooks));
(1, (module Node_b_hooks));
(1, (module Node_c_hooks));
(1, (module Node_d_hooks));
]
Scenario M5
1 . There are four bakers : A , B , C , and D.
2 . A proposes at level 1 round 0 . Its proposal reaches A , B , C , and D , but with
a delay of 1 second . There are no problems with propagation of
preendorsements and endorsements .
3 . At the level 1 all four bakers have proposer slots , however we block possible
proposals from B and C at higher rounds .
4 . Check that D proposes at the level 2 round 0 , which means that it has
observed QC .
Scenario M5
1. There are four bakers: A, B, C, and D.
2. A proposes at level 1 round 0. Its proposal reaches A, B, C, and D, but with
a delay of 1 second. There are no problems with propagation of
preendorsements and endorsements.
3. At the level 1 all four bakers have proposer slots, however we block possible
proposals from B and C at higher rounds.
4. Check that D proposes at the level 2 round 0, which means that it has
observed QC.
*)
let test_scenario_m5 () =
let stop_on_event0 = function
| Baking_state.New_proposal {block; _} -> block.shell.level >= 2l
| _ -> false
in
let module Node_a_hooks : Hooks = struct
include Default_hooks
let on_inject_block ~level ~round ~block_hash ~block_header ~operations
~protocol_data:_ =
match (level, round) with
| 1l, 0l ->
check_block_signature
~block_hash
~block_header
~public_key:Mockup_simulator.bootstrap1
>>=? fun () ->
return
(block_hash, block_header, operations, [Pass; Pass; Pass; Delay 1.0])
| _ ->
failwith
"unexpected injection on the node A, level = %ld / round = %ld"
level
round
let stop_on_event = stop_on_event0
end in
let module Other_hooks : Hooks = struct
include Default_hooks
let on_inject_block ~level:_ ~round:_ ~block_hash ~block_header ~operations
~protocol_data:_ =
return (block_hash, block_header, operations, [Block; Block; Block; Block])
let stop_on_event = stop_on_event0
end in
let module Node_d_hooks : Hooks = struct
include Default_hooks
let stop_on_event = stop_on_event0
end in
let config =
{
default_config with
initial_seed =
some_seed "rngGJmwLi7kPvGwV2LR3kjNQ6xamGPCZ9ooep9QcafbqRXZhYEciT";
delegate_selection =
[
( 1l,
[
(0l, bootstrap1);
(1l, bootstrap2);
(2l, bootstrap3);
(3l, bootstrap4);
] );
];
round0 = 3L;
round1 = 4L;
}
in
run
~config
[
(1, (module Node_a_hooks));
(1, (module Other_hooks));
(1, (module Other_hooks));
(1, (module Node_d_hooks));
]
Scenario M6
1 . There are four bakers : A , B , C , and D.
2 . A proposes at level 1 round 0 . Its proposal reaches all nodes , and they
observe PQC . Only A observes a QC .
3 . At level 1 round 1 it is B 's turn to propose . Since it has observed the
PQC , it reproposes A 's proposal . A does not see it .
4 . B observes PQC and QC for its proposal .
5 . A proposes at level 2 round 0 . No one sees the proposal .
6 . B proposes at level 2 round 1 . A sees B 's proposal and switches its branch .
7 . We wait 2 more levels before checking A 's chain to verify that it has
adopted B 's proposal .
Scenario M6
1. There are four bakers: A, B, C, and D.
2. A proposes at level 1 round 0. Its proposal reaches all nodes, and they
observe PQC. Only A observes a QC.
3. At level 1 round 1 it is B's turn to propose. Since it has observed the
PQC, it reproposes A's proposal. A does not see it.
4. B observes PQC and QC for its proposal.
5. A proposes at level 2 round 0. No one sees the proposal.
6. B proposes at level 2 round 1. A sees B's proposal and switches its branch.
7. We wait 2 more levels before checking A's chain to verify that it has
adopted B's proposal.
*)
let test_scenario_m6 () =
let b_proposal_2_1 = ref None in
let stop_on_event0 = function
| Baking_state.New_proposal {block; _} -> block.shell.level > 4l
| _ -> false
in
let module Node_a_hooks : Hooks = struct
include Default_hooks
let on_inject_block ~level ~round ~block_hash ~block_header ~operations
~protocol_data:_ =
let propagation_vector =
match (level, round) with
| 2l, 0l -> [Pass; Block; Block; Block]
| _ -> [Pass; Pass; Pass; Pass]
in
return (block_hash, block_header, operations, propagation_vector)
let on_inject_operation ~op_hash ~op =
op_is_endorsement ~level:1l ~round:0l op_hash op
>>=? fun is_a10_endorsement ->
return
( op_hash,
op,
if is_a10_endorsement then [Pass; Block; Block; Block]
else [Pass; Pass; Pass; Pass] )
let stop_on_event = stop_on_event0
let check_chain_on_success ~chain =
match List.nth (List.rev chain) 2 with
| None -> failwith "Node A has empty chain"
| Some (block : block) ->
verify_payload_hash
~protocol_data:block.protocol_data
~original_proposal:b_proposal_2_1
~message:"A did not switch to B's proposal (level 2, round 1)"
end in
let module Node_b_hooks : Hooks = struct
include Default_hooks
let on_inject_block ~level ~round ~block_hash ~block_header ~operations
~protocol_data =
(match (level, round) with
| 1l, 1l -> return [Block; Delay 0.1; Delay 0.1; Delay 0.1]
| 2l, 1l ->
save_proposal_payload ~protocol_data ~var:b_proposal_2_1
>>=? fun () -> return [Pass; Pass; Pass; Pass]
| _ -> return [Pass; Pass; Pass; Pass])
>>=? fun propagation_vector ->
return (block_hash, block_header, operations, propagation_vector)
let on_inject_operation ~op_hash ~op =
op_is_endorsement ~level:1l ~round:0l op_hash op
>>=? fun is_a10_endorsement ->
return
( op_hash,
op,
if is_a10_endorsement then [Pass; Block; Block; Block]
else [Pass; Pass; Pass; Pass] )
let stop_on_event = stop_on_event0
end in
let module Other_node : Hooks = struct
include Default_hooks
let on_inject_block ~level:_ ~round:_ ~block_hash ~block_header ~operations
~protocol_data:_ =
return (block_hash, block_header, operations, [Pass; Pass; Pass; Pass])
let on_inject_operation ~op_hash ~op =
op_is_endorsement ~level:1l ~round:0l op_hash op
>>=? fun is_a10_endorsement ->
return
( op_hash,
op,
if is_a10_endorsement then [Pass; Block; Block; Block]
else [Pass; Pass; Pass; Pass] )
let stop_on_event = stop_on_event0
end in
let config =
{
default_config with
initial_seed =
some_seed "rngGnwG2gApiRzo1kdbCgQheqtZroUsAjsJzyw2RBbtg3gtTeMQ9F";
delegate_selection =
[
( 1l,
[
(0l, bootstrap1);
(1l, bootstrap2);
(2l, bootstrap3);
(3l, bootstrap4);
] );
( 2l,
[
(0l, bootstrap1);
(1l, bootstrap2);
(2l, bootstrap3);
(3l, bootstrap4);
] );
];
timeout = 60;
}
in
run
~config
[
(1, (module Node_a_hooks));
(1, (module Node_b_hooks));
(1, (module Other_node));
(1, (module Other_node));
]
Scenario M7
The same as M6 , but :
5 . B proposes at level 2 round 0 ( A does not see the proposal ) .
6 . A proposes at 2.1 . B switches to A 's branch when it receives 2.1 .
7 . We wait 2 more levels before checking everyone 's chain to verify that
A 's proposal has been selected .
Scenario M7
The same as M6, but:
5. B proposes at level 2 round 0 (A does not see the proposal).
6. A proposes at 2.1. B switches to A's branch when it receives 2.1.
7. We wait 2 more levels before checking everyone's chain to verify that
A's proposal has been selected.
*)
let test_scenario_m7 () =
let a_proposal_2_1 = ref None in
let c_received_2_1 = ref false in
let d_received_2_1 = ref false in
let stop_on_event0 = function
| Baking_state.New_proposal {block; _} -> block.shell.level > 4l
| _ -> false
in
let check_chain_on_success0 node_label ~chain =
match List.nth (List.rev chain) 2 with
| None -> failwith "Node %s has empty chain" node_label
| Some (block : block) ->
verify_payload_hash
~protocol_data:block.protocol_data
~original_proposal:a_proposal_2_1
~message:
(Format.sprintf
"%s did not switch to A's proposal (level 2, round 1)"
node_label)
in
let module Node_a_hooks : Hooks = struct
include Default_hooks
let on_inject_block ~level ~round ~block_hash ~block_header ~operations
~protocol_data =
(match (level, round) with
| 2l, 1l -> save_proposal_payload ~protocol_data ~var:a_proposal_2_1
| _ -> return_unit)
>>=? fun () ->
return (block_hash, block_header, operations, [Pass; Pass; Pass; Pass])
let on_inject_operation ~op_hash ~op =
op_is_endorsement ~level:1l ~round:0l op_hash op
>>=? fun is_a10_endorsement ->
return
( op_hash,
op,
if is_a10_endorsement then [Pass; Block; Block; Block]
else [Pass; Pass; Pass; Pass] )
let stop_on_event = stop_on_event0
let check_chain_on_success = check_chain_on_success0 "A"
end in
let module Node_b_hooks : Hooks = struct
include Default_hooks
let on_inject_block ~level ~round ~block_hash ~block_header ~operations
~protocol_data:_ =
(match (level, round) with
| 1l, 1l -> return [Block; Delay 0.1; Delay 0.1; Delay 0.1]
| 2l, 0l -> return [Block; Pass; Pass; Pass]
| _ -> return [Pass; Pass; Pass; Pass])
>>=? fun propagation_vector ->
return (block_hash, block_header, operations, propagation_vector)
let on_inject_operation ~op_hash ~op =
op_is_endorsement ~level:1l ~round:0l op_hash op
>>=? fun is_a10_endorsement ->
op_is_preendorsement ~level:2l op_hash op
>>=? fun level2_preendorsement ->
op_is_endorsement ~level:2l op_hash op >>=? fun level2_endorsement ->
let propagation_vector =
match
(is_a10_endorsement, level2_preendorsement, level2_endorsement)
with
| true, _, _ -> [Pass; Block; Block; Block]
| _, true, _ | _, _, true -> [Block; Block; Block; Block]
| _, _, _ -> [Pass; Pass; Pass; Pass]
in
return (op_hash, op, propagation_vector)
let stop_on_event = stop_on_event0
let check_chain_on_success = check_chain_on_success0 "B"
end in
let module Node_c_hooks : Hooks = struct
include Default_hooks
let on_inject_block ~level:_ ~round:_ ~block_hash ~block_header ~operations
~protocol_data:_ =
let propagation_vector =
if !c_received_2_1 then [Pass; Pass; Pass; Pass]
else [Block; Block; Block; Block]
in
return (block_hash, block_header, operations, propagation_vector)
let check_chain_after_processing ~level ~round ~chain:_ =
match (level, round) with
| 2l, 1l ->
c_received_2_1 := true ;
return_unit
| _ -> return_unit
let on_inject_operation ~op_hash ~op =
op_is_endorsement ~level:1l ~round:0l op_hash op
>>=? fun is_a10_endorsement ->
op_is_preendorsement ~level:2l op_hash op
>>=? fun level2_preendorsement ->
op_is_endorsement ~level:2l op_hash op >>=? fun level2_endorsement ->
let propagation_vector =
match
( is_a10_endorsement,
!c_received_2_1,
level2_preendorsement,
level2_endorsement )
with
| true, _, _, _ -> [Pass; Block; Block; Block]
| _, false, true, _ | _, false, _, true -> [Block; Block; Block; Block]
| _, _, _, _ -> [Pass; Pass; Pass; Pass]
in
return (op_hash, op, propagation_vector)
let stop_on_event = stop_on_event0
let check_chain_on_success = check_chain_on_success0 "C"
end in
let module Node_d_hooks : Hooks = struct
include Default_hooks
let on_inject_block ~level:_ ~round:_ ~block_hash ~block_header ~operations
~protocol_data:_ =
let propagation_vector =
if !d_received_2_1 then [Pass; Pass; Pass; Pass]
else [Block; Block; Block; Block]
in
return (block_hash, block_header, operations, propagation_vector)
let check_chain_after_processing ~level ~round ~chain:_ =
match (level, round) with
| 2l, 1l ->
d_received_2_1 := true ;
return_unit
| _ -> return_unit
let on_inject_operation ~op_hash ~op =
op_is_endorsement ~level:1l ~round:0l op_hash op
>>=? fun is_a10_endorsement ->
op_is_preendorsement ~level:2l op_hash op
>>=? fun level2_preendorsement ->
op_is_endorsement ~level:2l op_hash op >>=? fun level2_endorsement ->
let propagation_vector =
match
( is_a10_endorsement,
!d_received_2_1,
level2_preendorsement,
level2_endorsement )
with
| true, _, _, _ -> [Pass; Block; Block; Block]
| _, false, true, _ | _, false, _, true -> [Block; Block; Block; Block]
| _, _, _, _ -> [Pass; Pass; Pass; Pass]
in
return (op_hash, op, propagation_vector)
let stop_on_event = stop_on_event0
let check_chain_on_success = check_chain_on_success0 "D"
end in
let config =
{
default_config with
initial_seed =
some_seed "rngGJ7ReXwsjWuzpeqCgHAjudFwJtxdYz44Genz1FnyJ8R226hoKh";
delegate_selection =
[
( 1l,
[
(0l, bootstrap1);
(1l, bootstrap2);
(2l, bootstrap3);
(3l, bootstrap4);
] );
( 2l,
[
(0l, bootstrap2);
(1l, bootstrap1);
(2l, bootstrap3);
(3l, bootstrap4);
] );
];
timeout = 60;
}
in
run
~config
[
(1, (module Node_a_hooks));
(1, (module Node_b_hooks));
(1, (module Node_c_hooks));
(1, (module Node_d_hooks));
]
Scenario M8
5 . B proposes at 2.0 and observes PQC but not QC .
6 . C re - proposes at 2.1 and similarly observes PQC but not QC .
7 . A proposes at 2.2 . B , C , and D do not switch to A 's branch ; moreover A
switches to their branch when it receives the next proposal ( 2.3 ) . This
happens because B , C , and D have PQC despite A having a higher round ( 2 > 1 ) .
8 . We wait 2 more levels before checking everyone 's chain to verify that
B 's proposal has been selected .
Scenario M8
5. B proposes at 2.0 and observes PQC but not QC.
6. C re-proposes at 2.1 and similarly observes PQC but not QC.
7. A proposes at 2.2. B, C, and D do not switch to A's branch; moreover A
switches to their branch when it receives the next proposal (2.3). This
happens because B, C, and D have PQC despite A having a higher round (2 > 1).
8. We wait 2 more levels before checking everyone's chain to verify that
B's proposal has been selected.
*)
let test_scenario_m8 () =
let b_proposal_2_0 = ref None in
let stop_on_event0 = function
| Baking_state.New_proposal {block; _} -> block.shell.level > 4l
| _ -> false
in
let on_inject_operation0 ~op_hash ~op =
op_is_endorsement ~level:1l ~round:0l op_hash op
>>=? fun is_a10_endorsement ->
op_is_endorsement ~level:2l ~round:0l op_hash op
>>=? fun is_b20_endorsement ->
op_is_endorsement ~level:2l ~round:1l op_hash op
>>=? fun is_c21_endorsement ->
let propagation_vector =
if is_a10_endorsement then [Pass; Block; Block; Block]
else if is_b20_endorsement || is_c21_endorsement then
[Block; Block; Block; Block]
else [Pass; Pass; Pass; Pass]
in
return (op_hash, op, propagation_vector)
in
let check_chain_on_success0 node_label ~chain =
match List.nth (List.rev chain) 2 with
| None -> failwith "Node %s has empty chain" node_label
| Some (block : block) ->
verify_payload_hash
~protocol_data:block.protocol_data
~original_proposal:b_proposal_2_0
~message:
(Format.sprintf
"%s did not switch to B's proposal (level 2, round 0)"
node_label)
in
let module Node_a_hooks : Hooks = struct
include Default_hooks
let on_inject_block ~level:_ ~round:_ ~block_hash ~block_header ~operations
~protocol_data:_ =
return (block_hash, block_header, operations, [Pass; Pass; Pass; Pass])
let on_inject_operation = on_inject_operation0
let stop_on_event = stop_on_event0
let check_chain_on_success = check_chain_on_success0 "A"
end in
let module Node_b_hooks : Hooks = struct
include Default_hooks
let on_inject_block ~level ~round ~block_hash ~block_header ~operations
~protocol_data =
(match (level, round) with
| 1l, 1l -> return [Block; Delay 0.1; Delay 0.1; Delay 0.1]
| 2l, 0l ->
save_proposal_payload ~protocol_data ~var:b_proposal_2_0
>>=? fun () -> return [Block; Pass; Pass; Pass]
| _ -> return [Pass; Pass; Pass; Pass])
>>=? fun propagation_vector ->
return (block_hash, block_header, operations, propagation_vector)
let on_inject_operation = on_inject_operation0
let stop_on_event = stop_on_event0
let check_chain_on_success = check_chain_on_success0 "B"
end in
let module Node_c_hooks : Hooks = struct
include Default_hooks
let on_inject_block ~level ~round ~block_hash ~block_header ~operations
~protocol_data:_ =
let propagation_vector =
match (level, round) with
| 2l, 1l -> [Block; Pass; Pass; Pass]
| _ -> [Pass; Pass; Pass; Pass]
in
return (block_hash, block_header, operations, propagation_vector)
let on_inject_operation = on_inject_operation0
let stop_on_event = stop_on_event0
let check_chain_on_success = check_chain_on_success0 "C"
end in
let module Node_d_hooks : Hooks = struct
include Default_hooks
let on_inject_block ~level:_ ~round:_ ~block_hash ~block_header ~operations
~protocol_data:_ =
return (block_hash, block_header, operations, [Pass; Pass; Pass; Pass])
let on_inject_operation = on_inject_operation0
let stop_on_event = stop_on_event0
let check_chain_on_success = check_chain_on_success0 "D"
end in
let config =
{
default_config with
initial_seed =
some_seed "rngFy2zFmgg25SXrE6aawqQVhD1kdw9eCCRxc843RLQjz5MZ6MGER";
delegate_selection =
[
( 1l,
[
(0l, bootstrap1);
(1l, bootstrap2);
(2l, bootstrap3);
(3l, bootstrap4);
] );
( 2l,
[
(0l, bootstrap2);
(1l, bootstrap3);
(2l, bootstrap1);
(3l, bootstrap4);
] );
];
timeout = 60;
}
in
run
~config
[
(1, (module Node_a_hooks));
(1, (module Node_b_hooks));
(1, (module Node_c_hooks));
(1, (module Node_d_hooks));
]
let tests =
let open Tezos_base_test_helpers.Tztest in
[
tztest "reaches level 5" `Quick test_level_5;
tztest "scenario t1" `Quick test_scenario_t1;
tztest "scenario t2" `Quick test_scenario_t2;
tztest "scenario t3" `Quick test_scenario_t3;
(* See issue -labs/tezos/-/issues/518 *)
(* tztest "scenario f1" `Quick test_scenario_f1; *)
tztest "scenario f2" `Quick test_scenario_f2;
tztest "scenario m1" `Quick test_scenario_m1;
tztest "scenario m2" `Quick test_scenario_m2;
tztest "scenario m3" `Quick test_scenario_m3;
tztest "scenario m4" `Quick test_scenario_m4;
tztest "scenario m5" `Quick test_scenario_m5;
tztest "scenario m6" `Quick test_scenario_m6;
tztest "scenario m7" `Quick test_scenario_m7;
tztest "scenario m8" `Quick test_scenario_m8;
]
let () =
Alcotest_lwt.run "lib_delegate" [(Protocol.name ^ ": scenario", tests)]
|> Lwt_main.run
| null | https://raw.githubusercontent.com/tezos/tezos-mirror/b1f694dc625868bfb6cd1a24b0cf86aeb7a51da6/src/proto_015_PtLimaPt/lib_delegate/test/test_scenario.ml | ocaml | Stop the node as soon as we receive a proposal with a level
higher than [level_to_reach].
Here we use custom hooks to make each node/baker behave according to
its role in the scenario.
If any of the checks fails the whole scenario will fail.
Node A stops immediately.
Stop as soon as B has proposed. This ends the test.
stop immediately
See issue -labs/tezos/-/issues/518
tztest "scenario f1" `Quick test_scenario_f1; | open Mockup_simulator
let bootstrap1 = Tezos_crypto.Signature.V0.Public_key.hash bootstrap1
let bootstrap2 = Tezos_crypto.Signature.V0.Public_key.hash bootstrap2
let bootstrap3 = Tezos_crypto.Signature.V0.Public_key.hash bootstrap3
let bootstrap4 = Tezos_crypto.Signature.V0.Public_key.hash bootstrap4
let bootstrap5 = Tezos_crypto.Signature.V0.Public_key.hash bootstrap5
let some_seed s = Some (Protocol.State_hash.of_b58check_exn s)
Test that the chain reaches the 5th level .
Test that the chain reaches the 5th level.
*)
let test_level_5 () =
let level_to_reach = 5l in
let module Hooks : Hooks = struct
include Default_hooks
let stop_on_event = function
| Baking_state.New_proposal {block; _} ->
block.shell.level > level_to_reach
| _ -> false
let check_chain_on_success ~chain =
Make sure that all decided blocks have been decided at round 0 .
let round_is_zero block =
let level = block.rpc_context.block_header.level in
get_block_round block >>=? fun round ->
if Int32.equal round 0l then return ()
else failwith "block at level %ld was selected at round %ld" level round
in
List.iter_es round_is_zero chain
end in
Here we start two bakers , one with 3 delegates ( bootstrap1 , bootstrap2 ,
bootstrap3 ) and the other with 2 delegates ( bootstrap4 , ) .
The simulation continues till both nodes stop , see [ stop_on_event ]
above .
bootstrap3) and the other with 2 delegates (bootstrap4, bootstrap5).
The simulation continues till both nodes stop, see [stop_on_event]
above. *)
let config =
{
default_config with
timeout = Int32.to_int level_to_reach * 3 * 2;
round0 = 2L;
round1 = 3L;
}
in
run ~config [(3, (module Hooks)); (2, (module Hooks))]
Scenario T1
1 . Node A proposes at the round 0 .
2 . Both node A and node B preendorse .
3 . Node A stops .
4 . Node B endorses in the round 0 and locks . No decision is taken at the
round 0 because A did not endorse .
5 . We check that in round 1 ( the next slot for B ) , B proposes the same
value as A proposed in the round 0 , not a new proposal .
Scenario T1
1. Node A proposes at the round 0.
2. Both node A and node B preendorse.
3. Node A stops.
4. Node B endorses in the round 0 and locks. No decision is taken at the
round 0 because A did not endorse.
5. We check that in round 1 (the next slot for B), B proposes the same
value as A proposed in the round 0, not a new proposal.
*)
let test_scenario_t1 () =
let original_proposal = ref None in
let a_preendorsed = ref false in
let b_preendorsed = ref false in
let b_endorsed = ref false in
let b_reproposed = ref false in
let module Node_a_hooks : Hooks = struct
include Default_hooks
let check_mempool_after_processing ~mempool =
mempool_has_op_ref
~mempool
~predicate:
(op_is_both
(op_is_signed_by ~public_key:Mockup_simulator.bootstrap1)
(op_is_preendorsement ~level:1l ~round:0l))
~var:a_preendorsed
let stop_on_event _ = !a_preendorsed
end in
let module Node_b_hooks : Hooks = struct
include Default_hooks
let check_block_before_processing ~level ~round ~block_hash ~block_header
~(protocol_data : Protocol.Alpha_context.Block_header.protocol_data) =
(match (!b_endorsed, level, round) with
| false, 1l, 0l ->
check_block_signature
~block_hash
~block_header
~public_key:Mockup_simulator.bootstrap1
>>=? fun () ->
save_proposal_payload ~protocol_data ~var:original_proposal
| true, 1l, 1l ->
check_block_signature
~block_hash
~block_header
~public_key:Mockup_simulator.bootstrap2
>>=? fun () ->
verify_payload_hash
~protocol_data
~original_proposal
~message:"a new block proposed instead of reproposal"
>>=? fun () ->
b_reproposed := true ;
return_unit
| _ -> failwith "unexpected level = %ld / round = %ld" level round)
>>=? fun () -> return_unit
let check_mempool_after_processing ~mempool =
mempool_has_op_ref
~mempool
~predicate:
(op_is_both
(op_is_signed_by ~public_key:Mockup_simulator.bootstrap2)
(op_is_preendorsement ~level:1l ~round:0l))
~var:b_preendorsed
>>=? fun () ->
mempool_has_op_ref
~mempool
~predicate:
(op_is_both
(op_is_signed_by ~public_key:Mockup_simulator.bootstrap2)
(op_is_preendorsement ~level:1l ~round:0l))
~var:b_endorsed
let stop_on_event _ = !b_reproposed
end in
let config =
{
default_config with
initial_seed = None;
delegate_selection = [(1l, [(0l, bootstrap1); (1l, bootstrap2)])];
}
in
run ~config [(1, (module Node_a_hooks)); (1, (module Node_b_hooks))]
Scenario T2
1 . Node A should propose at the round 0 , but it is dead .
2 . Node B waits til it has its proposal slot at round 1 and proposes then .
Scenario T2
1. Node A should propose at the round 0, but it is dead.
2. Node B waits til it has its proposal slot at round 1 and proposes then.
*)
let test_scenario_t2 () =
let b_proposed = ref false in
let module Node_a_hooks : Hooks = struct
include Default_hooks
end in
let module Node_b_hooks : Hooks = struct
include Default_hooks
let check_block_before_processing ~level ~round ~block_hash ~block_header
~protocol_data:_ =
Here we test that the only block that B observes is its own
proposal for level 1 at round 1 .
proposal for level 1 at round 1. *)
match (level, round) with
| 1l, 1l ->
check_block_signature
~block_hash
~block_header
~public_key:Mockup_simulator.bootstrap2
>>=? fun () ->
b_proposed := true ;
return_unit
| _ -> failwith "unexpected level = %ld / round = %ld" level round
let stop_on_event _ =
!b_proposed
end in
let config =
{
default_config with
initial_seed = None;
delegate_selection = [(1l, [(0l, bootstrap1); (1l, bootstrap2)])];
}
in
run ~config [(1, (module Node_a_hooks)); (1, (module Node_b_hooks))]
Scenario T3
1 . There are four nodes : A , B , C , and D.
2 . C is the proposer at the round 0 . It sends the proposal , which is
received by all bakers except for D.
3 . Due to how the messages propagate , only B sees 3 preendorsements . It
endorses and locks . Other nodes all see fewer than 3 preendorsements .
A - > A and B
B - > B
C - > C and B
4 . D proposes at the round 1 . Its message reaches 3 nodes , including B.
D - > D , B , C
5 . B does not preendorse because it is locked .
6 . No decision is taken at the round 1 .
7 . B proposes at the round 2 . There are no more problems with propagation of
messages , so a decision is reached .
Scenario T3
1. There are four nodes: A, B, C, and D.
2. C is the proposer at the round 0. It sends the proposal, which is
received by all bakers except for D.
3. Due to how the messages propagate, only B sees 3 preendorsements. It
endorses and locks. Other nodes all see fewer than 3 preendorsements.
A -> A and B
B -> B
C -> C and B
4. D proposes at the round 1. Its message reaches 3 nodes, including B.
D -> D, B, C
5. B does not preendorse because it is locked.
6. No decision is taken at the round 1.
7. B proposes at the round 2. There are no more problems with propagation of
messages, so a decision is reached.
*)
let test_scenario_t3 () =
let b_observed_pqc = ref false in
let original_proposal = ref None in
let we_are_done = ref false in
let stop_on_event0 _ = !we_are_done in
let module Node_a_hooks : Hooks = struct
include Default_hooks
let on_inject_operation ~op_hash ~op =
if !b_observed_pqc then return (op_hash, op, [Pass; Pass; Pass; Pass])
else
op_is_preendorsement ~level:1l ~round:0l op_hash op
>>=? fun is_preendorsement ->
if is_preendorsement then
return (op_hash, op, [Pass; Pass; Block; Block])
else failwith "unexpected operation from the node D"
let stop_on_event = stop_on_event0
end in
let module Node_b_hooks : Hooks = struct
include Default_hooks
let on_inject_block ~level ~round ~block_hash ~block_header ~operations
~(protocol_data : Protocol.Alpha_context.Block_header.protocol_data) =
match (level, round) with
| 1l, 2l ->
check_block_signature
~block_hash
~block_header
~public_key:Mockup_simulator.bootstrap2
>>=? fun () ->
we_are_done := true ;
verify_payload_hash
~protocol_data
~original_proposal
~message:"a new block proposed instead of reproposal"
>>=? fun () ->
return (block_hash, block_header, operations, [Pass; Pass; Pass; Pass])
| _ ->
failwith
"unexpected injection on the node B, level = %ld / round = %ld"
level
round
let on_inject_operation ~op_hash ~op =
if !b_observed_pqc then return (op_hash, op, [Pass; Pass; Pass; Pass])
else
op_is_preendorsement ~level:1l ~round:0l op_hash op
>>=? fun is_preendorsement ->
if is_preendorsement then
return (op_hash, op, [Block; Pass; Block; Block])
else failwith "unexpected operation from the node B"
let check_mempool_after_processing ~mempool =
let predicate op_hash op =
op_is_preendorsement ~level:1l ~round:0l op_hash op
in
mempool_count_ops ~mempool ~predicate >>=? fun n ->
if n > 3 then
failwith "B received too many preendorsements, expected to see only 3"
else if n = 3 then (
b_observed_pqc := true ;
return_unit)
else return_unit
let stop_on_event = stop_on_event0
end in
let module Node_c_hooks : Hooks = struct
include Default_hooks
let on_inject_block ~level ~round ~block_hash ~block_header ~operations
~(protocol_data : Protocol.Alpha_context.Block_header.protocol_data) =
match (level, round) with
| 1l, 0l ->
check_block_signature
~block_hash
~block_header
~public_key:Mockup_simulator.bootstrap3
>>=? fun () ->
save_proposal_payload ~protocol_data ~var:original_proposal
>>=? fun () ->
return
(block_hash, block_header, operations, [Pass; Pass; Pass; Block])
| _ ->
failwith
"unexpected injection on the node C, level = %ld / round = %ld"
level
round
let on_inject_operation ~op_hash ~op =
if !b_observed_pqc then return (op_hash, op, [Pass; Pass; Pass; Pass])
else
op_is_preendorsement ~level:1l ~round:0l op_hash op
>>=? fun is_preendorsement ->
if is_preendorsement then
return (op_hash, op, [Block; Pass; Pass; Block])
else failwith "unexpected operation from the node C"
let stop_on_event = stop_on_event0
end in
let module Node_d_hooks : Hooks = struct
include Default_hooks
let on_inject_block ~level ~round ~block_hash ~block_header ~operations
~protocol_data:_ =
match (level, round) with
| 1l, 1l ->
return
(block_hash, block_header, operations, [Block; Pass; Pass; Pass])
| _ ->
failwith
"unexpected injection on the node D, level = %ld / round = %ld"
level
round
let on_inject_operation ~op_hash ~op =
if !b_observed_pqc then return (op_hash, op, [Pass; Pass; Pass; Pass])
else return (op_hash, op, [Block; Block; Block; Block])
let stop_on_event = stop_on_event0
end in
let config =
{
default_config with
initial_seed =
some_seed "rngFtAUcm1EneHCCrxxSWAaxSukwEhSPvpTnFjVdKLEjgkapUy1pP";
delegate_selection =
[
( 1l,
[
(0l, bootstrap3);
(1l, bootstrap4);
(2l, bootstrap2);
(3l, bootstrap1);
] );
( 2l,
[
(0l, bootstrap1);
(1l, bootstrap2);
(2l, bootstrap3);
(3l, bootstrap4);
] );
];
}
in
run
~config
[
(1, (module Node_a_hooks));
(1, (module Node_b_hooks));
(1, (module Node_c_hooks));
(1, (module Node_d_hooks));
]
Scenario F1
1 . Node C ( bootstrap3 ) proposes at level 1 round 0 , its proposal reaches all
nodes .
2 . Propagation of preendorsements happens in such a way that only Node A
( bootstrap1 ) observes :
A - > A
B - > B and A
C - > C and A
D - > D and A
Node A locks .
3 . At the level 1 round 1 node D ( bootstrap4 ) proposes . Propagation of
messages is normal .
4 . Node A ( bootstrap1 ) should propose at level 2 round 0 .
Scenario F1
1. Node C (bootstrap3) proposes at level 1 round 0, its proposal reaches all
nodes.
2. Propagation of preendorsements happens in such a way that only Node A
(bootstrap1) observes PQC:
A -> A
B -> B and A
C -> C and A
D -> D and A
Node A locks.
3. At the level 1 round 1 node D (bootstrap4) proposes. Propagation of
messages is normal.
4. Node A (bootstrap1) should propose at level 2 round 0.
*)
let test_scenario_f1 () =
let c_proposed_l1_r0 = ref false in
let d_proposed_l1_r1 = ref false in
let a_proposed_l2_r0 = ref false in
let stop_on_event0 _ = !a_proposed_l2_r0 in
let module Node_a_hooks : Hooks = struct
include Default_hooks
let on_inject_block ~level ~round ~block_hash ~block_header ~operations
~protocol_data:_ =
match (!c_proposed_l1_r0, !d_proposed_l1_r1, level, round) with
| true, true, 2l, 0l ->
check_block_signature
~block_hash
~block_header
~public_key:Mockup_simulator.bootstrap1
>>=? fun () ->
(a_proposed_l2_r0 := true ;
return_unit)
>>=? fun () ->
return (block_hash, block_header, operations, [Pass; Pass; Pass; Pass])
| _ ->
failwith
"unexpected injection on the node A, level = %ld / round = %ld"
level
round
let on_inject_operation ~op_hash ~op =
match (!c_proposed_l1_r0, !d_proposed_l1_r1) with
| true, false -> return (op_hash, op, [Pass; Block; Block; Block])
| _ -> return (op_hash, op, [Pass; Pass; Pass; Pass])
let stop_on_event = stop_on_event0
end in
let module Node_b_hooks : Hooks = struct
include Default_hooks
let on_inject_operation ~op_hash ~op =
match (!c_proposed_l1_r0, !d_proposed_l1_r1) with
| true, false -> return (op_hash, op, [Pass; Pass; Block; Block])
| _ -> return (op_hash, op, [Pass; Pass; Pass; Pass])
let stop_on_event = stop_on_event0
end in
let module Node_c_hooks : Hooks = struct
include Default_hooks
let on_inject_block ~level ~round ~block_hash ~block_header ~operations
~protocol_data:_ =
match (!c_proposed_l1_r0, !d_proposed_l1_r1, level, round) with
| false, false, 1l, 0l ->
check_block_signature
~block_hash
~block_header
~public_key:Mockup_simulator.bootstrap3
>>=? fun () ->
(c_proposed_l1_r0 := true ;
return_unit)
>>=? fun () ->
return (block_hash, block_header, operations, [Pass; Pass; Pass; Pass])
| _ ->
failwith
"unexpected injection on the node C, level = %ld / round = %ld"
level
round
let on_inject_operation ~op_hash ~op =
match (!c_proposed_l1_r0, !d_proposed_l1_r1) with
| true, false -> return (op_hash, op, [Pass; Block; Pass; Block])
| _ -> return (op_hash, op, [Pass; Pass; Pass; Pass])
let stop_on_event = stop_on_event0
end in
let module Node_d_hooks : Hooks = struct
include Default_hooks
let on_inject_block ~level ~round ~block_hash ~block_header ~operations
~protocol_data:_ =
match (!d_proposed_l1_r1, level, round) with
| false, 1l, 1l ->
check_block_signature
~block_hash
~block_header
~public_key:Mockup_simulator.bootstrap4
>>=? fun () ->
(d_proposed_l1_r1 := true ;
return_unit)
>>=? fun () ->
return (block_hash, block_header, operations, [Pass; Pass; Pass; Pass])
| _ ->
failwith
"unexpected injection on the node D, level = %ld / round = %ld"
level
round
let on_inject_operation ~op_hash ~op =
match (!c_proposed_l1_r0, !d_proposed_l1_r1) with
| true, false -> return (op_hash, op, [Pass; Block; Block; Pass])
| _ -> return (op_hash, op, [Pass; Pass; Pass; Pass])
let stop_on_event = stop_on_event0
end in
let config =
{
default_config with
initial_seed =
some_seed "rngGohKUZjXzv69sxvDqAYRd4XPDQSxDoEpP72znu2jduBuhcYiSE";
delegate_selection =
[
( 1l,
[
(0l, bootstrap3);
(1l, bootstrap4);
(2l, bootstrap1);
(3l, bootstrap2);
] );
( 2l,
[
(0l, bootstrap1);
(1l, bootstrap4);
(2l, bootstrap2);
(3l, bootstrap3);
] );
];
timeout = 60;
}
in
run
~config
[
(1, (module Node_a_hooks));
(1, (module Node_b_hooks));
(1, (module Node_c_hooks));
(1, (module Node_d_hooks));
]
Scenario F2
1 . There are four nodes : A , B , C , and D.
2 . A proposes at 1.0 and observes EQC .
3 . A has the slot at 2.0 but somehow it does n't propose or its proposal is lost .
4 . B , C , and D have the rounds 1 , 2 , and 3 respectively , but they also do not propose .
5 . A should still propose at 2.4 .
Scenario F2
1. There are four nodes: A, B, C, and D.
2. A proposes at 1.0 and observes EQC.
3. A has the slot at 2.0 but somehow it doesn't propose or its proposal is lost.
4. B, C, and D have the rounds 1, 2, and 3 respectively, but they also do not propose.
5. A should still propose at 2.4.
*)
let test_scenario_f2 () =
let proposal_2_4_observed = ref false in
let module Hooks : Hooks = struct
include Default_hooks
let on_inject_block ~level ~round ~block_hash ~block_header ~operations
~protocol_data:_ =
let propagation_vector =
match (level, round) with
| 1l, 0l -> [Pass; Pass; Pass; Pass]
| 2l, 0l -> [Pass; Block; Block; Block]
| 2l, 4l ->
proposal_2_4_observed := true ;
[Pass; Pass; Pass; Pass]
| _ -> [Block; Block; Block; Block]
in
return (block_hash, block_header, operations, propagation_vector)
let stop_on_event _ = !proposal_2_4_observed
end in
let config =
{
default_config with
initial_seed =
some_seed "rngGPSm87ZqWxJmZu7rewiLiyKY72ffCQQvxDuWmFBw59dWAL5VTB";
delegate_selection =
[
(1l, [(0l, bootstrap1)]);
( 2l,
[
(0l, bootstrap1);
(1l, bootstrap2);
(2l, bootstrap3);
(3l, bootstrap4);
(4l, bootstrap1);
] );
];
timeout = 60;
round0 = 2L;
round1 = 3L;
}
in
run
~config
[
(1, (module Hooks));
(1, (module Hooks));
(1, (module Hooks));
(1, (module Hooks));
]
Scenario M1
1 . Four nodes start , each with 1 delegate .
2 . As soon as 2nd level is proposed all communication between nodes becomes
impossible .
3 . The situation continues for 5 seconds .
4 . After communication is resumed the bakers must continue making progress .
Scenario M1
1. Four nodes start, each with 1 delegate.
2. As soon as 2nd level is proposed all communication between nodes becomes
impossible.
3. The situation continues for 5 seconds.
4. After communication is resumed the bakers must continue making progress.
*)
let test_scenario_m1 () =
let observed_level2_timestamp = ref None in
let network_down_sec = 5. in
let module Hooks : Hooks = struct
include Default_hooks
let on_inject_block ~level ~round:_ ~block_hash ~block_header ~operations
~protocol_data:_ =
let propagation_vector =
match !observed_level2_timestamp with
| None ->
if Compare.Int32.(level >= 2l) then (
observed_level2_timestamp := Some (Unix.time ()) ;
[Pass; Pass; Pass; Pass])
else [Pass; Pass; Pass; Pass]
| Some level2_observed ->
if Unix.time () -. level2_observed < network_down_sec then
[Block; Block; Block; Block]
else [Pass; Pass; Pass; Pass]
in
return (block_hash, block_header, operations, propagation_vector)
let on_inject_operation ~op_hash ~op =
let propagation_vector =
match !observed_level2_timestamp with
| None -> [Pass; Pass; Pass; Pass]
| Some level2_observed ->
if Unix.time () -. level2_observed < network_down_sec then
[Block; Block; Block; Block]
else [Pass; Pass; Pass; Pass]
in
return (op_hash, op, propagation_vector)
let stop_on_event = function
| Baking_state.New_proposal {block; _} -> block.shell.level > 4l
| _ -> false
end in
let config = {default_config with timeout = 60} in
run
~config
[
(1, (module Hooks));
(1, (module Hooks));
(1, (module Hooks));
(1, (module Hooks));
]
Scenario M2
1 . Five nodes start ( single delegate per node ) .
2 . They decide level 1 .
3 . However , the node that has the slot for level 2 round 0 is not there
to participate .
4 . We check that the chain continues advancing despite that .
Scenario M2
1. Five nodes start (single delegate per node).
2. They decide level 1.
3. However, the node that has the slot for level 2 round 0 is not there
to participate.
4. We check that the chain continues advancing despite that.
*)
let test_scenario_m2 () =
let module Normal_node : Hooks = struct
include Default_hooks
let stop_on_event = function
| Baking_state.New_proposal {block; _} -> block.shell.level > 5l
| _ -> false
end in
let module Missing_node : Hooks = struct
include Default_hooks
end in
let config =
{
default_config with
initial_seed =
some_seed "rngGo77zNC59bYiQMk2M14aDZZu4KXG8BV1C8pi7afjJ7cXyqB3M1";
delegate_selection =
[
( 1l,
[
(0l, bootstrap1);
(1l, bootstrap2);
(2l, bootstrap3);
(3l, bootstrap4);
] );
( 2l,
[
(0l, bootstrap5);
(1l, bootstrap1);
(2l, bootstrap2);
(3l, bootstrap3);
(4l, bootstrap4);
] );
];
round0 = 2L;
round1 = 3L;
timeout = 60;
}
in
run
~config
[
(1, (module Normal_node));
(1, (module Normal_node));
(1, (module Normal_node));
(1, (module Normal_node));
(1, (module Missing_node));
]
Scenario M3
1 . There are four nodes : A , B , C , and D.
2 . A and B propose in turns . Messages from A reach every node , but messages
from other nodes only go to A.
3 . The chain should not make progress . Since we have both bootstrap1 and
bootstrap2 in delegate selection they have equal voting power . Therefore
it is necessary to have 2 votes for pre - quorums ( which is achieved when A
is proposing ) and 2 votes for quorums ( impossible because B has no way to
obtain PQC and thus can not send endorsements ) .
Scenario M3
1. There are four nodes: A, B, C, and D.
2. A and B propose in turns. Messages from A reach every node, but messages
from other nodes only go to A.
3. The chain should not make progress. Since we have both bootstrap1 and
bootstrap2 in delegate selection they have equal voting power. Therefore
it is necessary to have 2 votes for pre-quorums (which is achieved when A
is proposing) and 2 votes for quorums (impossible because B has no way to
obtain PQC and thus cannot send endorsements).
*)
let test_scenario_m3 () =
let stop_on_event0 = function
| Baking_state.New_proposal {block; _} ->
block.shell.level = 1l
&& Protocol.Alpha_context.Round.to_int32 block.round = 6l
| _ -> false
in
let module Node_a_hooks : Hooks = struct
include Default_hooks
let stop_on_event = stop_on_event0
end in
let module Other_hooks : Hooks = struct
include Default_hooks
let on_inject_block ~level:_ ~round:_ ~block_hash ~block_header ~operations
~protocol_data:_ =
return (block_hash, block_header, operations, [Pass; Block; Block; Block])
let on_inject_operation ~op_hash ~op =
return (op_hash, op, [Pass; Block; Block; Block])
let stop_on_event = stop_on_event0
end in
let config =
{
default_config with
initial_seed =
some_seed "rngGaxNJcwEVJLgQXmnN8KN5skn6fhU4Awtu8zVDKViTd5gsfT51M";
delegate_selection =
[
( 1l,
[
(0l, bootstrap1);
(1l, bootstrap2);
(2l, bootstrap1);
(3l, bootstrap2);
(4l, bootstrap1);
(5l, bootstrap2);
(6l, bootstrap1);
] );
];
round0 = 2L;
round1 = 3L;
timeout = 60;
}
in
run
~config
[
(1, (module Node_a_hooks));
(1, (module Other_hooks));
(1, (module Other_hooks));
(1, (module Other_hooks));
]
Scenario M4
1 . There are four bakers : A , B , C , and D.
2 . A proposes at level 1 round 0 . Its proposal reaches A , B , C , and D , but
with a delay of 0.5 seconds .
3 . 3 votes are enough for consensus , because voting powers of all delegates
are equal . Preendorsements propagate freely , however endorsements from C
are blocked .
4 . Check that at level 1 round 0 quorum is reached ( from the point of view
of A ) . This means that D sends an endorsement despite receiving
preendorsements before the proposal .
Scenario M4
1. There are four bakers: A, B, C, and D.
2. A proposes at level 1 round 0. Its proposal reaches A, B, C, and D, but
with a delay of 0.5 seconds.
3. 3 votes are enough for consensus, because voting powers of all delegates
are equal. Preendorsements propagate freely, however endorsements from C
are blocked.
4. Check that at level 1 round 0 quorum is reached (from the point of view
of A). This means that D sends an endorsement despite receiving
preendorsements before the proposal.
*)
let test_scenario_m4 () =
let a_observed_qc = ref false in
let stop_on_event0 _ = !a_observed_qc in
let module Node_a_hooks : Hooks = struct
include Default_hooks
let on_inject_block ~level ~round ~block_hash ~block_header ~operations
~protocol_data:_ =
match (level, round) with
| 1l, 0l ->
check_block_signature
~block_hash
~block_header
~public_key:Mockup_simulator.bootstrap1
>>=? fun () ->
return
(block_hash, block_header, operations, [Pass; Pass; Pass; Delay 0.5])
| _ ->
failwith
"unexpected injection on the node A, level = %ld / round = %ld"
level
round
let check_mempool_after_processing ~mempool =
let predicate op_hash op =
op_is_endorsement ~level:1l ~round:0l op_hash op
in
mempool_count_ops ~mempool ~predicate >>=? fun n ->
if n > 3 then
failwith "A received too many endorsements, expected to see only 3"
else if n = 3 then (
a_observed_qc := true ;
return_unit)
else return_unit
let stop_on_event = stop_on_event0
end in
let module Node_b_hooks : Hooks = struct
include Default_hooks
let stop_on_event = stop_on_event0
end in
let module Node_c_hooks : Hooks = struct
include Default_hooks
let on_inject_operation ~op_hash ~op =
op_is_endorsement ~level:1l ~round:0l op_hash op
>>=? fun is_endorsement ->
return
( op_hash,
op,
if is_endorsement then [Block; Block; Block; Block]
else [Pass; Pass; Pass; Pass] )
let stop_on_event = stop_on_event0
end in
let module Node_d_hooks : Hooks = struct
include Default_hooks
let stop_on_event = stop_on_event0
end in
let config =
{
default_config with
initial_seed =
some_seed "rngGJmwLi7kPvGwV2LR3kjNQ6xamGPCZ9ooep9QcafbqRXZhYEciT";
delegate_selection =
[
( 1l,
[
(0l, bootstrap1);
(1l, bootstrap2);
(2l, bootstrap3);
(3l, bootstrap4);
] );
];
}
in
run
~config
[
(1, (module Node_a_hooks));
(1, (module Node_b_hooks));
(1, (module Node_c_hooks));
(1, (module Node_d_hooks));
]
Scenario M5
1 . There are four bakers : A , B , C , and D.
2 . A proposes at level 1 round 0 . Its proposal reaches A , B , C , and D , but with
a delay of 1 second . There are no problems with propagation of
preendorsements and endorsements .
3 . At the level 1 all four bakers have proposer slots , however we block possible
proposals from B and C at higher rounds .
4 . Check that D proposes at the level 2 round 0 , which means that it has
observed QC .
Scenario M5
1. There are four bakers: A, B, C, and D.
2. A proposes at level 1 round 0. Its proposal reaches A, B, C, and D, but with
a delay of 1 second. There are no problems with propagation of
preendorsements and endorsements.
3. At the level 1 all four bakers have proposer slots, however we block possible
proposals from B and C at higher rounds.
4. Check that D proposes at the level 2 round 0, which means that it has
observed QC.
*)
let test_scenario_m5 () =
let stop_on_event0 = function
| Baking_state.New_proposal {block; _} -> block.shell.level >= 2l
| _ -> false
in
let module Node_a_hooks : Hooks = struct
include Default_hooks
let on_inject_block ~level ~round ~block_hash ~block_header ~operations
~protocol_data:_ =
match (level, round) with
| 1l, 0l ->
check_block_signature
~block_hash
~block_header
~public_key:Mockup_simulator.bootstrap1
>>=? fun () ->
return
(block_hash, block_header, operations, [Pass; Pass; Pass; Delay 1.0])
| _ ->
failwith
"unexpected injection on the node A, level = %ld / round = %ld"
level
round
let stop_on_event = stop_on_event0
end in
let module Other_hooks : Hooks = struct
include Default_hooks
let on_inject_block ~level:_ ~round:_ ~block_hash ~block_header ~operations
~protocol_data:_ =
return (block_hash, block_header, operations, [Block; Block; Block; Block])
let stop_on_event = stop_on_event0
end in
let module Node_d_hooks : Hooks = struct
include Default_hooks
let stop_on_event = stop_on_event0
end in
let config =
{
default_config with
initial_seed =
some_seed "rngGJmwLi7kPvGwV2LR3kjNQ6xamGPCZ9ooep9QcafbqRXZhYEciT";
delegate_selection =
[
( 1l,
[
(0l, bootstrap1);
(1l, bootstrap2);
(2l, bootstrap3);
(3l, bootstrap4);
] );
];
round0 = 3L;
round1 = 4L;
}
in
run
~config
[
(1, (module Node_a_hooks));
(1, (module Other_hooks));
(1, (module Other_hooks));
(1, (module Node_d_hooks));
]
Scenario M6
1 . There are four bakers : A , B , C , and D.
2 . A proposes at level 1 round 0 . Its proposal reaches all nodes , and they
observe PQC . Only A observes a QC .
3 . At level 1 round 1 it is B 's turn to propose . Since it has observed the
PQC , it reproposes A 's proposal . A does not see it .
4 . B observes PQC and QC for its proposal .
5 . A proposes at level 2 round 0 . No one sees the proposal .
6 . B proposes at level 2 round 1 . A sees B 's proposal and switches its branch .
7 . We wait 2 more levels before checking A 's chain to verify that it has
adopted B 's proposal .
Scenario M6
1. There are four bakers: A, B, C, and D.
2. A proposes at level 1 round 0. Its proposal reaches all nodes, and they
observe PQC. Only A observes a QC.
3. At level 1 round 1 it is B's turn to propose. Since it has observed the
PQC, it reproposes A's proposal. A does not see it.
4. B observes PQC and QC for its proposal.
5. A proposes at level 2 round 0. No one sees the proposal.
6. B proposes at level 2 round 1. A sees B's proposal and switches its branch.
7. We wait 2 more levels before checking A's chain to verify that it has
adopted B's proposal.
*)
let test_scenario_m6 () =
let b_proposal_2_1 = ref None in
let stop_on_event0 = function
| Baking_state.New_proposal {block; _} -> block.shell.level > 4l
| _ -> false
in
let module Node_a_hooks : Hooks = struct
include Default_hooks
let on_inject_block ~level ~round ~block_hash ~block_header ~operations
~protocol_data:_ =
let propagation_vector =
match (level, round) with
| 2l, 0l -> [Pass; Block; Block; Block]
| _ -> [Pass; Pass; Pass; Pass]
in
return (block_hash, block_header, operations, propagation_vector)
let on_inject_operation ~op_hash ~op =
op_is_endorsement ~level:1l ~round:0l op_hash op
>>=? fun is_a10_endorsement ->
return
( op_hash,
op,
if is_a10_endorsement then [Pass; Block; Block; Block]
else [Pass; Pass; Pass; Pass] )
let stop_on_event = stop_on_event0
let check_chain_on_success ~chain =
match List.nth (List.rev chain) 2 with
| None -> failwith "Node A has empty chain"
| Some (block : block) ->
verify_payload_hash
~protocol_data:block.protocol_data
~original_proposal:b_proposal_2_1
~message:"A did not switch to B's proposal (level 2, round 1)"
end in
let module Node_b_hooks : Hooks = struct
include Default_hooks
let on_inject_block ~level ~round ~block_hash ~block_header ~operations
~protocol_data =
(match (level, round) with
| 1l, 1l -> return [Block; Delay 0.1; Delay 0.1; Delay 0.1]
| 2l, 1l ->
save_proposal_payload ~protocol_data ~var:b_proposal_2_1
>>=? fun () -> return [Pass; Pass; Pass; Pass]
| _ -> return [Pass; Pass; Pass; Pass])
>>=? fun propagation_vector ->
return (block_hash, block_header, operations, propagation_vector)
let on_inject_operation ~op_hash ~op =
op_is_endorsement ~level:1l ~round:0l op_hash op
>>=? fun is_a10_endorsement ->
return
( op_hash,
op,
if is_a10_endorsement then [Pass; Block; Block; Block]
else [Pass; Pass; Pass; Pass] )
let stop_on_event = stop_on_event0
end in
let module Other_node : Hooks = struct
include Default_hooks
let on_inject_block ~level:_ ~round:_ ~block_hash ~block_header ~operations
~protocol_data:_ =
return (block_hash, block_header, operations, [Pass; Pass; Pass; Pass])
let on_inject_operation ~op_hash ~op =
op_is_endorsement ~level:1l ~round:0l op_hash op
>>=? fun is_a10_endorsement ->
return
( op_hash,
op,
if is_a10_endorsement then [Pass; Block; Block; Block]
else [Pass; Pass; Pass; Pass] )
let stop_on_event = stop_on_event0
end in
let config =
{
default_config with
initial_seed =
some_seed "rngGnwG2gApiRzo1kdbCgQheqtZroUsAjsJzyw2RBbtg3gtTeMQ9F";
delegate_selection =
[
( 1l,
[
(0l, bootstrap1);
(1l, bootstrap2);
(2l, bootstrap3);
(3l, bootstrap4);
] );
( 2l,
[
(0l, bootstrap1);
(1l, bootstrap2);
(2l, bootstrap3);
(3l, bootstrap4);
] );
];
timeout = 60;
}
in
run
~config
[
(1, (module Node_a_hooks));
(1, (module Node_b_hooks));
(1, (module Other_node));
(1, (module Other_node));
]
Scenario M7
The same as M6 , but :
5 . B proposes at level 2 round 0 ( A does not see the proposal ) .
6 . A proposes at 2.1 . B switches to A 's branch when it receives 2.1 .
7 . We wait 2 more levels before checking everyone 's chain to verify that
A 's proposal has been selected .
Scenario M7
The same as M6, but:
5. B proposes at level 2 round 0 (A does not see the proposal).
6. A proposes at 2.1. B switches to A's branch when it receives 2.1.
7. We wait 2 more levels before checking everyone's chain to verify that
A's proposal has been selected.
*)
let test_scenario_m7 () =
let a_proposal_2_1 = ref None in
let c_received_2_1 = ref false in
let d_received_2_1 = ref false in
let stop_on_event0 = function
| Baking_state.New_proposal {block; _} -> block.shell.level > 4l
| _ -> false
in
let check_chain_on_success0 node_label ~chain =
match List.nth (List.rev chain) 2 with
| None -> failwith "Node %s has empty chain" node_label
| Some (block : block) ->
verify_payload_hash
~protocol_data:block.protocol_data
~original_proposal:a_proposal_2_1
~message:
(Format.sprintf
"%s did not switch to A's proposal (level 2, round 1)"
node_label)
in
let module Node_a_hooks : Hooks = struct
include Default_hooks
let on_inject_block ~level ~round ~block_hash ~block_header ~operations
~protocol_data =
(match (level, round) with
| 2l, 1l -> save_proposal_payload ~protocol_data ~var:a_proposal_2_1
| _ -> return_unit)
>>=? fun () ->
return (block_hash, block_header, operations, [Pass; Pass; Pass; Pass])
let on_inject_operation ~op_hash ~op =
op_is_endorsement ~level:1l ~round:0l op_hash op
>>=? fun is_a10_endorsement ->
return
( op_hash,
op,
if is_a10_endorsement then [Pass; Block; Block; Block]
else [Pass; Pass; Pass; Pass] )
let stop_on_event = stop_on_event0
let check_chain_on_success = check_chain_on_success0 "A"
end in
let module Node_b_hooks : Hooks = struct
include Default_hooks
let on_inject_block ~level ~round ~block_hash ~block_header ~operations
~protocol_data:_ =
(match (level, round) with
| 1l, 1l -> return [Block; Delay 0.1; Delay 0.1; Delay 0.1]
| 2l, 0l -> return [Block; Pass; Pass; Pass]
| _ -> return [Pass; Pass; Pass; Pass])
>>=? fun propagation_vector ->
return (block_hash, block_header, operations, propagation_vector)
let on_inject_operation ~op_hash ~op =
op_is_endorsement ~level:1l ~round:0l op_hash op
>>=? fun is_a10_endorsement ->
op_is_preendorsement ~level:2l op_hash op
>>=? fun level2_preendorsement ->
op_is_endorsement ~level:2l op_hash op >>=? fun level2_endorsement ->
let propagation_vector =
match
(is_a10_endorsement, level2_preendorsement, level2_endorsement)
with
| true, _, _ -> [Pass; Block; Block; Block]
| _, true, _ | _, _, true -> [Block; Block; Block; Block]
| _, _, _ -> [Pass; Pass; Pass; Pass]
in
return (op_hash, op, propagation_vector)
let stop_on_event = stop_on_event0
let check_chain_on_success = check_chain_on_success0 "B"
end in
let module Node_c_hooks : Hooks = struct
include Default_hooks
let on_inject_block ~level:_ ~round:_ ~block_hash ~block_header ~operations
~protocol_data:_ =
let propagation_vector =
if !c_received_2_1 then [Pass; Pass; Pass; Pass]
else [Block; Block; Block; Block]
in
return (block_hash, block_header, operations, propagation_vector)
let check_chain_after_processing ~level ~round ~chain:_ =
match (level, round) with
| 2l, 1l ->
c_received_2_1 := true ;
return_unit
| _ -> return_unit
let on_inject_operation ~op_hash ~op =
op_is_endorsement ~level:1l ~round:0l op_hash op
>>=? fun is_a10_endorsement ->
op_is_preendorsement ~level:2l op_hash op
>>=? fun level2_preendorsement ->
op_is_endorsement ~level:2l op_hash op >>=? fun level2_endorsement ->
let propagation_vector =
match
( is_a10_endorsement,
!c_received_2_1,
level2_preendorsement,
level2_endorsement )
with
| true, _, _, _ -> [Pass; Block; Block; Block]
| _, false, true, _ | _, false, _, true -> [Block; Block; Block; Block]
| _, _, _, _ -> [Pass; Pass; Pass; Pass]
in
return (op_hash, op, propagation_vector)
let stop_on_event = stop_on_event0
let check_chain_on_success = check_chain_on_success0 "C"
end in
let module Node_d_hooks : Hooks = struct
include Default_hooks
let on_inject_block ~level:_ ~round:_ ~block_hash ~block_header ~operations
~protocol_data:_ =
let propagation_vector =
if !d_received_2_1 then [Pass; Pass; Pass; Pass]
else [Block; Block; Block; Block]
in
return (block_hash, block_header, operations, propagation_vector)
let check_chain_after_processing ~level ~round ~chain:_ =
match (level, round) with
| 2l, 1l ->
d_received_2_1 := true ;
return_unit
| _ -> return_unit
let on_inject_operation ~op_hash ~op =
op_is_endorsement ~level:1l ~round:0l op_hash op
>>=? fun is_a10_endorsement ->
op_is_preendorsement ~level:2l op_hash op
>>=? fun level2_preendorsement ->
op_is_endorsement ~level:2l op_hash op >>=? fun level2_endorsement ->
let propagation_vector =
match
( is_a10_endorsement,
!d_received_2_1,
level2_preendorsement,
level2_endorsement )
with
| true, _, _, _ -> [Pass; Block; Block; Block]
| _, false, true, _ | _, false, _, true -> [Block; Block; Block; Block]
| _, _, _, _ -> [Pass; Pass; Pass; Pass]
in
return (op_hash, op, propagation_vector)
let stop_on_event = stop_on_event0
let check_chain_on_success = check_chain_on_success0 "D"
end in
let config =
{
default_config with
initial_seed =
some_seed "rngGJ7ReXwsjWuzpeqCgHAjudFwJtxdYz44Genz1FnyJ8R226hoKh";
delegate_selection =
[
( 1l,
[
(0l, bootstrap1);
(1l, bootstrap2);
(2l, bootstrap3);
(3l, bootstrap4);
] );
( 2l,
[
(0l, bootstrap2);
(1l, bootstrap1);
(2l, bootstrap3);
(3l, bootstrap4);
] );
];
timeout = 60;
}
in
run
~config
[
(1, (module Node_a_hooks));
(1, (module Node_b_hooks));
(1, (module Node_c_hooks));
(1, (module Node_d_hooks));
]
Scenario M8
5 . B proposes at 2.0 and observes PQC but not QC .
6 . C re - proposes at 2.1 and similarly observes PQC but not QC .
7 . A proposes at 2.2 . B , C , and D do not switch to A 's branch ; moreover A
switches to their branch when it receives the next proposal ( 2.3 ) . This
happens because B , C , and D have PQC despite A having a higher round ( 2 > 1 ) .
8 . We wait 2 more levels before checking everyone 's chain to verify that
B 's proposal has been selected .
Scenario M8
5. B proposes at 2.0 and observes PQC but not QC.
6. C re-proposes at 2.1 and similarly observes PQC but not QC.
7. A proposes at 2.2. B, C, and D do not switch to A's branch; moreover A
switches to their branch when it receives the next proposal (2.3). This
happens because B, C, and D have PQC despite A having a higher round (2 > 1).
8. We wait 2 more levels before checking everyone's chain to verify that
B's proposal has been selected.
*)
let test_scenario_m8 () =
let b_proposal_2_0 = ref None in
let stop_on_event0 = function
| Baking_state.New_proposal {block; _} -> block.shell.level > 4l
| _ -> false
in
let on_inject_operation0 ~op_hash ~op =
op_is_endorsement ~level:1l ~round:0l op_hash op
>>=? fun is_a10_endorsement ->
op_is_endorsement ~level:2l ~round:0l op_hash op
>>=? fun is_b20_endorsement ->
op_is_endorsement ~level:2l ~round:1l op_hash op
>>=? fun is_c21_endorsement ->
let propagation_vector =
if is_a10_endorsement then [Pass; Block; Block; Block]
else if is_b20_endorsement || is_c21_endorsement then
[Block; Block; Block; Block]
else [Pass; Pass; Pass; Pass]
in
return (op_hash, op, propagation_vector)
in
let check_chain_on_success0 node_label ~chain =
match List.nth (List.rev chain) 2 with
| None -> failwith "Node %s has empty chain" node_label
| Some (block : block) ->
verify_payload_hash
~protocol_data:block.protocol_data
~original_proposal:b_proposal_2_0
~message:
(Format.sprintf
"%s did not switch to B's proposal (level 2, round 0)"
node_label)
in
let module Node_a_hooks : Hooks = struct
include Default_hooks
let on_inject_block ~level:_ ~round:_ ~block_hash ~block_header ~operations
~protocol_data:_ =
return (block_hash, block_header, operations, [Pass; Pass; Pass; Pass])
let on_inject_operation = on_inject_operation0
let stop_on_event = stop_on_event0
let check_chain_on_success = check_chain_on_success0 "A"
end in
let module Node_b_hooks : Hooks = struct
include Default_hooks
let on_inject_block ~level ~round ~block_hash ~block_header ~operations
~protocol_data =
(match (level, round) with
| 1l, 1l -> return [Block; Delay 0.1; Delay 0.1; Delay 0.1]
| 2l, 0l ->
save_proposal_payload ~protocol_data ~var:b_proposal_2_0
>>=? fun () -> return [Block; Pass; Pass; Pass]
| _ -> return [Pass; Pass; Pass; Pass])
>>=? fun propagation_vector ->
return (block_hash, block_header, operations, propagation_vector)
let on_inject_operation = on_inject_operation0
let stop_on_event = stop_on_event0
let check_chain_on_success = check_chain_on_success0 "B"
end in
let module Node_c_hooks : Hooks = struct
include Default_hooks
let on_inject_block ~level ~round ~block_hash ~block_header ~operations
~protocol_data:_ =
let propagation_vector =
match (level, round) with
| 2l, 1l -> [Block; Pass; Pass; Pass]
| _ -> [Pass; Pass; Pass; Pass]
in
return (block_hash, block_header, operations, propagation_vector)
let on_inject_operation = on_inject_operation0
let stop_on_event = stop_on_event0
let check_chain_on_success = check_chain_on_success0 "C"
end in
let module Node_d_hooks : Hooks = struct
include Default_hooks
let on_inject_block ~level:_ ~round:_ ~block_hash ~block_header ~operations
~protocol_data:_ =
return (block_hash, block_header, operations, [Pass; Pass; Pass; Pass])
let on_inject_operation = on_inject_operation0
let stop_on_event = stop_on_event0
let check_chain_on_success = check_chain_on_success0 "D"
end in
let config =
{
default_config with
initial_seed =
some_seed "rngFy2zFmgg25SXrE6aawqQVhD1kdw9eCCRxc843RLQjz5MZ6MGER";
delegate_selection =
[
( 1l,
[
(0l, bootstrap1);
(1l, bootstrap2);
(2l, bootstrap3);
(3l, bootstrap4);
] );
( 2l,
[
(0l, bootstrap2);
(1l, bootstrap3);
(2l, bootstrap1);
(3l, bootstrap4);
] );
];
timeout = 60;
}
in
run
~config
[
(1, (module Node_a_hooks));
(1, (module Node_b_hooks));
(1, (module Node_c_hooks));
(1, (module Node_d_hooks));
]
let tests =
let open Tezos_base_test_helpers.Tztest in
[
tztest "reaches level 5" `Quick test_level_5;
tztest "scenario t1" `Quick test_scenario_t1;
tztest "scenario t2" `Quick test_scenario_t2;
tztest "scenario t3" `Quick test_scenario_t3;
tztest "scenario f2" `Quick test_scenario_f2;
tztest "scenario m1" `Quick test_scenario_m1;
tztest "scenario m2" `Quick test_scenario_m2;
tztest "scenario m3" `Quick test_scenario_m3;
tztest "scenario m4" `Quick test_scenario_m4;
tztest "scenario m5" `Quick test_scenario_m5;
tztest "scenario m6" `Quick test_scenario_m6;
tztest "scenario m7" `Quick test_scenario_m7;
tztest "scenario m8" `Quick test_scenario_m8;
]
let () =
Alcotest_lwt.run "lib_delegate" [(Protocol.name ^ ": scenario", tests)]
|> Lwt_main.run
|
d1593ba5a6606d28c6c8b1dcc770759e060fed5acd894ba2b455b8077a37ef92 | haskell/containers | DeprecatedDebug.hs | # LANGUAGE CPP , FlexibleContexts , DataKinds , MonoLocalBinds #
module Data.IntMap.Internal.DeprecatedDebug where
import Data.IntMap.Internal (IntMap)
import Utils.Containers.Internal.TypeError
| ' showTree ' has moved to ' Data . IntMap . Internal . Debug.showTree '
showTree :: Whoops "Data.IntMap.showTree has moved to Data.IntMap.Internal.Debug.showTree"
=> IntMap a -> String
showTree _ = undefined
| ' showTreeWith ' has moved to ' Data . IntMap . Internal . Debug.showTreeWith '
showTreeWith :: Whoops "Data.IntMap.showTreeWith has moved to Data.IntMap.Internal.Debug.showTreeWith"
=> Bool -> Bool -> IntMap a -> String
showTreeWith _ _ _ = undefined
| null | https://raw.githubusercontent.com/haskell/containers/7fb91ca53b1aca7c077b36a0c1f8f785d177da34/containers/src/Data/IntMap/Internal/DeprecatedDebug.hs | haskell | # LANGUAGE CPP , FlexibleContexts , DataKinds , MonoLocalBinds #
module Data.IntMap.Internal.DeprecatedDebug where
import Data.IntMap.Internal (IntMap)
import Utils.Containers.Internal.TypeError
| ' showTree ' has moved to ' Data . IntMap . Internal . Debug.showTree '
showTree :: Whoops "Data.IntMap.showTree has moved to Data.IntMap.Internal.Debug.showTree"
=> IntMap a -> String
showTree _ = undefined
| ' showTreeWith ' has moved to ' Data . IntMap . Internal . Debug.showTreeWith '
showTreeWith :: Whoops "Data.IntMap.showTreeWith has moved to Data.IntMap.Internal.Debug.showTreeWith"
=> Bool -> Bool -> IntMap a -> String
showTreeWith _ _ _ = undefined
| |
e995a86252846ebb09ff0053c7d580ba47bfbd4a8e83e979579af60f75f5dd32 | Frama-C/Frama-C-snapshot | empty.ml | An empty ml file in order to test dynamic module
| null | https://raw.githubusercontent.com/Frama-C/Frama-C-snapshot/639a3647736bf8ac127d00ebe4c4c259f75f9b87/tests/dynamic/empty.ml | ocaml | An empty ml file in order to test dynamic module
| |
00a2e285df237bef91e72164abbfe2f336f8995debb58f72fb2073abfad561e2 | andersfugmann/amqp-client | gen_spec.ml | open Printf
module List = ListLabels
let indent = ref 0
let emit_location = ref true
let option_map ~f = function
| Some v -> f v
| None -> None
let option_iter ~f = function
| Some v -> f v
| None -> ()
let emit_loc loc =
match !emit_location with
| true ->
let indent = String.make (!indent * 2) ' ' in
printf "%s(* %s:%d *)\n" indent __FILE__ loc
| false ->
printf "# %d \"%s\"\n" loc __FILE__
let emit ?loc fmt =
option_iter ~f:emit_loc loc;
assert (!indent >= 0);
let indent = String.make (!indent * 2) ' ' in
(* Get last location *)
printf ("%s" ^^ fmt ^^ "\n") indent
let emit_doc = function
| Some doc ->
emit "";
emit "(** %s *)" doc
| None -> ()
module Field = struct
type t = { name: string; tpe: string; reserved: bool; doc: string option }
end
module Constant = struct
type t = { name: string; value: int; doc: string option }
end
module Domain = struct
type t = { name: string; amqp_type: string; doc: string option }
end
module Method = struct
type t = { name: string; arguments: Field.t list;
response: string list; content: bool;
index: int; synchronous: bool; server: bool; client: bool;
doc: string option
}
end
module Class = struct
type t = { name: string; content: Field.t list; index: int;
methods: Method.t list; doc: string option }
end
type elem =
| Constant of Constant.t
| Domain of Domain.t
| Class of Class.t
let blanks = Str.regexp "[ \t\n]+"
let doc xml =
try
Ezxmlm.member "doc" xml
|> Ezxmlm.data_to_string
|> (fun x -> Some x)
with
| Ezxmlm.Tag_not_found _ -> None
let parse_field (attrs, nodes) =
(* Only look at the attributes *)
ignore nodes;
let name =
match Ezxmlm.get_attr "name" attrs with
| "type" -> "amqp_type"
| name -> name
in
let tpe =
match Ezxmlm.get_attr "domain" attrs with
| d -> d
| exception Not_found -> Ezxmlm.get_attr "type" attrs
in
let reserved = Ezxmlm.mem_attr "reserved" "1" attrs in
{ Field.name; tpe; reserved; doc = doc nodes }
let parse_constant (attrs, nodes) =
let name = Ezxmlm.get_attr "name" attrs in
let value = Ezxmlm.get_attr "value" attrs |> int_of_string in
Constant { Constant.name; value; doc = doc nodes }
let parse_domain (attrs, nodes) =
ignore nodes;
let name = Ezxmlm.get_attr "name" attrs in
let amqp_type = Ezxmlm.get_attr "type" attrs in
Domain { Domain.name; amqp_type; doc = doc nodes}
let parse_method (attrs, nodes) =
let name = Ezxmlm.get_attr "name" attrs in
incr indent;
let index = Ezxmlm.get_attr "index" attrs |> int_of_string in
let response =
Ezxmlm.members_with_attr "response" nodes
|> List.map ~f:(fun (attrs, _) -> Ezxmlm.get_attr "name" attrs)
in
let synchronous =
match Ezxmlm.get_attr "synchronous" attrs with
| "1" -> true
| _ -> false
| exception Not_found -> false
in
let content =
match Ezxmlm.get_attr "content" attrs with
| "1" -> true
| _ -> false
| exception Not_found -> false
in
let arguments = Ezxmlm.members_with_attr "field" nodes |> List.map ~f:parse_field in
let chassis =
Ezxmlm.members_with_attr "chassis" nodes
|> List.map ~f:(fun (attrs, _) -> Ezxmlm.get_attr "name" attrs)
in
let client = List.mem "client" ~set:chassis in
let server = List.mem "server" ~set:chassis in
decr indent;
{ Method.name; arguments; response; content; index; synchronous;
client; server; doc = doc nodes }
let parse_class (attrs, nodes) =
(* All field nodes goes into content *)
let name = Ezxmlm.get_attr "name" attrs in
incr indent;
let index = Ezxmlm.get_attr "index" attrs |> int_of_string in
let fields = Ezxmlm.members_with_attr "field" nodes |> List.map ~f:parse_field in
let methods = Ezxmlm.members_with_attr "method" nodes |> List.map ~f:parse_method in
decr indent;
Class { Class.name; index; content=fields; methods; doc = doc nodes }
let parse = function
| `Data _ -> None
| `El (((_, "constant"), attrs), nodes) -> Some (parse_constant (attrs, nodes))
| `El (((_, "domain"), attrs), nodes) -> Some (parse_domain (attrs, nodes))
| `El (((_, "class"), attrs), nodes) -> Some (parse_class (attrs, nodes))
| `El (((_, name), _), _) -> failwith ("Unknown type: " ^ name)
let parse_amqp xml =
Ezxmlm.member "amqp" xml
|> List.map ~f:parse
|> List.fold_left ~f:(fun acc -> function None -> acc | Some v -> v :: acc) ~init:[]
|> List.rev
let bind_name str =
String.map (function '-' -> '_' | c -> Char.lowercase_ascii c) str
let variant_name str =
bind_name str
|> String.capitalize_ascii
let pvariant_name str =
"`" ^ (variant_name str)
(* Remove domains *)
let emit_domains tree =
let domains = Hashtbl.create 0 in
List.iter ~f:(function
| Domain {Domain.name; amqp_type; doc} when name <> amqp_type ->
Hashtbl.add domains name (amqp_type, doc)
| _ -> ()
) tree;
emit "(* Domains *)";
Hashtbl.iter (fun d (t, doc) ->
emit_doc doc;
emit ~loc:__LINE__ "type %s = %s" (bind_name d) (bind_name t);
) domains;
emit "";
emit "(**/**)";
emit ~loc:__LINE__ "module Internal_alias = struct";
incr indent;
Hashtbl.iter (fun d (t, _) ->
emit "let %s = %s" (bind_name d) (variant_name t);
) domains;
decr indent;
emit "end";
emit "(**/**)";
emit "";
(* Alter the tree *)
let replace lst =
let open Field in
List.map ~f:(fun t ->
let tpe = match Hashtbl.mem domains t.tpe with
| true -> bind_name t.tpe
| false -> variant_name t.tpe
in
{ t with tpe }
) lst
in
let map = function
| Domain _ -> None
| Constant c -> Some (Constant c)
| Class ({ Class.content; methods; _ } as c) ->
let methods =
List.map ~f:(function {Method.arguments; _ } as m ->
{ m with Method.arguments = replace arguments }
) methods
in
Some (Class { c with Class.methods; content = replace content })
in
List.fold_left ~f:(fun acc e -> match map e with Some x -> x :: acc | None -> acc) ~init:[] tree
let emit_constants tree =
emit "(* Constants *)";
List.iter ~f:(function Constant { Constant.name; value; doc } ->
emit_doc doc;
emit ~loc:__LINE__ "let %s = %d" (bind_name name) value | _ -> ()
) tree
let emit_class_index tree =
emit "(* Class index *)";
let idx = ref 0 in
emit ~loc:__LINE__ "let index_of_class = function";
incr indent;
List.iter ~f:(function Class { Class.index; _ } -> emit "| %d -> %d" index !idx; incr idx | _ -> ()) tree;
emit "| _ -> failwith \"Unknown class\"";
decr indent;
emit ~loc:__LINE__ "let classes = %d" !idx
let emit_method_index tree =
emit "(* Class - Method index *)";
let idx = ref 0 in
emit ~loc:__LINE__ "let index_of_class_method = function";
incr indent;
List.iter ~f:(function
| Class { Class.index; methods; _ } ->
emit "| %d -> begin function" index;
incr indent;
List.iter ~f:(fun { Method.index; _ } ->
emit "| %d -> %d" index !idx;
incr idx
) methods;
emit "| _ -> failwith \"Unknown method\"";
emit "end";
decr indent;
| _ -> ()
) tree;
emit "| _ -> failwith \"Unknown class\"";
decr indent;
emit ~loc:__LINE__ "let methods = %d" !idx
let spec_str arguments =
arguments
|> List.map ~f:(fun t -> t.Field.tpe)
|> fun a -> List.append a ["[]"]
|> String.concat " :: "
let emit_method ?(is_content=false) class_index
{ Method.name;
arguments;
response;
content;
index;
synchronous;
client;
server;
doc;
} =
emit_doc doc;
emit ~loc:__LINE__ "module %s = struct" (variant_name name);
incr indent;
let t_args =
arguments
|> List.filter ~f:(fun t -> not t.Field.reserved)
in
let option = if is_content then " option" else "" in
let doc_str = function
| None -> ""
| Some doc -> "(** " ^ doc ^ " *)"
in
let types = List.map ~f:(fun t -> (bind_name t.Field.name), (bind_name t.Field.tpe) ^ option, doc_str t.Field.doc) t_args in
let t_args = match types with
| [] -> "()"
| t -> List.map ~f:(fun (a, _, _) -> a) t |> String.concat "; " |> sprintf "{ %s }"
in
let names =
arguments
|> List.map ~f:(function t when t.Field.reserved -> "_" | t -> bind_name t.Field.name)
in
let values =
arguments
|> List.map ~f:(function
| t when t.Field.reserved ->
"(reserved_value " ^ t.Field.tpe ^ ")"
| t -> bind_name t.Field.name
)
|> String.concat " "
in
(match types with
| [] -> emit ~loc:__LINE__ "type t = unit"
| t ->
emit ~loc:__LINE__ "type t = {";
incr indent;
List.iter ~f:(fun (a, b, doc) -> emit "%s: %s; %s" a b doc) t;
decr indent;
emit "}");
emit "";
emit "(**/**)";
emit ~loc:__LINE__ "module Internal = struct";
incr indent;
emit "open Internal_alias [@@warning \"-33\"]";
if is_content then
emit "open Protocol.Content"
else
emit "open Protocol.Spec";
emit_loc __LINE__;
emit "let spec = %s" (spec_str arguments);
emit "let make %s = %s" (String.concat " " names) t_args;
emit "let apply f %s = f %s" t_args values;
emit "let def = ((%d, %d), spec, make, apply)" class_index index;
begin match is_content, content with
| false, false ->
emit ~loc:__LINE__ "let write = write_method def";
emit ~loc:__LINE__ "let read = read_method def"
| false, true ->
emit ~loc:__LINE__ "let write = write_method_content def Content.Internal.def";
emit ~loc:__LINE__ "let read = read_method_content def Content.Internal.def"
| true, _ ->
()
end;
decr indent;
emit "end";
emit "(**/**)";
emit "";
let inames = List.filter ~f:((<>) "_") names in
begin match is_content with
| true ->
emit ~loc:__LINE__ "let init %s () = Internal.make %s" (List.map ~f:(fun n -> "?" ^ n) inames |> String.concat " ") (String.concat " " inames)
| false ->
emit ~loc:__LINE__ "let init %s () = Internal.make %s" (List.map ~f:(fun n -> "~" ^ n) inames |> String.concat " ") (String.concat " " inames)
end;
let response = List.map ~f:variant_name response in
if List.length response >= 0 && ((synchronous && response != []) || not synchronous) then begin
let id r =
if List.length response > 1 then
"(fun m -> `" ^ r ^ " m)"
else
""
in
if client then
emit ~loc:__LINE__ "let reply = reply%d Internal.read %s"
(List.length response)
(response |> List.map ~f:(fun s -> Printf.sprintf "%s.Internal.write %s" s (id s)) |> String.concat " ");
if server then
emit ~loc:__LINE__ "let request = request%d Internal.write %s"
(List.length response)
(response |> List.map ~f:(fun s -> Printf.sprintf "%s.Internal.read %s" s (id s)) |> String.concat " ");
end;
decr indent;
emit "end";
()
let emit_class { Class.name; content; index; methods; doc } =
(* Reorder modules based on dependencies *)
let rec reorder methods =
let rec move_down = function
| { Method.response; _} as m :: x :: xs when
List.exists ~f:(fun r -> List.exists ~f:(fun {Method.name; _} -> name = r) (x :: xs)) response -> x :: move_down (m :: xs)
| x :: xs -> x :: move_down xs
| [] -> []
in
let ms = move_down methods in
if ms = methods then ms
else reorder ms
in
let methods = reorder methods in
emit_doc doc;
emit ~loc:__LINE__ "module %s = struct" (variant_name name);
incr indent;
if (content != []) then
emit_method ~is_content:true
index { Method.name = "content";
arguments = content;
response = [];
content = false;
must be zero
synchronous = false;
server=false;
client=false;
doc = None;
};
List.iter ~f:(emit_method index) methods;
decr indent;
emit "end";
()
let emit_printer tree =
emit_loc __LINE__;
emit "module Printer = struct";
incr indent;
emit "let id_to_string (cid, mid) =";
incr indent;
emit "match cid with";
incr indent;
List.iter ~f:(function
| Class {Class.name; index; _} ->
emit "| %d -> \"%s\" ^ \", \" ^(%s.method_to_string mid)" index name (variant_name name)
| _ -> ()
) tree;
emit "| _ -> Printf.sprintf \"<%%d>, <%%d>\" mid cid";
decr indent;
decr indent;
decr indent;
emit "end";
()
let emit_specification tree =
emit_loc __LINE__;
emit "open Amqp_client_lib";
emit "open Types";
emit "open Protocol";
emit "open Protocol_helpers";
emit_domains tree
|> List.iter ~f:(function Class x -> emit_class x | _ -> ());
(* emit_printer tree; *)
()
type output = Constants | Specification
let () =
(* Argument parsing *)
let output_type = ref Specification in
let filename = ref "" in
Arg.parse
["-type", Arg.Symbol (["constants"; "specification"],
fun t -> output_type := match t with
| "constants" -> Constants
| "specification" -> Specification
| _ -> failwith "Illegal argument"
), "Type of output";
"-noloc", Arg.Clear emit_location, "Inhibit emission of location pointers"
]
(fun f -> filename := f)
"Generate protocol code";
let xml =
let in_ch = open_in !filename in
let (_, xml) = Ezxmlm.from_channel in_ch in
close_in in_ch;
xml
in
let tree = xml |> parse_amqp in
emit "(** Internal - Low level protocol description *)";
emit "(***********************************)";
emit "(* AUTOGENERATED FILE: DO NOT EDIT *)";
emit "(* %s %s %s %s *)" Sys.argv.(0) Sys.argv.(1) Sys.argv.(2) Sys.argv.(3);
emit "(***********************************)";
emit "";
emit "";
begin
match !output_type with
| Constants ->
emit_constants tree;
()
| Specification -> emit_specification tree
end;
assert (!indent = 0);
()
| null | https://raw.githubusercontent.com/andersfugmann/amqp-client/e6e92225b91742fa8777a02ad9b59a1dde45e752/spec/gen_spec.ml | ocaml | Get last location
Only look at the attributes
All field nodes goes into content
Remove domains
Alter the tree
Reorder modules based on dependencies
emit_printer tree;
Argument parsing | open Printf
module List = ListLabels
let indent = ref 0
let emit_location = ref true
let option_map ~f = function
| Some v -> f v
| None -> None
let option_iter ~f = function
| Some v -> f v
| None -> ()
let emit_loc loc =
match !emit_location with
| true ->
let indent = String.make (!indent * 2) ' ' in
printf "%s(* %s:%d *)\n" indent __FILE__ loc
| false ->
printf "# %d \"%s\"\n" loc __FILE__
let emit ?loc fmt =
option_iter ~f:emit_loc loc;
assert (!indent >= 0);
let indent = String.make (!indent * 2) ' ' in
printf ("%s" ^^ fmt ^^ "\n") indent
let emit_doc = function
| Some doc ->
emit "";
emit "(** %s *)" doc
| None -> ()
module Field = struct
type t = { name: string; tpe: string; reserved: bool; doc: string option }
end
module Constant = struct
type t = { name: string; value: int; doc: string option }
end
module Domain = struct
type t = { name: string; amqp_type: string; doc: string option }
end
module Method = struct
type t = { name: string; arguments: Field.t list;
response: string list; content: bool;
index: int; synchronous: bool; server: bool; client: bool;
doc: string option
}
end
module Class = struct
type t = { name: string; content: Field.t list; index: int;
methods: Method.t list; doc: string option }
end
type elem =
| Constant of Constant.t
| Domain of Domain.t
| Class of Class.t
let blanks = Str.regexp "[ \t\n]+"
let doc xml =
try
Ezxmlm.member "doc" xml
|> Ezxmlm.data_to_string
|> (fun x -> Some x)
with
| Ezxmlm.Tag_not_found _ -> None
let parse_field (attrs, nodes) =
ignore nodes;
let name =
match Ezxmlm.get_attr "name" attrs with
| "type" -> "amqp_type"
| name -> name
in
let tpe =
match Ezxmlm.get_attr "domain" attrs with
| d -> d
| exception Not_found -> Ezxmlm.get_attr "type" attrs
in
let reserved = Ezxmlm.mem_attr "reserved" "1" attrs in
{ Field.name; tpe; reserved; doc = doc nodes }
let parse_constant (attrs, nodes) =
let name = Ezxmlm.get_attr "name" attrs in
let value = Ezxmlm.get_attr "value" attrs |> int_of_string in
Constant { Constant.name; value; doc = doc nodes }
let parse_domain (attrs, nodes) =
ignore nodes;
let name = Ezxmlm.get_attr "name" attrs in
let amqp_type = Ezxmlm.get_attr "type" attrs in
Domain { Domain.name; amqp_type; doc = doc nodes}
let parse_method (attrs, nodes) =
let name = Ezxmlm.get_attr "name" attrs in
incr indent;
let index = Ezxmlm.get_attr "index" attrs |> int_of_string in
let response =
Ezxmlm.members_with_attr "response" nodes
|> List.map ~f:(fun (attrs, _) -> Ezxmlm.get_attr "name" attrs)
in
let synchronous =
match Ezxmlm.get_attr "synchronous" attrs with
| "1" -> true
| _ -> false
| exception Not_found -> false
in
let content =
match Ezxmlm.get_attr "content" attrs with
| "1" -> true
| _ -> false
| exception Not_found -> false
in
let arguments = Ezxmlm.members_with_attr "field" nodes |> List.map ~f:parse_field in
let chassis =
Ezxmlm.members_with_attr "chassis" nodes
|> List.map ~f:(fun (attrs, _) -> Ezxmlm.get_attr "name" attrs)
in
let client = List.mem "client" ~set:chassis in
let server = List.mem "server" ~set:chassis in
decr indent;
{ Method.name; arguments; response; content; index; synchronous;
client; server; doc = doc nodes }
let parse_class (attrs, nodes) =
let name = Ezxmlm.get_attr "name" attrs in
incr indent;
let index = Ezxmlm.get_attr "index" attrs |> int_of_string in
let fields = Ezxmlm.members_with_attr "field" nodes |> List.map ~f:parse_field in
let methods = Ezxmlm.members_with_attr "method" nodes |> List.map ~f:parse_method in
decr indent;
Class { Class.name; index; content=fields; methods; doc = doc nodes }
let parse = function
| `Data _ -> None
| `El (((_, "constant"), attrs), nodes) -> Some (parse_constant (attrs, nodes))
| `El (((_, "domain"), attrs), nodes) -> Some (parse_domain (attrs, nodes))
| `El (((_, "class"), attrs), nodes) -> Some (parse_class (attrs, nodes))
| `El (((_, name), _), _) -> failwith ("Unknown type: " ^ name)
let parse_amqp xml =
Ezxmlm.member "amqp" xml
|> List.map ~f:parse
|> List.fold_left ~f:(fun acc -> function None -> acc | Some v -> v :: acc) ~init:[]
|> List.rev
let bind_name str =
String.map (function '-' -> '_' | c -> Char.lowercase_ascii c) str
let variant_name str =
bind_name str
|> String.capitalize_ascii
let pvariant_name str =
"`" ^ (variant_name str)
let emit_domains tree =
let domains = Hashtbl.create 0 in
List.iter ~f:(function
| Domain {Domain.name; amqp_type; doc} when name <> amqp_type ->
Hashtbl.add domains name (amqp_type, doc)
| _ -> ()
) tree;
emit "(* Domains *)";
Hashtbl.iter (fun d (t, doc) ->
emit_doc doc;
emit ~loc:__LINE__ "type %s = %s" (bind_name d) (bind_name t);
) domains;
emit "";
emit "(**/**)";
emit ~loc:__LINE__ "module Internal_alias = struct";
incr indent;
Hashtbl.iter (fun d (t, _) ->
emit "let %s = %s" (bind_name d) (variant_name t);
) domains;
decr indent;
emit "end";
emit "(**/**)";
emit "";
let replace lst =
let open Field in
List.map ~f:(fun t ->
let tpe = match Hashtbl.mem domains t.tpe with
| true -> bind_name t.tpe
| false -> variant_name t.tpe
in
{ t with tpe }
) lst
in
let map = function
| Domain _ -> None
| Constant c -> Some (Constant c)
| Class ({ Class.content; methods; _ } as c) ->
let methods =
List.map ~f:(function {Method.arguments; _ } as m ->
{ m with Method.arguments = replace arguments }
) methods
in
Some (Class { c with Class.methods; content = replace content })
in
List.fold_left ~f:(fun acc e -> match map e with Some x -> x :: acc | None -> acc) ~init:[] tree
let emit_constants tree =
emit "(* Constants *)";
List.iter ~f:(function Constant { Constant.name; value; doc } ->
emit_doc doc;
emit ~loc:__LINE__ "let %s = %d" (bind_name name) value | _ -> ()
) tree
let emit_class_index tree =
emit "(* Class index *)";
let idx = ref 0 in
emit ~loc:__LINE__ "let index_of_class = function";
incr indent;
List.iter ~f:(function Class { Class.index; _ } -> emit "| %d -> %d" index !idx; incr idx | _ -> ()) tree;
emit "| _ -> failwith \"Unknown class\"";
decr indent;
emit ~loc:__LINE__ "let classes = %d" !idx
let emit_method_index tree =
emit "(* Class - Method index *)";
let idx = ref 0 in
emit ~loc:__LINE__ "let index_of_class_method = function";
incr indent;
List.iter ~f:(function
| Class { Class.index; methods; _ } ->
emit "| %d -> begin function" index;
incr indent;
List.iter ~f:(fun { Method.index; _ } ->
emit "| %d -> %d" index !idx;
incr idx
) methods;
emit "| _ -> failwith \"Unknown method\"";
emit "end";
decr indent;
| _ -> ()
) tree;
emit "| _ -> failwith \"Unknown class\"";
decr indent;
emit ~loc:__LINE__ "let methods = %d" !idx
let spec_str arguments =
arguments
|> List.map ~f:(fun t -> t.Field.tpe)
|> fun a -> List.append a ["[]"]
|> String.concat " :: "
let emit_method ?(is_content=false) class_index
{ Method.name;
arguments;
response;
content;
index;
synchronous;
client;
server;
doc;
} =
emit_doc doc;
emit ~loc:__LINE__ "module %s = struct" (variant_name name);
incr indent;
let t_args =
arguments
|> List.filter ~f:(fun t -> not t.Field.reserved)
in
let option = if is_content then " option" else "" in
let doc_str = function
| None -> ""
| Some doc -> "(** " ^ doc ^ " *)"
in
let types = List.map ~f:(fun t -> (bind_name t.Field.name), (bind_name t.Field.tpe) ^ option, doc_str t.Field.doc) t_args in
let t_args = match types with
| [] -> "()"
| t -> List.map ~f:(fun (a, _, _) -> a) t |> String.concat "; " |> sprintf "{ %s }"
in
let names =
arguments
|> List.map ~f:(function t when t.Field.reserved -> "_" | t -> bind_name t.Field.name)
in
let values =
arguments
|> List.map ~f:(function
| t when t.Field.reserved ->
"(reserved_value " ^ t.Field.tpe ^ ")"
| t -> bind_name t.Field.name
)
|> String.concat " "
in
(match types with
| [] -> emit ~loc:__LINE__ "type t = unit"
| t ->
emit ~loc:__LINE__ "type t = {";
incr indent;
List.iter ~f:(fun (a, b, doc) -> emit "%s: %s; %s" a b doc) t;
decr indent;
emit "}");
emit "";
emit "(**/**)";
emit ~loc:__LINE__ "module Internal = struct";
incr indent;
emit "open Internal_alias [@@warning \"-33\"]";
if is_content then
emit "open Protocol.Content"
else
emit "open Protocol.Spec";
emit_loc __LINE__;
emit "let spec = %s" (spec_str arguments);
emit "let make %s = %s" (String.concat " " names) t_args;
emit "let apply f %s = f %s" t_args values;
emit "let def = ((%d, %d), spec, make, apply)" class_index index;
begin match is_content, content with
| false, false ->
emit ~loc:__LINE__ "let write = write_method def";
emit ~loc:__LINE__ "let read = read_method def"
| false, true ->
emit ~loc:__LINE__ "let write = write_method_content def Content.Internal.def";
emit ~loc:__LINE__ "let read = read_method_content def Content.Internal.def"
| true, _ ->
()
end;
decr indent;
emit "end";
emit "(**/**)";
emit "";
let inames = List.filter ~f:((<>) "_") names in
begin match is_content with
| true ->
emit ~loc:__LINE__ "let init %s () = Internal.make %s" (List.map ~f:(fun n -> "?" ^ n) inames |> String.concat " ") (String.concat " " inames)
| false ->
emit ~loc:__LINE__ "let init %s () = Internal.make %s" (List.map ~f:(fun n -> "~" ^ n) inames |> String.concat " ") (String.concat " " inames)
end;
let response = List.map ~f:variant_name response in
if List.length response >= 0 && ((synchronous && response != []) || not synchronous) then begin
let id r =
if List.length response > 1 then
"(fun m -> `" ^ r ^ " m)"
else
""
in
if client then
emit ~loc:__LINE__ "let reply = reply%d Internal.read %s"
(List.length response)
(response |> List.map ~f:(fun s -> Printf.sprintf "%s.Internal.write %s" s (id s)) |> String.concat " ");
if server then
emit ~loc:__LINE__ "let request = request%d Internal.write %s"
(List.length response)
(response |> List.map ~f:(fun s -> Printf.sprintf "%s.Internal.read %s" s (id s)) |> String.concat " ");
end;
decr indent;
emit "end";
()
let emit_class { Class.name; content; index; methods; doc } =
let rec reorder methods =
let rec move_down = function
| { Method.response; _} as m :: x :: xs when
List.exists ~f:(fun r -> List.exists ~f:(fun {Method.name; _} -> name = r) (x :: xs)) response -> x :: move_down (m :: xs)
| x :: xs -> x :: move_down xs
| [] -> []
in
let ms = move_down methods in
if ms = methods then ms
else reorder ms
in
let methods = reorder methods in
emit_doc doc;
emit ~loc:__LINE__ "module %s = struct" (variant_name name);
incr indent;
if (content != []) then
emit_method ~is_content:true
index { Method.name = "content";
arguments = content;
response = [];
content = false;
must be zero
synchronous = false;
server=false;
client=false;
doc = None;
};
List.iter ~f:(emit_method index) methods;
decr indent;
emit "end";
()
let emit_printer tree =
emit_loc __LINE__;
emit "module Printer = struct";
incr indent;
emit "let id_to_string (cid, mid) =";
incr indent;
emit "match cid with";
incr indent;
List.iter ~f:(function
| Class {Class.name; index; _} ->
emit "| %d -> \"%s\" ^ \", \" ^(%s.method_to_string mid)" index name (variant_name name)
| _ -> ()
) tree;
emit "| _ -> Printf.sprintf \"<%%d>, <%%d>\" mid cid";
decr indent;
decr indent;
decr indent;
emit "end";
()
let emit_specification tree =
emit_loc __LINE__;
emit "open Amqp_client_lib";
emit "open Types";
emit "open Protocol";
emit "open Protocol_helpers";
emit_domains tree
|> List.iter ~f:(function Class x -> emit_class x | _ -> ());
()
type output = Constants | Specification
let () =
let output_type = ref Specification in
let filename = ref "" in
Arg.parse
["-type", Arg.Symbol (["constants"; "specification"],
fun t -> output_type := match t with
| "constants" -> Constants
| "specification" -> Specification
| _ -> failwith "Illegal argument"
), "Type of output";
"-noloc", Arg.Clear emit_location, "Inhibit emission of location pointers"
]
(fun f -> filename := f)
"Generate protocol code";
let xml =
let in_ch = open_in !filename in
let (_, xml) = Ezxmlm.from_channel in_ch in
close_in in_ch;
xml
in
let tree = xml |> parse_amqp in
emit "(** Internal - Low level protocol description *)";
emit "(***********************************)";
emit "(* AUTOGENERATED FILE: DO NOT EDIT *)";
emit "(* %s %s %s %s *)" Sys.argv.(0) Sys.argv.(1) Sys.argv.(2) Sys.argv.(3);
emit "(***********************************)";
emit "";
emit "";
begin
match !output_type with
| Constants ->
emit_constants tree;
()
| Specification -> emit_specification tree
end;
assert (!indent = 0);
()
|
781f4a95f4c67eaaeb1652609aadc5c2f03ec2e7bcaacc382eb9e9f870eb9942 | septract/jstar-old | load_logic.ml | * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
This file is part of jStar
src / parsing / load_logic.ml
Release
$ Release$
Version
$ Rev$
$ Copyright$
jStar is distributed under a BSD license , see ,
LICENSE.txt
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
This file is part of jStar
src/parsing/load_logic.ml
Release
$Release$
Version
$Rev$
$Copyright$
jStar is distributed under a BSD license, see,
LICENSE.txt
********************************************************)
(* File to read a logic file and its imports. *)
open Debug
open Format
open Load
open Psyntax
open System
let load_logic_extra_rules
dirs filename extra_rules
: (Psyntax.sequent_rule list * Psyntax.rewrite_rule list * string list) =
let fileentrys = import_flatten_extra_rules dirs filename extra_rules (Jparser.rule_file Jlexer.token) in
let rl = expand_equiv_rules fileentrys in
let sl,rm,cn =
List.fold_left
(fun (sl,rm,cn) rule ->
match rule with
| ConsDecl(f) -> (sl,rm,f::cn)
| SeqRule(r) -> (r::sl,rm,cn)
| RewriteRule(r) -> (sl,r::rm,cn)
| EquivRule(r) -> assert false)
([], [], [])
rl
in
if log log_load then
fprintf logf "@[<2>Sequent rules%a@." (pp_list pp_sequent_rule) sl;
(sl,rm,cn)
let load_logic_internal
dirs filename
: (sequent_rule list * rewrite_rule list * string list) =
load_logic_extra_rules dirs filename []
let load_logic = load_logic_internal Cli_utils.logic_dirs
let load_abstractions = load_logic_internal Cli_utils.abs_dirs
| null | https://raw.githubusercontent.com/septract/jstar-old/c3b4fc6c1efc098efcdb864edbf0c666130f5fe5/src/parsing/load_logic.ml | ocaml | File to read a logic file and its imports. | * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
This file is part of jStar
src / parsing / load_logic.ml
Release
$ Release$
Version
$ Rev$
$ Copyright$
jStar is distributed under a BSD license , see ,
LICENSE.txt
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
This file is part of jStar
src/parsing/load_logic.ml
Release
$Release$
Version
$Rev$
$Copyright$
jStar is distributed under a BSD license, see,
LICENSE.txt
********************************************************)
open Debug
open Format
open Load
open Psyntax
open System
let load_logic_extra_rules
dirs filename extra_rules
: (Psyntax.sequent_rule list * Psyntax.rewrite_rule list * string list) =
let fileentrys = import_flatten_extra_rules dirs filename extra_rules (Jparser.rule_file Jlexer.token) in
let rl = expand_equiv_rules fileentrys in
let sl,rm,cn =
List.fold_left
(fun (sl,rm,cn) rule ->
match rule with
| ConsDecl(f) -> (sl,rm,f::cn)
| SeqRule(r) -> (r::sl,rm,cn)
| RewriteRule(r) -> (sl,r::rm,cn)
| EquivRule(r) -> assert false)
([], [], [])
rl
in
if log log_load then
fprintf logf "@[<2>Sequent rules%a@." (pp_list pp_sequent_rule) sl;
(sl,rm,cn)
let load_logic_internal
dirs filename
: (sequent_rule list * rewrite_rule list * string list) =
load_logic_extra_rules dirs filename []
let load_logic = load_logic_internal Cli_utils.logic_dirs
let load_abstractions = load_logic_internal Cli_utils.abs_dirs
|
f892384dd4780399cd5c45928dd05a4f61d27608e32a51d6b80b7f329fb462b2 | kdltr/chicken-core | environment-tests.scm | ;;;; environment-tests.scm
(import (chicken load))
(load-relative "test.scm")
(test-begin "evaluation environment tests")
(test-equal (eval 123) 123)
(test-equal (eval 123 (interaction-environment)) 123)
(test-equal (eval 'car (interaction-environment)) car)
(test-error (eval 'foo (interaction-environment)))
(test-equal (eval '(begin (set! foo 99) foo) (interaction-environment)) 99)
(test-equal (eval 123) 123)
(test-equal (eval 123 (scheme-report-environment 5)) 123)
(test-equal (eval 'car (scheme-report-environment 5)) car)
(test-error (eval 'foo (scheme-report-environment 5)))
(test-error (eval 'values (scheme-report-environment 4)))
(test-equal (eval 'values (scheme-report-environment 5)) values)
(test-error (eval '(set! foo 99) (scheme-report-environment 5)))
(test-error (eval '(define-syntax foo (syntax-rules () ((_) 1)))
(scheme-report-environment 5)))
(test-error (eval 'car (null-environment 5)))
(test-error (eval '(cond-expand (chicken 1) (else 2)) (null-environment 4)))
(test-error (eval '(cond-expand (chicken 1) (else 2)) (null-environment 5)))
(test-error (eval '(cond-expand (chicken 1) (else 2)) (scheme-report-environment 4)))
(test-error (eval '(cond-expand (chicken 1) (else 2)) (scheme-report-environment 5)))
(test-equal 1 (eval '(if #t 1 2) (scheme-report-environment 5)))
(test-equal 1 (eval '(if #t 1 2) (null-environment 4)))
(test-equal 1 (eval '(if #t 1 2) (null-environment 5)))
(test-equal (eval '((lambda (x) x) 123) (null-environment 5)) 123)
(import (chicken eval))
(define baz 100)
(module foo (bar)
(import r5rs)
(define (bar) 99))
(define foo-env (module-environment 'foo))
(define csi-env (module-environment '(chicken csi)))
(define format-env (module-environment 'chicken.format))
(test-equal (eval '(bar) foo-env) 99)
(test-error (eval 'baz foo-env))
(test-equal (eval '(editor-command) csi-env) #f)
(test-error (eval 'baz csi-env))
(test-equal (eval '(format "~a" 1) format-env) "1")
(test-error (eval 'baz format-env))
(test-end)
(test-exit)
| null | https://raw.githubusercontent.com/kdltr/chicken-core/b2e6c5243dd469064bec947cb3b49dafaa1514e5/tests/environment-tests.scm | scheme | environment-tests.scm |
(import (chicken load))
(load-relative "test.scm")
(test-begin "evaluation environment tests")
(test-equal (eval 123) 123)
(test-equal (eval 123 (interaction-environment)) 123)
(test-equal (eval 'car (interaction-environment)) car)
(test-error (eval 'foo (interaction-environment)))
(test-equal (eval '(begin (set! foo 99) foo) (interaction-environment)) 99)
(test-equal (eval 123) 123)
(test-equal (eval 123 (scheme-report-environment 5)) 123)
(test-equal (eval 'car (scheme-report-environment 5)) car)
(test-error (eval 'foo (scheme-report-environment 5)))
(test-error (eval 'values (scheme-report-environment 4)))
(test-equal (eval 'values (scheme-report-environment 5)) values)
(test-error (eval '(set! foo 99) (scheme-report-environment 5)))
(test-error (eval '(define-syntax foo (syntax-rules () ((_) 1)))
(scheme-report-environment 5)))
(test-error (eval 'car (null-environment 5)))
(test-error (eval '(cond-expand (chicken 1) (else 2)) (null-environment 4)))
(test-error (eval '(cond-expand (chicken 1) (else 2)) (null-environment 5)))
(test-error (eval '(cond-expand (chicken 1) (else 2)) (scheme-report-environment 4)))
(test-error (eval '(cond-expand (chicken 1) (else 2)) (scheme-report-environment 5)))
(test-equal 1 (eval '(if #t 1 2) (scheme-report-environment 5)))
(test-equal 1 (eval '(if #t 1 2) (null-environment 4)))
(test-equal 1 (eval '(if #t 1 2) (null-environment 5)))
(test-equal (eval '((lambda (x) x) 123) (null-environment 5)) 123)
(import (chicken eval))
(define baz 100)
(module foo (bar)
(import r5rs)
(define (bar) 99))
(define foo-env (module-environment 'foo))
(define csi-env (module-environment '(chicken csi)))
(define format-env (module-environment 'chicken.format))
(test-equal (eval '(bar) foo-env) 99)
(test-error (eval 'baz foo-env))
(test-equal (eval '(editor-command) csi-env) #f)
(test-error (eval 'baz csi-env))
(test-equal (eval '(format "~a" 1) format-env) "1")
(test-error (eval 'baz format-env))
(test-end)
(test-exit)
|
df9a97f909864c4c00be1d80c8ab164bd16115896fcde2e1e832039ff30e39c5 | nextjournal/clerk | ssr.cljs | (ns ssr
"Dev helper to run server-side-rendering using Node.
Use this to iterate on it, then make sure the advanced bundle works
in Graal via `nextjournal.clerk.ssr`."
(:require ["./../public/js/viewer.js" :as viewer]
the above is the dev build , the one below the relase ( generate it via ` bb release : js ` )
#_["./../build/viewer.js" :as viewer]
[babashka.cli :as cli]
[promesa.core :as p]
[nbb.core :refer [slurp]]))
(defn -main [& args]
(p/let [{:keys [file edn url]} (:opts (cli/parse-args args {:alias {:u :url :f :file}}))
edn-string (cond file (slurp file)
edn edn)]
(if edn-string
(println (js/nextjournal.clerk.static_app.ssr edn-string))
(binding [*out* *err*]
(println "must provide --file or --edn arg")))))
| null | https://raw.githubusercontent.com/nextjournal/clerk/2b192241c686a351f542f15462e5af7cb9632ed5/ui_tests/ssr.cljs | clojure | (ns ssr
"Dev helper to run server-side-rendering using Node.
Use this to iterate on it, then make sure the advanced bundle works
in Graal via `nextjournal.clerk.ssr`."
(:require ["./../public/js/viewer.js" :as viewer]
the above is the dev build , the one below the relase ( generate it via ` bb release : js ` )
#_["./../build/viewer.js" :as viewer]
[babashka.cli :as cli]
[promesa.core :as p]
[nbb.core :refer [slurp]]))
(defn -main [& args]
(p/let [{:keys [file edn url]} (:opts (cli/parse-args args {:alias {:u :url :f :file}}))
edn-string (cond file (slurp file)
edn edn)]
(if edn-string
(println (js/nextjournal.clerk.static_app.ssr edn-string))
(binding [*out* *err*]
(println "must provide --file or --edn arg")))))
| |
809d1f50e4399c7dc9c7cc5eacbaad5652babc4351a680ce53e85b14cdb85788 | privet-kitty/cl-competitive | eratosthenes.lisp | (defpackage :cp/eratosthenes
(:use :cl)
(:export #:make-prime-table #:make-prime-sequence #:prime-data #:make-prime-data
#:prime-data-seq #:prime-data-table #:prime-data-p
#:factorize #:make-omega-table))
(in-package :cp/eratosthenes)
(eval-when (:compile-toplevel :load-toplevel :execute)
(assert (= sb-vm:n-word-bits 64)))
(declaim (ftype (function * (values simple-bit-vector &optional)) make-prime-table))
(defun make-prime-table (length)
"Returns a simple-bit-vector of LENGTH, whose (0-based) i-th bit is 1 if i is
prime and 0 otherwise.
Example: (make-prime-table 10) => #*0011010100"
(declare (optimize (speed 3) (safety 0)))
(check-type length (mod #.array-dimension-limit))
(when (<= length 1)
(return-from make-prime-table
(make-array length :element-type 'bit :initial-element 0)))
(let ((table (make-array length :element-type 'bit :initial-element 0)))
special treatment for p = 2
(when (> length 2)
(dotimes (i (ceiling length 64))
(setf (sb-kernel:%vector-raw-bits table i) #xAAAAAAAAAAAAAAAA)))
(setf (sbit table 1) 0
(sbit table 2) 1)
p > = 3
(loop for p from 3 to (+ 1 (isqrt (- length 1))) by 2
when (= 1 (sbit table p))
do (loop for composite from (* p p) below length by p
do (setf (sbit table composite) 0)))
table))
(declaim (ftype (function * (values (simple-array (integer 0 #.most-positive-fixnum) (*))
simple-bit-vector
&optional))
make-prime-sequence))
(defun make-prime-sequence (length)
"Returns the ascending sequence of primes smaller than LENGTH. Internally
calls MAKE-PRIME-TABLE and returns its result as the second value."
(declare (optimize (speed 3) (safety 0)))
(check-type length (mod #.array-dimension-limit))
(let* ((table (make-prime-table length))
(pnumber (count 1 table))
(result (make-array pnumber :element-type '(integer 0 #.most-positive-fixnum)))
(index 0))
(loop for x below length
when (= 1 (sbit table x))
do (setf (aref result index) x)
(incf index))
(values result table)))
(defstruct (prime-data (:constructor %make-prime-data (seq table))
(:copier nil))
(seq nil :type (simple-array (integer 0 #.most-positive-fixnum) (*)))
(table nil :type simple-bit-vector))
(defun make-prime-data (length)
(multiple-value-call #'%make-prime-data (make-prime-sequence length)))
(declaim (inline factorize)
(ftype (function * (values list list &optional)) factorize))
(defun factorize (x prime-data)
"Returns the associative list of prime factors of X, which is composed
of (<prime> . <exponent>). E.g. (factorize 40 <prime-table>) => '((2 . 3) (5
. 1)).
- Any numbers beyond the range of PRIME-DATA are regarded as prime.
- The returned list is in ascending order w.r.t. prime factors."
(declare (integer x))
(let* ((x (abs x))
(prime-seq (prime-data-seq prime-data))
(result (load-time-value (list :root)))
(tail result))
(labels ((add (x)
(setf (cdr tail) (list x)
tail (cdr tail))))
(loop for prime of-type unsigned-byte across prime-seq
until (= x 1)
do (loop for exponent of-type (integer 0 #.most-positive-fixnum) from 0
do (multiple-value-bind (quot rem) (floor x prime)
(unless (zerop rem)
(when (> exponent 0)
(add (cons prime exponent)))
(return))
(setq x quot)))
finally (unless (= x 1)
(add (cons x 1))))
(multiple-value-prog1 (values (cdr result)
(if (eq result tail) nil tail))
(setf (cdr result) nil)))))
(defun make-omega-table (length prime-data)
"Returns the table of prime omega function on {0, 1, ..., LENGTH-1}."
(declare ((unsigned-byte 31) length))
( assert ( > = ( ( aref prime - seq ( - ( length prime - seq ) 1 ) ) 2 ) ( - length 1 ) ) )
(let ((prime-seq (prime-data-seq prime-data))
(table (make-array length :element-type '(unsigned-byte 31)))
(res (make-array length :element-type '(unsigned-byte 8))))
(dotimes (i (length table))
(setf (aref table i) i))
(loop for p of-type (integer 0 #.most-positive-fixnum) across prime-seq
do (loop for i from p below length by p
do (loop
(multiple-value-bind (quot rem) (floor (aref table i) p)
(unless (zerop rem)
(return))
(incf (aref res i))
(setf (aref table i) quot)))))
(loop for i below length
unless (= 1 (aref table i))
do (incf (aref res i)))
res))
| null | https://raw.githubusercontent.com/privet-kitty/cl-competitive/876b3be1c42480deec735ad845604af1e0af4469/module/eratosthenes.lisp | lisp | (defpackage :cp/eratosthenes
(:use :cl)
(:export #:make-prime-table #:make-prime-sequence #:prime-data #:make-prime-data
#:prime-data-seq #:prime-data-table #:prime-data-p
#:factorize #:make-omega-table))
(in-package :cp/eratosthenes)
(eval-when (:compile-toplevel :load-toplevel :execute)
(assert (= sb-vm:n-word-bits 64)))
(declaim (ftype (function * (values simple-bit-vector &optional)) make-prime-table))
(defun make-prime-table (length)
"Returns a simple-bit-vector of LENGTH, whose (0-based) i-th bit is 1 if i is
prime and 0 otherwise.
Example: (make-prime-table 10) => #*0011010100"
(declare (optimize (speed 3) (safety 0)))
(check-type length (mod #.array-dimension-limit))
(when (<= length 1)
(return-from make-prime-table
(make-array length :element-type 'bit :initial-element 0)))
(let ((table (make-array length :element-type 'bit :initial-element 0)))
special treatment for p = 2
(when (> length 2)
(dotimes (i (ceiling length 64))
(setf (sb-kernel:%vector-raw-bits table i) #xAAAAAAAAAAAAAAAA)))
(setf (sbit table 1) 0
(sbit table 2) 1)
p > = 3
(loop for p from 3 to (+ 1 (isqrt (- length 1))) by 2
when (= 1 (sbit table p))
do (loop for composite from (* p p) below length by p
do (setf (sbit table composite) 0)))
table))
(declaim (ftype (function * (values (simple-array (integer 0 #.most-positive-fixnum) (*))
simple-bit-vector
&optional))
make-prime-sequence))
(defun make-prime-sequence (length)
"Returns the ascending sequence of primes smaller than LENGTH. Internally
calls MAKE-PRIME-TABLE and returns its result as the second value."
(declare (optimize (speed 3) (safety 0)))
(check-type length (mod #.array-dimension-limit))
(let* ((table (make-prime-table length))
(pnumber (count 1 table))
(result (make-array pnumber :element-type '(integer 0 #.most-positive-fixnum)))
(index 0))
(loop for x below length
when (= 1 (sbit table x))
do (setf (aref result index) x)
(incf index))
(values result table)))
(defstruct (prime-data (:constructor %make-prime-data (seq table))
(:copier nil))
(seq nil :type (simple-array (integer 0 #.most-positive-fixnum) (*)))
(table nil :type simple-bit-vector))
(defun make-prime-data (length)
(multiple-value-call #'%make-prime-data (make-prime-sequence length)))
(declaim (inline factorize)
(ftype (function * (values list list &optional)) factorize))
(defun factorize (x prime-data)
"Returns the associative list of prime factors of X, which is composed
of (<prime> . <exponent>). E.g. (factorize 40 <prime-table>) => '((2 . 3) (5
. 1)).
- Any numbers beyond the range of PRIME-DATA are regarded as prime.
- The returned list is in ascending order w.r.t. prime factors."
(declare (integer x))
(let* ((x (abs x))
(prime-seq (prime-data-seq prime-data))
(result (load-time-value (list :root)))
(tail result))
(labels ((add (x)
(setf (cdr tail) (list x)
tail (cdr tail))))
(loop for prime of-type unsigned-byte across prime-seq
until (= x 1)
do (loop for exponent of-type (integer 0 #.most-positive-fixnum) from 0
do (multiple-value-bind (quot rem) (floor x prime)
(unless (zerop rem)
(when (> exponent 0)
(add (cons prime exponent)))
(return))
(setq x quot)))
finally (unless (= x 1)
(add (cons x 1))))
(multiple-value-prog1 (values (cdr result)
(if (eq result tail) nil tail))
(setf (cdr result) nil)))))
(defun make-omega-table (length prime-data)
"Returns the table of prime omega function on {0, 1, ..., LENGTH-1}."
(declare ((unsigned-byte 31) length))
( assert ( > = ( ( aref prime - seq ( - ( length prime - seq ) 1 ) ) 2 ) ( - length 1 ) ) )
(let ((prime-seq (prime-data-seq prime-data))
(table (make-array length :element-type '(unsigned-byte 31)))
(res (make-array length :element-type '(unsigned-byte 8))))
(dotimes (i (length table))
(setf (aref table i) i))
(loop for p of-type (integer 0 #.most-positive-fixnum) across prime-seq
do (loop for i from p below length by p
do (loop
(multiple-value-bind (quot rem) (floor (aref table i) p)
(unless (zerop rem)
(return))
(incf (aref res i))
(setf (aref table i) quot)))))
(loop for i below length
unless (= 1 (aref table i))
do (incf (aref res i)))
res))
| |
1fe0d706a91d5785fee04cb5c02bf7b3e02b51435577ee2d60467062221a439b | lemaetech/reparse | json.ml | * Implement JSON parser as defined at .
Assumes UTF-8 character encoding . However , it does n't do any validation .
Note : It is unknown if the parser fully conforms to RFC 8259 as no testing ,
validation is done . The RFC is used mainly as a guidance and the sample is
meant to demonstrate parser construction using reparse rather than a
production grade parser .
Sample top_level inputs ;
{ v
parse " true " ; ; parse " false " ; ;
parse " null " ; ; parse " 123 " ; ;
parse " 123.345 " ; ;
parse " 123e123 " ; ;
parse " 123.33E123 " ; ;
parse { |{"field1":123,"field2 " : " value2"}| } ; ;
parse { |{"field1":[123,"hello",-123.23 ] , " field2":123 } | } ; ;
parse { |{"field1":123 , " field2":123 } | } ; ;
parse { |[123,"hello",-123.23 , 123.33e13 , 123E23 ] | } ; ;
v }
Assumes UTF-8 character encoding. However, it doesn't do any validation.
Note: It is unknown if the parser fully conforms to RFC 8259 as no testing,
validation is done. The RFC is used mainly as a guidance and the sample is
meant to demonstrate parser construction using reparse rather than a
production grade parser.
Sample top_level inputs;
{v
parse "true";; parse "false";;
parse "null";; parse "123";;
parse "123.345";;
parse "123e123";;
parse "123.33E123";;
parse {|{"field1":123,"field2": "value2"}|};;
parse {|{"field1":[123,"hello",-123.23], "field2":123} |};;
parse {|{"field1":123, "field2":123} |};;
parse {|[123,"hello",-123.23, 123.33e13, 123E23] |};;
v} *)
open Reparse.String
type value =
| Object of (string * value) list
| Array of value list
| Number of
{negative: bool; int: string; frac: string option; exponent: string option}
| String of string
| False
| True
| Null
let ws =
skip (char_if (function ' ' | '\t' | '\n' | '\r' -> true | _ -> false))
let struct_char c = ws *> char c <* ws
let null_value = ws *> string_cs "null" *> ws *> return Null
let false_value = ws *> string_cs "false" *> ws *> return False
let true_value = ws *> string_cs "true" *> ws *> return True
let number_value =
let* negative =
optional (char '-') >>| function Some '-' -> true | _ -> false
in
let* int =
let digits1_to_9 = char_if (function '1' .. '9' -> true | _ -> false) in
let num =
map2
(fun first_ch digits -> Format.sprintf "%c%s" first_ch digits)
digits1_to_9 digits
in
any [string_cs "0"; num]
in
let* frac = optional (char '.' *> digits) in
let+ exponent =
optional
(let* e = char 'E' <|> char 'e' in
let* sign = optional (char '-' <|> char '+') in
let sign =
match sign with Some c -> Format.sprintf "%c" c | None -> ""
in
let+ digits = digits in
Format.sprintf "%c%s%s" e sign digits )
in
Number {negative; int; frac; exponent}
let string =
let escaped =
let ch =
char '\\'
*> char_if (function
| '"' | '\\' | '/' | 'b' | 'f' | 'n' | 'r' | 't' -> true
| _ -> false )
>>| Format.sprintf "\\%c"
in
let hex4digit =
let+ hex =
string_cs "\\u" *> take ~at_least:4 ~up_to:4 hex_digit
>>= string_of_chars
in
Format.sprintf "\\u%s" hex
in
any [ch; hex4digit]
in
let unescaped =
take_while ~while_:(is_not (any [char '\\'; control; dquote])) any_char
>>= string_of_chars
in
let+ str = dquote *> take (any [escaped; unescaped]) <* dquote in
String.concat "" str
let string_value = string >>| fun s -> String s
let json_value =
recur (fun value ->
let value_sep = struct_char ',' in
let object_value =
let member =
let* nm = string <* struct_char ':' in
let+ v = value in
(nm, v)
in
let+ object_value =
struct_char '{' *> take member ~sep_by:value_sep <* struct_char '}'
in
Object object_value
in
let array_value =
let+ vals =
struct_char '[' *> take value ~sep_by:value_sep <* struct_char ']'
in
Array vals
in
any
[ object_value
; array_value
; number_value
; string_value
; false_value
; true_value
; null_value ] )
let parse s = parse s json_value
------------------------------------------------------------------------- *
Copyright ( c ) 2020 . All rights reserved . * * This Source Code
Form is subject to the terms of the Mozilla Public * License , v. 2.0 . If a
copy of the MPL was not distributed with this * file , You can obtain one at
/. * * % % NAME%% % % * -------------------------------------------------------------------------
Copyright (c) 2020 Bikal Gurung. All rights reserved. * * This Source Code
Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a
copy of the MPL was not distributed with this * file, You can obtain one at
/. * * %%NAME%% %%VERSION%%
*-------------------------------------------------------------------------*)
| null | https://raw.githubusercontent.com/lemaetech/reparse/0b9096cf3e4779813f8b82d5a0ba5d82035cca0e/examples/json.ml | ocaml | * Implement JSON parser as defined at .
Assumes UTF-8 character encoding . However , it does n't do any validation .
Note : It is unknown if the parser fully conforms to RFC 8259 as no testing ,
validation is done . The RFC is used mainly as a guidance and the sample is
meant to demonstrate parser construction using reparse rather than a
production grade parser .
Sample top_level inputs ;
{ v
parse " true " ; ; parse " false " ; ;
parse " null " ; ; parse " 123 " ; ;
parse " 123.345 " ; ;
parse " 123e123 " ; ;
parse " 123.33E123 " ; ;
parse { |{"field1":123,"field2 " : " value2"}| } ; ;
parse { |{"field1":[123,"hello",-123.23 ] , " field2":123 } | } ; ;
parse { |{"field1":123 , " field2":123 } | } ; ;
parse { |[123,"hello",-123.23 , 123.33e13 , 123E23 ] | } ; ;
v }
Assumes UTF-8 character encoding. However, it doesn't do any validation.
Note: It is unknown if the parser fully conforms to RFC 8259 as no testing,
validation is done. The RFC is used mainly as a guidance and the sample is
meant to demonstrate parser construction using reparse rather than a
production grade parser.
Sample top_level inputs;
{v
parse "true";; parse "false";;
parse "null";; parse "123";;
parse "123.345";;
parse "123e123";;
parse "123.33E123";;
parse {|{"field1":123,"field2": "value2"}|};;
parse {|{"field1":[123,"hello",-123.23], "field2":123} |};;
parse {|{"field1":123, "field2":123} |};;
parse {|[123,"hello",-123.23, 123.33e13, 123E23] |};;
v} *)
open Reparse.String
type value =
| Object of (string * value) list
| Array of value list
| Number of
{negative: bool; int: string; frac: string option; exponent: string option}
| String of string
| False
| True
| Null
let ws =
skip (char_if (function ' ' | '\t' | '\n' | '\r' -> true | _ -> false))
let struct_char c = ws *> char c <* ws
let null_value = ws *> string_cs "null" *> ws *> return Null
let false_value = ws *> string_cs "false" *> ws *> return False
let true_value = ws *> string_cs "true" *> ws *> return True
let number_value =
let* negative =
optional (char '-') >>| function Some '-' -> true | _ -> false
in
let* int =
let digits1_to_9 = char_if (function '1' .. '9' -> true | _ -> false) in
let num =
map2
(fun first_ch digits -> Format.sprintf "%c%s" first_ch digits)
digits1_to_9 digits
in
any [string_cs "0"; num]
in
let* frac = optional (char '.' *> digits) in
let+ exponent =
optional
(let* e = char 'E' <|> char 'e' in
let* sign = optional (char '-' <|> char '+') in
let sign =
match sign with Some c -> Format.sprintf "%c" c | None -> ""
in
let+ digits = digits in
Format.sprintf "%c%s%s" e sign digits )
in
Number {negative; int; frac; exponent}
let string =
let escaped =
let ch =
char '\\'
*> char_if (function
| '"' | '\\' | '/' | 'b' | 'f' | 'n' | 'r' | 't' -> true
| _ -> false )
>>| Format.sprintf "\\%c"
in
let hex4digit =
let+ hex =
string_cs "\\u" *> take ~at_least:4 ~up_to:4 hex_digit
>>= string_of_chars
in
Format.sprintf "\\u%s" hex
in
any [ch; hex4digit]
in
let unescaped =
take_while ~while_:(is_not (any [char '\\'; control; dquote])) any_char
>>= string_of_chars
in
let+ str = dquote *> take (any [escaped; unescaped]) <* dquote in
String.concat "" str
let string_value = string >>| fun s -> String s
let json_value =
recur (fun value ->
let value_sep = struct_char ',' in
let object_value =
let member =
let* nm = string <* struct_char ':' in
let+ v = value in
(nm, v)
in
let+ object_value =
struct_char '{' *> take member ~sep_by:value_sep <* struct_char '}'
in
Object object_value
in
let array_value =
let+ vals =
struct_char '[' *> take value ~sep_by:value_sep <* struct_char ']'
in
Array vals
in
any
[ object_value
; array_value
; number_value
; string_value
; false_value
; true_value
; null_value ] )
let parse s = parse s json_value
------------------------------------------------------------------------- *
Copyright ( c ) 2020 . All rights reserved . * * This Source Code
Form is subject to the terms of the Mozilla Public * License , v. 2.0 . If a
copy of the MPL was not distributed with this * file , You can obtain one at
/. * * % % NAME%% % % * -------------------------------------------------------------------------
Copyright (c) 2020 Bikal Gurung. All rights reserved. * * This Source Code
Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a
copy of the MPL was not distributed with this * file, You can obtain one at
/. * * %%NAME%% %%VERSION%%
*-------------------------------------------------------------------------*)
| |
f81b90cc78228364e80bd9e688827b27394dca66193989efdd12d81032089cb8 | Workiva/eva | data_readers.clj | Copyright 2015 - 2019 Workiva Inc.
;;
;; Licensed under the Eclipse Public License 1.0 (the "License");
;; you may not use this file except in compliance with the License.
;; You may obtain a copy of the License at
;;
;; -1.0.php
;;
;; 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.
{db/id eva.readers/read-db-id
db/fn eva.readers/read-db-fn}
| null | https://raw.githubusercontent.com/Workiva/eva/b7b8a6a5215cccb507a92aa67e0168dc777ffeac/core/resources/data_readers.clj | clojure |
Licensed under the Eclipse Public License 1.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
-1.0.php
Unless required by applicable law or agreed to in writing, software
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License. | Copyright 2015 - 2019 Workiva Inc.
distributed under the License is distributed on an " AS IS " BASIS ,
{db/id eva.readers/read-db-id
db/fn eva.readers/read-db-fn}
|
598c3e628a4448f33948bdf70b8f357076b44c73e438672bbd718fdfe3a77432 | timothyrenner/turbine | routes_test.clj | (ns turbine.routes-test
(:require [clojure.core.async :refer [<!! >!! chan]]
[turbine.routes :refer :all]
[turbine.core :refer :all]
[clojure.test :refer :all]))
(deftest xform-aliases-test
(testing "Properly extracts aliases from a fan-out route specifier."
(is (= {:out1 :xform1 :out2 :xform2}
(xform-aliases [:scatter :in1 [[:out1 :xform1]
[:out2 :xform2]]]))))
(testing "Properly extracts aliases from a fan-in route specifier."
(is (= {:out1 :xform1}
(xform-aliases [:union [:in1 :in2] [:out1 :xform1]]))))
(testing "Properly extracts aliases from a sink route specifier."
(is (= {} (xform-aliases [:sink :out1 :println]))))
(testing "Properly extracts aliases from an input route specifier."
(is (= {:in1 :xform1}
(xform-aliases [:in :in1 :xform1])))))
| null | https://raw.githubusercontent.com/timothyrenner/turbine/cabe7f3aa156878218cab621ebb85adad47afe0f/test/turbine/routes_test.clj | clojure | (ns turbine.routes-test
(:require [clojure.core.async :refer [<!! >!! chan]]
[turbine.routes :refer :all]
[turbine.core :refer :all]
[clojure.test :refer :all]))
(deftest xform-aliases-test
(testing "Properly extracts aliases from a fan-out route specifier."
(is (= {:out1 :xform1 :out2 :xform2}
(xform-aliases [:scatter :in1 [[:out1 :xform1]
[:out2 :xform2]]]))))
(testing "Properly extracts aliases from a fan-in route specifier."
(is (= {:out1 :xform1}
(xform-aliases [:union [:in1 :in2] [:out1 :xform1]]))))
(testing "Properly extracts aliases from a sink route specifier."
(is (= {} (xform-aliases [:sink :out1 :println]))))
(testing "Properly extracts aliases from an input route specifier."
(is (= {:in1 :xform1}
(xform-aliases [:in :in1 :xform1])))))
| |
92cd97b1870e706fbd8414b60a699aca03ab28d650df574d7298db50a234b77a | AntidoteDB/antidote | antidote_crdt_counter_b.erl | %% -------------------------------------------------------------------
%%
Copyright < 2013 - 2018 > <
Technische Universität Kaiserslautern , Germany
, France
Universidade NOVA de Lisboa , Portugal
Université catholique de Louvain ( UCL ) , Belgique
, Portugal
%% >
%%
This file is provided to you under the Apache License ,
%% Version 2.0 (the "License"); you may not use this file
except in compliance with the License . You may obtain
%% a copy of the License at
%%
%% -2.0
%%
%% Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
" AS IS " BASIS , WITHOUT WARRANTIES OR CONDITIONS OF ANY
%% KIND, either expressed or implied. See the License for the
%% specific language governing permissions and limitations
%% under the License.
%%
List of the contributors to the development of Antidote : see file .
%% Description and complete License: see LICENSE file.
%% @doc
An operation based implementation of the bounded counter CRDT .
%% This counter is able to maintain a non-negative value by
%% explicitly exchanging permissions to execute decrement operations.
All operations on this CRDT are monotonic and do not keep extra tombstones .
%%
%% In the code, the variable `V' is used for a positive integer.
%% In the code, the variable `P' is used for `transfers()' which is a defined type.
%% In the code, the variable `D' is used for `decrements()' which is a defined type.
%% @end
-module(antidote_crdt_counter_b).
-behaviour(antidote_crdt).
-include("antidote_crdt.hrl").
%% Call backs
-export([
new/0,
value/1,
downstream/2,
update/2,
equal/2,
to_binary/1,
from_binary/1,
is_operation/1,
require_state_downstream/1,
generate_downstream_check/4
]).
%% API
-export([
local_permissions/2,
permissions/1
]).
-ifdef(TEST).
-include_lib("eunit/include/eunit.hrl").
-endif.
%% A replica's identifier.
-type id() :: term().
%% The orddict that maps
-type transfers() :: orddict:orddict({id(), id()}, pos_integer()).
-type decrements() :: orddict:orddict(id(), pos_integer()).
-type antidote_crdt_counter_b() :: {transfers(), decrements()}.
-type antidote_crdt_counter_b_op() ::
{increment | decrement, {pos_integer(), id()}} | {transfer, {pos_integer(), id(), id()}}.
-type antidote_crdt_counter_b_effect() :: {
{increment | decrement, pos_integer()} | {transfer, pos_integer(), id()}, id()
}.
%% @doc Return a new, empty `antidote_crdt_counter_b()'.
-spec new() -> antidote_crdt_counter_b().
new() ->
{orddict:new(), orddict:new()}.
%% @doc Return the available permissions of replica `Id' in a `antidote_crdt_counter_b()'.
-spec local_permissions(id(), antidote_crdt_counter_b()) -> non_neg_integer().
local_permissions(Id, {P, D}) ->
Received = orddict:fold(
fun(_, V, Acc) ->
Acc + V
end,
0,
orddict:filter(
fun
({_, ToId}, _) when ToId == Id ->
true;
(_, _) ->
false
end,
P
)
),
Granted = orddict:fold(
fun(_, V, Acc) ->
Acc + V
end,
0,
orddict:filter(
fun
({FromId, ToId}, _) when FromId == Id andalso ToId /= Id ->
true;
(_, _) ->
false
end,
P
)
),
case orddict:find(Id, D) of
{ok, Decrements} ->
Received - Granted - Decrements;
error ->
Received - Granted
end.
%% @doc Return the total available permissions in a `antidote_crdt_counter_b()'.
-spec permissions(antidote_crdt_counter_b()) -> non_neg_integer().
permissions({P, D}) ->
TotalIncrements = orddict:fold(
fun
({K, K}, V, Acc) ->
V + Acc;
(_, _, Acc) ->
Acc
end,
0,
P
),
TotalDecrements = orddict:fold(
fun(_, V, Acc) ->
V + Acc
end,
0,
D
),
TotalIncrements - TotalDecrements.
%% @doc Return the read value of a given `antidote_crdt_counter_b()', itself.
-spec value(antidote_crdt_counter_b()) -> antidote_crdt_counter_b().
value(Counter) -> Counter.
%% @doc Generate a downstream operation.
The first parameter is either ` { increment , ( ) } ' or ` { decrement , ( ) } ' ,
which specify the operation and amount , or ` { transfer , ( ) , i d ( ) } '
%% that additionally specifies the target replica.
The second parameter is an ` actor ( ) ' who identifies the source replica ,
and the third parameter is a ` antidote_crdt_counter_b ( ) ' which holds the current snapshot .
%%
%% Returns a tuple containing the operation and source replica.
%% This operation fails and returns `{error, no_permissions}'
%% if it tries to consume resources unavailable to the source replica
%% (which prevents logging of forbidden attempts).
-spec downstream(antidote_crdt_counter_b_op(), antidote_crdt_counter_b()) ->
{ok, antidote_crdt_counter_b_effect()} | {error, no_permissions}.
downstream({increment, {V, Actor}}, _Counter) when is_integer(V), V > 0 ->
{ok, {{increment, V}, Actor}};
downstream({decrement, {V, Actor}}, Counter) when is_integer(V), V > 0 ->
generate_downstream_check({decrement, V}, Actor, Counter, V);
downstream({transfer, {V, ToId, Actor}}, Counter) when is_integer(V), V > 0 ->
generate_downstream_check({transfer, V, ToId}, Actor, Counter, V).
generate_downstream_check(Op, Actor, Counter, V) ->
Available = local_permissions(Actor, Counter),
if
Available >= V -> {ok, {Op, Actor}};
Available < V -> {error, no_permissions}
end.
%% @doc Update a `antidote_crdt_counter_b()' with a downstream operation,
%% usually created with `generate_downstream'.
%%
%% Return the resulting `antidote_crdt_counter_b()' after applying the operation.
-spec update(antidote_crdt_counter_b_effect(), antidote_crdt_counter_b()) ->
{ok, antidote_crdt_counter_b()}.
update({{increment, V}, Id}, Counter) ->
increment(Id, V, Counter);
update({{decrement, V}, Id}, Counter) ->
decrement(Id, V, Counter);
update({{transfer, V, ToId}, FromId}, Counter) ->
transfer(FromId, ToId, V, Counter).
%% Add a given amount of permissions to a replica.
-spec increment(id(), pos_integer(), antidote_crdt_counter_b()) -> {ok, antidote_crdt_counter_b()}.
increment(Id, V, {P, D}) ->
{ok, {orddict:update_counter({Id, Id}, V, P), D}}.
%% Consume a given amount of permissions from a replica.
-spec decrement(id(), pos_integer(), antidote_crdt_counter_b()) -> {ok, antidote_crdt_counter_b()}.
decrement(Id, V, {P, D}) ->
{ok, {P, orddict:update_counter(Id, V, D)}}.
Transfer a given amount of permissions from one replica to another .
-spec transfer(id(), id(), pos_integer(), antidote_crdt_counter_b()) ->
{ok, antidote_crdt_counter_b()}.
transfer(FromId, ToId, V, {P, D}) ->
{ok, {orddict:update_counter({FromId, ToId}, V, P), D}}.
%% doc Return the binary representation of a `antidote_crdt_counter_b()'.
-spec to_binary(antidote_crdt_counter_b()) -> binary().
to_binary(C) -> term_to_binary(C).
%% doc Return a `antidote_crdt_counter_b()' from its binary representation.
-spec from_binary(binary()) -> {ok, antidote_crdt_counter_b()}.
from_binary(<<B/binary>>) -> {ok, binary_to_term(B)}.
%% @doc The following operation verifies
that Operation is supported by this particular CRDT .
-spec is_operation(term()) -> boolean().
is_operation({increment, {V, _Actor}}) -> is_pos_integer(V);
is_operation({decrement, {V, _Actor}}) -> is_pos_integer(V);
is_operation({transfer, {V, _, _Actor}}) -> is_pos_integer(V);
is_operation(_) -> false.
-spec is_pos_integer(term()) -> boolean().
is_pos_integer(V) -> is_integer(V) andalso (V > 0).
%% The antidote_crdt_counter_b requires no state downstream for increment.
-spec require_state_downstream(antidote_crdt_counter_b_op()) -> boolean().
require_state_downstream({increment, {_, _}}) ->
false;
require_state_downstream(_) ->
true.
%% Checks equality.
Since all contents of the antidote_crdt_counter_b are ordered ( two orddicts )
%% they will be equal if the content is equal.
-spec equal(antidote_crdt_counter_b(), antidote_crdt_counter_b()) -> boolean().
equal(BCounter1, BCounter2) ->
BCounter1 == BCounter2.
%% ===================================================================
EUnit tests
%% ===================================================================
-ifdef(TEST).
%% Utility to generate and apply downstream operations.
apply_op(Op, Counter) ->
{ok, OP_DS} = downstream(Op, Counter),
{ok, NewCounter} = update(OP_DS, Counter),
NewCounter.
%% Tests creating a new `antidote_crdt_counter_b()'.
new_test() ->
?assertEqual({orddict:new(), orddict:new()}, new()).
%% Tests increment operations.
increment_test() ->
Counter0 = new(),
Counter1 = apply_op({increment, {10, r1}}, Counter0),
Counter2 = apply_op({increment, {5, r2}}, Counter1),
%% Test replicas' values.
?assertEqual(5, local_permissions(r2, Counter2)),
?assertEqual(10, local_permissions(r1, Counter2)),
%% Test total value.
?assertEqual(15, permissions(Counter2)).
%% Tests the function `local_permissions()'.
local_permissions_test() ->
Counter0 = new(),
Counter1 = apply_op({increment, {10, r1}}, Counter0),
%% Test replica with positive amount of permissions.
?assertEqual(10, local_permissions(r1, Counter1)),
%% Test nonexistent replica.
?assertEqual(0, local_permissions(r2, Counter1)).
%% Tests decrement operations.
decrement_test() ->
Counter0 = new(),
Counter1 = apply_op({increment, {10, r1}}, Counter0),
%% Test allowed decrement.
Counter2 = apply_op({decrement, {6, r1}}, Counter1),
?assertEqual(4, permissions(Counter2)),
%% Test nonexistent replica.
?assertEqual(0, local_permissions(r2, Counter1)),
%% Test forbidden decrement.
OP_DS = downstream({decrement, {6, r1}}, Counter2),
?assertEqual({error, no_permissions}, OP_DS).
%% Tests a more complex chain of increment and decrement operations.
decrement_increment_test() ->
Counter0 = new(),
Counter1 = apply_op({increment, {10, r1}}, Counter0),
Counter2 = apply_op({decrement, {6, r1}}, Counter1),
Counter3 = apply_op({increment, {6, r2}}, Counter2),
%% Test several replicas (balance each other).
?assertEqual(10, permissions(Counter3)),
%% Test forbidden permissions, when total is higher than consumed.
OP_DS = downstream({decrement, {6, r1}}, Counter3),
?assertEqual({error, no_permissions}, OP_DS),
%% Test the same operation is allowed on another replica with enough permissions.
Counter4 = apply_op({decrement, {6, r2}}, Counter3),
?assertEqual(4, permissions(Counter4)).
%% Tests transferring permissions.
transfer_test() ->
Counter0 = new(),
Counter1 = apply_op({increment, {10, r1}}, Counter0),
Test transferring permissions from one replica to another .
Counter2 = apply_op({transfer, {6, r2, r1}}, Counter1),
?assertEqual(4, local_permissions(r1, Counter2)),
?assertEqual(6, local_permissions(r2, Counter2)),
?assertEqual(10, permissions(Counter2)),
%% Test transference forbidden by lack of previously transfered resources.
OP_DS = downstream({transfer, {5, r2, r1}}, Counter2),
?assertEqual({error, no_permissions}, OP_DS),
%% Test transference enabled by previously transfered resources.
Counter3 = apply_op({transfer, {5, r1, r2}}, Counter2),
?assertEqual(9, local_permissions(r1, Counter3)),
?assertEqual(1, local_permissions(r2, Counter3)),
?assertEqual(10, permissions(Counter3)).
%% Tests the function `value()'.
value_test() ->
%% Test on `antidote_crdt_counter_b()' resulting from applying all kinds of operation.
Counter0 = new(),
Counter1 = apply_op({increment, {10, r1}}, Counter0),
Counter2 = apply_op({decrement, {6, r1}}, Counter1),
Counter3 = apply_op({transfer, {2, r2, r1}}, Counter2),
%% Assert `value()' returns `antidote_crdt_counter_b()' itself.
?assertEqual(Counter3, value(Counter3)).
transfer_to_self_is_is_not_allowed_if_not_enough_local_permissions_exist_test() ->
Counter0 = new(),
Counter1 = apply_op({increment, {8, r1}}, Counter0),
DownstreamResult = downstream({transfer, {10, r1, r1}}, Counter1),
?assertEqual({error, no_permissions}, DownstreamResult).
transfer_to_self_is_increment_if_enough_local_permissions_exist_test() ->
Counter0 = new(),
Counter1 = apply_op({increment, {10, r1}}, Counter0),
Counter2 = apply_op({increment, {10, r1}}, Counter0),
Counter3 = apply_op({increment, {10, r1}}, Counter1),
Counter4 = apply_op({transfer, {10, r1, r1}}, Counter2),
?assertEqual(Counter3, Counter4).
%% Tests serialization functions `to_binary()' and `from_binary()'.
binary_test() ->
%% Test on `antidote_crdt_counter_b()' resulting from applying all kinds of operation.
Counter0 = new(),
Counter1 = apply_op({increment, {10, r1}}, Counter0),
Counter2 = apply_op({decrement, {6, r1}}, Counter1),
Counter3 = apply_op({transfer, {2, r2, r1}}, Counter2),
%% Assert marshaling and unmarshaling holds the same `antidote_crdt_counter_b()'.
B = to_binary(Counter3),
?assertEqual({ok, Counter3}, from_binary(B)).
%% Tests that operations are correctly detected.
is_operation_test() ->
?assertEqual(true, is_operation({transfer, {2, r2, r1}})),
?assertEqual(true, is_operation({increment, {50, r1}})),
?assertEqual(false, is_operation(increment)),
?assertEqual(true, is_operation({decrement, {50, r1}})),
?assertEqual(false, is_operation(decrement)),
?assertEqual(false, is_operation({anything, [1, 2, 3]})).
-endif.
| null | https://raw.githubusercontent.com/AntidoteDB/antidote/32a89d42be644d3ba616ebf705fce4fa43e781ab/apps/antidote_crdt/src/antidote_crdt_counter_b.erl | erlang | -------------------------------------------------------------------
>
Version 2.0 (the "License"); you may not use this file
a copy of the License at
-2.0
Unless required by applicable law or agreed to in writing,
KIND, either expressed or implied. See the License for the
specific language governing permissions and limitations
under the License.
Description and complete License: see LICENSE file.
@doc
This counter is able to maintain a non-negative value by
explicitly exchanging permissions to execute decrement operations.
In the code, the variable `V' is used for a positive integer.
In the code, the variable `P' is used for `transfers()' which is a defined type.
In the code, the variable `D' is used for `decrements()' which is a defined type.
@end
Call backs
API
A replica's identifier.
The orddict that maps
@doc Return a new, empty `antidote_crdt_counter_b()'.
@doc Return the available permissions of replica `Id' in a `antidote_crdt_counter_b()'.
@doc Return the total available permissions in a `antidote_crdt_counter_b()'.
@doc Return the read value of a given `antidote_crdt_counter_b()', itself.
@doc Generate a downstream operation.
that additionally specifies the target replica.
Returns a tuple containing the operation and source replica.
This operation fails and returns `{error, no_permissions}'
if it tries to consume resources unavailable to the source replica
(which prevents logging of forbidden attempts).
@doc Update a `antidote_crdt_counter_b()' with a downstream operation,
usually created with `generate_downstream'.
Return the resulting `antidote_crdt_counter_b()' after applying the operation.
Add a given amount of permissions to a replica.
Consume a given amount of permissions from a replica.
doc Return the binary representation of a `antidote_crdt_counter_b()'.
doc Return a `antidote_crdt_counter_b()' from its binary representation.
@doc The following operation verifies
The antidote_crdt_counter_b requires no state downstream for increment.
Checks equality.
they will be equal if the content is equal.
===================================================================
===================================================================
Utility to generate and apply downstream operations.
Tests creating a new `antidote_crdt_counter_b()'.
Tests increment operations.
Test replicas' values.
Test total value.
Tests the function `local_permissions()'.
Test replica with positive amount of permissions.
Test nonexistent replica.
Tests decrement operations.
Test allowed decrement.
Test nonexistent replica.
Test forbidden decrement.
Tests a more complex chain of increment and decrement operations.
Test several replicas (balance each other).
Test forbidden permissions, when total is higher than consumed.
Test the same operation is allowed on another replica with enough permissions.
Tests transferring permissions.
Test transference forbidden by lack of previously transfered resources.
Test transference enabled by previously transfered resources.
Tests the function `value()'.
Test on `antidote_crdt_counter_b()' resulting from applying all kinds of operation.
Assert `value()' returns `antidote_crdt_counter_b()' itself.
Tests serialization functions `to_binary()' and `from_binary()'.
Test on `antidote_crdt_counter_b()' resulting from applying all kinds of operation.
Assert marshaling and unmarshaling holds the same `antidote_crdt_counter_b()'.
Tests that operations are correctly detected. | Copyright < 2013 - 2018 > <
Technische Universität Kaiserslautern , Germany
, France
Universidade NOVA de Lisboa , Portugal
Université catholique de Louvain ( UCL ) , Belgique
, Portugal
This file is provided to you under the Apache License ,
except in compliance with the License . You may obtain
software distributed under the License is distributed on an
" AS IS " BASIS , WITHOUT WARRANTIES OR CONDITIONS OF ANY
List of the contributors to the development of Antidote : see file .
An operation based implementation of the bounded counter CRDT .
All operations on this CRDT are monotonic and do not keep extra tombstones .
-module(antidote_crdt_counter_b).
-behaviour(antidote_crdt).
-include("antidote_crdt.hrl").
-export([
new/0,
value/1,
downstream/2,
update/2,
equal/2,
to_binary/1,
from_binary/1,
is_operation/1,
require_state_downstream/1,
generate_downstream_check/4
]).
-export([
local_permissions/2,
permissions/1
]).
-ifdef(TEST).
-include_lib("eunit/include/eunit.hrl").
-endif.
-type id() :: term().
-type transfers() :: orddict:orddict({id(), id()}, pos_integer()).
-type decrements() :: orddict:orddict(id(), pos_integer()).
-type antidote_crdt_counter_b() :: {transfers(), decrements()}.
-type antidote_crdt_counter_b_op() ::
{increment | decrement, {pos_integer(), id()}} | {transfer, {pos_integer(), id(), id()}}.
-type antidote_crdt_counter_b_effect() :: {
{increment | decrement, pos_integer()} | {transfer, pos_integer(), id()}, id()
}.
-spec new() -> antidote_crdt_counter_b().
new() ->
{orddict:new(), orddict:new()}.
-spec local_permissions(id(), antidote_crdt_counter_b()) -> non_neg_integer().
local_permissions(Id, {P, D}) ->
Received = orddict:fold(
fun(_, V, Acc) ->
Acc + V
end,
0,
orddict:filter(
fun
({_, ToId}, _) when ToId == Id ->
true;
(_, _) ->
false
end,
P
)
),
Granted = orddict:fold(
fun(_, V, Acc) ->
Acc + V
end,
0,
orddict:filter(
fun
({FromId, ToId}, _) when FromId == Id andalso ToId /= Id ->
true;
(_, _) ->
false
end,
P
)
),
case orddict:find(Id, D) of
{ok, Decrements} ->
Received - Granted - Decrements;
error ->
Received - Granted
end.
-spec permissions(antidote_crdt_counter_b()) -> non_neg_integer().
permissions({P, D}) ->
TotalIncrements = orddict:fold(
fun
({K, K}, V, Acc) ->
V + Acc;
(_, _, Acc) ->
Acc
end,
0,
P
),
TotalDecrements = orddict:fold(
fun(_, V, Acc) ->
V + Acc
end,
0,
D
),
TotalIncrements - TotalDecrements.
-spec value(antidote_crdt_counter_b()) -> antidote_crdt_counter_b().
value(Counter) -> Counter.
The first parameter is either ` { increment , ( ) } ' or ` { decrement , ( ) } ' ,
which specify the operation and amount , or ` { transfer , ( ) , i d ( ) } '
The second parameter is an ` actor ( ) ' who identifies the source replica ,
and the third parameter is a ` antidote_crdt_counter_b ( ) ' which holds the current snapshot .
-spec downstream(antidote_crdt_counter_b_op(), antidote_crdt_counter_b()) ->
{ok, antidote_crdt_counter_b_effect()} | {error, no_permissions}.
downstream({increment, {V, Actor}}, _Counter) when is_integer(V), V > 0 ->
{ok, {{increment, V}, Actor}};
downstream({decrement, {V, Actor}}, Counter) when is_integer(V), V > 0 ->
generate_downstream_check({decrement, V}, Actor, Counter, V);
downstream({transfer, {V, ToId, Actor}}, Counter) when is_integer(V), V > 0 ->
generate_downstream_check({transfer, V, ToId}, Actor, Counter, V).
generate_downstream_check(Op, Actor, Counter, V) ->
Available = local_permissions(Actor, Counter),
if
Available >= V -> {ok, {Op, Actor}};
Available < V -> {error, no_permissions}
end.
-spec update(antidote_crdt_counter_b_effect(), antidote_crdt_counter_b()) ->
{ok, antidote_crdt_counter_b()}.
update({{increment, V}, Id}, Counter) ->
increment(Id, V, Counter);
update({{decrement, V}, Id}, Counter) ->
decrement(Id, V, Counter);
update({{transfer, V, ToId}, FromId}, Counter) ->
transfer(FromId, ToId, V, Counter).
-spec increment(id(), pos_integer(), antidote_crdt_counter_b()) -> {ok, antidote_crdt_counter_b()}.
increment(Id, V, {P, D}) ->
{ok, {orddict:update_counter({Id, Id}, V, P), D}}.
-spec decrement(id(), pos_integer(), antidote_crdt_counter_b()) -> {ok, antidote_crdt_counter_b()}.
decrement(Id, V, {P, D}) ->
{ok, {P, orddict:update_counter(Id, V, D)}}.
Transfer a given amount of permissions from one replica to another .
-spec transfer(id(), id(), pos_integer(), antidote_crdt_counter_b()) ->
{ok, antidote_crdt_counter_b()}.
transfer(FromId, ToId, V, {P, D}) ->
{ok, {orddict:update_counter({FromId, ToId}, V, P), D}}.
-spec to_binary(antidote_crdt_counter_b()) -> binary().
to_binary(C) -> term_to_binary(C).
-spec from_binary(binary()) -> {ok, antidote_crdt_counter_b()}.
from_binary(<<B/binary>>) -> {ok, binary_to_term(B)}.
that Operation is supported by this particular CRDT .
-spec is_operation(term()) -> boolean().
is_operation({increment, {V, _Actor}}) -> is_pos_integer(V);
is_operation({decrement, {V, _Actor}}) -> is_pos_integer(V);
is_operation({transfer, {V, _, _Actor}}) -> is_pos_integer(V);
is_operation(_) -> false.
-spec is_pos_integer(term()) -> boolean().
is_pos_integer(V) -> is_integer(V) andalso (V > 0).
-spec require_state_downstream(antidote_crdt_counter_b_op()) -> boolean().
require_state_downstream({increment, {_, _}}) ->
false;
require_state_downstream(_) ->
true.
Since all contents of the antidote_crdt_counter_b are ordered ( two orddicts )
-spec equal(antidote_crdt_counter_b(), antidote_crdt_counter_b()) -> boolean().
equal(BCounter1, BCounter2) ->
BCounter1 == BCounter2.
EUnit tests
-ifdef(TEST).
apply_op(Op, Counter) ->
{ok, OP_DS} = downstream(Op, Counter),
{ok, NewCounter} = update(OP_DS, Counter),
NewCounter.
new_test() ->
?assertEqual({orddict:new(), orddict:new()}, new()).
increment_test() ->
Counter0 = new(),
Counter1 = apply_op({increment, {10, r1}}, Counter0),
Counter2 = apply_op({increment, {5, r2}}, Counter1),
?assertEqual(5, local_permissions(r2, Counter2)),
?assertEqual(10, local_permissions(r1, Counter2)),
?assertEqual(15, permissions(Counter2)).
local_permissions_test() ->
Counter0 = new(),
Counter1 = apply_op({increment, {10, r1}}, Counter0),
?assertEqual(10, local_permissions(r1, Counter1)),
?assertEqual(0, local_permissions(r2, Counter1)).
decrement_test() ->
Counter0 = new(),
Counter1 = apply_op({increment, {10, r1}}, Counter0),
Counter2 = apply_op({decrement, {6, r1}}, Counter1),
?assertEqual(4, permissions(Counter2)),
?assertEqual(0, local_permissions(r2, Counter1)),
OP_DS = downstream({decrement, {6, r1}}, Counter2),
?assertEqual({error, no_permissions}, OP_DS).
decrement_increment_test() ->
Counter0 = new(),
Counter1 = apply_op({increment, {10, r1}}, Counter0),
Counter2 = apply_op({decrement, {6, r1}}, Counter1),
Counter3 = apply_op({increment, {6, r2}}, Counter2),
?assertEqual(10, permissions(Counter3)),
OP_DS = downstream({decrement, {6, r1}}, Counter3),
?assertEqual({error, no_permissions}, OP_DS),
Counter4 = apply_op({decrement, {6, r2}}, Counter3),
?assertEqual(4, permissions(Counter4)).
transfer_test() ->
Counter0 = new(),
Counter1 = apply_op({increment, {10, r1}}, Counter0),
Test transferring permissions from one replica to another .
Counter2 = apply_op({transfer, {6, r2, r1}}, Counter1),
?assertEqual(4, local_permissions(r1, Counter2)),
?assertEqual(6, local_permissions(r2, Counter2)),
?assertEqual(10, permissions(Counter2)),
OP_DS = downstream({transfer, {5, r2, r1}}, Counter2),
?assertEqual({error, no_permissions}, OP_DS),
Counter3 = apply_op({transfer, {5, r1, r2}}, Counter2),
?assertEqual(9, local_permissions(r1, Counter3)),
?assertEqual(1, local_permissions(r2, Counter3)),
?assertEqual(10, permissions(Counter3)).
value_test() ->
Counter0 = new(),
Counter1 = apply_op({increment, {10, r1}}, Counter0),
Counter2 = apply_op({decrement, {6, r1}}, Counter1),
Counter3 = apply_op({transfer, {2, r2, r1}}, Counter2),
?assertEqual(Counter3, value(Counter3)).
transfer_to_self_is_is_not_allowed_if_not_enough_local_permissions_exist_test() ->
Counter0 = new(),
Counter1 = apply_op({increment, {8, r1}}, Counter0),
DownstreamResult = downstream({transfer, {10, r1, r1}}, Counter1),
?assertEqual({error, no_permissions}, DownstreamResult).
transfer_to_self_is_increment_if_enough_local_permissions_exist_test() ->
Counter0 = new(),
Counter1 = apply_op({increment, {10, r1}}, Counter0),
Counter2 = apply_op({increment, {10, r1}}, Counter0),
Counter3 = apply_op({increment, {10, r1}}, Counter1),
Counter4 = apply_op({transfer, {10, r1, r1}}, Counter2),
?assertEqual(Counter3, Counter4).
binary_test() ->
Counter0 = new(),
Counter1 = apply_op({increment, {10, r1}}, Counter0),
Counter2 = apply_op({decrement, {6, r1}}, Counter1),
Counter3 = apply_op({transfer, {2, r2, r1}}, Counter2),
B = to_binary(Counter3),
?assertEqual({ok, Counter3}, from_binary(B)).
is_operation_test() ->
?assertEqual(true, is_operation({transfer, {2, r2, r1}})),
?assertEqual(true, is_operation({increment, {50, r1}})),
?assertEqual(false, is_operation(increment)),
?assertEqual(true, is_operation({decrement, {50, r1}})),
?assertEqual(false, is_operation(decrement)),
?assertEqual(false, is_operation({anything, [1, 2, 3]})).
-endif.
|
f4cdbb3f871222e531aac47c7b9b380683506992b209190b000d44477ad31f58 | davidlazar/ocaml-semantics | match-or05.ml | match (4,2) with ((a,b) | (b,a)) -> b / a | _ -> 1
| null | https://raw.githubusercontent.com/davidlazar/ocaml-semantics/6f302c6b9cced0407d501d70ad25c2d2aefbb77d/tests/unit/match-or05.ml | ocaml | match (4,2) with ((a,b) | (b,a)) -> b / a | _ -> 1
| |
eeee21de8cf2c031a56a2598918f18d819c08e7b5436f73007bd7afb3cedf717 | elastic/eui-cljs | use_mouse_move.cljs | (ns eui.services.use-mouse-move
(:require ["@elastic/eui/lib/services/hooks/useMouseMove.js" :as eui]))
(def useMouseMove eui/useMouseMove)
(def isMouseEvent eui/isMouseEvent)
| null | https://raw.githubusercontent.com/elastic/eui-cljs/ad60b57470a2eb8db9bca050e02f52dd964d9f8e/src/eui/services/use_mouse_move.cljs | clojure | (ns eui.services.use-mouse-move
(:require ["@elastic/eui/lib/services/hooks/useMouseMove.js" :as eui]))
(def useMouseMove eui/useMouseMove)
(def isMouseEvent eui/isMouseEvent)
| |
6270e5e89e37e94ddc6d092c25a761a4dd4bff9e667826e13cd6c6a2095bf43f | dtgoitia/civil-autolisp | SelectAlongPolyline.lsp | ; (defun c:xx ()
; ; Trigger
( DT : AutoLoadFileFromCivilTemp " SelectAlongPolyline.lsp " )
( c : )
;
; v0.0 - 2017.08.16 - First issue
; Author :
; Last revision : 2017.08.16
; )
(defun c:SelectAlongPolyline ( / ename entList )
Command version of DT :
(if (setq ename (car (entsel "\nSelect polyline of reference: ")))
(progn
(DT:SelectAlongPolyline ename)
);END progn
);END if
v0.0 - 2017.08.16 - First issue
Author :
Last revision : 2017.08.16
)
(defun DT:SelectAlongPolyline ( ename / vertexList )
; Select objects along ename polyline (using "F" mode selection)
(if (DT:Arg 'DT:SelectAlongPolyline '((ename 'ename)))
(progn
; Remove objects crossed by ename
(if (setq vertexList (DT:GetLwpolyPoints ename))
(if (setq ss (ssget "CP" vertexList))
(sssetfirst nil ss)
);END if
);END if
);END progn
);END if
v0.0 - 2017.08.16 - First issue
Author :
Last revision : 2017.08.16
)
| null | https://raw.githubusercontent.com/dtgoitia/civil-autolisp/72d68139d372c84014d160f8e4918f062356349f/Dump%20folder/SelectAlongPolyline.lsp | lisp | (defun c:xx ()
; Trigger
v0.0 - 2017.08.16 - First issue
Author :
Last revision : 2017.08.16
)
END progn
END if
Select objects along ename polyline (using "F" mode selection)
Remove objects crossed by ename
END if
END if
END progn
END if | ( DT : AutoLoadFileFromCivilTemp " SelectAlongPolyline.lsp " )
( c : )
(defun c:SelectAlongPolyline ( / ename entList )
Command version of DT :
(if (setq ename (car (entsel "\nSelect polyline of reference: ")))
(progn
(DT:SelectAlongPolyline ename)
v0.0 - 2017.08.16 - First issue
Author :
Last revision : 2017.08.16
)
(defun DT:SelectAlongPolyline ( ename / vertexList )
(if (DT:Arg 'DT:SelectAlongPolyline '((ename 'ename)))
(progn
(if (setq vertexList (DT:GetLwpolyPoints ename))
(if (setq ss (ssget "CP" vertexList))
(sssetfirst nil ss)
v0.0 - 2017.08.16 - First issue
Author :
Last revision : 2017.08.16
)
|
584ec866b9a9d383c4fa100c5c5437c59f08c549631ba09ef928edd85560abea | JoelSanchez/ventas | crud_table.cljs | (ns ventas.components.crud-table
"Implementation of ventas.components.table for the most common and boring
use of it."
(:require
[re-frame.core :as rf]
[ventas.i18n :refer [i18n]]
[ventas.components.base :as base]
[ventas.server.api.admin :as api.admin]
[ventas.routes :as routes]
[ventas.components.table :as table]
[ventas.i18n :as i18n]))
(def state-key ::state)
(rf/reg-event-fx
::remove
(fn [_ [_ state-path id]]
{:pre [state-path id]}
{:dispatch [::api.admin/admin.entities.remove
{:params {:id id}
:success [::remove.next state-path id]}]}))
(rf/reg-event-db
::remove.next
(fn [db [_ state-path id]]
(update-in db
(conj state-path :rows)
(fn [items]
(remove #(= (:id %) id)
items)))))
(defn action-column-component [state-path {:keys [id]}]
[:div
[base/button {:icon true
:on-click #(rf/dispatch [::remove state-path id])}
[base/icon {:name "remove"}]]])
(defn action-column [state-path]
{:id :actions
:label (i18n ::actions)
:component (partial #'action-column-component state-path)
:width 110})
(defn- footer [edit-route]
[base/button {:on-click #(routes/go-to edit-route :id 0)}
(i18n ::create)])
(rf/reg-event-fx
::fetch
(fn [{:keys [db]} [_ entity-type state-path]]
(let [{:keys [page items-per-page sort-direction sort-column]} (table/get-state db state-path)]
{:dispatch [::api.admin/admin.entities.list
{:success [::fetch.next state-path]
:params {:type entity-type
:pagination {:page page
:items-per-page items-per-page}
:sorting {:direction sort-direction
:field sort-column}}}]})))
(rf/reg-event-db
::fetch.next
(fn [db [_ state-path {:keys [items total]}]]
(-> db
(assoc-in (conj state-path :rows) items)
(assoc-in (conj state-path :total) total))))
(rf/reg-event-fx
::init
(fn [{:keys [db]} [_ state-path {:keys [columns edit-route entity-type]} extra-config]]
{:db (assoc-in db state-path nil)
:dispatch [::table/init state-path
(merge {:fetch-fx [::fetch entity-type]
:columns columns
:footer (partial footer edit-route)}
extra-config)]}))
(i18n/register-translations!
{:en_US {::actions "Actions"
::create "Create"
::submit "Submit"}
:es_ES {::actions "Acciones"
::create "Nuevo"
::submit "Enviar"}}) | null | https://raw.githubusercontent.com/JoelSanchez/ventas/dc8fc8ff9f63dfc8558ecdaacfc4983903b8e9a1/src/cljs/ventas/components/crud_table.cljs | clojure | (ns ventas.components.crud-table
"Implementation of ventas.components.table for the most common and boring
use of it."
(:require
[re-frame.core :as rf]
[ventas.i18n :refer [i18n]]
[ventas.components.base :as base]
[ventas.server.api.admin :as api.admin]
[ventas.routes :as routes]
[ventas.components.table :as table]
[ventas.i18n :as i18n]))
(def state-key ::state)
(rf/reg-event-fx
::remove
(fn [_ [_ state-path id]]
{:pre [state-path id]}
{:dispatch [::api.admin/admin.entities.remove
{:params {:id id}
:success [::remove.next state-path id]}]}))
(rf/reg-event-db
::remove.next
(fn [db [_ state-path id]]
(update-in db
(conj state-path :rows)
(fn [items]
(remove #(= (:id %) id)
items)))))
(defn action-column-component [state-path {:keys [id]}]
[:div
[base/button {:icon true
:on-click #(rf/dispatch [::remove state-path id])}
[base/icon {:name "remove"}]]])
(defn action-column [state-path]
{:id :actions
:label (i18n ::actions)
:component (partial #'action-column-component state-path)
:width 110})
(defn- footer [edit-route]
[base/button {:on-click #(routes/go-to edit-route :id 0)}
(i18n ::create)])
(rf/reg-event-fx
::fetch
(fn [{:keys [db]} [_ entity-type state-path]]
(let [{:keys [page items-per-page sort-direction sort-column]} (table/get-state db state-path)]
{:dispatch [::api.admin/admin.entities.list
{:success [::fetch.next state-path]
:params {:type entity-type
:pagination {:page page
:items-per-page items-per-page}
:sorting {:direction sort-direction
:field sort-column}}}]})))
(rf/reg-event-db
::fetch.next
(fn [db [_ state-path {:keys [items total]}]]
(-> db
(assoc-in (conj state-path :rows) items)
(assoc-in (conj state-path :total) total))))
(rf/reg-event-fx
::init
(fn [{:keys [db]} [_ state-path {:keys [columns edit-route entity-type]} extra-config]]
{:db (assoc-in db state-path nil)
:dispatch [::table/init state-path
(merge {:fetch-fx [::fetch entity-type]
:columns columns
:footer (partial footer edit-route)}
extra-config)]}))
(i18n/register-translations!
{:en_US {::actions "Actions"
::create "Create"
::submit "Submit"}
:es_ES {::actions "Acciones"
::create "Nuevo"
::submit "Enviar"}}) | |
1c98bee1c5a28ab6456b82efa27b41db97664385bb23ea86aa79e90d01476e30 | ds-wizard/engine-backend | Api.hs | module Registry.Api.Handler.Package.Api where
import Servant
import Registry.Api.Handler.Package.Detail_Bundle_GET
import Registry.Api.Handler.Package.Detail_GET
import Registry.Api.Handler.Package.List_Bundle_POST
import Registry.Api.Handler.Package.List_GET
import Registry.Model.Context.BaseContext
type PackageAPI =
List_GET
:<|> List_Bundle_POST
:<|> Detail_GET
:<|> Detail_Bundle_GET
packageApi :: Proxy PackageAPI
packageApi = Proxy
packageServer :: ServerT PackageAPI BaseContextM
packageServer = list_GET :<|> list_bundle_POST :<|> detail_GET :<|> detail_bundle_GET
| null | https://raw.githubusercontent.com/ds-wizard/engine-backend/a76d04c3dc5e0a3cb52303c90272f8deb24d28ae/engine-registry/src/Registry/Api/Handler/Package/Api.hs | haskell | module Registry.Api.Handler.Package.Api where
import Servant
import Registry.Api.Handler.Package.Detail_Bundle_GET
import Registry.Api.Handler.Package.Detail_GET
import Registry.Api.Handler.Package.List_Bundle_POST
import Registry.Api.Handler.Package.List_GET
import Registry.Model.Context.BaseContext
type PackageAPI =
List_GET
:<|> List_Bundle_POST
:<|> Detail_GET
:<|> Detail_Bundle_GET
packageApi :: Proxy PackageAPI
packageApi = Proxy
packageServer :: ServerT PackageAPI BaseContextM
packageServer = list_GET :<|> list_bundle_POST :<|> detail_GET :<|> detail_bundle_GET
| |
45199d991f553703556b271c92ccd347fef202c3b9a94e4faf859d4e450c7abc | ericclack/overtone-loops | sticks1.clj | (ns overtone-loops.music.sticks1
(:use [overtone.live]
[overtone.inst.synth]
[overtone-loops.loops]
[overtone-loops.samples]))
(set-up)
;; 1 e & a 2 e & a 3 e & a 4 e & a
(defloop sticks 1/4 stick [8 _ _ _ 6 _ _ 6 _ _ 6 _ _ 6 _ _ ])
(defloop kicks 1 kick [8 8 8 8 ])
(defloop clicks 1/4 finger [_ _ _ 3 _ _ 4 _ _ 3 _ _ _ _ 5 _ ])
(defn o [[n a]]
(overpad (note n) :amp (/ a 9)))
;;
(defloop bass-line 1/4 o [[:f2 4] _ _ _ _ _ _ _ [:g2 5] _ [:b3 3] _ _ _ [:a3 2] [:g2 2]])
(defn k [[n a]]
(ks1 (note n) :amp (/ a 9)))
(defloop melody1 1 k [[:g4 8] [:a4 8] [:b4 8] [:c5 8] _ _ _ _])
1 2 3 4 5 6 7 8
(defloop melody2 1/2 k [_ _ _ _ _ _ _ _ _ _ _ [:c5 8] [:a4 8] [:b4 8] [:g4 8] [:f4 8]])
;; ---------------------------------------------
(bpm 85)
(beats-in-bar 4)
(at-bar 1
(sticks )
(kicks )
)
(at-bar 3
(clicks)
)
(at-bar 5
(bass-line )
)
(at-bar 13
(melody1)
)
(at-bar 17
(melody2)
)
(comment ; all play for only a few phrases
;; Play these with Ctrl-X Ctrl-E
(melody1 (metro))
)
;;(stop)
| null | https://raw.githubusercontent.com/ericclack/overtone-loops/54b0c230c1e6bd3d378583af982db4e9ae4bda69/src/overtone_loops/music/sticks1.clj | clojure | 1 e & a 2 e & a 3 e & a 4 e & a
---------------------------------------------
all play for only a few phrases
Play these with Ctrl-X Ctrl-E
(stop) | (ns overtone-loops.music.sticks1
(:use [overtone.live]
[overtone.inst.synth]
[overtone-loops.loops]
[overtone-loops.samples]))
(set-up)
(defloop sticks 1/4 stick [8 _ _ _ 6 _ _ 6 _ _ 6 _ _ 6 _ _ ])
(defloop kicks 1 kick [8 8 8 8 ])
(defloop clicks 1/4 finger [_ _ _ 3 _ _ 4 _ _ 3 _ _ _ _ 5 _ ])
(defn o [[n a]]
(overpad (note n) :amp (/ a 9)))
(defloop bass-line 1/4 o [[:f2 4] _ _ _ _ _ _ _ [:g2 5] _ [:b3 3] _ _ _ [:a3 2] [:g2 2]])
(defn k [[n a]]
(ks1 (note n) :amp (/ a 9)))
(defloop melody1 1 k [[:g4 8] [:a4 8] [:b4 8] [:c5 8] _ _ _ _])
1 2 3 4 5 6 7 8
(defloop melody2 1/2 k [_ _ _ _ _ _ _ _ _ _ _ [:c5 8] [:a4 8] [:b4 8] [:g4 8] [:f4 8]])
(bpm 85)
(beats-in-bar 4)
(at-bar 1
(sticks )
(kicks )
)
(at-bar 3
(clicks)
)
(at-bar 5
(bass-line )
)
(at-bar 13
(melody1)
)
(at-bar 17
(melody2)
)
(melody1 (metro))
)
|
e36be852d370a2aaec8bb4af3be95273351cbbf40c9f24d7a54013eacc18a0bf | witan-org/witan | interp.ml | (*************************************************************************)
This file is part of Witan .
(* *)
Copyright ( C ) 2017
CEA ( Commissariat à l'énergie atomique et aux énergies
(* alternatives) *)
( Institut National de Recherche en Informatique et en
(* Automatique) *)
CNRS ( Centre national de la recherche scientifique )
(* *)
(* 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 ) .
(*************************************************************************)
open Witan_popop_lib
open Std
module Register = struct
let ids : (Term.id -> Nodes.Value.t list -> Nodes.Value.t option) list ref = ref []
let id f = ids := f::!ids
module ThInterp = Nodes.ThTermKind.MkVector(struct
type ('a,_) t = (interp:(Nodes.Node.t -> Nodes.Value.t) -> 'a -> Nodes.Value.t)
end)
let thterms = ThInterp.create 10
let thterm sem f =
if not (ThInterp.is_uninitialized thterms sem)
then invalid_arg (Format.asprintf "Interpretation for semantic value %a already done" Nodes.ThTermKind.pp sem);
ThInterp.set thterms sem f
let models = Ty.H.create 16
let model ty (f:Egraph.t -> Nodes.Node.t -> Nodes.Value.t) =
Ty.H.add models ty f
end
exception NoInterpretation of Term.id
exception CantInterpretTerm of Term.t
exception CantInterpretThTerm of Nodes.ThTerm.t
type leaf = Term.t -> Nodes.Value.t option
(** No cache currently because there is no guaranty
that the variable in the let is unique *)
let term ?(leaf=(fun _ -> None)) t =
let rec interp leaf t =
match leaf t with
| Some v -> v
| None ->
let rec aux leaf args = function
| { Term.term = App (f, arg); _ } ->
aux leaf ((interp leaf arg) :: args) f
| { Term.term = Let (v,e,t); _ } ->
let v' = interp leaf e in
let leaf t = match t.Term.term with
| Id id when Term.Id.equal v id -> Some v'
| _ -> leaf t in
aux leaf args t
| { Term.term = Id id; _ } ->
let rec find = function
| [] -> raise (NoInterpretation id)
| f::l ->
match f id args with
| None -> find l
| Some v -> v
in
find !Register.ids
| t -> raise (CantInterpretTerm t)
in
aux leaf [] t
in
interp leaf t
let rec node ?(leaf=(fun _ -> None)) n =
match Nodes.Only_for_solver.open_node n with
| Nodes.Only_for_solver.ThTerm t -> thterm ~leaf t
| Nodes.Only_for_solver.Value v -> v
and thterm ?(leaf=(fun _ -> None)) t =
match Nodes.Only_for_solver.sem_of_node t with
| Nodes.Only_for_solver.ThTerm (sem,v) ->
* check if it is not a synterm
match Nodes.ThTermKind.Eq.eq_type sem SynTerm.key with
| Poly.Eq -> term ~leaf (v:Term.t)
| Poly.Neq ->
if Register.ThInterp.is_uninitialized Register.thterms sem
then raise (CantInterpretThTerm t);
(Register.ThInterp.get Register.thterms sem) ~interp:(node ~leaf) v
let model d n =
match Ty.H.find_opt Register.models (Nodes.Node.ty n) with
| None -> invalid_arg "Uninterpreted type"
| Some f -> f d n
let () = Exn_printer.register (fun fmt exn ->
match exn with
| NoInterpretation id ->
Format.fprintf fmt "Can't interpret the id %a."
Term.Id.pp id
| CantInterpretTerm t ->
Format.fprintf fmt "Can't interpret the term %a."
Term.pp t
| CantInterpretThTerm th ->
Format.fprintf fmt "Can't interpret the thterm %a."
Nodes.ThTerm.pp th
| exn -> raise exn
)
| null | https://raw.githubusercontent.com/witan-org/witan/d26f9f810fc34bf44daccb91f71ad3258eb62037/src/core/interp.ml | ocaml | ***********************************************************************
alternatives)
Automatique)
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.
See the GNU Lesser General Public License version 2.1
***********************************************************************
* No cache currently because there is no guaranty
that the variable in the let is unique | This file is part of Witan .
Copyright ( C ) 2017
CEA ( Commissariat à l'énergie atomique et aux énergies
( Institut National de Recherche en Informatique et en
CNRS ( Centre national de la recherche scientifique )
Lesser General Public License as published by the Free Software
Foundation , version 2.1 .
for more details ( enclosed in the file licenses / LGPLv2.1 ) .
open Witan_popop_lib
open Std
module Register = struct
let ids : (Term.id -> Nodes.Value.t list -> Nodes.Value.t option) list ref = ref []
let id f = ids := f::!ids
module ThInterp = Nodes.ThTermKind.MkVector(struct
type ('a,_) t = (interp:(Nodes.Node.t -> Nodes.Value.t) -> 'a -> Nodes.Value.t)
end)
let thterms = ThInterp.create 10
let thterm sem f =
if not (ThInterp.is_uninitialized thterms sem)
then invalid_arg (Format.asprintf "Interpretation for semantic value %a already done" Nodes.ThTermKind.pp sem);
ThInterp.set thterms sem f
let models = Ty.H.create 16
let model ty (f:Egraph.t -> Nodes.Node.t -> Nodes.Value.t) =
Ty.H.add models ty f
end
exception NoInterpretation of Term.id
exception CantInterpretTerm of Term.t
exception CantInterpretThTerm of Nodes.ThTerm.t
type leaf = Term.t -> Nodes.Value.t option
let term ?(leaf=(fun _ -> None)) t =
let rec interp leaf t =
match leaf t with
| Some v -> v
| None ->
let rec aux leaf args = function
| { Term.term = App (f, arg); _ } ->
aux leaf ((interp leaf arg) :: args) f
| { Term.term = Let (v,e,t); _ } ->
let v' = interp leaf e in
let leaf t = match t.Term.term with
| Id id when Term.Id.equal v id -> Some v'
| _ -> leaf t in
aux leaf args t
| { Term.term = Id id; _ } ->
let rec find = function
| [] -> raise (NoInterpretation id)
| f::l ->
match f id args with
| None -> find l
| Some v -> v
in
find !Register.ids
| t -> raise (CantInterpretTerm t)
in
aux leaf [] t
in
interp leaf t
let rec node ?(leaf=(fun _ -> None)) n =
match Nodes.Only_for_solver.open_node n with
| Nodes.Only_for_solver.ThTerm t -> thterm ~leaf t
| Nodes.Only_for_solver.Value v -> v
and thterm ?(leaf=(fun _ -> None)) t =
match Nodes.Only_for_solver.sem_of_node t with
| Nodes.Only_for_solver.ThTerm (sem,v) ->
* check if it is not a synterm
match Nodes.ThTermKind.Eq.eq_type sem SynTerm.key with
| Poly.Eq -> term ~leaf (v:Term.t)
| Poly.Neq ->
if Register.ThInterp.is_uninitialized Register.thterms sem
then raise (CantInterpretThTerm t);
(Register.ThInterp.get Register.thterms sem) ~interp:(node ~leaf) v
let model d n =
match Ty.H.find_opt Register.models (Nodes.Node.ty n) with
| None -> invalid_arg "Uninterpreted type"
| Some f -> f d n
let () = Exn_printer.register (fun fmt exn ->
match exn with
| NoInterpretation id ->
Format.fprintf fmt "Can't interpret the id %a."
Term.Id.pp id
| CantInterpretTerm t ->
Format.fprintf fmt "Can't interpret the term %a."
Term.pp t
| CantInterpretThTerm th ->
Format.fprintf fmt "Can't interpret the thterm %a."
Nodes.ThTerm.pp th
| exn -> raise exn
)
|
ea8dbe5859c3a40332dc1094dc05ccdf07f88d8b290b62c769918e98504d0377 | Rainist/kubeletter | redis_store_test.clj | (ns kubeletter.stores.redis-store-test
(:require [kubeletter.stores.redis-store :as redis]
[clojure.test :refer :all]))
(def ^:private samples
{:simple-key "test-redis-key"
:simple-val "test-redis-val"
:obj-key "test-redis-obj-key"
:obj-val {:hash {:a 1}
:vector [:a 1]
:list '(:a 1)}})
(if (redis/selectable?)
(let []
(deftest redis-feature-test
(->> (redis/ping)
(= "PONG")
is
(testing "redis ping pong"))
(->> (samples :simple-val)
(redis/set-val (samples :simple-key))
(= "OK")
is
(testing "redis set val test"))
(->> (samples :simple-key)
(redis/get-val)
(= (samples :simple-val))
is
(testing "redis get val test"))
(->> (samples :obj-val)
(redis/set-val (samples :obj-key))
(= "OK")
is
(testing "redis set obj val test"))
(->> (samples :obj-key)
(redis/get-val)
(= (samples :obj-val))
is
(testing "redis get obj val test"))
)))
| null | https://raw.githubusercontent.com/Rainist/kubeletter/da326a067147f45b069a49d22730ea07675f9e16/kubeletter/test/kubeletter/stores/redis_store_test.clj | clojure | (ns kubeletter.stores.redis-store-test
(:require [kubeletter.stores.redis-store :as redis]
[clojure.test :refer :all]))
(def ^:private samples
{:simple-key "test-redis-key"
:simple-val "test-redis-val"
:obj-key "test-redis-obj-key"
:obj-val {:hash {:a 1}
:vector [:a 1]
:list '(:a 1)}})
(if (redis/selectable?)
(let []
(deftest redis-feature-test
(->> (redis/ping)
(= "PONG")
is
(testing "redis ping pong"))
(->> (samples :simple-val)
(redis/set-val (samples :simple-key))
(= "OK")
is
(testing "redis set val test"))
(->> (samples :simple-key)
(redis/get-val)
(= (samples :simple-val))
is
(testing "redis get val test"))
(->> (samples :obj-val)
(redis/set-val (samples :obj-key))
(= "OK")
is
(testing "redis set obj val test"))
(->> (samples :obj-key)
(redis/get-val)
(= (samples :obj-val))
is
(testing "redis get obj val test"))
)))
| |
006f92605c7ea61a1494f7a7fae1c8b3d0938481678a004f24fc220ba66c4e7b | robert-strandh/SICL | enable-defclass.lisp | (cl:in-package #:sicl-boot-phase-3)
(defun define-ensure-class-using-class (e1 e2 e3)
(let ((client (env:client e3)))
(setf (env:fdefinition
client e2 'sicl-clos:ensure-class-using-class)
(lambda (class-or-nil
class-name
&rest keys
&key
name
direct-superclasses
(metaclass 'standard-class)
&allow-other-keys)
(loop while (remf keys :metaclass))
(cond ((typep class-or-nil 'class)
class-or-nil)
((null class-or-nil)
(setf (env:find-class client e3 class-name)
(apply (env:fdefinition client e1 'make-instance)
metaclass
:name (make-symbol (symbol-name name))
:direct-superclasses
(loop for class-or-name in direct-superclasses
collect (if (symbolp class-or-name)
(env:find-class client e3 class-or-name)
class-or-name))
keys)))
(t
(error 'type-error
:expected-type '(or null class)
:datum class-or-nil)))))))
(defun define-ensure-class (e2 e3)
(let ((client (env:client e2)))
(with-intercepted-function-cells
(e3
(sicl-clos:ensure-class-using-class
(env:function-cell
client e2 'sicl-clos:ensure-class-using-class)))
(load-source-file "CLOS/ensure-class.lisp" e3))))
(defun enable-defclass (e1 e2 e3)
(define-ensure-class-using-class e1 e2 e3)
(define-ensure-class e2 e3))
| null | https://raw.githubusercontent.com/robert-strandh/SICL/4189e85e231f12cdbd8a9a4b3f0bd1d69a2c5afe/Code/Boot/Phase-3/enable-defclass.lisp | lisp | (cl:in-package #:sicl-boot-phase-3)
(defun define-ensure-class-using-class (e1 e2 e3)
(let ((client (env:client e3)))
(setf (env:fdefinition
client e2 'sicl-clos:ensure-class-using-class)
(lambda (class-or-nil
class-name
&rest keys
&key
name
direct-superclasses
(metaclass 'standard-class)
&allow-other-keys)
(loop while (remf keys :metaclass))
(cond ((typep class-or-nil 'class)
class-or-nil)
((null class-or-nil)
(setf (env:find-class client e3 class-name)
(apply (env:fdefinition client e1 'make-instance)
metaclass
:name (make-symbol (symbol-name name))
:direct-superclasses
(loop for class-or-name in direct-superclasses
collect (if (symbolp class-or-name)
(env:find-class client e3 class-or-name)
class-or-name))
keys)))
(t
(error 'type-error
:expected-type '(or null class)
:datum class-or-nil)))))))
(defun define-ensure-class (e2 e3)
(let ((client (env:client e2)))
(with-intercepted-function-cells
(e3
(sicl-clos:ensure-class-using-class
(env:function-cell
client e2 'sicl-clos:ensure-class-using-class)))
(load-source-file "CLOS/ensure-class.lisp" e3))))
(defun enable-defclass (e1 e2 e3)
(define-ensure-class-using-class e1 e2 e3)
(define-ensure-class e2 e3))
| |
ae4b16bccbbeafefd359499623ee9c2f73550573439b09066ed7cd933f5f909d | denisshevchenko/circlehs | Main.hs | {-# LANGUAGE OverloadedStrings #-}
# LANGUAGE LambdaCase #
module Main where
import Network.CircleCI
main :: IO ()
main = putStrLn "Test will be implemented soon!"
| null | https://raw.githubusercontent.com/denisshevchenko/circlehs/0c01693723a234bb46ff8d1e6e114cce91dfa032/test/Main.hs | haskell | # LANGUAGE OverloadedStrings # | # LANGUAGE LambdaCase #
module Main where
import Network.CircleCI
main :: IO ()
main = putStrLn "Test will be implemented soon!"
|
99fb88a89727150e3f41393a2e7944c9264b98b7025daa84fb9b0186176f92d7 | antoniogarrote/egearmand-server | rfc4627_jsonrpc_sup.erl | @author < >
@author LShift Ltd. < >
2007 , 2008 and LShift Ltd.
@license
%%
%% Permission is hereby granted, free of charge, to any person
%% obtaining a copy of this software and associated documentation
files ( the " Software " ) , to deal in the Software without
%% restriction, including without limitation the rights to use, copy,
%% modify, merge, publish, distribute, sublicense, and/or sell copies
of the Software , and to permit persons to whom the Software is
%% furnished to do so, subject to the following conditions:
%%
%% The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software .
%%
THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND ,
%% EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
%% MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
%% NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
BE LIABLE FOR ANY CLAIM , DAMAGES OR OTHER LIABILITY , WHETHER IN AN
%% ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
%% CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
%% SOFTWARE.
-module(rfc4627_jsonrpc_sup).
-behaviour(supervisor).
-export([start_link/0, init/1]).
start_link() ->
supervisor:start_link({local, ?MODULE}, ?MODULE, _Arg = []).
init([]) ->
{ok, {{one_for_one, 3, 10},
[{rfc4627_jsonrpc,
{rfc4627_jsonrpc, start_link, []},
permanent,
10000,
worker,
[rfc4627_jsonrpc]}
]}}.
| null | https://raw.githubusercontent.com/antoniogarrote/egearmand-server/45296fb40e3ddb77f71225121188545a371d2237/contrib/erlang-rfc4627/dist/src/rfc4627_jsonrpc_sup.erl | erlang |
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
restriction, including without limitation the rights to use, copy,
modify, merge, publish, distribute, sublicense, and/or sell copies
furnished to do so, subject to 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
ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE. | @author < >
@author LShift Ltd. < >
2007 , 2008 and LShift Ltd.
@license
files ( the " Software " ) , to deal in the Software without
of the Software , and to permit persons to whom the Software is
included in all copies or substantial portions of the Software .
THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND ,
BE LIABLE FOR ANY CLAIM , DAMAGES OR OTHER LIABILITY , WHETHER IN AN
-module(rfc4627_jsonrpc_sup).
-behaviour(supervisor).
-export([start_link/0, init/1]).
start_link() ->
supervisor:start_link({local, ?MODULE}, ?MODULE, _Arg = []).
init([]) ->
{ok, {{one_for_one, 3, 10},
[{rfc4627_jsonrpc,
{rfc4627_jsonrpc, start_link, []},
permanent,
10000,
worker,
[rfc4627_jsonrpc]}
]}}.
|
d27591db8e91a1c3f147fd2d484f994a81d9828eaa2fb7a43e2da9035663fae2 | kappamodeler/kappa | network.ml | (**Implementation of non interleaving semantics of computation traces*)
open Mods2
type eid = int
type node = (eid*Rule.modif_type)
kind:= 0 : intro 1 : classic 2 : obs
type event = {r:Rule.t;label:string;s_depth:int;g_depth:int ;kind:int;nodes:Rule.modif_type list PortMap.t}
let empty_event = {r=Rule.empty;label="";s_depth=(-1); g_depth=(-1); kind=(-1);nodes=PortMap.empty}
let is_empty_event e = (e.s_depth = (-1))
(*e.nodes : wire_id -> modif_type (or Not_found) *)
module Wire :
sig
type t
val empty : t
val plug : string -> (int*string) -> node -> t -> t
val rename_before_plugging : int IntMap.t -> (int*string) -> node -> t -> int IntMap.t
val unsafe_plug : node -> t -> t
exception Empty
val top_event : t -> node
val backtrack : t -> eid -> t
val last_mod : t -> eid
val testing : t -> eid list
val print : t -> unit
val fold_left : ('a -> node -> 'a) -> 'a -> t -> 'a
val exists: (node -> bool) -> t -> bool
val can_push_to_collapse: t -> eid -> eid -> bool
end
=
struct
type t = node list
let exists = List.exists
let fold_left f a b = List.fold_left f a (List.rev b)
let empty = []
let rec can_push_to_collapse w eid rm_id =
match w with
[] ->
let s = "Wire.push_to_collapse: empty wire" in
Error.runtime
(Some "network.ml",
Some 47,
Some s)
s
| (i,modif)::tl ->
if i=rm_id then can_push_to_collapse tl eid rm_id
else
if i=eid then true
else
if Rule.is_pure_test [modif] then can_push_to_collapse tl eid rm_id
else false
pluggin a new quark modif / test without consistency requirement - > strong compression
node::w
safe pluggin of a new quark modif / test
if w = [] then [node] (*if wire is empty, plugging always succeeds*)
else
let old_state = (fun (x,y) -> y)(List.hd w)
and new_state = (fun (x,y) -> y) node
in
let old_state =
let rec aux old_state =
match old_state with Rule.Before_After (_,y) -> aux y
| _ -> old_state in
aux old_state in
let error b =
let err x = (*if !Data.sanity_check then*) Error.runtime (Some "network.ml",Some b,Some x) x (*else Error.warning*) in
let add_msg = Printf.sprintf "\nIn rule %s\n" rule_str in
err (
(string_of_port (i,s))^": "
^"Consistency check failed, adding "
^(Rule.string_of_modif_type new_state)
^" when previous node was "
^(Rule.string_of_modif_type old_state)
^add_msg
)
in
let push (eid,modif) w =
match w with
[] -> [(eid,modif)]
| (eid',_)::tl -> if eid=eid' then (eid,modif)::tl else (eid,modif)::w
in
let rec aux new_state =
match new_state with
Rule.Before_After (_,y) -> aux y
| Rule.Test_bound (i,s) -> (
match old_state with
(Rule.Bound (i',s') | Rule.Init_bound (_,i',s') | Rule.Test_bound (i',s')) ->
if (i'=i) && (s=s') then push node w else error 95
| Rule.Test_any_bound -> push node w
| _ -> error 98
)
| Rule.Test_marked s -> (
match old_state with
(Rule.Test_marked s' | Rule.Marked (_,s') | Rule.Init_mark (_,s')) -> if s'=s then push node w else error 102
| _ -> error 103
)
| Rule.Test_any_bound -> (
match old_state with
(Rule.Before_After _ |Rule.Init_bound _ | Rule.Bound _ | Rule.Test_bound _ | Rule.Test_any_bound) -> push node w
| _ -> error 108
)
| Rule.Test_free -> (
match old_state with
(Rule.Before_After _ | Rule.Init_free _ | Rule.Test_free | Rule.Break _ | Rule.Side_break _) -> push node w
| _ -> error 113
)
| Rule.Bound (i,s) -> (
match old_state with
| Rule.Init_free _ | Rule.Break _ | Rule.Test_free | Rule.Side_break _ -> push node w
| _ -> error 118
)
| Rule.Break (i,s) ->
(match old_state with Rule.Before_After _ -> push node w
| _ ->
if (old_state = Rule.Bound(i,s)) or (old_state = Rule.Test_bound(i,s)) or (old_state = Rule.Test_any_bound)
or (match old_state with Rule.Init_bound (_,i',s') when i=i' && s=s' -> true | _ -> false)
then push node w else error 125)
| Rule.Marked (old_m,_) -> (
match old_state with
(Rule.Marked (_,s') | Rule.Init_mark (_,s') | Rule.Test_marked s') ->
if (old_m = s') then push node w else error 129
| _ -> error 130
)
| Rule.Remove -> push node w (*remove action is always compatible*)
| Rule.Side_break (i,s) ->
if (old_state = Rule.Bound(i,s))
or (match old_state with Rule.Init_bound(_,i',s') when i=i' && s=s' -> true | _ -> false)
or (old_state = Rule.Test_bound(i,s))
or (old_state = Rule.Test_any_bound)
then push node w else error 138
| Rule.Init_bound _ ->
begin
match old_state with
Rule.Init_free _ -> push node w
| _ ->
let s = "Network.plug: invalid sequence of modif on a single quark" in
Error.runtime
(Some "network.ml",
Some 147,
Some s)
s
end
| Rule.Init_mark _ | Rule.Init_free _ ->
let s = "Network.plug: adding an initial state to a non empty wire." in
Error.runtime
(Some "network.ml",
Some 155,
Some s)
s in
aux new_state
let rec rename_before_plugging sigma (i,s) node w =
let codomain =
IntMap.fold
(fun _ -> IntSet.add) sigma IntSet.empty in
let f x = try IntMap.find x sigma with Not_found ->
if IntSet.mem x codomain then x else x in
let i' = f i in
let node' = (fst node,Rule.subs_act sigma (snd node)) in
safe pluggin of a new quark modif / test
if w = [] then raise Exit (*if wire is empty, plugging always fails*)
else
let old_state = (fun (x,y) -> y)(List.hd w)
and new_state = (fun (x,y) -> y) node'
in
let old_state =
let rec aux old_state =
match old_state with Rule.Before_After (_,y) -> aux y
| _ -> old_state in
aux old_state in
let old_state = Rule.subs_act sigma old_state in
let new_state = Rule.subs_act sigma new_state in
let error (b) = let s (*Error.runtime*)
= (string_of_port (i',s))^": "
^"Consistency check failed, adding "
^(Rule.string_of_modif_type new_state)
^" when previous node was "
^(Rule.string_of_modif_type old_state)
in
Error.runtime
(Some "network.ml",
Some b,
Some s)
s
in
let unify i i' sigma =
try (let _ = IntMap.find i sigma in None)
with Not_found ->
try (let _ = IntMap.find i' sigma in None)
with Not_found ->
Some (IntMap.add i i' (IntMap.add i' i sigma))
in
let rec aux new_state =
match new_state with
Rule.Before_After (_,y) -> aux y
| Rule.Test_bound (i,s) -> (
match old_state with
(Rule.Bound (i',s') | Rule.Init_bound (_,i',s') | Rule.Test_bound (i',s')) ->
if (i'=i) && (s=s') then sigma else
begin
if s=s' then
match unify i i' sigma with
None -> error 210
|Some sigma -> sigma
else
error 213
end
| Rule.Test_any_bound -> sigma
| _ -> error 216
)
| Rule.Test_marked s -> (
match old_state with
(Rule.Test_marked s' | Rule.Marked (_,s') | Rule.Init_mark (_,s')) -> if s'=s then sigma else error 220
| _ -> error 221
)
| Rule.Test_any_bound -> (
match old_state with
(Rule.Before_After _ |Rule.Init_bound _ | Rule.Bound _ | Rule.Test_bound _ | Rule.Test_any_bound) -> sigma
| _ -> error 226
)
| Rule.Test_free -> (
match old_state with
(Rule.Before_After _ | Rule.Init_free _ | Rule.Test_free | Rule.Break _ | Rule.Side_break _) -> sigma
| _ -> error 231
)
| Rule.Bound (i,s) -> (
match old_state with
| Rule.Init_free _ | Rule.Break _ | Rule.Test_free | Rule.Side_break _ -> sigma
| _ -> error 236
)
| Rule.Break (i,s) ->
(match old_state with Rule.Before_After _ -> sigma
| _ ->
(match old_state with Rule.Bound(i',s')
| Rule.Test_bound(i',s')
|Rule.Init_bound (_,i',s') ->
if i=i' && s=s' then sigma
else if s=s' then
match unify i i' sigma
with Some sigma' -> sigma'
| None -> error 249
else error 250
| _ -> error 251
))
| Rule.Marked (old_m,_) ->
(
match old_state with
(Rule.Marked (_,s') | Rule.Init_mark (_,s') | Rule.Test_marked s') ->
if (old_m = s') then sigma else error 257
| _ -> error 258
)
| Rule.Remove -> sigma (*remove action is always compatible*)
| Rule.Side_break (i,s) ->
(match old_state
with
Rule.Bound(i',s')
|Rule.Init_bound(_,i',s')
| Rule.Test_bound(i',s') -> if i=i' && s=s' then sigma else if s = s' then
match unify i i' sigma with
None -> error 268
|Some sigma -> sigma
else error 270
|
Rule.Test_any_bound -> sigma
| _ -> error 273)
| (Rule.Init_bound _|Rule.Init_mark _|Rule.Init_free _) ->
let s = "Network.plug: adding an initial state to a non empty wire." in
Error.runtime
(Some "network.ml",
Some 279,
Some s)
s
in
aux new_state
exception Empty
(*backtracks last modif of wire *)
let rec backtrack w eid =
match w with
(eid',state)::tl ->
if (eid = eid') then tl
else
if (Rule.is_pure_test [state]) then (eid',state)::(backtrack tl eid) (*sanity check*)
else
let s = "Network.Wire.backtrack: sanity check failed" in
Error.runtime
(Some "network.ml",
Some 297,
Some s)
s
| [] -> raise Empty
let rec last_mod w =
match w with
(eid,state)::tl -> if Rule.contains_modif [state] then eid else (last_mod tl)
| [] -> raise Not_found
let rec testing w =
match w with
(eid,state)::tl -> if Rule.is_pure_test [state] then (eid::(testing tl)) else []
| [] -> []
let top_event w =
match w with
(eid,state)::_ -> (eid,state)
| [] -> raise Empty
let rec print w =
match w with
(eid,state)::tl -> Printf.printf "%d--(%s)\n" eid (Rule.string_of_modif_type state); print tl
| [] -> ()
end
module EventArray = Array_ext.Make(struct type t = event let default = empty_event end)
(*Replace wires by extensible array*)
type t = {fresh_id:eid; (*new event identifier*)
name_of_agent:string array option;
events: int EventArray.t ;
: eid - > { eids } -- set of identifiers that precede pid
weak predecessors of eid
rid_preds: IntSet.t IntMap.t; (*set of rule id that belong to s_preds(eid)*)
wires : ( i , s ) - > Wire.t = [ Test;Test; ... ( i , s ) ; .... ]
last: IntSet.t ;
}
let strong_preds eid net = try IntMap.find eid net.s_preds with Not_found -> IntSet.empty
let weak_preds eid net = try IntMap.find eid net.w_preds with Not_found -> IntSet.empty
let rid_preds eid net = try IntMap.find eid net.rid_preds with Not_found -> IntSet.empty
type marshalized_t = {f_fresh_id:eid; (*new event identifier*)
f_name_of_agent:string list ;
f_events: (int*event) list ;
: eid - > { eids } -- set of identifiers that precede pid
f_w_preds: IntSet.t IntMap.t ;
f_rid_preds: IntSet.t IntMap.t ;
wires : ( i , s ) - > Wire.t = [ Test;Test; ... ( i , s ) ; .... ]
f_last: IntSet.t ;
}
let marshal net =
{f_fresh_id = net.fresh_id ;
f_name_of_agent =
begin
match net.name_of_agent with
None -> []
| Some n_of_a -> Array.to_list n_of_a
end;
f_events = EventArray.fold (fun i e cont -> (i,e)::cont) net.events [] ;
f_s_preds = net.s_preds ;
f_w_preds = net.w_preds ;
f_rid_preds = net.rid_preds ;
f_wires = net.wires ;
f_last = net.last
}
let unmarshal f_net =
{fresh_id = f_net.f_fresh_id ;
name_of_agent =
begin
match f_net.f_name_of_agent with
[] -> None
| n_of_a -> Some (Array.of_list n_of_a)
end;
events = List.fold_left (fun ar (i,e) -> let ar = EventArray.add i e ar in ar) (EventArray.create 1) f_net.f_events ;
s_preds = f_net.f_s_preds ;
w_preds = f_net.f_w_preds ;
rid_preds = f_net.f_rid_preds ;
wires = f_net.f_wires ;
last = f_net.f_last
}
let empty() =
{fresh_id=0;
events = EventArray.create 100 ;
wires = PortMap.empty;
s_preds = IntMap.empty ;
w_preds = IntMap.empty ;
rid_preds = IntMap.empty ;
last = IntSet.empty;
name_of_agent = None;
}
let is_empty net = EventArray.is_empty net.events
let copy net =
let name_of_agent'=
match net.name_of_agent with
None -> None
| Some n_of_a -> Some (Array.copy n_of_a)
in
{net with events = EventArray.copy net.events ; name_of_agent = name_of_agent'}
let event_of_id i net =
try
(*IntMap.find i net.events *)
EventArray.find i net.events
with
Not_found ->
let error = Printf.sprintf "event_of_id: %d does not correspond to any event" i
in
Error.runtime
(Some "network.ml",
Some 407,
Some error)
error
let unsafe_add_wire (i,s) node (wires:Wire.t PortMap.t) =
let w = try PortMap.find (i,s) wires with Not_found -> Wire.empty in
PortMap.add (i,s) (Wire.unsafe_plug node w) wires
let add_wire str (i,s) node (wires:Wire.t PortMap.t) =
let w = try PortMap.find (i,s) wires with Not_found -> Wire.empty in
PortMap.add (i,s) (Wire.plug str (i,s) node w) wires
let rename_before_adding_wire sigma (i,s) node (wires:Wire.t PortMap.t) =
let w = try PortMap.find
((try IntMap.find i sigma with Not_found -> i),s) wires with Not_found -> Wire.empty in
let sigma = Wire.rename_before_plugging sigma (i,s) node w in
sigma
let add_intro (str,modifs) safe net =
let add_wire = if safe then add_wire str else unsafe_add_wire in
let eid = net.fresh_id in
let e = {r=Rule.empty;label=str;s_depth=0;g_depth=0;kind=0;nodes=PortMap.empty}
in
let net =
PortMap.fold (fun (i,s) state net ->
let node = (eid,List.hd state) in (*no need to add sequence of modifications since there is no previous event*)
let e =
try EventArray.find eid net.events with Not_found -> e
in
let e = {e with nodes = PortMap.add (i,s) state e.nodes}
in
let wires = add_wire
(i,s)
node
net.wires
in
{net with
events = EventArray.add eid e net.events ;
wires = wires;
last = IntSet.add eid net.last}
) modifs net
in
{net with fresh_id = net.fresh_id+1}
let preds_closure net closure with_rids =
let rec f net closure (todo_set,rids) =
let news,rids =
IntSet.fold (fun i (set,rids) ->
let p_i = strong_preds i net in
IntSet.fold (fun i (set,rids) ->
if IntSet.mem i closure then (set,rids)
else
let e = event_of_id i net in
(IntSet.add i set, IntSet.remove e.r.Rule.id rids)
) p_i (set,rids)
) todo_set (IntSet.empty,rids)
in
if IntSet.is_empty news then if IntSet.is_empty rids then (Some closure) else None
else f net (IntSet.union todo_set (IntSet.union news closure)) (news,rids)
in
f net closure (closure,IntSet.fold (fun eid rids ->
let e = event_of_id eid net in
let r_id = e.r.Rule.id in
IntSet.remove r_id rids
) closure with_rids)
returns immediate predecessors of eid , whether weak or strong , which are maximal if eid is removed
let immediate_preds eid net =
let is_top_after_removal rm_id kept_id net =
try
PortMap.fold (fun (i,s) modif _ ->
let w_is = PortMap.find (i,s) net.wires in
if Wire.can_push_to_collapse w_is eid rm_id then ()
else raise False
) (event_of_id kept_id net).nodes () ; true
with
False -> false
| _ ->
let s = "Network.immediate_preds: event or wire not found in network" in
Error.runtime
(Some "network.ml",
Some 484,
Some s)
s
in
let weak = weak_preds eid net
and strong = strong_preds eid net
in
let prob_preds = IntSet.union weak strong in
let set,_ =
IntSet.fold (fun j (set,blacklist) ->
let weak_j = weak_preds j net
and strong_j = strong_preds j net
in
let set = IntSet.fold (fun i set -> IntSet.remove i set) weak_j set in
let set = IntSet.fold (fun i set -> IntSet.remove i set) strong_j set in
let blacklist = IntSet.union weak_j (IntSet.union strong_j blacklist) in
if IntSet.mem j blacklist then (set,blacklist) else
if is_top_after_removal eid j net then (IntSet.add j set,blacklist)
else (set,IntSet.add j blacklist)
) prob_preds (IntSet.empty,IntSet.empty)
in
set
(**Adding the new event [eid] and updating precedence relation if necessary*)
let add_event ?(replay=false) eid (r,modifs) add_wire net =
let net =
PortMap.fold (fun (i,s) modif_list net ->
List.fold_right (fun state net ->
if Rule.contains_test [state] then (*adding a test node*)
let preds_eid,weak_preds,rid = (*predecessors are modifications of wires of eid*)
let w_is = try PortMap.find (i,s) net.wires with Not_found -> Wire.empty in
let l_test = if Rule.contains_modif [state] then Wire.testing w_is else [] in
event . ( i , s )
and old_strong = strong_preds eid net
and old_weak = weak_preds eid net
and old_rid = rid_preds eid net
in
let strong,weak,rid = List.fold_right (fun j (strong,weak,rid) ->
if event has multiple
else
let weak = IntSet.remove j weak
and strong = IntSet.add j strong
and rid =
let e = event_of_id j net in
IntSet.add (e.r.Rule.id) rid
in
(strong,weak,rid)
) l_mod (old_strong,old_weak,old_rid)
in
let weak =
List.fold_right (fun j set ->
if (j=eid) or (IntSet.mem j strong) then set
else
IntSet.add j set
) l_test weak
in
(strong,weak,rid)
in
let wires = add_wire (i,s) (eid,state) net.wires
in
{net with
s_preds = IntMap.add eid preds_eid net.s_preds;
w_preds = IntMap.add eid weak_preds net.w_preds;
rid_preds = IntMap.add eid rid net.rid_preds;
wires = wires
}
else (*Pure modif of a quark does not genereate precedence but may generate non permutation*)
let weak_preds =
let w_is = try PortMap.find (i,s) net.wires with Not_found -> Wire.empty in
let l_test = Wire.testing w_is in
let old_strong = strong_preds eid net in
let old_weak = weak_preds eid net in
List.fold_right (fun i set ->
if i=eid or IntSet.mem i old_strong then set
else IntSet.add i set
) l_test old_weak
in
let wires = add_wire (i,s) (eid,state) net.wires in
{net with
w_preds = IntMap.add eid weak_preds net.w_preds;
wires = wires
}
) modif_list net
) modifs net
in
let strong = strong_preds eid net in
let weak = weak_preds eid net in
let _ =
if !Data.sanity_check then
let set = IntSet.inter weak strong in
if IntSet.is_empty set then ()
else
let s = "QA failed in Network.event_add: weak and strong precedence should have an emtpy intersection"
in
Error.runtime
(Some "network.ml",
Some 575,
Some s)
s
else ()
in
let s_d,g_d,last =
IntSet.fold (fun i (s_mx,g_mx,last) ->
try
let last = IntSet.remove i last in
let e = EventArray.find i net.events
in
let s_mx = if (e.s_depth > s_mx) && (IntSet.mem i strong) then e.s_depth else s_mx
and g_mx = if (e.g_depth > g_mx) then e.g_depth else g_mx
in
weak does not change depth of events
with Not_found ->
let s =
("Network.add: event "^(string_of_int i)^" not found in predecessors of "^(string_of_int eid))
in
Error.runtime
(Some "network.ml",
Some 596,
Some s)
s
) (IntSet.union strong weak) (0,0,net.last)
in
let e = {r=r;
label=PortMap.fold (fun (i,s) _ label ->
if (s="_!" or s="_~") then label else
Printf.sprintf "<%d,%s>%s" i s label
) modifs (Printf.sprintf "\n%s" r.Rule.input) ;
s_depth=s_d+1;
g_depth=g_d+1;
kind=1;
nodes = modifs ;
}
in
{net with
events = EventArray.add eid e net.events ;
fresh_id = net.fresh_id+1;
last = IntSet.add eid last
}
let add sol net (r,modifs) debug compress =
try
(*raise (Rule.Opposite e.nodes) in case of success*)
let _ =
if compress then
let candidates =
PortMap.fold (fun (i,s) states candidates ->
if not (Rule.contains_modif states) or (Rule.is_creation states) or (Rule.is_deletion states)
if List.hd contains than so other actions in List.tl
else
let w_is = try PortMap.find (i,s) net.wires with Not_found ->
let s = (Printf.sprintf "Network.add: Wire (%d,%s) not found!" i s) in
Error.runtime
(Some "network.ml",
Some 632,
Some s)
s
in
let opt_eid_state = (try Some (Wire.top_event w_is) with Wire.Empty -> None) in
match opt_eid_state with
Some (eid',state') ->
if not (IntSet.mem eid' net.last) then candidates else
let e = event_of_id eid' net in
if e.kind=0 then candidates
else
if Rule.contains_modif [state'] then IntSet.add eid' candidates
else IntSet.empty (*a pure test is preventing trivial compression*)
| None -> candidates
) modifs IntSet.empty
in
try
IntSet.iter (fun eid ->
let e = EventArray.find eid net.events
in
(*Printf.printf "%s\n%s\n" e.label r.Rule.input; flush stdout ; *)
Rule.opposite modifs e.nodes sol
) candidates
with Not_found ->
let s = "Network.add: event not found" in
Error.runtime
(Some "network.ml",
Some 659,
Some s)
s
else ()
in
let eid = net.fresh_id in
(try
add_event eid (r,modifs) (add_wire (Printf.sprintf "%s_%d" r.Rule.input eid)) net (*If there is no trivial compression*)
with Not_found ->
let s = "Network.add_event: not found raised" in
Error.runtime
(Some "network.ml",
Some 671,
Some s)
s)
with
Rule.Opposite nodes -> (**When added event can collapse nodes in [nodes]*)
begin
let opt = PortMap.fold (fun (i,s) states opt ->
if not (Rule.contains_modif states) then opt
else
let eid,_ = Wire.top_event (PortMap.find (i,s) net.wires) in
match opt with
Some eid' ->
if eid=eid' then Some eid
else
begin
let msg =
Printf.sprintf
"Network.add: invariant violation, cannot collapse \n%s\n%s\n with"
(PortMap.fold (fun (i,s) _ label ->
if (s="_!" or s="_~") then label else
Printf.sprintf "<%d,%s>%s" i s label
) modifs "")
r.Rule.input
and msg2 =
let event = event_of_id eid net
and event'= event_of_id eid' net
in
Printf.sprintf "%d:%s\n%d:%s\n" eid event.label eid' event'.label
in
Printf.printf "last:%s\n" (string_of_set string_of_int IntSet.fold net.last) ; flush stdout ;
let s = (msg^"\n"^msg2) in
Error.runtime
(Some "network.ml",
Some 704,
Some s)
s
end
| None -> Some eid
) nodes None
in
let rm_eid =
match opt with
None ->
let s = "Network.add: invalid argument" in
Error.runtime
(Some "network.ml",
Some 715,
Some s)
s
| Some eid -> eid in
let _ =
if IntSet.mem rm_eid net.last then ()
else
let s = "Network.add: removed event is not maximal" in
Error.runtime
(Some "network.ml",
Some 727,
Some s)
s
in
try IntMap.find rm_eid net.preds with Not_found - > IntSet.empty in
let events,preds,w_preds =
(
EventArray.remove rm_eid net.events, (*removing rm_eid from network*)
removing information about of rm_eid which is now useless
IntMap.remove rm_eid net.w_preds
)
in
let _ =
if !Data.sanity_check then
(
IntMap.fold (fun eid set _ ->
if IntSet.mem rm_eid set then
let s = (Printf.sprintf "QA failed in Network.add: removed eid is a weak predecessor of event %d" eid) in
Error.runtime
(Some "network.ml",
Some 747,
Some s)
s
else ()
) net.w_preds () ;
IntMap.fold (fun eid set _ ->
if IntSet.mem rm_eid set then
let s = (Printf.sprintf "QA failed in Network.add: removed eid is a strong predecessor of event %d" eid) in
Error.runtime
(Some "network.ml",
Some 757,
Some s)
s
else ()
) net.s_preds ()
)
in
let net =
PortMap.fold (fun (i,s) _ net ->
let wires =
try
let w_is = PortMap.find (i,s) net.wires in
let w_is'= Wire.backtrack w_is rm_eid in
PortMap.add (i,s) w_is' net.wires
with
Wire.Empty ->
let msg = Printf.sprintf "Wire (%d,%s) is empty" i s in
Error.runtime
(Some "network.ml",
Some 777,
Some msg)
msg
| Not_found ->
let msg=Printf.sprintf "Wire (%d,%s) not found" i s in
Error.runtime
(Some "network.ml",
Some 784,
Some msg)
msg
in
{net with wires=wires}
) nodes {net with events=events;s_preds=preds; w_preds=w_preds ; fresh_id=net.fresh_id+1}
in
let last =
IntSet.fold (fun eid last -> IntSet.add eid last) preds_rm (IntSet.remove rm_eid net.last)
in
{net with last = last}
end
| Not_found ->
let s = "Network.add: not found raised" in
Error.runtime
(Some "network.ml",
Some 800,
Some s)
s
let re_add net (r,modifs) safe =
let add_wire = if safe then (add_wire r.Rule.input) else unsafe_add_wire in
let eid = net.fresh_id in
add_event ~replay:true eid (r,modifs) add_wire net
let re_add_rename sigma net (r,modifs) safe =
let add_wire = if safe then (add_wire r.Rule.input) else unsafe_add_wire in
let eid = net.fresh_id in
let arg =
PortMap.fold
(fun ((i,_)) modif_list sol ->
let rec aux a sol =
match a with
Rule.Bound (j,_)
| Rule.Test_bound (j,_)
| Rule.Side_break (j,_)
| Rule.Break (j,_)
| Rule.Init_bound (_,j,_) -> (IntSet.add j sol)
| Rule.Test_marked _
| Rule.Test_any_bound | Rule.Test_free | Rule.Remove | Rule.Marked _ | Rule.Init_mark _ | Rule.Init_free _ -> sol
| Rule.Before_After (x,y) -> aux x (aux y sol)
in
List.fold_left
(fun sol a -> aux a sol)
(IntSet.add i sol) modif_list)
modifs IntSet.empty
in
let unify_port (i,s) state sigma =
(*if Rule.is_pure_test state then (*adding a test node*)*)
let sigma = rename_before_adding_wire sigma (i,s) (eid,state) net.wires
in
sigma
(*else (*adding a modification node*)
let sigma = rename_before_adding_wire sigma (i,s) (eid,state) net.wires
in
sigma
*)
in
try
begin
let sigma =
PortMap.fold
(fun (i,s) modif_list sigma ->
let state = List.hd (List.rev modif_list) in
try (let _ = IntMap.find i sigma in
unify_port (i,s) state sigma )
with Not_found -> sigma)
modifs sigma
in
let f x = try (IntMap.find x sigma) with Not_found -> x in
let _ =
IntSet.fold
(fun i set -> let j = f i in
if IntSet.mem j set then raise Exit
else IntSet.add j set)
arg IntSet.empty in
let net = add_event ~replay:true eid (r,modifs) add_wire net in
(net,sigma,true)
end
with _ -> (net,sigma,false)
let cut net (rids,obs_str) =
let ids =
IntSet.singleton (net.fresh_id-1) (*if flagged rule then obs is simply the last event*)
in
let opt = preds_closure net ids rids
in
match opt with
None -> None (*returns None is preds_closure doesn't contain rules specified by rids*)
| Some preds_star ->
let h =
IntSet.fold (fun i h ->
let e =
try EventArray.find i net.events
with Not_found ->
let s = "Network.cut: event not bound" in
Error.runtime
(Some "network.ml",
Some 879,
Some s)
s
in
{h with
events = EventArray.add i e h.events ;
s_preds = IntMap.add i (strong_preds i net) h.s_preds ;
w_preds =
begin
let w_ids = weak_preds i net in
(*only adding weak arrows that are internal to the story*)
let w_ids =
IntSet.fold (fun eid set ->
if IntSet.mem eid preds_star then
IntSet.add eid set
else set
) w_ids IntSet.empty
in
IntMap.add i w_ids h.w_preds
end;
fresh_id = if (i >= h.fresh_id) then (i+1) else h.fresh_id ;
last = if IntSet.mem i net.last then IntSet.add i h.last else h.last ;
}
) preds_star {(empty()) with wires = net.wires}
in
(*if port_obs = [] then *)
let id_obs =
try IntSet.choose h.last with Not_found ->
let s = "Network.cut: empty story" in
Error.runtime
(Some "network.ml",
Some 910,
Some s)
s
should be only one
let e_obs = (*IntMap.find id_obs h.events *)
try EventArray.find id_obs h.events
with Not_found ->
let s = "Network.cut: empty story" in
Error.runtime
(Some "network.ml",
Some 920,
Some s)
s
in
(Some {h with events = EventArray.add id_obs {e_obs with kind=2} h.events})
let obs_story h =
let rec find_obs last =
if IntSet.is_empty last
then
let s = "No observable in story" in
Error.runtime
(Some "network.ml",
Some 934,
Some s)
s
else
let i = IntSet.choose last in
let e = (*IntMap.find i h.events*) EventArray.find i h.events in
if e.kind = 2 then
match Rule.flag e.r with
None -> e.label
| Some flg -> flg
else
let s = "No observable in story" in
Error.runtime
(Some "network.ml",
Some 948,
Some s)
s
(*find_obs (IntSet.remove i last)*)
in
find_obs h.last
let weigth net =
if !Data.reorder_by_depth then
let map =
EventArray.fold
(fun i j map ->
let depth = j.g_depth in
let old =
try (IntMap.find depth map)
with Not_found -> 0 in
IntMap.add depth (old+1) map)
net.events
IntMap.empty in
IntMap.fold (fun depth n sol -> if n=0 then sol else (depth,n)::sol)
map []
else
[0,net.fresh_id]
let rec compare_net w w' =
match w,w'
with
[],[] -> 0
| [],_ -> -1
| _,[] -> 1
| (a,b)::q,(a',b')::q' ->
if a<a' then -1
else if a>a' then 1
else if b<b' then -1
else if b>b' then 1
else compare_net q q'
| null | https://raw.githubusercontent.com/kappamodeler/kappa/de63d1857898b1fc3b7f112f1027768b851ce14d/simplx_rep/src/stories/network.ml | ocaml | *Implementation of non interleaving semantics of computation traces
e.nodes : wire_id -> modif_type (or Not_found)
if wire is empty, plugging always succeeds
if !Data.sanity_check then
else Error.warning
remove action is always compatible
if wire is empty, plugging always fails
Error.runtime
remove action is always compatible
backtracks last modif of wire
sanity check
Replace wires by extensible array
new event identifier
set of rule id that belong to s_preds(eid)
new event identifier
IntMap.find i net.events
no need to add sequence of modifications since there is no previous event
*Adding the new event [eid] and updating precedence relation if necessary
adding a test node
predecessors are modifications of wires of eid
Pure modif of a quark does not genereate precedence but may generate non permutation
raise (Rule.Opposite e.nodes) in case of success
a pure test is preventing trivial compression
Printf.printf "%s\n%s\n" e.label r.Rule.input; flush stdout ;
If there is no trivial compression
*When added event can collapse nodes in [nodes]
removing rm_eid from network
if Rule.is_pure_test state then (*adding a test node
else (*adding a modification node
if flagged rule then obs is simply the last event
returns None is preds_closure doesn't contain rules specified by rids
only adding weak arrows that are internal to the story
if port_obs = [] then
IntMap.find id_obs h.events
IntMap.find i h.events
find_obs (IntSet.remove i last) |
open Mods2
type eid = int
type node = (eid*Rule.modif_type)
kind:= 0 : intro 1 : classic 2 : obs
type event = {r:Rule.t;label:string;s_depth:int;g_depth:int ;kind:int;nodes:Rule.modif_type list PortMap.t}
let empty_event = {r=Rule.empty;label="";s_depth=(-1); g_depth=(-1); kind=(-1);nodes=PortMap.empty}
let is_empty_event e = (e.s_depth = (-1))
module Wire :
sig
type t
val empty : t
val plug : string -> (int*string) -> node -> t -> t
val rename_before_plugging : int IntMap.t -> (int*string) -> node -> t -> int IntMap.t
val unsafe_plug : node -> t -> t
exception Empty
val top_event : t -> node
val backtrack : t -> eid -> t
val last_mod : t -> eid
val testing : t -> eid list
val print : t -> unit
val fold_left : ('a -> node -> 'a) -> 'a -> t -> 'a
val exists: (node -> bool) -> t -> bool
val can_push_to_collapse: t -> eid -> eid -> bool
end
=
struct
type t = node list
let exists = List.exists
let fold_left f a b = List.fold_left f a (List.rev b)
let empty = []
let rec can_push_to_collapse w eid rm_id =
match w with
[] ->
let s = "Wire.push_to_collapse: empty wire" in
Error.runtime
(Some "network.ml",
Some 47,
Some s)
s
| (i,modif)::tl ->
if i=rm_id then can_push_to_collapse tl eid rm_id
else
if i=eid then true
else
if Rule.is_pure_test [modif] then can_push_to_collapse tl eid rm_id
else false
pluggin a new quark modif / test without consistency requirement - > strong compression
node::w
safe pluggin of a new quark modif / test
else
let old_state = (fun (x,y) -> y)(List.hd w)
and new_state = (fun (x,y) -> y) node
in
let old_state =
let rec aux old_state =
match old_state with Rule.Before_After (_,y) -> aux y
| _ -> old_state in
aux old_state in
let error b =
let add_msg = Printf.sprintf "\nIn rule %s\n" rule_str in
err (
(string_of_port (i,s))^": "
^"Consistency check failed, adding "
^(Rule.string_of_modif_type new_state)
^" when previous node was "
^(Rule.string_of_modif_type old_state)
^add_msg
)
in
let push (eid,modif) w =
match w with
[] -> [(eid,modif)]
| (eid',_)::tl -> if eid=eid' then (eid,modif)::tl else (eid,modif)::w
in
let rec aux new_state =
match new_state with
Rule.Before_After (_,y) -> aux y
| Rule.Test_bound (i,s) -> (
match old_state with
(Rule.Bound (i',s') | Rule.Init_bound (_,i',s') | Rule.Test_bound (i',s')) ->
if (i'=i) && (s=s') then push node w else error 95
| Rule.Test_any_bound -> push node w
| _ -> error 98
)
| Rule.Test_marked s -> (
match old_state with
(Rule.Test_marked s' | Rule.Marked (_,s') | Rule.Init_mark (_,s')) -> if s'=s then push node w else error 102
| _ -> error 103
)
| Rule.Test_any_bound -> (
match old_state with
(Rule.Before_After _ |Rule.Init_bound _ | Rule.Bound _ | Rule.Test_bound _ | Rule.Test_any_bound) -> push node w
| _ -> error 108
)
| Rule.Test_free -> (
match old_state with
(Rule.Before_After _ | Rule.Init_free _ | Rule.Test_free | Rule.Break _ | Rule.Side_break _) -> push node w
| _ -> error 113
)
| Rule.Bound (i,s) -> (
match old_state with
| Rule.Init_free _ | Rule.Break _ | Rule.Test_free | Rule.Side_break _ -> push node w
| _ -> error 118
)
| Rule.Break (i,s) ->
(match old_state with Rule.Before_After _ -> push node w
| _ ->
if (old_state = Rule.Bound(i,s)) or (old_state = Rule.Test_bound(i,s)) or (old_state = Rule.Test_any_bound)
or (match old_state with Rule.Init_bound (_,i',s') when i=i' && s=s' -> true | _ -> false)
then push node w else error 125)
| Rule.Marked (old_m,_) -> (
match old_state with
(Rule.Marked (_,s') | Rule.Init_mark (_,s') | Rule.Test_marked s') ->
if (old_m = s') then push node w else error 129
| _ -> error 130
)
| Rule.Side_break (i,s) ->
if (old_state = Rule.Bound(i,s))
or (match old_state with Rule.Init_bound(_,i',s') when i=i' && s=s' -> true | _ -> false)
or (old_state = Rule.Test_bound(i,s))
or (old_state = Rule.Test_any_bound)
then push node w else error 138
| Rule.Init_bound _ ->
begin
match old_state with
Rule.Init_free _ -> push node w
| _ ->
let s = "Network.plug: invalid sequence of modif on a single quark" in
Error.runtime
(Some "network.ml",
Some 147,
Some s)
s
end
| Rule.Init_mark _ | Rule.Init_free _ ->
let s = "Network.plug: adding an initial state to a non empty wire." in
Error.runtime
(Some "network.ml",
Some 155,
Some s)
s in
aux new_state
let rec rename_before_plugging sigma (i,s) node w =
let codomain =
IntMap.fold
(fun _ -> IntSet.add) sigma IntSet.empty in
let f x = try IntMap.find x sigma with Not_found ->
if IntSet.mem x codomain then x else x in
let i' = f i in
let node' = (fst node,Rule.subs_act sigma (snd node)) in
safe pluggin of a new quark modif / test
else
let old_state = (fun (x,y) -> y)(List.hd w)
and new_state = (fun (x,y) -> y) node'
in
let old_state =
let rec aux old_state =
match old_state with Rule.Before_After (_,y) -> aux y
| _ -> old_state in
aux old_state in
let old_state = Rule.subs_act sigma old_state in
let new_state = Rule.subs_act sigma new_state in
= (string_of_port (i',s))^": "
^"Consistency check failed, adding "
^(Rule.string_of_modif_type new_state)
^" when previous node was "
^(Rule.string_of_modif_type old_state)
in
Error.runtime
(Some "network.ml",
Some b,
Some s)
s
in
let unify i i' sigma =
try (let _ = IntMap.find i sigma in None)
with Not_found ->
try (let _ = IntMap.find i' sigma in None)
with Not_found ->
Some (IntMap.add i i' (IntMap.add i' i sigma))
in
let rec aux new_state =
match new_state with
Rule.Before_After (_,y) -> aux y
| Rule.Test_bound (i,s) -> (
match old_state with
(Rule.Bound (i',s') | Rule.Init_bound (_,i',s') | Rule.Test_bound (i',s')) ->
if (i'=i) && (s=s') then sigma else
begin
if s=s' then
match unify i i' sigma with
None -> error 210
|Some sigma -> sigma
else
error 213
end
| Rule.Test_any_bound -> sigma
| _ -> error 216
)
| Rule.Test_marked s -> (
match old_state with
(Rule.Test_marked s' | Rule.Marked (_,s') | Rule.Init_mark (_,s')) -> if s'=s then sigma else error 220
| _ -> error 221
)
| Rule.Test_any_bound -> (
match old_state with
(Rule.Before_After _ |Rule.Init_bound _ | Rule.Bound _ | Rule.Test_bound _ | Rule.Test_any_bound) -> sigma
| _ -> error 226
)
| Rule.Test_free -> (
match old_state with
(Rule.Before_After _ | Rule.Init_free _ | Rule.Test_free | Rule.Break _ | Rule.Side_break _) -> sigma
| _ -> error 231
)
| Rule.Bound (i,s) -> (
match old_state with
| Rule.Init_free _ | Rule.Break _ | Rule.Test_free | Rule.Side_break _ -> sigma
| _ -> error 236
)
| Rule.Break (i,s) ->
(match old_state with Rule.Before_After _ -> sigma
| _ ->
(match old_state with Rule.Bound(i',s')
| Rule.Test_bound(i',s')
|Rule.Init_bound (_,i',s') ->
if i=i' && s=s' then sigma
else if s=s' then
match unify i i' sigma
with Some sigma' -> sigma'
| None -> error 249
else error 250
| _ -> error 251
))
| Rule.Marked (old_m,_) ->
(
match old_state with
(Rule.Marked (_,s') | Rule.Init_mark (_,s') | Rule.Test_marked s') ->
if (old_m = s') then sigma else error 257
| _ -> error 258
)
| Rule.Side_break (i,s) ->
(match old_state
with
Rule.Bound(i',s')
|Rule.Init_bound(_,i',s')
| Rule.Test_bound(i',s') -> if i=i' && s=s' then sigma else if s = s' then
match unify i i' sigma with
None -> error 268
|Some sigma -> sigma
else error 270
|
Rule.Test_any_bound -> sigma
| _ -> error 273)
| (Rule.Init_bound _|Rule.Init_mark _|Rule.Init_free _) ->
let s = "Network.plug: adding an initial state to a non empty wire." in
Error.runtime
(Some "network.ml",
Some 279,
Some s)
s
in
aux new_state
exception Empty
let rec backtrack w eid =
match w with
(eid',state)::tl ->
if (eid = eid') then tl
else
else
let s = "Network.Wire.backtrack: sanity check failed" in
Error.runtime
(Some "network.ml",
Some 297,
Some s)
s
| [] -> raise Empty
let rec last_mod w =
match w with
(eid,state)::tl -> if Rule.contains_modif [state] then eid else (last_mod tl)
| [] -> raise Not_found
let rec testing w =
match w with
(eid,state)::tl -> if Rule.is_pure_test [state] then (eid::(testing tl)) else []
| [] -> []
let top_event w =
match w with
(eid,state)::_ -> (eid,state)
| [] -> raise Empty
let rec print w =
match w with
(eid,state)::tl -> Printf.printf "%d--(%s)\n" eid (Rule.string_of_modif_type state); print tl
| [] -> ()
end
module EventArray = Array_ext.Make(struct type t = event let default = empty_event end)
name_of_agent:string array option;
events: int EventArray.t ;
: eid - > { eids } -- set of identifiers that precede pid
weak predecessors of eid
wires : ( i , s ) - > Wire.t = [ Test;Test; ... ( i , s ) ; .... ]
last: IntSet.t ;
}
let strong_preds eid net = try IntMap.find eid net.s_preds with Not_found -> IntSet.empty
let weak_preds eid net = try IntMap.find eid net.w_preds with Not_found -> IntSet.empty
let rid_preds eid net = try IntMap.find eid net.rid_preds with Not_found -> IntSet.empty
f_name_of_agent:string list ;
f_events: (int*event) list ;
: eid - > { eids } -- set of identifiers that precede pid
f_w_preds: IntSet.t IntMap.t ;
f_rid_preds: IntSet.t IntMap.t ;
wires : ( i , s ) - > Wire.t = [ Test;Test; ... ( i , s ) ; .... ]
f_last: IntSet.t ;
}
let marshal net =
{f_fresh_id = net.fresh_id ;
f_name_of_agent =
begin
match net.name_of_agent with
None -> []
| Some n_of_a -> Array.to_list n_of_a
end;
f_events = EventArray.fold (fun i e cont -> (i,e)::cont) net.events [] ;
f_s_preds = net.s_preds ;
f_w_preds = net.w_preds ;
f_rid_preds = net.rid_preds ;
f_wires = net.wires ;
f_last = net.last
}
let unmarshal f_net =
{fresh_id = f_net.f_fresh_id ;
name_of_agent =
begin
match f_net.f_name_of_agent with
[] -> None
| n_of_a -> Some (Array.of_list n_of_a)
end;
events = List.fold_left (fun ar (i,e) -> let ar = EventArray.add i e ar in ar) (EventArray.create 1) f_net.f_events ;
s_preds = f_net.f_s_preds ;
w_preds = f_net.f_w_preds ;
rid_preds = f_net.f_rid_preds ;
wires = f_net.f_wires ;
last = f_net.f_last
}
let empty() =
{fresh_id=0;
events = EventArray.create 100 ;
wires = PortMap.empty;
s_preds = IntMap.empty ;
w_preds = IntMap.empty ;
rid_preds = IntMap.empty ;
last = IntSet.empty;
name_of_agent = None;
}
let is_empty net = EventArray.is_empty net.events
let copy net =
let name_of_agent'=
match net.name_of_agent with
None -> None
| Some n_of_a -> Some (Array.copy n_of_a)
in
{net with events = EventArray.copy net.events ; name_of_agent = name_of_agent'}
let event_of_id i net =
try
EventArray.find i net.events
with
Not_found ->
let error = Printf.sprintf "event_of_id: %d does not correspond to any event" i
in
Error.runtime
(Some "network.ml",
Some 407,
Some error)
error
let unsafe_add_wire (i,s) node (wires:Wire.t PortMap.t) =
let w = try PortMap.find (i,s) wires with Not_found -> Wire.empty in
PortMap.add (i,s) (Wire.unsafe_plug node w) wires
let add_wire str (i,s) node (wires:Wire.t PortMap.t) =
let w = try PortMap.find (i,s) wires with Not_found -> Wire.empty in
PortMap.add (i,s) (Wire.plug str (i,s) node w) wires
let rename_before_adding_wire sigma (i,s) node (wires:Wire.t PortMap.t) =
let w = try PortMap.find
((try IntMap.find i sigma with Not_found -> i),s) wires with Not_found -> Wire.empty in
let sigma = Wire.rename_before_plugging sigma (i,s) node w in
sigma
let add_intro (str,modifs) safe net =
let add_wire = if safe then add_wire str else unsafe_add_wire in
let eid = net.fresh_id in
let e = {r=Rule.empty;label=str;s_depth=0;g_depth=0;kind=0;nodes=PortMap.empty}
in
let net =
PortMap.fold (fun (i,s) state net ->
let e =
try EventArray.find eid net.events with Not_found -> e
in
let e = {e with nodes = PortMap.add (i,s) state e.nodes}
in
let wires = add_wire
(i,s)
node
net.wires
in
{net with
events = EventArray.add eid e net.events ;
wires = wires;
last = IntSet.add eid net.last}
) modifs net
in
{net with fresh_id = net.fresh_id+1}
let preds_closure net closure with_rids =
let rec f net closure (todo_set,rids) =
let news,rids =
IntSet.fold (fun i (set,rids) ->
let p_i = strong_preds i net in
IntSet.fold (fun i (set,rids) ->
if IntSet.mem i closure then (set,rids)
else
let e = event_of_id i net in
(IntSet.add i set, IntSet.remove e.r.Rule.id rids)
) p_i (set,rids)
) todo_set (IntSet.empty,rids)
in
if IntSet.is_empty news then if IntSet.is_empty rids then (Some closure) else None
else f net (IntSet.union todo_set (IntSet.union news closure)) (news,rids)
in
f net closure (closure,IntSet.fold (fun eid rids ->
let e = event_of_id eid net in
let r_id = e.r.Rule.id in
IntSet.remove r_id rids
) closure with_rids)
returns immediate predecessors of eid , whether weak or strong , which are maximal if eid is removed
let immediate_preds eid net =
let is_top_after_removal rm_id kept_id net =
try
PortMap.fold (fun (i,s) modif _ ->
let w_is = PortMap.find (i,s) net.wires in
if Wire.can_push_to_collapse w_is eid rm_id then ()
else raise False
) (event_of_id kept_id net).nodes () ; true
with
False -> false
| _ ->
let s = "Network.immediate_preds: event or wire not found in network" in
Error.runtime
(Some "network.ml",
Some 484,
Some s)
s
in
let weak = weak_preds eid net
and strong = strong_preds eid net
in
let prob_preds = IntSet.union weak strong in
let set,_ =
IntSet.fold (fun j (set,blacklist) ->
let weak_j = weak_preds j net
and strong_j = strong_preds j net
in
let set = IntSet.fold (fun i set -> IntSet.remove i set) weak_j set in
let set = IntSet.fold (fun i set -> IntSet.remove i set) strong_j set in
let blacklist = IntSet.union weak_j (IntSet.union strong_j blacklist) in
if IntSet.mem j blacklist then (set,blacklist) else
if is_top_after_removal eid j net then (IntSet.add j set,blacklist)
else (set,IntSet.add j blacklist)
) prob_preds (IntSet.empty,IntSet.empty)
in
set
let add_event ?(replay=false) eid (r,modifs) add_wire net =
let net =
PortMap.fold (fun (i,s) modif_list net ->
List.fold_right (fun state net ->
let w_is = try PortMap.find (i,s) net.wires with Not_found -> Wire.empty in
let l_test = if Rule.contains_modif [state] then Wire.testing w_is else [] in
event . ( i , s )
and old_strong = strong_preds eid net
and old_weak = weak_preds eid net
and old_rid = rid_preds eid net
in
let strong,weak,rid = List.fold_right (fun j (strong,weak,rid) ->
if event has multiple
else
let weak = IntSet.remove j weak
and strong = IntSet.add j strong
and rid =
let e = event_of_id j net in
IntSet.add (e.r.Rule.id) rid
in
(strong,weak,rid)
) l_mod (old_strong,old_weak,old_rid)
in
let weak =
List.fold_right (fun j set ->
if (j=eid) or (IntSet.mem j strong) then set
else
IntSet.add j set
) l_test weak
in
(strong,weak,rid)
in
let wires = add_wire (i,s) (eid,state) net.wires
in
{net with
s_preds = IntMap.add eid preds_eid net.s_preds;
w_preds = IntMap.add eid weak_preds net.w_preds;
rid_preds = IntMap.add eid rid net.rid_preds;
wires = wires
}
let weak_preds =
let w_is = try PortMap.find (i,s) net.wires with Not_found -> Wire.empty in
let l_test = Wire.testing w_is in
let old_strong = strong_preds eid net in
let old_weak = weak_preds eid net in
List.fold_right (fun i set ->
if i=eid or IntSet.mem i old_strong then set
else IntSet.add i set
) l_test old_weak
in
let wires = add_wire (i,s) (eid,state) net.wires in
{net with
w_preds = IntMap.add eid weak_preds net.w_preds;
wires = wires
}
) modif_list net
) modifs net
in
let strong = strong_preds eid net in
let weak = weak_preds eid net in
let _ =
if !Data.sanity_check then
let set = IntSet.inter weak strong in
if IntSet.is_empty set then ()
else
let s = "QA failed in Network.event_add: weak and strong precedence should have an emtpy intersection"
in
Error.runtime
(Some "network.ml",
Some 575,
Some s)
s
else ()
in
let s_d,g_d,last =
IntSet.fold (fun i (s_mx,g_mx,last) ->
try
let last = IntSet.remove i last in
let e = EventArray.find i net.events
in
let s_mx = if (e.s_depth > s_mx) && (IntSet.mem i strong) then e.s_depth else s_mx
and g_mx = if (e.g_depth > g_mx) then e.g_depth else g_mx
in
weak does not change depth of events
with Not_found ->
let s =
("Network.add: event "^(string_of_int i)^" not found in predecessors of "^(string_of_int eid))
in
Error.runtime
(Some "network.ml",
Some 596,
Some s)
s
) (IntSet.union strong weak) (0,0,net.last)
in
let e = {r=r;
label=PortMap.fold (fun (i,s) _ label ->
if (s="_!" or s="_~") then label else
Printf.sprintf "<%d,%s>%s" i s label
) modifs (Printf.sprintf "\n%s" r.Rule.input) ;
s_depth=s_d+1;
g_depth=g_d+1;
kind=1;
nodes = modifs ;
}
in
{net with
events = EventArray.add eid e net.events ;
fresh_id = net.fresh_id+1;
last = IntSet.add eid last
}
let add sol net (r,modifs) debug compress =
try
let _ =
if compress then
let candidates =
PortMap.fold (fun (i,s) states candidates ->
if not (Rule.contains_modif states) or (Rule.is_creation states) or (Rule.is_deletion states)
if List.hd contains than so other actions in List.tl
else
let w_is = try PortMap.find (i,s) net.wires with Not_found ->
let s = (Printf.sprintf "Network.add: Wire (%d,%s) not found!" i s) in
Error.runtime
(Some "network.ml",
Some 632,
Some s)
s
in
let opt_eid_state = (try Some (Wire.top_event w_is) with Wire.Empty -> None) in
match opt_eid_state with
Some (eid',state') ->
if not (IntSet.mem eid' net.last) then candidates else
let e = event_of_id eid' net in
if e.kind=0 then candidates
else
if Rule.contains_modif [state'] then IntSet.add eid' candidates
| None -> candidates
) modifs IntSet.empty
in
try
IntSet.iter (fun eid ->
let e = EventArray.find eid net.events
in
Rule.opposite modifs e.nodes sol
) candidates
with Not_found ->
let s = "Network.add: event not found" in
Error.runtime
(Some "network.ml",
Some 659,
Some s)
s
else ()
in
let eid = net.fresh_id in
(try
with Not_found ->
let s = "Network.add_event: not found raised" in
Error.runtime
(Some "network.ml",
Some 671,
Some s)
s)
with
begin
let opt = PortMap.fold (fun (i,s) states opt ->
if not (Rule.contains_modif states) then opt
else
let eid,_ = Wire.top_event (PortMap.find (i,s) net.wires) in
match opt with
Some eid' ->
if eid=eid' then Some eid
else
begin
let msg =
Printf.sprintf
"Network.add: invariant violation, cannot collapse \n%s\n%s\n with"
(PortMap.fold (fun (i,s) _ label ->
if (s="_!" or s="_~") then label else
Printf.sprintf "<%d,%s>%s" i s label
) modifs "")
r.Rule.input
and msg2 =
let event = event_of_id eid net
and event'= event_of_id eid' net
in
Printf.sprintf "%d:%s\n%d:%s\n" eid event.label eid' event'.label
in
Printf.printf "last:%s\n" (string_of_set string_of_int IntSet.fold net.last) ; flush stdout ;
let s = (msg^"\n"^msg2) in
Error.runtime
(Some "network.ml",
Some 704,
Some s)
s
end
| None -> Some eid
) nodes None
in
let rm_eid =
match opt with
None ->
let s = "Network.add: invalid argument" in
Error.runtime
(Some "network.ml",
Some 715,
Some s)
s
| Some eid -> eid in
let _ =
if IntSet.mem rm_eid net.last then ()
else
let s = "Network.add: removed event is not maximal" in
Error.runtime
(Some "network.ml",
Some 727,
Some s)
s
in
try IntMap.find rm_eid net.preds with Not_found - > IntSet.empty in
let events,preds,w_preds =
(
removing information about of rm_eid which is now useless
IntMap.remove rm_eid net.w_preds
)
in
let _ =
if !Data.sanity_check then
(
IntMap.fold (fun eid set _ ->
if IntSet.mem rm_eid set then
let s = (Printf.sprintf "QA failed in Network.add: removed eid is a weak predecessor of event %d" eid) in
Error.runtime
(Some "network.ml",
Some 747,
Some s)
s
else ()
) net.w_preds () ;
IntMap.fold (fun eid set _ ->
if IntSet.mem rm_eid set then
let s = (Printf.sprintf "QA failed in Network.add: removed eid is a strong predecessor of event %d" eid) in
Error.runtime
(Some "network.ml",
Some 757,
Some s)
s
else ()
) net.s_preds ()
)
in
let net =
PortMap.fold (fun (i,s) _ net ->
let wires =
try
let w_is = PortMap.find (i,s) net.wires in
let w_is'= Wire.backtrack w_is rm_eid in
PortMap.add (i,s) w_is' net.wires
with
Wire.Empty ->
let msg = Printf.sprintf "Wire (%d,%s) is empty" i s in
Error.runtime
(Some "network.ml",
Some 777,
Some msg)
msg
| Not_found ->
let msg=Printf.sprintf "Wire (%d,%s) not found" i s in
Error.runtime
(Some "network.ml",
Some 784,
Some msg)
msg
in
{net with wires=wires}
) nodes {net with events=events;s_preds=preds; w_preds=w_preds ; fresh_id=net.fresh_id+1}
in
let last =
IntSet.fold (fun eid last -> IntSet.add eid last) preds_rm (IntSet.remove rm_eid net.last)
in
{net with last = last}
end
| Not_found ->
let s = "Network.add: not found raised" in
Error.runtime
(Some "network.ml",
Some 800,
Some s)
s
let re_add net (r,modifs) safe =
let add_wire = if safe then (add_wire r.Rule.input) else unsafe_add_wire in
let eid = net.fresh_id in
add_event ~replay:true eid (r,modifs) add_wire net
let re_add_rename sigma net (r,modifs) safe =
let add_wire = if safe then (add_wire r.Rule.input) else unsafe_add_wire in
let eid = net.fresh_id in
let arg =
PortMap.fold
(fun ((i,_)) modif_list sol ->
let rec aux a sol =
match a with
Rule.Bound (j,_)
| Rule.Test_bound (j,_)
| Rule.Side_break (j,_)
| Rule.Break (j,_)
| Rule.Init_bound (_,j,_) -> (IntSet.add j sol)
| Rule.Test_marked _
| Rule.Test_any_bound | Rule.Test_free | Rule.Remove | Rule.Marked _ | Rule.Init_mark _ | Rule.Init_free _ -> sol
| Rule.Before_After (x,y) -> aux x (aux y sol)
in
List.fold_left
(fun sol a -> aux a sol)
(IntSet.add i sol) modif_list)
modifs IntSet.empty
in
let unify_port (i,s) state sigma =
let sigma = rename_before_adding_wire sigma (i,s) (eid,state) net.wires
in
sigma
let sigma = rename_before_adding_wire sigma (i,s) (eid,state) net.wires
in
sigma
*)
in
try
begin
let sigma =
PortMap.fold
(fun (i,s) modif_list sigma ->
let state = List.hd (List.rev modif_list) in
try (let _ = IntMap.find i sigma in
unify_port (i,s) state sigma )
with Not_found -> sigma)
modifs sigma
in
let f x = try (IntMap.find x sigma) with Not_found -> x in
let _ =
IntSet.fold
(fun i set -> let j = f i in
if IntSet.mem j set then raise Exit
else IntSet.add j set)
arg IntSet.empty in
let net = add_event ~replay:true eid (r,modifs) add_wire net in
(net,sigma,true)
end
with _ -> (net,sigma,false)
let cut net (rids,obs_str) =
let ids =
in
let opt = preds_closure net ids rids
in
match opt with
| Some preds_star ->
let h =
IntSet.fold (fun i h ->
let e =
try EventArray.find i net.events
with Not_found ->
let s = "Network.cut: event not bound" in
Error.runtime
(Some "network.ml",
Some 879,
Some s)
s
in
{h with
events = EventArray.add i e h.events ;
s_preds = IntMap.add i (strong_preds i net) h.s_preds ;
w_preds =
begin
let w_ids = weak_preds i net in
let w_ids =
IntSet.fold (fun eid set ->
if IntSet.mem eid preds_star then
IntSet.add eid set
else set
) w_ids IntSet.empty
in
IntMap.add i w_ids h.w_preds
end;
fresh_id = if (i >= h.fresh_id) then (i+1) else h.fresh_id ;
last = if IntSet.mem i net.last then IntSet.add i h.last else h.last ;
}
) preds_star {(empty()) with wires = net.wires}
in
let id_obs =
try IntSet.choose h.last with Not_found ->
let s = "Network.cut: empty story" in
Error.runtime
(Some "network.ml",
Some 910,
Some s)
s
should be only one
try EventArray.find id_obs h.events
with Not_found ->
let s = "Network.cut: empty story" in
Error.runtime
(Some "network.ml",
Some 920,
Some s)
s
in
(Some {h with events = EventArray.add id_obs {e_obs with kind=2} h.events})
let obs_story h =
let rec find_obs last =
if IntSet.is_empty last
then
let s = "No observable in story" in
Error.runtime
(Some "network.ml",
Some 934,
Some s)
s
else
let i = IntSet.choose last in
if e.kind = 2 then
match Rule.flag e.r with
None -> e.label
| Some flg -> flg
else
let s = "No observable in story" in
Error.runtime
(Some "network.ml",
Some 948,
Some s)
s
in
find_obs h.last
let weigth net =
if !Data.reorder_by_depth then
let map =
EventArray.fold
(fun i j map ->
let depth = j.g_depth in
let old =
try (IntMap.find depth map)
with Not_found -> 0 in
IntMap.add depth (old+1) map)
net.events
IntMap.empty in
IntMap.fold (fun depth n sol -> if n=0 then sol else (depth,n)::sol)
map []
else
[0,net.fresh_id]
let rec compare_net w w' =
match w,w'
with
[],[] -> 0
| [],_ -> -1
| _,[] -> 1
| (a,b)::q,(a',b')::q' ->
if a<a' then -1
else if a>a' then 1
else if b<b' then -1
else if b>b' then 1
else compare_net q q'
|
b3b6aa8f4f5fce606c76151041bdf37cb11ccd4f6d46a7c8ce1fbf79884bdd50 | abakst/Brisk | Plugin.hs | module Plugin (plugin) where
import GhcPlugins
import IfaceEnv
import Finder
import OccName
import TcEnv
import TcRnMonad
plugin = briskPlugin
briskPlugin :: Plugin
briskPlugin = defaultPlugin {
installCoreToDos = installBrisk
}
installBrisk :: [CommandLineOption] -> [CoreToDo] -> CoreM [CoreToDo]
installBrisk bs todo
= do reinitializeGlobals
return (CoreDoPluginPass "Brisk" (briskPass bs) : todo)
briskPass :: [String] -> ModGuts -> CoreM ModGuts
briskPass bs guts
= do dflags <- getDynFlags
bindsOnlyPass (runBrisk bs guts) guts
runBrisk :: [String] -> ModGuts -> CoreProgram -> CoreM CoreProgram
runBrisk bs mg binds
= do hsenv <- getHscEnv
let occNm = mkOccName OccName.dataName "ProcessDefinition"
modNm = mkModuleName "Control.Distributed.Process.ManagedProcess"
liftIO $ do
found_module <- findImportedModule hsenv modNm Nothing
case found_module of
Found _ mod -> liftIO $ do
putStrLn "doing lookup"
initTcForLookup hsenv $ do
nm <- lookupOrig mod occNm
liftIO $ putStrLn "found orig"
tcLookup nm
putStrLn "OK"
return binds
| null | https://raw.githubusercontent.com/abakst/Brisk/3e4ce790a742d3e3b786dba45d36f715ea0e61ef/src/Plugin.hs | haskell | module Plugin (plugin) where
import GhcPlugins
import IfaceEnv
import Finder
import OccName
import TcEnv
import TcRnMonad
plugin = briskPlugin
briskPlugin :: Plugin
briskPlugin = defaultPlugin {
installCoreToDos = installBrisk
}
installBrisk :: [CommandLineOption] -> [CoreToDo] -> CoreM [CoreToDo]
installBrisk bs todo
= do reinitializeGlobals
return (CoreDoPluginPass "Brisk" (briskPass bs) : todo)
briskPass :: [String] -> ModGuts -> CoreM ModGuts
briskPass bs guts
= do dflags <- getDynFlags
bindsOnlyPass (runBrisk bs guts) guts
runBrisk :: [String] -> ModGuts -> CoreProgram -> CoreM CoreProgram
runBrisk bs mg binds
= do hsenv <- getHscEnv
let occNm = mkOccName OccName.dataName "ProcessDefinition"
modNm = mkModuleName "Control.Distributed.Process.ManagedProcess"
liftIO $ do
found_module <- findImportedModule hsenv modNm Nothing
case found_module of
Found _ mod -> liftIO $ do
putStrLn "doing lookup"
initTcForLookup hsenv $ do
nm <- lookupOrig mod occNm
liftIO $ putStrLn "found orig"
tcLookup nm
putStrLn "OK"
return binds
| |
4927f51a070ac7c050b0e943678b520b3f82dd80773d4edb51ce3a0b556b08e8 | shirok/Gauche | type.scm | ;; Tests for typeutil
(use gauche.test)
(test-start "typeutil")
(use gauche.typeutil)
(test-module 'gauche.typeutil)
(test-section "type constuctor memoization")
;; This tests the constructed types from the same arguments gets eq?,
;; because of the memoization.
(define-syntax t-equality
(syntax-rules ()
[(_ expect a b)
(test* (list 'a 'b) expect (eq? a b))]))
(t-equality #t (<?> <integer>) (<?> <integer>))
(t-equality #t (</> <integer> <string>) (</> <integer> <string>))
(t-equality #f (<?> <integer>) (<?> <int>))
(t-equality #t (</> <uint8> <uint16>) (</> <uint8> <uint16>))
(t-equality #f (</> <uint8> <uint16>) (</> <uint16> <uint8>))
(test-section "subtype?")
(define-syntax t-subtype
(syntax-rules ()
[(_ sub sup expect)
(test* (list 'subtype? 'sub 'sup) expect (subtype? sub sup))]))
(t-subtype <fixnum> <fixnum> #t)
(t-subtype <fixnum> <integer> #t)
(t-subtype <fixnum> <real> #t)
(t-subtype <fixnum> <number> #t)
(t-subtype <fixnum> <top> #t)
(t-subtype <bottom> <fixnum> #t)
(t-subtype <fixnum> <boolean> #f)
(t-subtype <short> <integer> #t)
(t-subtype <ushort> <integer> #t)
(t-subtype <int> <integer> #t)
(t-subtype <uint> <integer> #t)
(t-subtype <long> <integer> #t)
(t-subtype <ulong> <integer> #t)
(t-subtype <int8> <integer> #t)
(t-subtype <uint8> <integer> #t)
(t-subtype <int16> <integer> #t)
(t-subtype <uint16> <integer> #t)
(t-subtype <int32> <integer> #t)
(t-subtype <uint32> <integer> #t)
(t-subtype <int64> <integer> #t)
(t-subtype <uint64> <integer> #t)
(t-subtype <float> <integer> #f)
(t-subtype <float> <real> #t)
(t-subtype <float> <number> #t)
(t-subtype <double> <integer> #f)
(t-subtype <double> <real> #t)
(t-subtype <double> <number> #t)
(t-subtype <const-cstring> <const-cstring> #t)
(t-subtype <const-cstring> <string> #t)
(t-subtype <const-cstring> <boolean> #f)
(t-subtype <integer> (</> <integer> <string>) #t)
(t-subtype <integer> (</>) #f)
(t-subtype <integer> (</> <char> <string>) #f)
(t-subtype <integer> (</> <number> <string>) #t)
(t-subtype (</> <integer> <string>) <top> #t)
(t-subtype (</> <integer> <string>) <integer> #f)
(t-subtype (</> <integer> <string>) (</> <string> <integer>) #t)
(t-subtype (</> <integer> <string>) (</> <string> <char> <integer>) #t)
(t-subtype (</> <integer> <string>) (</> <char> <integer>) #f)
(t-subtype (</> <integer> <string>) (<?> (</> <number> <string>)) #t)
(t-subtype <integer> (<?> <integer>) #t)
(t-subtype <boolean> (<?> <integer>) #f)
(t-subtype <integer> (<?> <real>) #t)
(t-subtype <real> (<?> <integer>) #f)
(t-subtype (<?> <integer>) (<?> <real>) #t)
(t-subtype (<?> <integer>) <integer> #f)
(t-subtype (<?> <integer>) (</> (<?> <number>) (<?> <string>)) #t)
(t-subtype (<Tuple> <integer> <string>) <list> #t)
(t-subtype (<Tuple> <integer> <string>) (<Tuple> <integer> <string>) #t)
(t-subtype (<Tuple> <integer> <string>) (<Tuple> <integer> <string> <char>) #f)
(t-subtype (<Tuple> <integer> <string>) (<Tuple> <real> <string>) #t)
(t-subtype (<Tuple> <integer> <integer>) (<List> <integer>) #t)
(t-subtype (<Tuple> <integer> <integer>) (<List> <integer> 2) #t)
(t-subtype (<Tuple> <integer> <integer>) (<List> <integer> 0 2) #t)
(t-subtype (<Tuple> <integer> <integer>) (<List> <integer> 0 1) #f)
(t-subtype (<Tuple> <integer> <string>) (<List> <integer>) #f)
(t-subtype (<Tuple> <char> <string> *) <list> #t)
(t-subtype (<Tuple> <char> <string> *) (<Tuple> <char>) #f)
(t-subtype (<Tuple> <char> <string> *) (<Tuple> <char> <string>) #t)
(t-subtype (<Tuple> <char> <string> *) (<Tuple> <char> <string> <char>) #t)
(t-subtype (<Tuple> *) <list> #t)
(t-subtype (<Tuple> *) (<Tuple> <integer> *) #t)
(t-subtype (<Tuple> <integer>) (<Tuple> <integer> *) #t)
(t-subtype (<Tuple> <integer>) (<Tuple> <integer> <integer> *) #f)
(t-subtype (<Tuple> <integer> *) (<Tuple> <integer> <integer> *) #t)
(t-subtype (<List> <integer>) <list> #t)
(t-subtype (<List> <integer>) (<List> <number>) #t)
(t-subtype (<List> <number>) (<List> <integer>) #f)
(t-subtype (<List> <integer> 2 3) (<List> <integer> 0 4) #t)
(t-subtype (<List> <integer> 0 3) (<List> <integer> 2 3) #f)
(t-subtype (<List> <integer> 2 4) (<List> <integer> 2 3) #f)
(t-subtype (<List> <integer> #f 3) (<List> <integer> 0 4) #t)
(t-subtype (<List> <integer> #f 3) (<List> <integer> 0) #t)
(t-subtype (<List> <integer> 0) (<List> <integer> 0 3) #f)
(t-subtype (<List> <integer>) (<?> (<List> <number>)) #t)
(t-subtype (<List> <integer>) (</> (<List> <string>) (<List> <number>)) #t)
(t-subtype (<Vector> <integer>) <vector> #t)
(t-subtype (<Vector> <integer>) (<Vector> <number>) #t)
(t-subtype (<Vector> <number>) (<Vector> <integer>) #f)
(t-subtype (<Vector> <integer> 2 3) (<Vector> <integer> 0 4) #t)
(t-subtype (<Vector> <integer> 0 3) (<Vector> <integer> 2 3) #f)
(t-subtype (<Vector> <integer> 2 4) (<Vector> <integer> 2 3) #f)
(t-subtype (<Vector> <integer> #f 3) (<Vector> <integer> 0 4) #t)
(t-subtype (<Vector> <integer> #f 3) (<Vector> <integer> 0) #t)
(t-subtype (<Vector> <integer> 0) (<Vector> <integer> 0 3) #f)
(t-subtype (<Vector> <integer>) (<?> (<Vector> <number>)) #t)
(t-subtype (<Vector> <integer>) (</> (<Vector> <string>) (<Vector> <number>)) #t)
(test-section "built-in type constructors")
(define (validation-test type alist)
(dolist [p alist]
(test* (format "~a ~s" (class-name type) (car p))
(cdr p)
(of-type? (car p) type))))
(validation-test (</> <string> <integer>)
'(("abc" . #t)
(123 . #t)
(abc . #f)
(#f . #f)
(#t . #f)
(("abc") . #f)))
(validation-test (<Tuple> <char> <integer> <symbol>)
'(((#\a 1 a) . #t)
((#\a 1) . #f)
(() . #f)
((1 #\a b) . #f)
((#\a 1 b x) . #f)))
(validation-test (<?> <integer>)
'((3 . #t)
(#f . #t)
(#t . #f)
(3.5 . #f)))
(validation-test (<Tuple> (<?> <char>) (<?> <string>))
'((3 . #f)
((#\a "a") . #t)
((#f "a") . #t)
((#\a . "a") . #f)
((#\a "a" . z) . #f)
((#\a #f) . #t)
((#f #f) . #t)
((#f) . #f)
((#\a) . #f)
(("a") . #f)))
(validation-test (<Tuple> <integer> <real> *)
'(((2 2.3) . #t)
((2 2.3 3) . #t)
((2.2 3) . #f)
((2 2.3 . 3) . #f)))
(validation-test (<^> * -> *)
`((,car . #t)
(,cons . #t)
(,list . #t)
(1 . #f)
;;(#/abc/ . #t) ; applicable objects are not supported yet
))
(validation-test (<^> <top> -> *)
`((,car . #t)
(,cons . #f)
(,list . #f)
(,cons* . #t)
(,current-input-port . #f)
(,(lambda () #f) . #f)))
(validation-test (<^> -> *)
`((,(lambda () #f) . #t)
(,car . #f)
(,list . #t)))
(validation-test (<^> <top> <top> -> *)
`((,cons . #t)
(,car . #f)))
(validation-test (<^> <top> <top> -> *)
`((,(case-lambda ((a) 1) ((a b) 2)) . #t)))
(validation-test (</> (<^> <top> -> *) (<^> <top> <top> -> *))
`((,(case-lambda ((a) 1) ((a b) 2)) . #t)))
(validation-test (<List> <integer>)
'((() . #t)
((1) . #t)
((1 2 3 4 5 6 7) . #t)
((1 . 2) . #f)
((1 2 a 3 4) . #f)
(1 . #f)))
(validation-test (<List> <integer> 3)
'((() . #f)
((1) . #f)
((1 2 3) . #t)
((1 2 3 4) . #t)
((1 2 3 4 5 6 7) . #t)
((1 . 2) . #f)
((1 2 a 3 4) . #f)
(1 . #f)))
(validation-test (<List> <integer> #f 3)
'((() . #t)
((1) . #t)
((1 2 3) . #t)
((1 2 3 4) . #f)
((1 2 3 4 5 6 7) . #f)
((1 . 2) . #f)
((1 2 a 3 4) . #f)
(1 . #f)))
(validation-test (<List> <integer> 3 3)
'((() . #f)
((1) . #f)
((1 2 3) . #t)
((1 2 3 4) . #f)
((1 2 3 4 5 6 7) . #f)
((1 . 2) . #f)
((1 2 a 3 4) . #f)
(1 . #f)))
(validation-test (<Vector> <integer>)
'((#() . #t)
(#(1) . #t)
(#(1 2 3 4 5 6 7) . #t)
(#(1 2 a 3 4) . #f)
((1) . #f)))
(validation-test (<Vector> <integer> 3)
'((#() . #f)
(#(1) . #f)
(#(1 2 3) . #t)
(#(1 2 3 4) . #t)
(#(1 2 3 4 5 6 7) . #t)
(#(1 2 a 3 4) . #f)
((1) . #f)))
(validation-test (<Vector> <integer> #f 3)
'((#() . #t)
(#(1) . #t)
(#(1 2 3) . #t)
(#(1 2 3 4) . #f)
(#(1 2 3 4 5 6 7) . #f)
(#(1 2 a 3 4) . #f)
(1 . #f)))
(validation-test (<Vector> <integer> 3 3)
'((#() . #f)
(#(1) . #f)
(#(1 2 3) . #t)
(#(1 2 3 4) . #f)
(#(1 2 3 4 5 6 7) . #f)
(#(1 2 a 3 4) . #f)
(1 . #f)))
(test-section "procedure types")
(define-syntax proctype-test
(syntax-rules ()
[(_ proc supposed-type)
(test* '(procedure-type proc) supposed-type
(procedure-type proc))]))
(proctype-test cons (<^> <top> <top> -> <pair>))
(proctype-test car (<^> <pair> -> <top>))
(proctype-test list (<^> * -> <list>))
(proctype-test set-cdr! (<^> <pair> <top> -> <void>))
;; This tests gf's type is recomputed after method addition
(define-method a-gf ((x <number>)) x)
(proctype-test a-gf (</> (<^> <number> -> *)))
(define-method a-gf ((x <string>)) x)
(proctype-test a-gf (</> (<^> <string> -> *) (<^> <number> -> *)))
(test-end)
| null | https://raw.githubusercontent.com/shirok/Gauche/db8d3884a8057f1b980aaea08bb651649638abbd/test/type.scm | scheme | Tests for typeutil
This tests the constructed types from the same arguments gets eq?,
because of the memoization.
(#/abc/ . #t) ; applicable objects are not supported yet
This tests gf's type is recomputed after method addition |
(use gauche.test)
(test-start "typeutil")
(use gauche.typeutil)
(test-module 'gauche.typeutil)
(test-section "type constuctor memoization")
(define-syntax t-equality
(syntax-rules ()
[(_ expect a b)
(test* (list 'a 'b) expect (eq? a b))]))
(t-equality #t (<?> <integer>) (<?> <integer>))
(t-equality #t (</> <integer> <string>) (</> <integer> <string>))
(t-equality #f (<?> <integer>) (<?> <int>))
(t-equality #t (</> <uint8> <uint16>) (</> <uint8> <uint16>))
(t-equality #f (</> <uint8> <uint16>) (</> <uint16> <uint8>))
(test-section "subtype?")
(define-syntax t-subtype
(syntax-rules ()
[(_ sub sup expect)
(test* (list 'subtype? 'sub 'sup) expect (subtype? sub sup))]))
(t-subtype <fixnum> <fixnum> #t)
(t-subtype <fixnum> <integer> #t)
(t-subtype <fixnum> <real> #t)
(t-subtype <fixnum> <number> #t)
(t-subtype <fixnum> <top> #t)
(t-subtype <bottom> <fixnum> #t)
(t-subtype <fixnum> <boolean> #f)
(t-subtype <short> <integer> #t)
(t-subtype <ushort> <integer> #t)
(t-subtype <int> <integer> #t)
(t-subtype <uint> <integer> #t)
(t-subtype <long> <integer> #t)
(t-subtype <ulong> <integer> #t)
(t-subtype <int8> <integer> #t)
(t-subtype <uint8> <integer> #t)
(t-subtype <int16> <integer> #t)
(t-subtype <uint16> <integer> #t)
(t-subtype <int32> <integer> #t)
(t-subtype <uint32> <integer> #t)
(t-subtype <int64> <integer> #t)
(t-subtype <uint64> <integer> #t)
(t-subtype <float> <integer> #f)
(t-subtype <float> <real> #t)
(t-subtype <float> <number> #t)
(t-subtype <double> <integer> #f)
(t-subtype <double> <real> #t)
(t-subtype <double> <number> #t)
(t-subtype <const-cstring> <const-cstring> #t)
(t-subtype <const-cstring> <string> #t)
(t-subtype <const-cstring> <boolean> #f)
(t-subtype <integer> (</> <integer> <string>) #t)
(t-subtype <integer> (</>) #f)
(t-subtype <integer> (</> <char> <string>) #f)
(t-subtype <integer> (</> <number> <string>) #t)
(t-subtype (</> <integer> <string>) <top> #t)
(t-subtype (</> <integer> <string>) <integer> #f)
(t-subtype (</> <integer> <string>) (</> <string> <integer>) #t)
(t-subtype (</> <integer> <string>) (</> <string> <char> <integer>) #t)
(t-subtype (</> <integer> <string>) (</> <char> <integer>) #f)
(t-subtype (</> <integer> <string>) (<?> (</> <number> <string>)) #t)
(t-subtype <integer> (<?> <integer>) #t)
(t-subtype <boolean> (<?> <integer>) #f)
(t-subtype <integer> (<?> <real>) #t)
(t-subtype <real> (<?> <integer>) #f)
(t-subtype (<?> <integer>) (<?> <real>) #t)
(t-subtype (<?> <integer>) <integer> #f)
(t-subtype (<?> <integer>) (</> (<?> <number>) (<?> <string>)) #t)
(t-subtype (<Tuple> <integer> <string>) <list> #t)
(t-subtype (<Tuple> <integer> <string>) (<Tuple> <integer> <string>) #t)
(t-subtype (<Tuple> <integer> <string>) (<Tuple> <integer> <string> <char>) #f)
(t-subtype (<Tuple> <integer> <string>) (<Tuple> <real> <string>) #t)
(t-subtype (<Tuple> <integer> <integer>) (<List> <integer>) #t)
(t-subtype (<Tuple> <integer> <integer>) (<List> <integer> 2) #t)
(t-subtype (<Tuple> <integer> <integer>) (<List> <integer> 0 2) #t)
(t-subtype (<Tuple> <integer> <integer>) (<List> <integer> 0 1) #f)
(t-subtype (<Tuple> <integer> <string>) (<List> <integer>) #f)
(t-subtype (<Tuple> <char> <string> *) <list> #t)
(t-subtype (<Tuple> <char> <string> *) (<Tuple> <char>) #f)
(t-subtype (<Tuple> <char> <string> *) (<Tuple> <char> <string>) #t)
(t-subtype (<Tuple> <char> <string> *) (<Tuple> <char> <string> <char>) #t)
(t-subtype (<Tuple> *) <list> #t)
(t-subtype (<Tuple> *) (<Tuple> <integer> *) #t)
(t-subtype (<Tuple> <integer>) (<Tuple> <integer> *) #t)
(t-subtype (<Tuple> <integer>) (<Tuple> <integer> <integer> *) #f)
(t-subtype (<Tuple> <integer> *) (<Tuple> <integer> <integer> *) #t)
(t-subtype (<List> <integer>) <list> #t)
(t-subtype (<List> <integer>) (<List> <number>) #t)
(t-subtype (<List> <number>) (<List> <integer>) #f)
(t-subtype (<List> <integer> 2 3) (<List> <integer> 0 4) #t)
(t-subtype (<List> <integer> 0 3) (<List> <integer> 2 3) #f)
(t-subtype (<List> <integer> 2 4) (<List> <integer> 2 3) #f)
(t-subtype (<List> <integer> #f 3) (<List> <integer> 0 4) #t)
(t-subtype (<List> <integer> #f 3) (<List> <integer> 0) #t)
(t-subtype (<List> <integer> 0) (<List> <integer> 0 3) #f)
(t-subtype (<List> <integer>) (<?> (<List> <number>)) #t)
(t-subtype (<List> <integer>) (</> (<List> <string>) (<List> <number>)) #t)
(t-subtype (<Vector> <integer>) <vector> #t)
(t-subtype (<Vector> <integer>) (<Vector> <number>) #t)
(t-subtype (<Vector> <number>) (<Vector> <integer>) #f)
(t-subtype (<Vector> <integer> 2 3) (<Vector> <integer> 0 4) #t)
(t-subtype (<Vector> <integer> 0 3) (<Vector> <integer> 2 3) #f)
(t-subtype (<Vector> <integer> 2 4) (<Vector> <integer> 2 3) #f)
(t-subtype (<Vector> <integer> #f 3) (<Vector> <integer> 0 4) #t)
(t-subtype (<Vector> <integer> #f 3) (<Vector> <integer> 0) #t)
(t-subtype (<Vector> <integer> 0) (<Vector> <integer> 0 3) #f)
(t-subtype (<Vector> <integer>) (<?> (<Vector> <number>)) #t)
(t-subtype (<Vector> <integer>) (</> (<Vector> <string>) (<Vector> <number>)) #t)
(test-section "built-in type constructors")
(define (validation-test type alist)
(dolist [p alist]
(test* (format "~a ~s" (class-name type) (car p))
(cdr p)
(of-type? (car p) type))))
(validation-test (</> <string> <integer>)
'(("abc" . #t)
(123 . #t)
(abc . #f)
(#f . #f)
(#t . #f)
(("abc") . #f)))
(validation-test (<Tuple> <char> <integer> <symbol>)
'(((#\a 1 a) . #t)
((#\a 1) . #f)
(() . #f)
((1 #\a b) . #f)
((#\a 1 b x) . #f)))
(validation-test (<?> <integer>)
'((3 . #t)
(#f . #t)
(#t . #f)
(3.5 . #f)))
(validation-test (<Tuple> (<?> <char>) (<?> <string>))
'((3 . #f)
((#\a "a") . #t)
((#f "a") . #t)
((#\a . "a") . #f)
((#\a "a" . z) . #f)
((#\a #f) . #t)
((#f #f) . #t)
((#f) . #f)
((#\a) . #f)
(("a") . #f)))
(validation-test (<Tuple> <integer> <real> *)
'(((2 2.3) . #t)
((2 2.3 3) . #t)
((2.2 3) . #f)
((2 2.3 . 3) . #f)))
(validation-test (<^> * -> *)
`((,car . #t)
(,cons . #t)
(,list . #t)
(1 . #f)
))
(validation-test (<^> <top> -> *)
`((,car . #t)
(,cons . #f)
(,list . #f)
(,cons* . #t)
(,current-input-port . #f)
(,(lambda () #f) . #f)))
(validation-test (<^> -> *)
`((,(lambda () #f) . #t)
(,car . #f)
(,list . #t)))
(validation-test (<^> <top> <top> -> *)
`((,cons . #t)
(,car . #f)))
(validation-test (<^> <top> <top> -> *)
`((,(case-lambda ((a) 1) ((a b) 2)) . #t)))
(validation-test (</> (<^> <top> -> *) (<^> <top> <top> -> *))
`((,(case-lambda ((a) 1) ((a b) 2)) . #t)))
(validation-test (<List> <integer>)
'((() . #t)
((1) . #t)
((1 2 3 4 5 6 7) . #t)
((1 . 2) . #f)
((1 2 a 3 4) . #f)
(1 . #f)))
(validation-test (<List> <integer> 3)
'((() . #f)
((1) . #f)
((1 2 3) . #t)
((1 2 3 4) . #t)
((1 2 3 4 5 6 7) . #t)
((1 . 2) . #f)
((1 2 a 3 4) . #f)
(1 . #f)))
(validation-test (<List> <integer> #f 3)
'((() . #t)
((1) . #t)
((1 2 3) . #t)
((1 2 3 4) . #f)
((1 2 3 4 5 6 7) . #f)
((1 . 2) . #f)
((1 2 a 3 4) . #f)
(1 . #f)))
(validation-test (<List> <integer> 3 3)
'((() . #f)
((1) . #f)
((1 2 3) . #t)
((1 2 3 4) . #f)
((1 2 3 4 5 6 7) . #f)
((1 . 2) . #f)
((1 2 a 3 4) . #f)
(1 . #f)))
(validation-test (<Vector> <integer>)
'((#() . #t)
(#(1) . #t)
(#(1 2 3 4 5 6 7) . #t)
(#(1 2 a 3 4) . #f)
((1) . #f)))
(validation-test (<Vector> <integer> 3)
'((#() . #f)
(#(1) . #f)
(#(1 2 3) . #t)
(#(1 2 3 4) . #t)
(#(1 2 3 4 5 6 7) . #t)
(#(1 2 a 3 4) . #f)
((1) . #f)))
(validation-test (<Vector> <integer> #f 3)
'((#() . #t)
(#(1) . #t)
(#(1 2 3) . #t)
(#(1 2 3 4) . #f)
(#(1 2 3 4 5 6 7) . #f)
(#(1 2 a 3 4) . #f)
(1 . #f)))
(validation-test (<Vector> <integer> 3 3)
'((#() . #f)
(#(1) . #f)
(#(1 2 3) . #t)
(#(1 2 3 4) . #f)
(#(1 2 3 4 5 6 7) . #f)
(#(1 2 a 3 4) . #f)
(1 . #f)))
(test-section "procedure types")
(define-syntax proctype-test
(syntax-rules ()
[(_ proc supposed-type)
(test* '(procedure-type proc) supposed-type
(procedure-type proc))]))
(proctype-test cons (<^> <top> <top> -> <pair>))
(proctype-test car (<^> <pair> -> <top>))
(proctype-test list (<^> * -> <list>))
(proctype-test set-cdr! (<^> <pair> <top> -> <void>))
(define-method a-gf ((x <number>)) x)
(proctype-test a-gf (</> (<^> <number> -> *)))
(define-method a-gf ((x <string>)) x)
(proctype-test a-gf (</> (<^> <string> -> *) (<^> <number> -> *)))
(test-end)
|
b96b75f4c20984748b99bcf4fd52b775a776aa7588516c6b41f9d519808e0926 | anmonteiro/ocaml-mongodb | mongo.mli | * { b This is a major client - faced module , for the high level usage . }
This module includes a series of APIs that client can use directly to
communicate with MongoDB . The most important functions are for insert ,
udpate , delete , query , get_more . They are the essential interactions that a
client can have with MongoDB .
Please note that the current version of APIs here are all essential only .
For example , Clients can not set detailed flags for queries , etc . All
operations here are with default flags ( which is 0 ) .
A Mongo is bound to a db and a collection . All operations will be done upon
the bound db and collection only .
Please refer to
{ { : -driver/latest/legacy/mongodb-wire-protocol/ }
MongoDB Wire Protocol } for more information
This module includes a series of APIs that client can use directly to
communicate with MongoDB. The most important functions are for insert,
udpate, delete, query, get_more. They are the essential interactions that a
client can have with MongoDB.
Please note that the current version of APIs here are all essential only.
For example, Clients cannot set detailed flags for queries, etc. All
operations here are with default flags (which is 0).
A Mongo is bound to a db and a collection. All operations will be done upon
the bound db and collection only.
Please refer to
{{:-driver/latest/legacy/mongodb-wire-protocol/}
MongoDB Wire Protocol} for more information *)
(** the exception will be raised if anything is wrong, with a string message *)
module Config : sig
type t =
{ db : string
; collection : string
; host : string
; port : int
; max_connections : int
}
val create
: ?host:string
-> ?port:int
-> ?max_connections:int
-> db:string
-> collection:string
-> unit
-> t
end
module Response : sig
type t =
{ header : Header.t
; response_flags : int32
; cursor_id : int64
; starting_from : int32
; num_returned : int32
; document_list : Bson.t list
}
val to_string : t -> string
val pp_hum : Format.formatter -> t -> unit
end
module Connection : sig
type t
type error =
[ `Protocol_error of string
| `Eof
of Error_code.t * string
`Exn of exn
]
type ('a, 'b) response_handler = ('a, 'b) result -> unit
type error_handler = error -> unit
val create : config:Config.t -> t
val with_ : ?collection:string -> ?database:string -> t -> t
val with_collection : t -> string -> t
(** change instance collection *)
val message
: t
-> doc:Bson.t
-> response_handler:(Bson.t, 'a list) response_handler
-> unit
type write_error =
{ index : int
; code : int
; message : string
}
val insert
: ?ordered:bool
-> ?bypass_document_validation:bool
-> t
-> response_handler:((int, write_error list) result -> unit)
-> Bson.t list
-> unit
* { 6 Insert }
(** {6 Update} *)
type upserted =
{ index : int
; _id : string
}
type update_output =
{ found : int
; updated : int
; upserted : upserted list
}
val update
: t
-> ?ordered:bool
-> ?bypass_document_validation:bool
-> upsert:bool
-> all:bool
-> selector:Bson.t
-> response_handler:(update_output, write_error list) response_handler
-> Bson.t
-> unit
* update the { b first document } matched in MongoDB . e.g. , update_one m ( s ,
u ) ; ; m is the Mongo . s is the selector document , used to match the
documents that need to be updated . u is the update document and any
matched documents will be updated to u. May raise Mongo_failed exception .
u);; m is the Mongo. s is the selector document, used to match the
documents that need to be updated. u is the update document and any
matched documents will be updated to u. May raise Mongo_failed exception.*)
val update_one
: t
-> ?upsert:bool
-> selector:Bson.t
-> Bson.t
-> response_handler:((update_output, write_error list) result -> unit)
-> unit
val update_many
: t
-> ?upsert:bool
-> selector:Bson.t
-> Bson.t
-> response_handler:((update_output, write_error list) result -> unit)
-> unit
* update { b all documents } matched in MongoDB . e.g. , update m ( s , u ) ; ; m is
the Mongo . s is the selector document , used to match the documents that
need to be updated . u is the update document and any matched documents
will be updated to u. May raise Mongo_failed exception .
the Mongo. s is the selector document, used to match the documents that
need to be updated. u is the update document and any matched documents
will be updated to u. May raise Mongo_failed exception. *)
* { 6 Delete }
val delete
: ?ordered:bool
-> t
-> all:bool
-> selector:Bson.t
-> response_handler:(int, 'a list) response_handler
-> unit
val delete_one
: t
-> Bson.t
-> response_handler:(int, 'a list) response_handler
-> unit
* delete the { b first document } matched in MongoDB . e.g. , delete_one m s ; ; m
is the Mongo . s is the selector document , used to match the documents that
need to be deleted . May raise Mongo_failed exception .
is the Mongo. s is the selector document, used to match the documents that
need to be deleted. May raise Mongo_failed exception.*)
val delete_many
: t
-> Bson.t
-> response_handler:(int, 'a list) response_handler
-> unit
* delete the { b all documents } matched in MongoDB . e.g. , delete_one m s ; ; m
is the Mongo . s is the selector document , used to match the documents that
need to be deleted . May raise Mongo_failed exception .
is the Mongo. s is the selector document, used to match the documents that
need to be deleted. May raise Mongo_failed exception.*)
* { 6 Query / Find }
val find
: ?skip:int
-> ?limit:int
-> ?filter:Bson.t
-> ?sort:Bson.t
-> ?projection:Bson.t
-> t
-> response_handler:(Bson.t, 'a list) response_handler
-> unit
* find { b all / the default number } of documents in the db and collection .
May raise Mongo_failed exception .
May raise Mongo_failed exception.*)
val find_one
: ?skip:int
-> ?filter:Bson.t
-> ?projection:Bson.t
-> t
-> response_handler:(Bson.t, 'a list) response_handler
-> unit
* find { b the first } document in the db and collection . May raise
Mongo_failed exception .
Mongo_failed exception.*)
val find_and_modify
: ?bypass_document_validation:bool
-> ?query:Bson.t
-> ?sort:Bson.t
-> ?remove:bool
-> ?update:Bson.t
-> ?new_:bool
-> ?projection:Bson.t
-> ?upsert:bool
-> t
-> response_handler:(Bson.t, 'a list) response_handler
-> unit
val count
: ?skip:int
-> ?limit:int
-> ?query:Bson.t
-> t
-> response_handler:(int, 'a list) response_handler
-> unit
(** counts the number of documents in a collection *)
* { 6 Query / Find more via cursor }
val get_more
: t
-> ?limit:int
-> ?max_time_ms:int
-> response_handler:(Bson.t, 'a list) response_handler
-> int64
-> unit
* get { b all / the default number } of documents via a cursor_id . e.g.
cursor_id num . May raise Mongo_failed exception .
get_more_of_num m cursor_id num. May raise Mongo_failed exception.*)
* { 6 Kill cursor }
val kill_cursors
: t
-> int64 list
-> response_handler:(Bson.t, 'a list) response_handler
-> unit
* kill a list of cursors , to save MongoDB resources . e.g. , kill_cursors m
cursor_list . May raise Mongo_failed exception .
cursor_list. May raise Mongo_failed exception.*)
* { 6 Index }
(** option for index. See
{b
/#db.collection.ensureIndex}
for more info *)
type index_option =
| Background of bool
| Unique of bool
| Name of string
| DropDups of bool
| Sparse of bool
| ExpireAfterSeconds of int
| V of int
| Weight of Bson.t
| Default_language of string
| Language_override of string
val get_indexes
: t
-> response_handler:(Bson.t, 'a list) response_handler
-> unit
(** return a list of all indexes *)
val ensure_index
: t
-> key:Bson.t
-> options:index_option list
-> response_handler:((int, write_error list) result -> unit)
-> unit
(** ensure an index *)
val ensure_simple_index
: ?options:index_option list
-> t
-> string
-> response_handler:((int, write_error list) result -> unit)
-> unit
(** ensure an index (helper) *)
val ensure_multi_simple_index
: ?options:index_option list
-> t
-> string list
-> response_handler:((int, write_error list) result -> unit)
-> unit
(** ensure multi-fields index (helper) *)
val drop_index
: t
-> string
-> response_handler:(Bson.t, 'a list) response_handler
-> unit
(** drop a index *)
val drop_all_index
: t
-> response_handler:(Bson.t, 'a list) response_handler
-> unit
(** drop all index of a collection *)
* { 6 Instance Administration Commands }
val drop_collection
: t
-> response_handler:(Bson.t, 'a list) response_handler
-> unit
(** removes an entire collection from a database *)
val drop_database
: t
-> response_handler:(Bson.t, 'a list) response_handler
-> unit
(** drops a database, deleting the associated data files *)
module Admin : sig
val of_connection : t -> t
val command
: t
-> string
-> response_handler:(Bson.t, 'a list) response_handler
-> unit
val listDatabases
: t
-> response_handler:(Bson.t, 'a list) response_handler
-> unit
val buildInfo
: t
-> response_handler:(Bson.t, 'a list) response_handler
-> unit
val collStats
: t
-> response_handler:(Bson.t, 'a list) response_handler
-> unit
val connPoolStats
: t
-> response_handler:(Bson.t, 'a list) response_handler
-> unit
val cursorInfo
: t
-> response_handler:(Bson.t, 'a list) response_handler
-> unit
val getCmdLineOpts
: t
-> response_handler:(Bson.t, 'a list) response_handler
-> unit
val hostInfo
: t
-> response_handler:(Bson.t, 'a list) response_handler
-> unit
val listCommands
: t
-> response_handler:(Bson.t, 'a list) response_handler
-> unit
val serverStatus
: t
-> response_handler:(Bson.t, 'a list) response_handler
-> unit
end
val shutdown : t -> unit
* [ shutdown connection ] initiates the graceful shutdown of [ connection ] , and
sends an HTTP/2 GOAWAY frame with NO_ERROR on the output channel ( See
{ { : #section-6.8 } RFC7540§6.8 } for more
details ) .
sends an HTTP/2 GOAWAY frame with NO_ERROR on the output channel (See
{{:#section-6.8} RFC7540§6.8} for more
details). *)
val next_read_operation : t -> [> `Read | `Close ]
(** [next_read_operation t] returns a value describing the next operation that
the caller should conduct on behalf of the connection. *)
val read : t -> Bigstringaf.t -> off:int -> len:int -> int
* [ read t ~len ] reads bytes of input from the provided range
of [ bigstring ] and returns the number of bytes consumed by the connection .
{ ! read } should be called after { ! next_read_operation } returns a [ ` Read ]
value and additional input is available for the connection to consume .
of [bigstring] and returns the number of bytes consumed by the connection.
{!read} should be called after {!next_read_operation} returns a [`Read]
value and additional input is available for the connection to consume. *)
val read_eof : t -> Bigstringaf.t -> off:int -> len:int -> int
* [ read t ~len ] reads bytes of input from the provided range
of [ bigstring ] and returns the number of bytes consumed by the connection .
{ ! read } should be called after { ! next_read_operation } returns a [ ` Read ]
and an EOF has been received from the communication channel . The
connection will attempt to consume any buffered input and then shutdown
the HTTP parser for the connection .
of [bigstring] and returns the number of bytes consumed by the connection.
{!read} should be called after {!next_read_operation} returns a [`Read]
and an EOF has been received from the communication channel. The
connection will attempt to consume any buffered input and then shutdown
the HTTP parser for the connection. *)
val next_write_operation
: t
-> [ `Write of Bigstringaf.t Faraday.iovec list | `Yield | `Close of int ]
(** [next_write_operation t] returns a value describing the next operation
that the caller should conduct on behalf of the connection. *)
val report_write_result : t -> [ `Ok of int | `Closed ] -> unit
(** [report_write_result t result] reports the result of the latest write
attempt to the connection. {!report_write_result} should be called after a
call to {!next_write_operation} that returns a [`Write buffer] value.
- [`Ok n] indicates that the caller successfully wrote [n] bytes of output
from the buffer that the caller was provided by {!next_write_operation}.
- [`Closed] indicates that the output destination will no longer accept
bytes from the write processor. *)
val yield_writer : t -> (unit -> unit) -> unit
(** [yield_writer t continue] registers with the connection to call [continue]
when writing should resume. {!yield_writer} should be called after
{!next_write_operation} returns a [`Yield] value. *)
val yield_reader : t -> (unit -> unit) -> unit
(** [yield_reader t continue] immediately calls [continue]. This function *
shouldn't generally be called and it's only here to simplify adhering * to
the Gluten [RUNTIME] module type. *)
val report_exn : t -> exn -> unit
(** [report_exn t exn] reports that an error [exn] has been caught and that it
has been attributed to [t]. Calling this function will switch [t] into an
error state. Depending on the state [t] is transitioning from, it may call
its (connection-level) error handler before terminating the connection. *)
val is_closed : t -> bool
(** [is_closed t] is [true] if both the read and write processors have been
shutdown. When this is the case {!next_read_operation} will return
[`Close _] and {!next_write_operation} will do the same will return a
[`Write _] until all buffered output has been flushed, at which point it
will return [`Close]. *)
end
| null | https://raw.githubusercontent.com/anmonteiro/ocaml-mongodb/f491384652eaf24e423204ae79f590bb90fb6506/src/mongo.mli | ocaml | * the exception will be raised if anything is wrong, with a string message
* change instance collection
* {6 Update}
* counts the number of documents in a collection
* option for index. See
{b
/#db.collection.ensureIndex}
for more info
* return a list of all indexes
* ensure an index
* ensure an index (helper)
* ensure multi-fields index (helper)
* drop a index
* drop all index of a collection
* removes an entire collection from a database
* drops a database, deleting the associated data files
* [next_read_operation t] returns a value describing the next operation that
the caller should conduct on behalf of the connection.
* [next_write_operation t] returns a value describing the next operation
that the caller should conduct on behalf of the connection.
* [report_write_result t result] reports the result of the latest write
attempt to the connection. {!report_write_result} should be called after a
call to {!next_write_operation} that returns a [`Write buffer] value.
- [`Ok n] indicates that the caller successfully wrote [n] bytes of output
from the buffer that the caller was provided by {!next_write_operation}.
- [`Closed] indicates that the output destination will no longer accept
bytes from the write processor.
* [yield_writer t continue] registers with the connection to call [continue]
when writing should resume. {!yield_writer} should be called after
{!next_write_operation} returns a [`Yield] value.
* [yield_reader t continue] immediately calls [continue]. This function *
shouldn't generally be called and it's only here to simplify adhering * to
the Gluten [RUNTIME] module type.
* [report_exn t exn] reports that an error [exn] has been caught and that it
has been attributed to [t]. Calling this function will switch [t] into an
error state. Depending on the state [t] is transitioning from, it may call
its (connection-level) error handler before terminating the connection.
* [is_closed t] is [true] if both the read and write processors have been
shutdown. When this is the case {!next_read_operation} will return
[`Close _] and {!next_write_operation} will do the same will return a
[`Write _] until all buffered output has been flushed, at which point it
will return [`Close]. | * { b This is a major client - faced module , for the high level usage . }
This module includes a series of APIs that client can use directly to
communicate with MongoDB . The most important functions are for insert ,
udpate , delete , query , get_more . They are the essential interactions that a
client can have with MongoDB .
Please note that the current version of APIs here are all essential only .
For example , Clients can not set detailed flags for queries , etc . All
operations here are with default flags ( which is 0 ) .
A Mongo is bound to a db and a collection . All operations will be done upon
the bound db and collection only .
Please refer to
{ { : -driver/latest/legacy/mongodb-wire-protocol/ }
MongoDB Wire Protocol } for more information
This module includes a series of APIs that client can use directly to
communicate with MongoDB. The most important functions are for insert,
udpate, delete, query, get_more. They are the essential interactions that a
client can have with MongoDB.
Please note that the current version of APIs here are all essential only.
For example, Clients cannot set detailed flags for queries, etc. All
operations here are with default flags (which is 0).
A Mongo is bound to a db and a collection. All operations will be done upon
the bound db and collection only.
Please refer to
{{:-driver/latest/legacy/mongodb-wire-protocol/}
MongoDB Wire Protocol} for more information *)
module Config : sig
type t =
{ db : string
; collection : string
; host : string
; port : int
; max_connections : int
}
val create
: ?host:string
-> ?port:int
-> ?max_connections:int
-> db:string
-> collection:string
-> unit
-> t
end
module Response : sig
type t =
{ header : Header.t
; response_flags : int32
; cursor_id : int64
; starting_from : int32
; num_returned : int32
; document_list : Bson.t list
}
val to_string : t -> string
val pp_hum : Format.formatter -> t -> unit
end
module Connection : sig
type t
type error =
[ `Protocol_error of string
| `Eof
of Error_code.t * string
`Exn of exn
]
type ('a, 'b) response_handler = ('a, 'b) result -> unit
type error_handler = error -> unit
val create : config:Config.t -> t
val with_ : ?collection:string -> ?database:string -> t -> t
val with_collection : t -> string -> t
val message
: t
-> doc:Bson.t
-> response_handler:(Bson.t, 'a list) response_handler
-> unit
type write_error =
{ index : int
; code : int
; message : string
}
val insert
: ?ordered:bool
-> ?bypass_document_validation:bool
-> t
-> response_handler:((int, write_error list) result -> unit)
-> Bson.t list
-> unit
* { 6 Insert }
type upserted =
{ index : int
; _id : string
}
type update_output =
{ found : int
; updated : int
; upserted : upserted list
}
val update
: t
-> ?ordered:bool
-> ?bypass_document_validation:bool
-> upsert:bool
-> all:bool
-> selector:Bson.t
-> response_handler:(update_output, write_error list) response_handler
-> Bson.t
-> unit
* update the { b first document } matched in MongoDB . e.g. , update_one m ( s ,
u ) ; ; m is the Mongo . s is the selector document , used to match the
documents that need to be updated . u is the update document and any
matched documents will be updated to u. May raise Mongo_failed exception .
u);; m is the Mongo. s is the selector document, used to match the
documents that need to be updated. u is the update document and any
matched documents will be updated to u. May raise Mongo_failed exception.*)
val update_one
: t
-> ?upsert:bool
-> selector:Bson.t
-> Bson.t
-> response_handler:((update_output, write_error list) result -> unit)
-> unit
val update_many
: t
-> ?upsert:bool
-> selector:Bson.t
-> Bson.t
-> response_handler:((update_output, write_error list) result -> unit)
-> unit
* update { b all documents } matched in MongoDB . e.g. , update m ( s , u ) ; ; m is
the Mongo . s is the selector document , used to match the documents that
need to be updated . u is the update document and any matched documents
will be updated to u. May raise Mongo_failed exception .
the Mongo. s is the selector document, used to match the documents that
need to be updated. u is the update document and any matched documents
will be updated to u. May raise Mongo_failed exception. *)
* { 6 Delete }
val delete
: ?ordered:bool
-> t
-> all:bool
-> selector:Bson.t
-> response_handler:(int, 'a list) response_handler
-> unit
val delete_one
: t
-> Bson.t
-> response_handler:(int, 'a list) response_handler
-> unit
* delete the { b first document } matched in MongoDB . e.g. , delete_one m s ; ; m
is the Mongo . s is the selector document , used to match the documents that
need to be deleted . May raise Mongo_failed exception .
is the Mongo. s is the selector document, used to match the documents that
need to be deleted. May raise Mongo_failed exception.*)
val delete_many
: t
-> Bson.t
-> response_handler:(int, 'a list) response_handler
-> unit
* delete the { b all documents } matched in MongoDB . e.g. , delete_one m s ; ; m
is the Mongo . s is the selector document , used to match the documents that
need to be deleted . May raise Mongo_failed exception .
is the Mongo. s is the selector document, used to match the documents that
need to be deleted. May raise Mongo_failed exception.*)
* { 6 Query / Find }
val find
: ?skip:int
-> ?limit:int
-> ?filter:Bson.t
-> ?sort:Bson.t
-> ?projection:Bson.t
-> t
-> response_handler:(Bson.t, 'a list) response_handler
-> unit
* find { b all / the default number } of documents in the db and collection .
May raise Mongo_failed exception .
May raise Mongo_failed exception.*)
val find_one
: ?skip:int
-> ?filter:Bson.t
-> ?projection:Bson.t
-> t
-> response_handler:(Bson.t, 'a list) response_handler
-> unit
* find { b the first } document in the db and collection . May raise
Mongo_failed exception .
Mongo_failed exception.*)
val find_and_modify
: ?bypass_document_validation:bool
-> ?query:Bson.t
-> ?sort:Bson.t
-> ?remove:bool
-> ?update:Bson.t
-> ?new_:bool
-> ?projection:Bson.t
-> ?upsert:bool
-> t
-> response_handler:(Bson.t, 'a list) response_handler
-> unit
val count
: ?skip:int
-> ?limit:int
-> ?query:Bson.t
-> t
-> response_handler:(int, 'a list) response_handler
-> unit
* { 6 Query / Find more via cursor }
val get_more
: t
-> ?limit:int
-> ?max_time_ms:int
-> response_handler:(Bson.t, 'a list) response_handler
-> int64
-> unit
* get { b all / the default number } of documents via a cursor_id . e.g.
cursor_id num . May raise Mongo_failed exception .
get_more_of_num m cursor_id num. May raise Mongo_failed exception.*)
* { 6 Kill cursor }
val kill_cursors
: t
-> int64 list
-> response_handler:(Bson.t, 'a list) response_handler
-> unit
* kill a list of cursors , to save MongoDB resources . e.g. , kill_cursors m
cursor_list . May raise Mongo_failed exception .
cursor_list. May raise Mongo_failed exception.*)
* { 6 Index }
type index_option =
| Background of bool
| Unique of bool
| Name of string
| DropDups of bool
| Sparse of bool
| ExpireAfterSeconds of int
| V of int
| Weight of Bson.t
| Default_language of string
| Language_override of string
val get_indexes
: t
-> response_handler:(Bson.t, 'a list) response_handler
-> unit
val ensure_index
: t
-> key:Bson.t
-> options:index_option list
-> response_handler:((int, write_error list) result -> unit)
-> unit
val ensure_simple_index
: ?options:index_option list
-> t
-> string
-> response_handler:((int, write_error list) result -> unit)
-> unit
val ensure_multi_simple_index
: ?options:index_option list
-> t
-> string list
-> response_handler:((int, write_error list) result -> unit)
-> unit
val drop_index
: t
-> string
-> response_handler:(Bson.t, 'a list) response_handler
-> unit
val drop_all_index
: t
-> response_handler:(Bson.t, 'a list) response_handler
-> unit
* { 6 Instance Administration Commands }
val drop_collection
: t
-> response_handler:(Bson.t, 'a list) response_handler
-> unit
val drop_database
: t
-> response_handler:(Bson.t, 'a list) response_handler
-> unit
module Admin : sig
val of_connection : t -> t
val command
: t
-> string
-> response_handler:(Bson.t, 'a list) response_handler
-> unit
val listDatabases
: t
-> response_handler:(Bson.t, 'a list) response_handler
-> unit
val buildInfo
: t
-> response_handler:(Bson.t, 'a list) response_handler
-> unit
val collStats
: t
-> response_handler:(Bson.t, 'a list) response_handler
-> unit
val connPoolStats
: t
-> response_handler:(Bson.t, 'a list) response_handler
-> unit
val cursorInfo
: t
-> response_handler:(Bson.t, 'a list) response_handler
-> unit
val getCmdLineOpts
: t
-> response_handler:(Bson.t, 'a list) response_handler
-> unit
val hostInfo
: t
-> response_handler:(Bson.t, 'a list) response_handler
-> unit
val listCommands
: t
-> response_handler:(Bson.t, 'a list) response_handler
-> unit
val serverStatus
: t
-> response_handler:(Bson.t, 'a list) response_handler
-> unit
end
val shutdown : t -> unit
* [ shutdown connection ] initiates the graceful shutdown of [ connection ] , and
sends an HTTP/2 GOAWAY frame with NO_ERROR on the output channel ( See
{ { : #section-6.8 } RFC7540§6.8 } for more
details ) .
sends an HTTP/2 GOAWAY frame with NO_ERROR on the output channel (See
{{:#section-6.8} RFC7540§6.8} for more
details). *)
val next_read_operation : t -> [> `Read | `Close ]
val read : t -> Bigstringaf.t -> off:int -> len:int -> int
* [ read t ~len ] reads bytes of input from the provided range
of [ bigstring ] and returns the number of bytes consumed by the connection .
{ ! read } should be called after { ! next_read_operation } returns a [ ` Read ]
value and additional input is available for the connection to consume .
of [bigstring] and returns the number of bytes consumed by the connection.
{!read} should be called after {!next_read_operation} returns a [`Read]
value and additional input is available for the connection to consume. *)
val read_eof : t -> Bigstringaf.t -> off:int -> len:int -> int
* [ read t ~len ] reads bytes of input from the provided range
of [ bigstring ] and returns the number of bytes consumed by the connection .
{ ! read } should be called after { ! next_read_operation } returns a [ ` Read ]
and an EOF has been received from the communication channel . The
connection will attempt to consume any buffered input and then shutdown
the HTTP parser for the connection .
of [bigstring] and returns the number of bytes consumed by the connection.
{!read} should be called after {!next_read_operation} returns a [`Read]
and an EOF has been received from the communication channel. The
connection will attempt to consume any buffered input and then shutdown
the HTTP parser for the connection. *)
val next_write_operation
: t
-> [ `Write of Bigstringaf.t Faraday.iovec list | `Yield | `Close of int ]
val report_write_result : t -> [ `Ok of int | `Closed ] -> unit
val yield_writer : t -> (unit -> unit) -> unit
val yield_reader : t -> (unit -> unit) -> unit
val report_exn : t -> exn -> unit
val is_closed : t -> bool
end
|
0365de9a90a7ea4da59b2941ee14016ff5da1155e00a9075f997b729839e1308 | lispbuilder/lispbuilder | font-definition.lisp |
(in-package #:lispbuilder-sdl)
(defclass font-definition ()
((filename :accessor filename :initform nil :initarg :filename)
(loader :accessor loader :initform #'load-image :initarg :loader)
(char-size :reader char-size :initform nil :initarg :size)))
| null | https://raw.githubusercontent.com/lispbuilder/lispbuilder/589b3c6d552bbec4b520f61388117d6c7b3de5ab/lispbuilder-sdl/sdl/font-definition.lisp | lisp |
(in-package #:lispbuilder-sdl)
(defclass font-definition ()
((filename :accessor filename :initform nil :initarg :filename)
(loader :accessor loader :initform #'load-image :initarg :loader)
(char-size :reader char-size :initform nil :initarg :size)))
| |
b8e554787c1c95b5bddb3cf26c2ea78b8e37aaaf9063ac97a28f44bf0c83d696 | mhuebert/re-db | memo.cljc | (ns re-db.memo
"Subscriptions: named reactive computations cached globally for deduplication of effort"
(:refer-clojure :exclude [memoize fn defn])
(:require [clojure.core :as c]
[clojure.string :as str]
[re-db.reactive :as r :refer [add-on-dispose!]])
#?(:cljs (:require-macros re-db.memo)))
;; memoize, but with reference counting (& lifecycle)
(defn- new-entry!
"Adds an entry to the cache, with a dispose hook to remove when unwatched"
[!state args]
(let [value (apply (:init-fn @!state) args)]
(when (and value (satisfies? r/IReactiveValue value))
(swap! !state assoc-in [:cache args] value)
(add-on-dispose! value (c/fn [_] (swap! !state update :cache dissoc args))))
value))
(c/defn get-state [f] (::state (meta f)))
(c/defn reset-fn!
"Resets the init-fn for a memoized function"
[f init-fn]
(let [!state (get-state f)]
(swap! !state assoc :init-fn init-fn)
(doseq [[args old-rx] (:cache @!state)]
(r/become old-rx (apply init-fn args)))
f))
(c/defn constructor-fn [!state]
(with-meta (c/fn [& args]
(or (get-in @!state [:cache args])
(new-entry! !state args)))
{::state !state}))
(c/defn memoize [f]
(constructor-fn (atom {:cache {}
:init-fn f})))
(defmacro fn-memo [& args]
`(memoize (c/fn ~@args)))
(defmacro def-memo
"Defines a memoized function. If the return value implements re-db.reactive/IReactiveValue,
it will be removed from the memo cache when the last reference is removed."
([name doc f] `(re-db.memo/def-memo ~(with-meta name {:doc doc}) ~f))
([name f]
(assert (str/starts-with? (str name) "$") "A subscription's name must begin with $")
`(do (defonce ~name (memoize nil))
(reset-fn! ~name ~f)
~name)))
(c/defn- without-docstring [args] (cond-> args (string? (first args)) rest))
(defmacro defn-memo
"Defines a memoized function. If the return value implements re-db.reactive/IReactiveValue,
it will be removed from the memo cache when the last reference is removed."
[name & args]
`(def-memo ~name (c/fn ~name ~@(without-docstring args))))
(c/defn dispose! [memoized]
(let [!state (::state (meta memoized))]
(doseq [[args rx] (:cache @!state)]
(r/dispose! rx))
(swap! !state update :cache empty))
memoized)
(defmacro once
"Like defonce for `def-memo` and `defn-memo`"
[expr]
(let [name (second expr)]
`(when-not (r/var-present? ~name)
~expr)))
(comment
(def !a (r/atom 0))
(defn-memo $inc
[!ref]
(r/reaction
(prn :compute)
(re-db.hooks/use-effect
(fn [] (prn :init) #(prn :dispose)))
@!ref))
;; deref: activates
@($inc !a)
;; swap: recomputes
(swap! !a inc)
;; clear: disposes
(dispose! $inc)
session : init & dispose
(r/session
@($inc !a))
(require '[re-db.hooks :as hooks])
(defn-memo $sleeper [& {:as options
:keys [limit sleep]
:or {limit 50 sleep 2000}}]
(r/reaction
(let [!counter (hooks/use-state 0)
!future (hooks/use-memo #(atom nil))]
(prn :compute--- @!counter)
(hooks/use-effect
(fn []
(prn :init @!counter)
#(do (prn :dispose @!counter)
(some-> @!future future-cancel))))
(when (< @!counter limit)
(reset! !future (future (Thread/sleep sleep)
(swap! !counter inc))))
@!counter)))
;; adds watches (removes old watches)
(add-watch ($sleeper) :w (fn [_ _ _ n] (prn :watch n)))
(remove-watch ($sleeper) :w)
(dispose! $sleeper)
) | null | https://raw.githubusercontent.com/mhuebert/re-db/9072c5ec6f6398da5c088517d676b7ffd5cdb838/src/main/re_db/memo.cljc | clojure | memoize, but with reference counting (& lifecycle)
deref: activates
swap: recomputes
clear: disposes
adds watches (removes old watches) | (ns re-db.memo
"Subscriptions: named reactive computations cached globally for deduplication of effort"
(:refer-clojure :exclude [memoize fn defn])
(:require [clojure.core :as c]
[clojure.string :as str]
[re-db.reactive :as r :refer [add-on-dispose!]])
#?(:cljs (:require-macros re-db.memo)))
(defn- new-entry!
"Adds an entry to the cache, with a dispose hook to remove when unwatched"
[!state args]
(let [value (apply (:init-fn @!state) args)]
(when (and value (satisfies? r/IReactiveValue value))
(swap! !state assoc-in [:cache args] value)
(add-on-dispose! value (c/fn [_] (swap! !state update :cache dissoc args))))
value))
(c/defn get-state [f] (::state (meta f)))
(c/defn reset-fn!
"Resets the init-fn for a memoized function"
[f init-fn]
(let [!state (get-state f)]
(swap! !state assoc :init-fn init-fn)
(doseq [[args old-rx] (:cache @!state)]
(r/become old-rx (apply init-fn args)))
f))
(c/defn constructor-fn [!state]
(with-meta (c/fn [& args]
(or (get-in @!state [:cache args])
(new-entry! !state args)))
{::state !state}))
(c/defn memoize [f]
(constructor-fn (atom {:cache {}
:init-fn f})))
(defmacro fn-memo [& args]
`(memoize (c/fn ~@args)))
(defmacro def-memo
"Defines a memoized function. If the return value implements re-db.reactive/IReactiveValue,
it will be removed from the memo cache when the last reference is removed."
([name doc f] `(re-db.memo/def-memo ~(with-meta name {:doc doc}) ~f))
([name f]
(assert (str/starts-with? (str name) "$") "A subscription's name must begin with $")
`(do (defonce ~name (memoize nil))
(reset-fn! ~name ~f)
~name)))
(c/defn- without-docstring [args] (cond-> args (string? (first args)) rest))
(defmacro defn-memo
"Defines a memoized function. If the return value implements re-db.reactive/IReactiveValue,
it will be removed from the memo cache when the last reference is removed."
[name & args]
`(def-memo ~name (c/fn ~name ~@(without-docstring args))))
(c/defn dispose! [memoized]
(let [!state (::state (meta memoized))]
(doseq [[args rx] (:cache @!state)]
(r/dispose! rx))
(swap! !state update :cache empty))
memoized)
(defmacro once
"Like defonce for `def-memo` and `defn-memo`"
[expr]
(let [name (second expr)]
`(when-not (r/var-present? ~name)
~expr)))
(comment
(def !a (r/atom 0))
(defn-memo $inc
[!ref]
(r/reaction
(prn :compute)
(re-db.hooks/use-effect
(fn [] (prn :init) #(prn :dispose)))
@!ref))
@($inc !a)
(swap! !a inc)
(dispose! $inc)
session : init & dispose
(r/session
@($inc !a))
(require '[re-db.hooks :as hooks])
(defn-memo $sleeper [& {:as options
:keys [limit sleep]
:or {limit 50 sleep 2000}}]
(r/reaction
(let [!counter (hooks/use-state 0)
!future (hooks/use-memo #(atom nil))]
(prn :compute--- @!counter)
(hooks/use-effect
(fn []
(prn :init @!counter)
#(do (prn :dispose @!counter)
(some-> @!future future-cancel))))
(when (< @!counter limit)
(reset! !future (future (Thread/sleep sleep)
(swap! !counter inc))))
@!counter)))
(add-watch ($sleeper) :w (fn [_ _ _ n] (prn :watch n)))
(remove-watch ($sleeper) :w)
(dispose! $sleeper)
) |
b8490035f01346be6766f0a2a39630dce22671947f0cc84e2cc8a37b27568a41 | carl-eastlund/dracula | lang.rkt | #lang scheme
(require scheme "scheme.ss")
(provide (all-from-out scheme "scheme.ss"))
| null | https://raw.githubusercontent.com/carl-eastlund/dracula/a937f4b40463779246e3544e4021c53744a33847/private/scheme/lang.rkt | racket | #lang scheme
(require scheme "scheme.ss")
(provide (all-from-out scheme "scheme.ss"))
| |
fecea2f0eb3278095759373912f7f9c294765b9c1739cce0851e9dedfb8da7ee | tonyg/kali-scheme | write-image.scm | Copyright ( c ) 1993 , 1994 by and .
Copyright ( c ) 1996 by NEC Research Institute , Inc. See file COPYING .
Writing out a Scheme 48 image
; From vm/heap.scm
( % write - string " This is a Scheme 48 heap image file . " port )
; (%newline port)
; (%write-page port)
; (%newline port)
; (%write-string level port)
; (%write-number bytes-per-cell port)
; (%write-number (a-units->cells *newspace-begin*) port)
; (%write-number (a-units->cells *hp*) port)
; (%write-number restart-proc port)
; (%write-page port)
(define (write-image file start-proc id-string)
(if (not (= 0 (remainder bits-per-cell bits-per-io-byte)))
(error "io-bytes to not fit evenly into cells"))
(initialize-memory)
(call-with-output-file file
(lambda (port)
(let ((start (transport start-proc))) ; transport the start-proc
(display id-string port)
(newline port)
(write-page port)
(newline port)
(display architecture-version port)
(newline port)
(boot-write-number bytes-per-cell port)
(boot-write-number 0 port) ; newspace begin
(boot-write-number (a-units->cells *hp*) port)
(boot-write-number start port) ; start-proc
(write-page port)
(write-descriptor 1 port) ; endianness indicator
(write-heap port)))) ; write out the heap
)
(define bits-per-io-byte 8) ; for writing images
(define (write-page port)
(write-char (ascii->char 12) port))
(define (write-byte byte port)
(write-char (ascii->char byte) port))
(define io-byte-mask
(low-bits -1 bits-per-io-byte))
;(define bits-per-cell -- defined in data.scm
; (* bits-per-byte bytes-per-cell))
(define (big-endian-write-descriptor thing port)
(let loop ((i (- bits-per-cell bits-per-io-byte)))
(cond ((>= i 0)
(write-byte (bitwise-and io-byte-mask
(arithmetic-shift thing (- 0 i))) port)
(loop (- i bits-per-io-byte))))))
(define (little-endian-write-descriptor thing port)
(let loop ((i 0))
(cond ((< i bits-per-cell)
(write-byte (bitwise-and io-byte-mask
(arithmetic-shift thing (- 0 i))) port)
(loop (+ i bits-per-io-byte))))))
(define write-descriptor little-endian-write-descriptor)
(define (boot-write-number n port)
(display n port)
(newline port))
| null | https://raw.githubusercontent.com/tonyg/kali-scheme/79bf76b4964729b63fce99c4d2149b32cb067ac0/scheme/link/write-image.scm | scheme | From vm/heap.scm
(%newline port)
(%write-page port)
(%newline port)
(%write-string level port)
(%write-number bytes-per-cell port)
(%write-number (a-units->cells *newspace-begin*) port)
(%write-number (a-units->cells *hp*) port)
(%write-number restart-proc port)
(%write-page port)
transport the start-proc
newspace begin
start-proc
endianness indicator
write out the heap
for writing images
(define bits-per-cell -- defined in data.scm
(* bits-per-byte bytes-per-cell)) | Copyright ( c ) 1993 , 1994 by and .
Copyright ( c ) 1996 by NEC Research Institute , Inc. See file COPYING .
Writing out a Scheme 48 image
( % write - string " This is a Scheme 48 heap image file . " port )
(define (write-image file start-proc id-string)
(if (not (= 0 (remainder bits-per-cell bits-per-io-byte)))
(error "io-bytes to not fit evenly into cells"))
(initialize-memory)
(call-with-output-file file
(lambda (port)
(display id-string port)
(newline port)
(write-page port)
(newline port)
(display architecture-version port)
(newline port)
(boot-write-number bytes-per-cell port)
(boot-write-number (a-units->cells *hp*) port)
(write-page port)
)
(define (write-page port)
(write-char (ascii->char 12) port))
(define (write-byte byte port)
(write-char (ascii->char byte) port))
(define io-byte-mask
(low-bits -1 bits-per-io-byte))
(define (big-endian-write-descriptor thing port)
(let loop ((i (- bits-per-cell bits-per-io-byte)))
(cond ((>= i 0)
(write-byte (bitwise-and io-byte-mask
(arithmetic-shift thing (- 0 i))) port)
(loop (- i bits-per-io-byte))))))
(define (little-endian-write-descriptor thing port)
(let loop ((i 0))
(cond ((< i bits-per-cell)
(write-byte (bitwise-and io-byte-mask
(arithmetic-shift thing (- 0 i))) port)
(loop (+ i bits-per-io-byte))))))
(define write-descriptor little-endian-write-descriptor)
(define (boot-write-number n port)
(display n port)
(newline port))
|
068f2c46e6533678f470745a1e8d02a25b88020b6c37c31f841ad1f7a1520f8f | zotonic/zotonic | mod_video.erl | @author < >
2014
@doc Video support for Zotonic . Converts all video files to mp4 and extracts a previes image .
Copyright 2014
%%
Licensed under the Apache License , Version 2.0 ( the " License " ) ;
%% you may not use this file except in compliance with the License.
%% You may obtain a copy of the License at
%%
%% -2.0
%%
%% Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an " AS IS " BASIS ,
%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
%% See the License for the specific language governing permissions and
%% limitations under the License.
-module(mod_video).
-author("Marc Worrell <>").
-mod_title("Video").
-mod_description("Play and convert uploaded videos. Requires ffmpeg.").
-behaviour(supervisor).
-export([start_link/1]).
-export([init/1]).
-define(SERVER, ?MODULE).
-define(TEMP_IMAGE, <<"images/processing.gif">>).
-define(BROKEN_IMAGE, <<"images/broken.png">>).
% -define(POSTER_IMAGE, <<"images/poster.png">>).
-define(TASK_DELAY, 3600).
-include_lib("zotonic_core/include/zotonic.hrl").
-export([
observe_media_upload_preprocess/2,
observe_media_upload_props/3,
observe_media_viewer/2,
observe_media_stillimage/2,
post_insert_fun/5,
remove_task/2,
convert_task/2,
queue_path/2
]).
%% @doc If a video file is uploaded, queue it for conversion to video/mp4
observe_media_upload_preprocess(#media_upload_preprocess{mime= <<"video/mp4">>, file=undefined}, _Context) ->
undefined;
observe_media_upload_preprocess(#media_upload_preprocess{mime= <<"video/x-mp4-broken">>}, Context) ->
do_media_upload_broken(Context);
observe_media_upload_preprocess(#media_upload_preprocess{mime= <<"video/", _/binary>> = Mime, medium=Medium, file=File} = Upload, Context) ->
case maps:get(<<"is_video_ok">>, Medium, undefined) of
true ->
undefined;
undefined ->
case is_video_process_needed(Mime, File) of
true ->
do_media_upload_preprocess(Upload, Context);
false ->
undefined
end
end;
observe_media_upload_preprocess(#media_upload_preprocess{}, _Context) ->
undefined.
%% @doc Do not process landscape mp4 files with aac/h264 codecs.
is_video_process_needed(<<"video/mp4">>, File) ->
Info = z_video_info:info(File),
not (
is_orientation_ok(Info)
andalso is_audio_ok(Info)
andalso is_video_ok(Info)
);
is_video_process_needed(_Mime, _File) ->
true.
is_orientation_ok(#{ <<"orientation">> := 1 }) -> true;
is_orientation_ok(#{ <<"orientation">> := undefined }) -> true;
is_orientation_ok(_) -> false.
is_audio_ok(#{ <<"audio_codec">> := <<"aac">> }) -> true;
is_audio_ok(#{ <<"audio_codec">> := undefined }) -> true;
is_audio_ok(#{ <<"audio_codec">> := _ }) -> false;
is_audio_ok(_) -> true.
is_video_ok(#{ <<"video_codec">> := <<"h264">> }) -> true;
is_video_ok(#{ <<"video_codec">> := undefined }) -> true;
is_video_ok(#{ <<"video_codec">> := _ }) -> false;
is_video_ok(_) -> true.
do_media_upload_preprocess(Upload, Context) ->
case z_module_indexer:find(lib, ?TEMP_IMAGE, Context) of
{ok, #module_index{ filepath = Filename }} ->
ProcessNr = z_ids:identifier(20),
PostFun = fun(InsId, InsMedium, InsContext) ->
?MODULE:post_insert_fun(InsId, InsMedium, Upload, ProcessNr, InsContext)
end,
{ok, MInfo} = z_media_identify:identify_file(Filename, Context),
#media_upload_preprocess{
mime = <<"video/mp4">>,
file = undefined,
post_insert_fun = PostFun,
original_filename = undefined,
medium = #{
<<"preview_filename">> => <<"lib/", ?TEMP_IMAGE/binary>>,
<<"preview_width">> => maps:get(<<"width">>, MInfo, undefined),
<<"preview_height">> => maps:get(<<"height">>, MInfo, undefined),
<<"width">> => maps:get(<<"width">>, MInfo, undefined),
<<"height">> => maps:get(<<"height">>, MInfo, undefined),
<<"is_deletable_preview">> => false,
<<"is_video_processing">> => true,
<<"video_processing_nr">> => ProcessNr,
<<"original_filename">> => Upload#media_upload_preprocess.original_filename
}
};
{error, enoent} ->
undefined
end.
do_media_upload_broken(Context) ->
case z_module_indexer:find(lib, ?BROKEN_IMAGE, Context) of
{ok, #module_index{filepath=Filename}} ->
{ok, MInfo} = z_media_identify:identify_file(Filename, Context),
#media_upload_preprocess{
mime = <<"video/mp4">>,
file = undefined,
original_filename = undefined,
medium = #{
<<"preview_filename">> => <<"lib/", ?BROKEN_IMAGE/binary>>,
<<"preview_width">> => maps:get(<<"width">>, MInfo, undefined),
<<"preview_height">> => maps:get(<<"height">>, MInfo, undefined),
<<"width">> => maps:get(<<"width">>, MInfo, undefined),
<<"height">> => maps:get(<<"height">>, MInfo, undefined),
<<"is_deletable_preview">> => false,
<<"is_video_broken">> => true
}
};
{error, enoent} ->
undefined
end.
%% @doc After a video file is processed, generate a preview image.
observe_media_upload_props(#media_upload_props{archive_file=undefined, mime= <<"video/", _/binary>>}, Medium, _Context) ->
Medium;
observe_media_upload_props(#media_upload_props{id=Id, archive_file=File, mime= <<"video/", _/binary>>}, Medium, Context) ->
FileAbs = z_media_archive:abspath(File, Context),
Info = z_video_info:info(FileAbs),
Info2 = case z_video_preview:preview(FileAbs, Info) of
{ok, TmpFile} ->
PreviewFilename = preview_filename(Id, Context),
PreviewPath = z_media_archive:abspath(PreviewFilename, Context),
ok = z_media_preview:convert(TmpFile, PreviewPath, [{quality,70}], Context),
_ = file:delete(TmpFile),
Info#{
<<"preview_filename">> => PreviewFilename,
<<"preview_width">> => maps:get(<<"width">>, Info, undefined),
<<"preview_height">> => maps:get(<<"height">>, Info, undefined),
<<"is_deletable_preview">> => true
};
{error, _} ->
Info
end,
maps:merge(Medium, Info2);
observe_media_upload_props(#media_upload_props{}, Medium, _Context) ->
Medium.
%% @doc Return the media viewer for the mp4 video
-spec observe_media_viewer(#media_viewer{}, z:context()) -> undefined | {ok, template_compiler:render_result()}.
observe_media_viewer(#media_viewer{props=Props, options=Options}, Context) ->
case maps:get(<<"mime">>, Props, undefined) of
<<"video/mp4">> ->
Vars = [
{props, Props},
{options, Options}
],
{ok, z_template:render(#render{template="_video_viewer.tpl", vars = Vars}, Context)};
_ ->
undefined
end.
%% @doc Return the filename of a still image to be used for image tags.
-spec observe_media_stillimage(#media_stillimage{}, z:context()) -> undefined | {ok, file:filename_all()}.
observe_media_stillimage(#media_stillimage{ props = #{ <<"mime">> := <<"video/mp4">> } = Props }, _Context) ->
case z_convert:to_binary(maps:get(<<"preview_filename">>, Props, undefined)) of
<<>> -> {ok, <<"lib/images/poster.png">>};
PreviewFile -> {ok, PreviewFile}
end;
observe_media_stillimage(#media_stillimage{}, _Context) ->
undefined.
%% --------------- Supervisor callbacks ---------------
start_link(Args) ->
{context, Context} = proplists:lookup(context, Args),
ensure_job_queues(),
supervisor:start_link({local, z_utils:name_for_site(?SERVER, Context)}, ?MODULE, []).
init([]) ->
Element = {z_video_convert, {z_video_convert, start_link, []},
temporary, brutal_kill, worker, [z_video_convert]},
Children = [Element],
RestartStrategy = {simple_one_for_one, 0, 1},
{ok, {RestartStrategy, Children}}.
%% --------------- Support routines ---------------
ensure_job_queues() ->
jobs:run(zotonic_singular_job, fun ensure_job_queues_1/0).
ensure_job_queues_1() ->
case jobs:queue_info(video_jobs) of
undefined ->
jobs:add_queue(video_jobs, [
{regulators, [
{counter, [
{limit, 1},
{modifiers, [{cpu, 1}]}
]}
]}
]);
{queue, _} ->
ok
end,
case jobs:queue_info(media_preview_jobs) of
undefined ->
jobs:add_queue(media_preview_jobs, [
{regulators, [
{counter, [
{limit, 3},
{modifiers, [{cpu, 1}]}
]}
]}
]);
{queue, _} ->
ok
end.
%% @doc The medium record has been inserted, queue a conversion
post_insert_fun(Id, Medium, Upload, ProcessNr, Context) ->
% Move the temp file to the video_queue in the files folder
UploadedFile = Upload#media_upload_preprocess.file,
QueueFilename = lists:flatten([integer_to_list(Id), $-, z_convert:to_list(ProcessNr)]),
QueuePath = queue_path(QueueFilename, Context),
ok = z_filelib:ensure_dir(QueuePath),
case z_tempfile:is_tempfile(UploadedFile) of
true ->
case file:rename(UploadedFile, QueuePath) of
cross - fs rename is not supported by erlang , so copy and delete the file
{error, exdev} ->
{ok, _BytesCopied} = file:copy(UploadedFile, QueuePath),
ok = file:delete(UploadedFile);
ok ->
ok
end;
false ->
{ok, _BytesCopied} = file:copy(UploadedFile, QueuePath)
end,
Task = {convert_v2, Id, Medium, Upload, QueueFilename, ProcessNr, z_context:pickle(Context)},
z_pivot_rsc:insert_task_after(?TASK_DELAY, ?MODULE, convert_task, QueueFilename, [Task], Context),
supervisor:start_child(z_utils:name_for_site(?SERVER, Context), [Task, z_context:prune_for_async(Context)]),
ok.
-spec remove_task( file:filename_all(), z:context() ) -> non_neg_integer().
remove_task(QueueFilename, Context) ->
z_pivot_rsc:delete_task(?MODULE, convert_task, QueueFilename, Context).
convert_task(Task, Context) ->
_ = supervisor:start_child(z_utils:name_for_site(?SERVER, Context), [Task, Context]),
{delay, ?TASK_DELAY}.
queue_path(Filename, Context) ->
QueueDir = z_path:files_subdir("video_queue", Context),
filename:join(QueueDir, Filename).
preview_filename(Id, Context) ->
m_media:make_preview_unique(Id, <<".jpg">>, Context).
| null | https://raw.githubusercontent.com/zotonic/zotonic/852f627c28adf6e5212e8ad5383d4af3a2f25e3f/apps/zotonic_mod_video/src/mod_video.erl | erlang |
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
-2.0
Unless required by applicable law or agreed to in writing, software
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-define(POSTER_IMAGE, <<"images/poster.png">>).
@doc If a video file is uploaded, queue it for conversion to video/mp4
@doc Do not process landscape mp4 files with aac/h264 codecs.
@doc After a video file is processed, generate a preview image.
@doc Return the media viewer for the mp4 video
@doc Return the filename of a still image to be used for image tags.
--------------- Supervisor callbacks ---------------
--------------- Support routines ---------------
@doc The medium record has been inserted, queue a conversion
Move the temp file to the video_queue in the files folder | @author < >
2014
@doc Video support for Zotonic . Converts all video files to mp4 and extracts a previes image .
Copyright 2014
Licensed under the Apache License , Version 2.0 ( the " License " ) ;
distributed under the License is distributed on an " AS IS " BASIS ,
-module(mod_video).
-author("Marc Worrell <>").
-mod_title("Video").
-mod_description("Play and convert uploaded videos. Requires ffmpeg.").
-behaviour(supervisor).
-export([start_link/1]).
-export([init/1]).
-define(SERVER, ?MODULE).
-define(TEMP_IMAGE, <<"images/processing.gif">>).
-define(BROKEN_IMAGE, <<"images/broken.png">>).
-define(TASK_DELAY, 3600).
-include_lib("zotonic_core/include/zotonic.hrl").
-export([
observe_media_upload_preprocess/2,
observe_media_upload_props/3,
observe_media_viewer/2,
observe_media_stillimage/2,
post_insert_fun/5,
remove_task/2,
convert_task/2,
queue_path/2
]).
observe_media_upload_preprocess(#media_upload_preprocess{mime= <<"video/mp4">>, file=undefined}, _Context) ->
undefined;
observe_media_upload_preprocess(#media_upload_preprocess{mime= <<"video/x-mp4-broken">>}, Context) ->
do_media_upload_broken(Context);
observe_media_upload_preprocess(#media_upload_preprocess{mime= <<"video/", _/binary>> = Mime, medium=Medium, file=File} = Upload, Context) ->
case maps:get(<<"is_video_ok">>, Medium, undefined) of
true ->
undefined;
undefined ->
case is_video_process_needed(Mime, File) of
true ->
do_media_upload_preprocess(Upload, Context);
false ->
undefined
end
end;
observe_media_upload_preprocess(#media_upload_preprocess{}, _Context) ->
undefined.
is_video_process_needed(<<"video/mp4">>, File) ->
Info = z_video_info:info(File),
not (
is_orientation_ok(Info)
andalso is_audio_ok(Info)
andalso is_video_ok(Info)
);
is_video_process_needed(_Mime, _File) ->
true.
is_orientation_ok(#{ <<"orientation">> := 1 }) -> true;
is_orientation_ok(#{ <<"orientation">> := undefined }) -> true;
is_orientation_ok(_) -> false.
is_audio_ok(#{ <<"audio_codec">> := <<"aac">> }) -> true;
is_audio_ok(#{ <<"audio_codec">> := undefined }) -> true;
is_audio_ok(#{ <<"audio_codec">> := _ }) -> false;
is_audio_ok(_) -> true.
is_video_ok(#{ <<"video_codec">> := <<"h264">> }) -> true;
is_video_ok(#{ <<"video_codec">> := undefined }) -> true;
is_video_ok(#{ <<"video_codec">> := _ }) -> false;
is_video_ok(_) -> true.
do_media_upload_preprocess(Upload, Context) ->
case z_module_indexer:find(lib, ?TEMP_IMAGE, Context) of
{ok, #module_index{ filepath = Filename }} ->
ProcessNr = z_ids:identifier(20),
PostFun = fun(InsId, InsMedium, InsContext) ->
?MODULE:post_insert_fun(InsId, InsMedium, Upload, ProcessNr, InsContext)
end,
{ok, MInfo} = z_media_identify:identify_file(Filename, Context),
#media_upload_preprocess{
mime = <<"video/mp4">>,
file = undefined,
post_insert_fun = PostFun,
original_filename = undefined,
medium = #{
<<"preview_filename">> => <<"lib/", ?TEMP_IMAGE/binary>>,
<<"preview_width">> => maps:get(<<"width">>, MInfo, undefined),
<<"preview_height">> => maps:get(<<"height">>, MInfo, undefined),
<<"width">> => maps:get(<<"width">>, MInfo, undefined),
<<"height">> => maps:get(<<"height">>, MInfo, undefined),
<<"is_deletable_preview">> => false,
<<"is_video_processing">> => true,
<<"video_processing_nr">> => ProcessNr,
<<"original_filename">> => Upload#media_upload_preprocess.original_filename
}
};
{error, enoent} ->
undefined
end.
do_media_upload_broken(Context) ->
case z_module_indexer:find(lib, ?BROKEN_IMAGE, Context) of
{ok, #module_index{filepath=Filename}} ->
{ok, MInfo} = z_media_identify:identify_file(Filename, Context),
#media_upload_preprocess{
mime = <<"video/mp4">>,
file = undefined,
original_filename = undefined,
medium = #{
<<"preview_filename">> => <<"lib/", ?BROKEN_IMAGE/binary>>,
<<"preview_width">> => maps:get(<<"width">>, MInfo, undefined),
<<"preview_height">> => maps:get(<<"height">>, MInfo, undefined),
<<"width">> => maps:get(<<"width">>, MInfo, undefined),
<<"height">> => maps:get(<<"height">>, MInfo, undefined),
<<"is_deletable_preview">> => false,
<<"is_video_broken">> => true
}
};
{error, enoent} ->
undefined
end.
observe_media_upload_props(#media_upload_props{archive_file=undefined, mime= <<"video/", _/binary>>}, Medium, _Context) ->
Medium;
observe_media_upload_props(#media_upload_props{id=Id, archive_file=File, mime= <<"video/", _/binary>>}, Medium, Context) ->
FileAbs = z_media_archive:abspath(File, Context),
Info = z_video_info:info(FileAbs),
Info2 = case z_video_preview:preview(FileAbs, Info) of
{ok, TmpFile} ->
PreviewFilename = preview_filename(Id, Context),
PreviewPath = z_media_archive:abspath(PreviewFilename, Context),
ok = z_media_preview:convert(TmpFile, PreviewPath, [{quality,70}], Context),
_ = file:delete(TmpFile),
Info#{
<<"preview_filename">> => PreviewFilename,
<<"preview_width">> => maps:get(<<"width">>, Info, undefined),
<<"preview_height">> => maps:get(<<"height">>, Info, undefined),
<<"is_deletable_preview">> => true
};
{error, _} ->
Info
end,
maps:merge(Medium, Info2);
observe_media_upload_props(#media_upload_props{}, Medium, _Context) ->
Medium.
-spec observe_media_viewer(#media_viewer{}, z:context()) -> undefined | {ok, template_compiler:render_result()}.
observe_media_viewer(#media_viewer{props=Props, options=Options}, Context) ->
case maps:get(<<"mime">>, Props, undefined) of
<<"video/mp4">> ->
Vars = [
{props, Props},
{options, Options}
],
{ok, z_template:render(#render{template="_video_viewer.tpl", vars = Vars}, Context)};
_ ->
undefined
end.
-spec observe_media_stillimage(#media_stillimage{}, z:context()) -> undefined | {ok, file:filename_all()}.
observe_media_stillimage(#media_stillimage{ props = #{ <<"mime">> := <<"video/mp4">> } = Props }, _Context) ->
case z_convert:to_binary(maps:get(<<"preview_filename">>, Props, undefined)) of
<<>> -> {ok, <<"lib/images/poster.png">>};
PreviewFile -> {ok, PreviewFile}
end;
observe_media_stillimage(#media_stillimage{}, _Context) ->
undefined.
start_link(Args) ->
{context, Context} = proplists:lookup(context, Args),
ensure_job_queues(),
supervisor:start_link({local, z_utils:name_for_site(?SERVER, Context)}, ?MODULE, []).
init([]) ->
Element = {z_video_convert, {z_video_convert, start_link, []},
temporary, brutal_kill, worker, [z_video_convert]},
Children = [Element],
RestartStrategy = {simple_one_for_one, 0, 1},
{ok, {RestartStrategy, Children}}.
ensure_job_queues() ->
jobs:run(zotonic_singular_job, fun ensure_job_queues_1/0).
ensure_job_queues_1() ->
case jobs:queue_info(video_jobs) of
undefined ->
jobs:add_queue(video_jobs, [
{regulators, [
{counter, [
{limit, 1},
{modifiers, [{cpu, 1}]}
]}
]}
]);
{queue, _} ->
ok
end,
case jobs:queue_info(media_preview_jobs) of
undefined ->
jobs:add_queue(media_preview_jobs, [
{regulators, [
{counter, [
{limit, 3},
{modifiers, [{cpu, 1}]}
]}
]}
]);
{queue, _} ->
ok
end.
post_insert_fun(Id, Medium, Upload, ProcessNr, Context) ->
UploadedFile = Upload#media_upload_preprocess.file,
QueueFilename = lists:flatten([integer_to_list(Id), $-, z_convert:to_list(ProcessNr)]),
QueuePath = queue_path(QueueFilename, Context),
ok = z_filelib:ensure_dir(QueuePath),
case z_tempfile:is_tempfile(UploadedFile) of
true ->
case file:rename(UploadedFile, QueuePath) of
cross - fs rename is not supported by erlang , so copy and delete the file
{error, exdev} ->
{ok, _BytesCopied} = file:copy(UploadedFile, QueuePath),
ok = file:delete(UploadedFile);
ok ->
ok
end;
false ->
{ok, _BytesCopied} = file:copy(UploadedFile, QueuePath)
end,
Task = {convert_v2, Id, Medium, Upload, QueueFilename, ProcessNr, z_context:pickle(Context)},
z_pivot_rsc:insert_task_after(?TASK_DELAY, ?MODULE, convert_task, QueueFilename, [Task], Context),
supervisor:start_child(z_utils:name_for_site(?SERVER, Context), [Task, z_context:prune_for_async(Context)]),
ok.
-spec remove_task( file:filename_all(), z:context() ) -> non_neg_integer().
remove_task(QueueFilename, Context) ->
z_pivot_rsc:delete_task(?MODULE, convert_task, QueueFilename, Context).
convert_task(Task, Context) ->
_ = supervisor:start_child(z_utils:name_for_site(?SERVER, Context), [Task, Context]),
{delay, ?TASK_DELAY}.
queue_path(Filename, Context) ->
QueueDir = z_path:files_subdir("video_queue", Context),
filename:join(QueueDir, Filename).
preview_filename(Id, Context) ->
m_media:make_preview_unique(Id, <<".jpg">>, Context).
|
fd89ba9c046a7991cb3d34ab6a9746bba085861edac71ee6de5216defa105b1a | rescript-lang/rescript-editor-support | semantics.mli | val ast_to_comment :
permissive:bool ->
sections_allowed:Ast.sections_allowed ->
parent_of_sections:Paths.Identifier.label_parent ->
Ast.docs ->
((Comment.docs, Error.t) Error.result) Error.with_warnings
| null | https://raw.githubusercontent.com/rescript-lang/rescript-editor-support/f6afacf93194036fafcff050cdaff150a85ccbe0/src/vendor/odoc_parser/semantics.mli | ocaml | val ast_to_comment :
permissive:bool ->
sections_allowed:Ast.sections_allowed ->
parent_of_sections:Paths.Identifier.label_parent ->
Ast.docs ->
((Comment.docs, Error.t) Error.result) Error.with_warnings
| |
20df1e3aee4415d165b7a235a6d183d63f467cffd84c7f514a80a50e7043f451 | ddmcdonald/sparser | pathogen.lisp | ;;; -*- Mode:LISP; Syntax:Common-Lisp; Package:(SPARSER COMMON-LISP) -*-
Copyright ( c ) 2007 BBNT Solutions LLC . All Rights Reserved
copyright ( c ) 2013 - 2014 -- all rights reserved
;;;
;;; File: "pathogen"
;;; Module: "sl;disease:"
version : June 2014
;;category to represent named dieases, like bird flu.
;;I conspicuously decide not to name this file disease
;;in order to avoid confusion with the sl directory name
;;we can use this category to build up a representation for disease outbreaks in diease:spread
6/14/14 Turned off the HxNy generator . Better to analyze that as a category
;; and recognize it while walking the contiguous word sequence
(in-package :sparser)
;;;------------
;;; the object
;;;------------
;;this is just a bare-bones representation, but works for now
(define-category pathogen
:specializes physical-agent
:mixins (has-uid)
:binds ((name :primitive word)
(pathogen-type pathogen-type)) ;e.g. h5n1 is a virus, ecoli is a bacteria
;;(vector :primitive word) e.g. avian flu is spread by infected birds
:index (:permanent :key name)
:realization (:common-noun name))
;;;------
;;; form
;;;------
(defun define-pathogen (string)
(let ((name (define-or-find-individual
'pathogen :name string)))
name))
;;;------------
;;; cfrs
;;;------------
;;cfr to absorb pathogen-type
;;e.g. "the h5n1 virus"
(def-cfr pathogen (pathogen pathogen-type)
:form common-noun
:referent (:head left-edge
:bind (pathogen-type . right-edge)))
;;mirror of above
;;e.g. "the bird flu virus h5n1"
(def-cfr pathogen (pathogen-type pathogen)
:form common-noun
:referent (:head right-edge
:bind (pathogen-type . left-edge)))
| null | https://raw.githubusercontent.com/ddmcdonald/sparser/304bd02d0cf7337ca25c8f1d44b1d7912759460f/Sparser/code/s/grammar/model/sl/disease/pathogen.lisp | lisp | -*- Mode:LISP; Syntax:Common-Lisp; Package:(SPARSER COMMON-LISP) -*-
File: "pathogen"
Module: "sl;disease:"
category to represent named dieases, like bird flu.
I conspicuously decide not to name this file disease
in order to avoid confusion with the sl directory name
we can use this category to build up a representation for disease outbreaks in diease:spread
and recognize it while walking the contiguous word sequence
------------
the object
------------
this is just a bare-bones representation, but works for now
e.g. h5n1 is a virus, ecoli is a bacteria
(vector :primitive word) e.g. avian flu is spread by infected birds
------
form
------
------------
cfrs
------------
cfr to absorb pathogen-type
e.g. "the h5n1 virus"
mirror of above
e.g. "the bird flu virus h5n1" | Copyright ( c ) 2007 BBNT Solutions LLC . All Rights Reserved
copyright ( c ) 2013 - 2014 -- all rights reserved
version : June 2014
6/14/14 Turned off the HxNy generator . Better to analyze that as a category
(in-package :sparser)
(define-category pathogen
:specializes physical-agent
:mixins (has-uid)
:binds ((name :primitive word)
:index (:permanent :key name)
:realization (:common-noun name))
(defun define-pathogen (string)
(let ((name (define-or-find-individual
'pathogen :name string)))
name))
(def-cfr pathogen (pathogen pathogen-type)
:form common-noun
:referent (:head left-edge
:bind (pathogen-type . right-edge)))
(def-cfr pathogen (pathogen-type pathogen)
:form common-noun
:referent (:head right-edge
:bind (pathogen-type . left-edge)))
|
6ebcc12eb553b05baeb33532f77ce38bd999c004ab815712d0a2abb3cc62d368 | pink-gorilla/goldly | test.cljs | (ns test
(:require
[adder]
;[funny]
))
(adder/add 9 9)
;(funny/joke) | null | https://raw.githubusercontent.com/pink-gorilla/goldly/6f298355dbc99ce403763369bbe2a679655a3442/goldly-test/src/demo/notebook/test.cljs | clojure | [funny]
(funny/joke) | (ns test
(:require
[adder]
))
(adder/add 9 9) |
37e4cb46646260aec8e2d3837e914480aaccd3602d5dfc64e473ddc384bcf287 | danieljharvey/mimsa | Compilation.hs | {-# LANGUAGE OverloadedStrings #-}
module Test.Utils.Compilation
( testProjectCompile,
testModuleCompile,
testWholeProjectCompile,
)
where
import Control.Monad.Except
import Data.Foldable
import Data.Hashable
import qualified Data.Map.Strict as M
import qualified Data.Text as T
import qualified Data.Text.IO as T
import qualified Language.Mimsa.Actions.Compile as Actions
import qualified Language.Mimsa.Actions.Modules.Check as Actions
import qualified Language.Mimsa.Actions.Modules.Evaluate as Actions
import qualified Language.Mimsa.Actions.Modules.Imports as Actions
import qualified Language.Mimsa.Actions.Monad as Actions
import qualified Language.Mimsa.Actions.Types as Actions
import Language.Mimsa.Backend.Output
import Language.Mimsa.Backend.Shared
import Language.Mimsa.Backend.Types
import Language.Mimsa.Core
import Language.Mimsa.Project.Stdlib
import Language.Mimsa.Types.Project
import Language.Mimsa.Types.Store
import Test.Data.Project
import Test.Utils.Helpers
import Test.Utils.Serialisation
-- | evaluate an expression, then compile into a temp folder and return the
-- main filename
testProjectCompile ::
String ->
Backend ->
Expr Name Annotation ->
IO (FilePath, Int)
testProjectCompile folderPrefix be expr = do
let action = do
(_, _, newModule) <- Actions.evaluateModule expr mempty
(_, exprMap, _) <- Actions.compileModule be newModule
let exprName = case Actions.evalId of
DIName name -> name
_ -> error "broken evalId"
case M.lookup exprName exprMap of
Just eh -> pure eh
Nothing -> error "could not find outputted exprHash to compile"
let (_newProject_, outcomes, seHash) =
fromRight (Actions.run stdlib action)
writeFiles be folderPrefix seHash outcomes
-- | compile a module into a temp folder and return the main filename
testModuleCompile ::
String ->
Backend ->
T.Text ->
IO (FilePath, Int)
testModuleCompile folderPrefix be input = do
let action = do
-- parse a module from text
(parsedModule, _) <- Actions.checkModule mempty input
turn into TS / JS etc
(moduleHash, _, _) <- Actions.compileModule be (getAnnotationForType <$> parsedModule)
pure moduleHash
let (_newProject_, outcomes, modHash) =
fromRight (Actions.run testStdlib action)
writeModuleFiles be folderPrefix modHash outcomes
-- | compile a project into a temp folder and return the main filename
testWholeProjectCompile ::
String ->
Project Annotation ->
Backend ->
IO (FilePath, Int)
testWholeProjectCompile folderName project be = do
let action = do
_ <- Actions.compileProject be
pure ()
let (_newProject_, outcomes, _) =
fromRight (Actions.run project action)
-- clean up old rubbish
deleteOutputFolder folderName
-- re-create path
tsPath <- createOutputFolder folderName
-- write all files to temp folder
traverse_
( \(_, filename, Actions.SaveContents content) -> do
let savePath = tsPath <> show filename
liftIO $ T.writeFile savePath content
)
(Actions.writeFilesFromOutcomes outcomes)
-- hash of generated content for caching test results
let allFilesHash = hash (Actions.writeFilesFromOutcomes outcomes)
let actualIndexPath = tsPath <> "/" <> T.unpack (projectIndexFilename be)
pure (actualIndexPath, allFilesHash)
writeModuleFiles :: Backend -> String -> ModuleHash -> [Actions.ActionOutcome] -> IO (FilePath, Int)
writeModuleFiles be folderPrefix modHash outcomes = do
let folderName = folderPrefix <> "/compile-test-" <> show modHash
-- clean up old rubbish
deleteOutputFolder folderName
-- re-create path
tsPath <- createOutputFolder folderName
-- write all files to temp folder
traverse_
( \(_, filename, Actions.SaveContents content) -> do
let savePath = tsPath <> show filename
liftIO $ T.writeFile savePath content
)
(Actions.writeFilesFromOutcomes outcomes)
-- hash of generated content for caching test results
let allFilesHash = hash (Actions.writeFilesFromOutcomes outcomes)
-- make a new index file that imports the outcome and logs it
let actualIndex =
"import { main } from './"
<> moduleImport be modHash
<> "';\nconsole.log(main)"
-- get filename of index file
let actualIndexPath = tsPath <> T.unpack (projectIndexFilename be)
-- write actual index
liftIO (T.writeFile actualIndexPath actualIndex)
pure (actualIndexPath, allFilesHash)
writeFiles :: Backend -> String -> ExprHash -> [Actions.ActionOutcome] -> IO (FilePath, Int)
writeFiles be folderPrefix seHash outcomes = do
let folderName = folderPrefix <> "/compile-test-" <> show seHash
-- clean up old rubbish
deleteOutputFolder folderName
-- re-create path
tsPath <- createOutputFolder folderName
-- write all files to temp folder
traverse_
( \(_, filename, Actions.SaveContents content) -> do
let savePath = tsPath <> show filename
liftIO $ T.writeFile savePath content
)
(Actions.writeFilesFromOutcomes outcomes)
-- hash of generated content for caching test results
let allFilesHash = hash (Actions.writeFilesFromOutcomes outcomes)
-- make a new index file that imports the outcome and logs it
let actualIndex =
"import { main } from './"
<> storeExprFilename be seHash
<> "';\nconsole.log(main)"
-- get filename of index file
let actualIndexPath = tsPath <> T.unpack (projectIndexFilename be)
-- write actual index
liftIO (T.writeFile actualIndexPath actualIndex)
pure (actualIndexPath, allFilesHash)
| null | https://raw.githubusercontent.com/danieljharvey/mimsa/e6b177dd2c38e8a67d6e27063ca600406b3e6b56/compiler/test/Test/Utils/Compilation.hs | haskell | # LANGUAGE OverloadedStrings #
| evaluate an expression, then compile into a temp folder and return the
main filename
| compile a module into a temp folder and return the main filename
parse a module from text
| compile a project into a temp folder and return the main filename
clean up old rubbish
re-create path
write all files to temp folder
hash of generated content for caching test results
clean up old rubbish
re-create path
write all files to temp folder
hash of generated content for caching test results
make a new index file that imports the outcome and logs it
get filename of index file
write actual index
clean up old rubbish
re-create path
write all files to temp folder
hash of generated content for caching test results
make a new index file that imports the outcome and logs it
get filename of index file
write actual index |
module Test.Utils.Compilation
( testProjectCompile,
testModuleCompile,
testWholeProjectCompile,
)
where
import Control.Monad.Except
import Data.Foldable
import Data.Hashable
import qualified Data.Map.Strict as M
import qualified Data.Text as T
import qualified Data.Text.IO as T
import qualified Language.Mimsa.Actions.Compile as Actions
import qualified Language.Mimsa.Actions.Modules.Check as Actions
import qualified Language.Mimsa.Actions.Modules.Evaluate as Actions
import qualified Language.Mimsa.Actions.Modules.Imports as Actions
import qualified Language.Mimsa.Actions.Monad as Actions
import qualified Language.Mimsa.Actions.Types as Actions
import Language.Mimsa.Backend.Output
import Language.Mimsa.Backend.Shared
import Language.Mimsa.Backend.Types
import Language.Mimsa.Core
import Language.Mimsa.Project.Stdlib
import Language.Mimsa.Types.Project
import Language.Mimsa.Types.Store
import Test.Data.Project
import Test.Utils.Helpers
import Test.Utils.Serialisation
testProjectCompile ::
String ->
Backend ->
Expr Name Annotation ->
IO (FilePath, Int)
testProjectCompile folderPrefix be expr = do
let action = do
(_, _, newModule) <- Actions.evaluateModule expr mempty
(_, exprMap, _) <- Actions.compileModule be newModule
let exprName = case Actions.evalId of
DIName name -> name
_ -> error "broken evalId"
case M.lookup exprName exprMap of
Just eh -> pure eh
Nothing -> error "could not find outputted exprHash to compile"
let (_newProject_, outcomes, seHash) =
fromRight (Actions.run stdlib action)
writeFiles be folderPrefix seHash outcomes
testModuleCompile ::
String ->
Backend ->
T.Text ->
IO (FilePath, Int)
testModuleCompile folderPrefix be input = do
let action = do
(parsedModule, _) <- Actions.checkModule mempty input
turn into TS / JS etc
(moduleHash, _, _) <- Actions.compileModule be (getAnnotationForType <$> parsedModule)
pure moduleHash
let (_newProject_, outcomes, modHash) =
fromRight (Actions.run testStdlib action)
writeModuleFiles be folderPrefix modHash outcomes
testWholeProjectCompile ::
String ->
Project Annotation ->
Backend ->
IO (FilePath, Int)
testWholeProjectCompile folderName project be = do
let action = do
_ <- Actions.compileProject be
pure ()
let (_newProject_, outcomes, _) =
fromRight (Actions.run project action)
deleteOutputFolder folderName
tsPath <- createOutputFolder folderName
traverse_
( \(_, filename, Actions.SaveContents content) -> do
let savePath = tsPath <> show filename
liftIO $ T.writeFile savePath content
)
(Actions.writeFilesFromOutcomes outcomes)
let allFilesHash = hash (Actions.writeFilesFromOutcomes outcomes)
let actualIndexPath = tsPath <> "/" <> T.unpack (projectIndexFilename be)
pure (actualIndexPath, allFilesHash)
writeModuleFiles :: Backend -> String -> ModuleHash -> [Actions.ActionOutcome] -> IO (FilePath, Int)
writeModuleFiles be folderPrefix modHash outcomes = do
let folderName = folderPrefix <> "/compile-test-" <> show modHash
deleteOutputFolder folderName
tsPath <- createOutputFolder folderName
traverse_
( \(_, filename, Actions.SaveContents content) -> do
let savePath = tsPath <> show filename
liftIO $ T.writeFile savePath content
)
(Actions.writeFilesFromOutcomes outcomes)
let allFilesHash = hash (Actions.writeFilesFromOutcomes outcomes)
let actualIndex =
"import { main } from './"
<> moduleImport be modHash
<> "';\nconsole.log(main)"
let actualIndexPath = tsPath <> T.unpack (projectIndexFilename be)
liftIO (T.writeFile actualIndexPath actualIndex)
pure (actualIndexPath, allFilesHash)
writeFiles :: Backend -> String -> ExprHash -> [Actions.ActionOutcome] -> IO (FilePath, Int)
writeFiles be folderPrefix seHash outcomes = do
let folderName = folderPrefix <> "/compile-test-" <> show seHash
deleteOutputFolder folderName
tsPath <- createOutputFolder folderName
traverse_
( \(_, filename, Actions.SaveContents content) -> do
let savePath = tsPath <> show filename
liftIO $ T.writeFile savePath content
)
(Actions.writeFilesFromOutcomes outcomes)
let allFilesHash = hash (Actions.writeFilesFromOutcomes outcomes)
let actualIndex =
"import { main } from './"
<> storeExprFilename be seHash
<> "';\nconsole.log(main)"
let actualIndexPath = tsPath <> T.unpack (projectIndexFilename be)
liftIO (T.writeFile actualIndexPath actualIndex)
pure (actualIndexPath, allFilesHash)
|
1eb6989ce08414cb222bdf40940d84781a44c3f524af2ce70fd9052e876f94ba | nuprl/gradual-typing-performance | typed-racket.rkt | #lang racket/base
;; Supporting code for `typed-racket.scrbl`
;; - Render & organize benchmarks
;; - Make L-N/M figures
(provide ;; TEMPORARY
ALOT
MAX-OVERHEAD
new-untyped-bars
)
(provide
benchmark->tex-file
count-benchmarks
count-new-oo-benchmarks
bits
;; (-> String Any)
;; Use to format bitstrings
bm
;; (-> String Any)
;; Use to format benchmark names.
;; Asserts that its argument is a correctly-spelled benchmark name.
count-savings
( - > ( ) ( Values Natural Natural ) )
;; Count Anderson-Darling savings.
i.e. the number of data rows with 10 values rather than 30
count-all-configurations
;; (-> Natural)
get-lnm-table-data
render-table
tex-row
Low - level table builder
render-benchmark-descriptions
;; (-> Benchmark * Any)
Render a list of Benchmark structures .
;; Use the `benchmark` constructor to make a `Benchmark`
render-path-table
render-benchmarks-table
;; (-> Any)
;; Build a table describing static properties of the benchmarks
render-data-lattice
;; (-> Benchmark-Name Version-String Any)
;; where Benchmark-Name = (U String Symbol)
;; and Version-String = String
;; Finds the data file corresponding to the benchmark
;; at the specific version and renders a data lattice.
render-lnm-table
;; (-> Any)
render-exact-plot
render-typed/untyped-plot
render-deliverable-plot
render-uncertainty
render-karst
render-srs-sound
render-srs-precise
render-delta
render-iterations-table
render-srs-single
render-exact-table
;(rename-out [make-lnm lnm])
( - > * [ Symbol ] [ ] # : rest ( ) Lnm )
render-lnm-plot
( - > ( - > ( ) Any )
percent-diff
deliverable*
(rename-out
[ext:typed/untyped-ratio typed/untyped-ratio]
[ext:max-overhead max-overhead]
[ext:configuration->overhead configuration->overhead]
[ext:min-overhead min-overhead])
)
(require
benchmark-util/data-lattice
glob
gtp-summarize
(only-in gtp-summarize/bitstring natural->bitstring log2 bit-high?)
racket/match
(only-in pict blank hc-append vc-append)
(only-in "common.rkt" etal cite exact parag)
(only-in racket/file file->value)
(only-in racket/format ~r)
(only-in racket/list drop-right split-at last append*)
(only-in math/number-theory factorial)
(only-in racket/port with-input-from-string)
(only-in racket/string string-prefix? string-join)
scribble/core
scribble/base
version/utils
with-cache
;;
racket/contract
"benchmark.rkt"
"util.rkt"
)
(require (only-in racket/serialize
serialize
deserialize
))
;; =============================================================================
(define MAX-OVERHEAD
20)
(define ALOT ;; of samples for the overhead plots
250)
(define (count-benchmarks)
(*NUM-BENCHMARKS*))
(define (count-new-oo-benchmarks)
(*NUM-OO-BENCHMARKS*))
(define CACHE "./cache") ;; Where to store 'with-cache' cache files
(define MODULE-GRAPH "./module-graphs") ;; Where to store module graphs
;; -----------------------------------------------------------------------------
--- Syntax & Utils
( May be better off in libraries )
(define (count-all-configurations)
(*TOTAL-NUM-CONFIGURATIONS*))
(define (count-savings)
(with-cache (benchmark-savings-cache)
#:keys #false
#:read uncache-dataset
#:write cache-dataset
#:fasl? #false
new-count-savings))
(define (new-count-savings)
(define-values (skip total)
(for*/fold ([num-skip-runs 0]
[num-runs 0])
([rktd* (in-list (get-lnm-rktd**))]
[d (in-list rktd*)])
(with-input-from-file d
(lambda ()
(for/fold ([nsr num-skip-runs]
[nr num-runs])
([ln (in-lines)])
(define is-run? (eq? #\( (string-ref ln 0)))
(values
(+ nsr (if (and is-run? (= 10 (length (read-list ln)))) 1 0))
(+ nr (if is-run? 1 0))))))))
(list skip total))
(define (read-list str)
(with-handlers ([exn:fail? (lambda (e) #f)])
(let ([r (with-input-from-string str read)])
(and (list? r) r))))
;; Add '&' for TeX
(define (tex-row #:sep [sep #f] . x*)
(let loop ([x* x*])
(if (null? (cdr x*))
(list (car x*) (format " \\\\~a~n" (if sep (format "[~a]" sep) "")))
(list* (car x*) " & " (loop (cdr x*))))))
(define (percent-diff meas exp)
(/ (- meas exp) exp))
;; -----------------------------------------------------------------------------
;; --- Formatting
(define BENCHMARK-NAMES (map benchmark-name ALL-BENCHMARKS))
(define bits
tt)
;; Example #:write proc
(define (cache-table T)
(cons BENCHMARK-NAMES T))
;; Example #:read proc
(define (uncache-table tag+data)
(and (equal? (car tag+data) BENCHMARK-NAMES)
(cdr tag+data)))
(define (cache-dataset d)
(cons (get-lnm-rktd**) d))
(define (uncache-dataset fname+d)
(and (equal? (car fname+d) (get-lnm-rktd**))
(cdr fname+d)))
(define (render-table render-proc #:title title* #:cache cache-file #:sep [sep 0.2])
(exact
(format "\\setlength{\\tabcolsep}{~aem}" sep)
(format "\\begin{tabular}{l~a}" (make-string (sub1 (length title*)) #\r))
(list " \\toprule \n" (apply tex-row title*) " \\midrule \n")
(apply elem
(with-cache cache-file
#:fasl? #false
#:read uncache-table
#:write cache-table
render-proc))
"\\end{tabular}\n\n"))
(define ((list-cache-file tag) bm-or-bm*)
(ensure-dir CACHE)
(define bm* (if (list? bm-or-bm*) bm-or-bm* (list bm-or-bm*)))
(string-append
CACHE "/" tag
(string-join (map (compose1 symbol->string benchmark-name) bm*) "-")
".rktd"))
(define exact-cache-file
(list-cache-file "cache-exact-"))
(define typed/untyped-cache-file
(list-cache-file "cache-tu-"))
(define (deliverable-cache-file N)
(list-cache-file (format "cache-~a-deliverable-" N)))
(define (lattice-cache-file bm v)
(ensure-dir CACHE)
(string-append CACHE "/cache-lattice-" (symbol->string bm) "-" v ".rktd"))
(define (path-table-cache-file)
(ensure-dir CACHE)
(build-path CACHE "cache-path-table.rktd"))
(define (benchmarks-table-cache-file)
(ensure-dir CACHE)
(build-path CACHE (*BENCHMARK-TABLE-CACHE*)))
(define (benchmark-savings-cache)
(ensure-dir CACHE)
(build-path CACHE (*BENCHMARK-SAVINGS-CACHE*)))
(define (exact-table-cache)
(ensure-dir CACHE)
(build-path CACHE (*EXACT-TABLE-CACHE*)))
(define (lnm-table-cache)
(ensure-dir CACHE)
(build-path CACHE (*LNM-TABLE-CACHE*)))
(define (lnm-table-data-cache)
(ensure-dir CACHE)
(build-path CACHE (*LNM-TABLE-DATA-CACHE*)))
;; -----------------------------------------------------------------------------
;; --- Lattice
NOTE 2017 - 12 - 28 : can not use cache , the white rectangles do n't look right
(define (render-data-lattice bm v)
(parameterize ([*use-cache?* #false]
#;[*current-cache-keys* (list *LATTICE-BORDER-WIDTH* *LATTICE-BOX-BOT-MARGIN* *LATTICE-BOX-HEIGHT* *LATTICE-BOX-SEP* *LATTICE-BOX-TOP-MARGIN* *LATTICE-BOX-WIDTH* *LATTICE-CONFIG-MARGIN* *LATTICE-LEVEL-MARGIN* *LATTICE-FONT-SIZE* *LATTICE-TRUNCATE-DECIMALS?*)])
(with-cache (lattice-cache-file (benchmark-name bm) v)
#:read deserialize
#:write serialize
#:fasl? #false
(lambda () (file->performance-lattice (benchmark-rktd bm v))))))
;; -----------------------------------------------------------------------------
;; --- Benchmarks
;; (-> benchmark String)
(define (render-benchmark b+d)
(define b* (car b+d))
(define-values (b name)
(if (list? b*)
(values (car b*) (string-join (map (compose1 symbol->string benchmark-name) b*) ", "))
(values b* (symbol->string (benchmark-name b*)))))
(define d (cdr b+d))
(elem
"\\benchmark{"
name
"}{"
(benchmark-author b)
"}{"
(benchmark-origin b)
"}{"
(benchmark-purpose b)
"}{"
d
"}{"
(benchmark->tex-file b)
"}{"
(or (benchmark-lib* b) "N/A")
"}\n\n"))
(define (benchmark->tex-file b [scale 1])
(define M (benchmark-modulegraph b))
(define pn (modulegraph-project-name M))
(define mgd MODULE-GRAPH)
(ensure-dir mgd)
(define mgf (format "~a/~a.tex" mgd pn))
(unless (file-exists? mgf)
(WARNING "could not find modulegraph for project '~a', creating graph now." pn)
(call-with-output-file mgf
(lambda (p) (modulegraph->tex M p))))
(exact (format "\\modulegraph{~a}{~a}" mgf scale)))
;; (-> Benchmark * Any)
(define (render-benchmark-descriptions . b+d*)
(define key (equal-hash-code (map cdr b+d*)))
(parameterize ([*current-cache-keys* (list (lambda () key))]
[*use-cache?* #f]) ;; Sorry, can't serialize scribble elements
(with-cache (cachefile "benchmark-descriptions.rktd")
#:read deserialize
#:write serialize
#:fasl? #false
(lambda ()
( check - missing - benchmarks ( map ( compose1 benchmark - name car ) b+d * ) )
(define b+d*+ (sort b+d* benchmark<? #:key (lambda (x) (if (list? (car x)) (caar x) (car x)))))
(apply exact (map render-benchmark b+d*+))))))
(define PATH-D* '(1 3 5 10 20))
(define PATH-TABLE-TITLE*
(list* "Benchmark"
"\\# Mod."
(for/list ([d (in-list PATH-D*)])
(format "D = ~a" d))))
(define ITERATIONS-TABLE-TITLE*
(let ([row '("Benchmark" "v6.2" "v6.3" "v6.4")])
(append row '("") row)))
(define BENCHMARKS-TABLE-TITLE* '(
"Benchmark"
"\\twoline{Untyped}{LOC}"
"\\twoline{Annotation}{LOC}"
"\\# Mod."
"\\# Adp."
"\\# Bnd."
"\\# Exp."
))
(define EXACT-TABLE-TITLE* '(
"TBA"
))
(define (render-iterations-table)
(render-table new-iterations-table
#:title ITERATIONS-TABLE-TITLE*
#:cache (build-path CACHE "cache-iterations-table.rktd")))
(define (render-path-table)
(render-table new-path-table
#:title PATH-TABLE-TITLE*
#:cache (path-table-cache-file)))
(define (render-benchmarks-table)
(render-table new-benchmarks-table
#:title BENCHMARKS-TABLE-TITLE*
#:cache (benchmarks-table-cache-file)))
(define (new-benchmarks-table)
(for/list ([b (in-list ALL-BENCHMARKS)])
(define M (benchmark-modulegraph b))
(define num-adaptor (benchmark-num-adaptor b))
(define uloc (modulegraph->untyped-loc M))
(define tloc (modulegraph->typed-loc M))
TODO do n't pad last row
(format "{\\tt ~a}" (benchmark-name b))
(number->string uloc)
(if (zero? uloc) "0" (format-percent-diff tloc uloc))
(number->string (modulegraph->num-modules M))
(number->string num-adaptor)
(number->string (modulegraph->num-edges M))
(number->string (modulegraph->num-identifiers M)))))
(define (new-iterations-table)
(define version* (*RKT-VERSIONS*))
(two-column
(for/list ([bm (in-list ALL-BENCHMARKS)])
(cons
(format "{\\tt ~a}" (benchmark-name bm))
(for/list ([v (in-list version*)])
(number->string (benchmark->num-iterations bm v)))))))
(define (two-column x*)
(define-values (first-half second-half) (split-at x* (quotient (length x*) 2)))
(for/list ([a (in-list first-half)]
[b (in-list second-half)])
(apply tex-row (append a (list "~~~~~~") b))))
(define (deliverable-paths% S D)
(define num-deliv
(for*/sum ([c* (all-paths S)]
#:when (andmap (lambda (cfg) (<= (configuration->overhead S cfg) D))
(cdr (drop-right c* 1))))
1))
(define total-paths (factorial (get-num-modules S)))
(* 100 (/ num-deliv total-paths)))
(define (new-path-table)
(for/list ([bm (in-list ALL-BENCHMARKS)]
#:when (<= (benchmark->num-modules bm) 11))
(define S (from-rktd (benchmark-rktd bm "6.4")))
(apply tex-row
(format "{\\tt ~a}" (benchmark-name bm))
(format "~a" (benchmark->num-modules bm))
(for/list ([D (in-list PATH-D*)])
(number->string (deliverable-paths% S D))))))
( tex - row " { \\tt sieve } " " 2 " " 0 " " 0 " " 0 " " 0 " " 0.50 " )
;(tex-row "{\\tt forth}" "4" "0" "0" "0" "0" "0")
( tex - row " { \\tt fsm } " " 4 " " 0 " " 0 " " 0 " " 0 " " 0 " )
;(tex-row "{\\tt fsmoo}" "4" "0" "0" "0" "0" "0")
;(tex-row "{\\tt mbta}" "4" "0" "1" "1" "1" "1")
;(tex-row "{\\tt morsecode}" "4" "0" "1" "1" "1" "1")
( tex - row " { \\tt dungeon } " " 5 " " 0 " " 0 " " 0 " " 0.50 " " 1 " )
( tex - row " { \\tt zombie } " " 5 " " 0 " " 0 " " 0 " " 0 " " 0 " )
( tex - row " { \\tt zordoz } " " 5 " " 0 " " 1 " " 1 " " 1 " " 1 " )
( tex - row " { \\tt lnm } " " 6 " " 0.17 " " 1 " " 1 " " 1 " " 1 " )
( tex - row " { } " " 6 " " 0 " " 0 " " 0 " " 0 " " 0.17 " )
( tex - row " { \\tt kcfa } " " 7 " " 0 " " 0.20 " " 0.97 " " 1 " " 1 " )
( tex - row " { \\tt snake } " " 8 " " 0 " " 0 " " 0 " " 0.8 " " 0.50 " )
;(tex-row "{\\tt take5}" "8" "0" "1" "1" "1" "1")
( tex - row " { \\tt acquire } " " 9 " " 0 " " 0.2 " " 0.83 " " 1 " " 1 " )
;(tex-row "{\\tt tetris}" "9" "0" "0" "0" "0.17" "0.17")
( tex - row " { \\tt synth } " " 10 " " 0 " " 0 " " 0 " " 0 " " 0 " )
(define (format-percent-diff meas exp)
(define diff (- meas exp))
(define pct (round (* 100 (percent-diff meas exp))))
(format "~a~~~~~a(~a\\%)"
diff
(if (< pct 10) "\\hphantom{0}" "")
pct))
;; =============================================================================
(struct lnm (name description))
(define (make-lnm name . descr*)
(lnm name (apply elem descr*)))
;;;
;(define (lnm<? l1 l2)
( benchmark < ? ( lnm->benchmark l1 )
; (lnm->benchmark l2)))
;
;;; (-> Lnm * Any)
;(define (render-lnm-descriptions . l*)
; (check-missing-benchmarks (map lnm-name l*) #:exact? #t)
; (map render-lnm-description (sort l* lnm<?)))
(define (render-lnm-description l)
(elem
(parag (symbol->string (lnm-name l)))
(elem (lnm-description l))))
(define (render-lnm-plot pict*->elem #:rktd*** [rktd*** #f] #:index [cache-offset 1])
Sort & make figures of with 6 plots each or whatever
(parameterize ([*AXIS-LABELS?* #f]
[*CACHE-PREFIX* "./cache/cache-lnm-"]
[*COLOR-OFFSET* 1]
[*L* '(0 1)]
[*L-LABELS?* #t]
[*LEGEND?* (or (not rktd***)
(for*/or ([rktd** (in-list rktd***)]
[rktd* (in-list rktd**)])
(< 1 (length rktd*))))]
[*LINE-LABELS?* #f]
[*LOG-TRANSFORM?* #t]
[*M* #f]
[*MAX-OVERHEAD* MAX-OVERHEAD]
[*N* #f]
[*NUM-SAMPLES* ALOT]
[*PLOT-FONT-SCALE* 0.04]
[*PLOT-HEIGHT* 100]
[*PLOT-WIDTH* 210]
[*SINGLE-PLOT?* #f]
[*X-MINOR-TICKS* (append (for/list ([i (in-range 12 MAX-OVERHEAD 2)]) (/ i 10))
(for/list ([i (in-range 4 MAX-OVERHEAD 2)]) i))]
[*X-TICK-LINES?* #t]
[*X-TICKS* '(1 2 20)]
[ * Y - MINOR - TICKS * ' ( 25 75 ) ]
[*Y-NUM-TICKS* 3]
[*Y-TICK-LINES?* #t]
[*Y-STYLE* '%])
(define cache? (*CACHE?*))
(pict*->elem
(for/list ([rktd** (in-list (or rktd*** (split-list 5 (get-lnm-rktd**))))]
[i (in-naturals cache-offset)])
(parameterize ([*CACHE-TAG* (if cache? (number->string i) #f)])
(collect-garbage 'major)
(render-lnm (list->vector (append* rktd**))))))))
;; Get data for each benchmark for each version of racket
(define (get-lnm-rktd**)
(for/list ([b (in-list ALL-BENCHMARKS)])
(for/list ([v->rktd (in-list (benchmark-rktd* b))])
;; Drops the version tags
(cdr v->rktd))))
(define LNM-TABLE-TITLE* '(
"Benchmark"
"\\twoline{Typed/Untyped}{Ratio}"
"Mean Overhead"
"Max Overhead"
( for / list ( [ over ( in - list LNM - OVERHEAD * ) ] )
; (format "~a-deliverable" over))
))
(define (render-lnm-table)
(with-cache (lnm-table-cache)
#:read (lambda (tag+data)
(let ([d (uncache-table tag+data)])
(and d (deserialize d))))
#:write (compose1 cache-table serialize)
#:fasl? #false
new-lnm-bars))
(define (get-lnm-table-data)
(with-cache (lnm-table-data-cache)
#:read uncache-dataset
#:write cache-dataset
#:fasl? #false
(lambda ()
(call-with-values new-lnm-table-data list))))
(define (new-untyped-data)
(let loop ([rktd** (get-lnm-rktd**)])
(if (null? rktd**)
(values '() '())
(let-values ([(n* r**) (loop (cdr rktd**))]
[(_) (collect-garbage 'major)]
[(S*) (for/list ([rktd (in-list (car rktd**))])
(from-rktd rktd))])
(values
(cons (fname->title (caar rktd**)) n*)
(cons (map untyped-mean S*) r**))))))
(define (new-lnm-table-data)
(let loop ([rktd** (get-lnm-rktd**)])
(if (null? rktd**)
(values '() '() '() '())
(let-values ([(n* r** m** x**) (loop (cdr rktd**))]
[(_) (collect-garbage 'major)]
: ( Summary )
([rktd (in-list (car rktd**))])
(from-rktd rktd))])
(values
(cons (fname->title (caar rktd**)) n*)
(cons (map typed/untyped-ratio S*) r**)
(cons (map avg-overhead S*) m**)
(cons (map max-overhead S*) x**))))))
(define (new-untyped-bars)
(parameterize ([*PLOT-WIDTH* 420]
[*PLOT-HEIGHT* 140]
[*PLOT-FONT-SCALE* 0.04]
[*LOG-TRANSFORM?* #f])
(apply render-untyped-bars (call-with-values new-untyped-data list))))
(define (new-lnm-bars)
(parameterize ([*PLOT-WIDTH* 420]
[*PLOT-HEIGHT* 140]
[*PLOT-FONT-SCALE* 0.04]
[*LOG-TRANSFORM?* #t])
(apply render-bars (get-lnm-table-data))))
(define (new-lnm-dots)
(parameterize ([*PLOT-WIDTH* 300]
[*PLOT-HEIGHT* 20])
(render-dots (get-lnm-rktd**))))
(define (old-render-lnm-table)
(render-table new-lnm-table
#:title LNM-TABLE-TITLE*
#:cache (lnm-table-cache)))
(define (new-lnm-table)
(for/list ([rktd* (in-list (get-lnm-rktd**))])
(define name (fname->title (car rktd*)))
(collect-garbage 'major)
(define S* (map from-rktd rktd*))
(tex-row
name
(format-stat* typed/untyped-ratio S* #:precision 2)
(format-stat* avg-overhead S*)
(format-stat* max-overhead S*)
( for / list ( [ overhead ( in - list LNM - OVERHEAD * ) ] )
; (format-stat* (N-deliverable overhead) S*))
)))
TODO put these in sub - table
(define (format-stat* f S* #:precision [p 0])
(string-join
(for/list ((S (in-list S*)))
(~r (f S) #:precision p))
"~~"))
;; -----------------------------------------------------------------------------
(define (benchmark->rktd* bm)
(for/list ([v (in-list (*RKT-VERSIONS*))])
(benchmark-rktd bm v)))
(define (render-exact-plot . bm*)
(with-cache (exact-cache-file bm*)
#:keys #false
#:read deserialize
#:write serialize
#:fasl? #false
(lambda ()
(parameterize ([*LEGEND?* #f]
[*PLOT-FONT-SCALE* 0.04]
[*PLOT-HEIGHT* 200]
[*PLOT-WIDTH* 430]
[*POINT-SIZE* 6]
[*POINT-ALPHA* 0.7])
(render-exact*
(for*/list ([bm (in-list bm*)])
(list->vector (benchmark->rktd* bm))))))))
(define (render-exact-table bm)
(render-table
new-exact-table
#:title EXACT-TABLE-TITLE*
#:cache (cachefile "exact-table")))
(define (new-exact-table)
(for/list ([b (in-list ALL-BENCHMARKS)])
(tex-row "?")))
(define (render-typed/untyped-plot . bm*)
(with-cache (typed/untyped-cache-file bm*)
#:read deserialize
#:write serialize
#:fasl? #false
#:keys #false
(lambda ()
(parameterize ([*LEGEND?* #f]
[*ERROR-BAR-WIDTH* 20]
[*ERROR-BAR-LINE-WIDTH* 1]
[*PLOT-FONT-SCALE* 0.04]
[*PLOT-HEIGHT* 320]
[*PLOT-WIDTH* 430]
[*POINT-SIZE* 5]
[*Y-NUM-TICKS* 4]
[*POINT-ALPHA* 0.7])
(render-typed/untyped
(for*/list ([bm (in-list bm*)])
(list->vector (benchmark->rktd* bm))))))))
(define (render-deliverable-plot D . bm*)
(with-cache ((deliverable-cache-file D) bm*)
#:read deserialize
#:write serialize
#:fasl? #false
#:keys #false
(lambda ()
(parameterize ([*LEGEND?* #f]
[*ERROR-BAR-WIDTH* (*RECTANGLE-WIDTH*)]
[*ERROR-BAR-LINE-WIDTH* (*RECTANGLE-WIDTH*)]
[*Y-NUM-TICKS* 3]
[*POINT-ALPHA* 0.7]
[*PLOT-FONT-SCALE* 0.04]
[*PLOT-HEIGHT* 180]
[*PLOT-WIDTH* 440])
(render-deliverable D
(for*/list ([bm (in-list bm*)])
(list->vector (benchmark->rktd* bm))))))))
(define (render-uncertainty bm*)
(vc-append 20
(apply render-typed/untyped-plot bm*)
( hc - append 0 ( blank 10 0 ) ( apply render - typed / untyped - plot bm * ) )
#;(apply render-deliverable-plot D bm*)
(render-bars-xlabels 33 (map (compose1 symbol->string benchmark-name) bm*))))
(define (render-karst csv)
(parameterize ([*current-cache-keys* (list (lambda () csv))])
[*LEGEND?* #f]
[*ERROR-BAR-WIDTH* 0.2]
[*ERROR-BAR-LINE-WIDTH* 1]
[*PLOT-FONT-SCALE* 0.04]
[*PLOT-HEIGHT* 140]
[*PLOT-WIDTH* 430]
[*POINT-SIZE* 5]
[*COLOR-OFFSET* 4]
[*Y-NUM-TICKS* 4]
[*POINT-ALPHA* 0.7])
(with-cache (cachefile "cache-karst.rktd")
#:read deserialize
#:write serialize
#:fasl? #false
(lambda ()
(render-karst-pict csv))))
(define (render-srs-sound bm* factor*)
(define rktd**
(for/list ([bm (in-list bm*)])
(for/list ([v (in-list (*RKT-VERSIONS*))])
(benchmark-rktd bm v))))
(with-cache (build-path "cache" "cache-srs-sound.rktd")
#:read deserialize
#:write serialize
#:fasl? #false
#:keys #false
(lambda ()
(render-srs-sound-pict rktd** factor*))))
(define (render-srs-precise bm* factor*)
(define rktd**
(for/list ([bm (in-list bm*)])
(for/list ([v (in-list (*RKT-VERSIONS*))])
(benchmark-rktd bm v))))
(with-cache ((list-cache-file "cache-srs-precise-") bm*)
#:read deserialize
#:write serialize
#:fasl? #false
#:keys #false
(lambda ()
(render-srs-precise-pict rktd** factor*))))
(define (render-srs-single bm sample-size-factor)
(define name (benchmark-name bm))
(parameterize ([*current-cache-keys* (list (lambda () sample-size-factor) (lambda () name))]
[*L* '(0)]
[*L-LABELS?* #t]
TODO fix width
[*NUM-SAMPLES* ALOT]
[*PLOT-HEIGHT* 100]
[*PLOT-WIDTH* 210]
[*PLOT-FONT-SCALE* 0.04]
[*SINGLE-PLOT?* #f]
[*X-MINOR-TICKS* (append (for/list ([i (in-range 12 20 2)]) (/ i 10))
(for/list ([i (in-range 4 20 2)]) i))]
[*X-TICK-LINES?* #t]
[*X-TICKS* '(1 2 20)]
[*Y-NUM-TICKS* 3]
[*Y-TICK-LINES?* #t]
[*Y-STYLE* '%]
[*AXIS-LABELS?* #f]
[*LEGEND?* #f]
[*LINE-LABELS?* #f]
[*LOG-TRANSFORM?* #t]
[*M* #f]
[*MAX-OVERHEAD* 20]
[*N* #f]
[*SINGLE-PLOT?* #f])
(hc-append (*GRAPH-HSPACE*)
(render-srs-sound (list bm) (list sample-size-factor))
(render-srs-precise (list bm) (list sample-size-factor)))))
(define (render-delta bm* #:sample-factor [sample-factor #f] #:sample-style [sample-style #f])
(define versions (*RKT-VERSIONS*))
(unless (= 2 (length versions))
(raise-user-error 'render-delta "Cannot compare more than 2 versions of Racket, got ~a~n" versions))
(parameterize ([*AXIS-LABELS?* #f]
[*LEGEND?* #f]
[*LINE-LABELS?* #f]
[*LNM-WIDTH* (+ 0.5 (*LNM-WIDTH*))]
[*MAX-OVERHEAD* 20]
[*NUM-SAMPLES* ALOT])
(define name*
(for/list ([bm (in-list bm*)])
(symbol->string (benchmark-name bm))))
(define rktd**
(for/list ([bm (in-list bm*)])
(for/list ([v (in-list versions)])
(benchmark-rktd bm v))))
(parameterize ([*current-cache-keys* (list (lambda () rktd**))])
(with-cache ((list-cache-file "cache-delta-") bm*)
#:read deserialize
#:write serialize
#:fasl? #false
(lambda ()
(render-delta-pict name* rktd** #:title (format "v~a - v~a" (cadr versions) (car versions)) #:sample-factor sample-factor #:sample-style sample-style))))))
(define (ext:max-overhead rktd)
(max-overhead (from-rktd rktd)))
(define (ext:typed/untyped-ratio rktd)
(typed/untyped-ratio rktd))
(define (ext:configuration->overhead rktd cfg)
(add-x (rnd (configuration->overhead rktd cfg))))
(define (add-x str)
(string-append str "x"))
(define (ext:min-overhead rktd)
(add-x (rnd (min-overhead (from-rktd rktd)))))
(define (deliverable* D v bm*)
(parameterize ([*current-cache-keys* (list (lambda () bm*))]
[*use-cache?* #f])
(with-cache (cachefile (format "cache-~a-deliverable-count" D))
(lambda ()
(for/sum ((bm (in-list bm*)))
(define rktd (benchmark-rktd bm v))
((D-deliverable D) (from-rktd rktd)))))))
;; -----------------------------------------------------------------------------
;
;;; For each benchmark, assign each function a weight of importance
( 2016 - 06 - 07 : unitless for now , but will eventually make this official )
;(define (weigh-functions)
; ;; for benchmarks, get-lnm-data* ...
; (with-output-to-file "yolo.txt" #:exists 'replace (lambda ()
; (for ([rktd* (in-list (get-lnm-rktd**))])
( define ( last rktd * ) )
; (define title (fname->title rktd))
; (define mg (symbol->modulegraph (string->symbol title)))
( define f * ( module - names ) )
; (printf "title: ~a, dataset: ~a\n" title rktd)
( for ( [ w ( in - list ( get - weights f * ) ) ] )
; (printf "- ~a\n" w))))))
;
;(define (mean2 xs)
( rnd ( call - with - values
; (lambda () (for/fold ((sum 0) (len 0)) ((x (in-list xs))) (values (+ x sum) (+ 1 len))))
; /)))
;
( define ( get - weights f * )
; (define v (file->value rktd))
; (define num-modules (length f*))
; (define (nat->bits n)
; (natural->bitstring n #:pad num-modules))
; (for/list ((f (in-list f*))
; (fun-idx (in-naturals)))
; ;; fun-idx corresponds to a function we want to compare typed/untyped
; (define-values (u* t*)
; (for/fold ([u* '()]
; [t* '()])
; ([row (in-vector v)]
; [row-idx (in-naturals)])
; (define cfg (nat->bits row-idx))
; (if (bit-high? cfg fun-idx)
; (values u* (append row t*))
; (values (append row u*) t*))))
; (when (or (null? u*) (null? t*))
( raise - user - error ' weigh " not good for ~a at ~a ~a ~a " ) )
; (define um (mean2 u*))
; (define tm (mean2 t*))
; (list f um tm (abs (- (string->number um) (string->number tm))))))
;
;; =============================================================================
(module+ test
(require rackunit rackunit-abbrevs)
(check-apply* read-list
["()" => '()]
["( 1 2 3 )" => '(1 2 3)]
["( 2 1 () 5)" => '(2 1 () 5)]
["yolo" => #f]
[")( " => #f])
(test-case "typed/untyped-ratio"
(let ([z6.2 (ext:typed/untyped-ratio (benchmark-rktd zordoz "6.2"))]
[z6.3 (ext:typed/untyped-ratio (benchmark-rktd zordoz "6.3"))])
(check-true (< z6.3 z6.2)))
(let ([fsm6.2 (ext:typed/untyped-ratio (benchmark-rktd fsm "6.2"))]
[fsm6.3 (ext:typed/untyped-ratio (benchmark-rktd fsm "6.3"))]
[fsmoo6.2 (ext:typed/untyped-ratio (benchmark-rktd fsmoo "6.2"))]
[fsmoo6.3 (ext:typed/untyped-ratio (benchmark-rktd fsmoo "6.3"))])
(check-true (> fsm6.3 fsm6.2))
(check-true (= fsmoo6.3 fsmoo6.2))))
)
| null | https://raw.githubusercontent.com/nuprl/gradual-typing-performance/35442b3221299a9cadba6810573007736b0d65d4/paper/jfp-2016/typed-racket.rkt | racket | Supporting code for `typed-racket.scrbl`
- Render & organize benchmarks
- Make L-N/M figures
TEMPORARY
(-> String Any)
Use to format bitstrings
(-> String Any)
Use to format benchmark names.
Asserts that its argument is a correctly-spelled benchmark name.
Count Anderson-Darling savings.
(-> Natural)
(-> Benchmark * Any)
Use the `benchmark` constructor to make a `Benchmark`
(-> Any)
Build a table describing static properties of the benchmarks
(-> Benchmark-Name Version-String Any)
where Benchmark-Name = (U String Symbol)
and Version-String = String
Finds the data file corresponding to the benchmark
at the specific version and renders a data lattice.
(-> Any)
(rename-out [make-lnm lnm])
=============================================================================
of samples for the overhead plots
Where to store 'with-cache' cache files
Where to store module graphs
-----------------------------------------------------------------------------
Add '&' for TeX
-----------------------------------------------------------------------------
--- Formatting
Example #:write proc
Example #:read proc
-----------------------------------------------------------------------------
--- Lattice
[*current-cache-keys* (list *LATTICE-BORDER-WIDTH* *LATTICE-BOX-BOT-MARGIN* *LATTICE-BOX-HEIGHT* *LATTICE-BOX-SEP* *LATTICE-BOX-TOP-MARGIN* *LATTICE-BOX-WIDTH* *LATTICE-CONFIG-MARGIN* *LATTICE-LEVEL-MARGIN* *LATTICE-FONT-SIZE* *LATTICE-TRUNCATE-DECIMALS?*)])
-----------------------------------------------------------------------------
--- Benchmarks
(-> benchmark String)
(-> Benchmark * Any)
Sorry, can't serialize scribble elements
(tex-row "{\\tt forth}" "4" "0" "0" "0" "0" "0")
(tex-row "{\\tt fsmoo}" "4" "0" "0" "0" "0" "0")
(tex-row "{\\tt mbta}" "4" "0" "1" "1" "1" "1")
(tex-row "{\\tt morsecode}" "4" "0" "1" "1" "1" "1")
(tex-row "{\\tt take5}" "8" "0" "1" "1" "1" "1")
(tex-row "{\\tt tetris}" "9" "0" "0" "0" "0.17" "0.17")
=============================================================================
(define (lnm<? l1 l2)
(lnm->benchmark l2)))
(-> Lnm * Any)
(define (render-lnm-descriptions . l*)
(check-missing-benchmarks (map lnm-name l*) #:exact? #t)
(map render-lnm-description (sort l* lnm<?)))
Get data for each benchmark for each version of racket
Drops the version tags
(format "~a-deliverable" over))
(format-stat* (N-deliverable overhead) S*))
-----------------------------------------------------------------------------
(apply render-deliverable-plot D bm*)
-----------------------------------------------------------------------------
For each benchmark, assign each function a weight of importance
(define (weigh-functions)
;; for benchmarks, get-lnm-data* ...
(with-output-to-file "yolo.txt" #:exists 'replace (lambda ()
(for ([rktd* (in-list (get-lnm-rktd**))])
(define title (fname->title rktd))
(define mg (symbol->modulegraph (string->symbol title)))
(printf "title: ~a, dataset: ~a\n" title rktd)
(printf "- ~a\n" w))))))
(define (mean2 xs)
(lambda () (for/fold ((sum 0) (len 0)) ((x (in-list xs))) (values (+ x sum) (+ 1 len))))
/)))
(define v (file->value rktd))
(define num-modules (length f*))
(define (nat->bits n)
(natural->bitstring n #:pad num-modules))
(for/list ((f (in-list f*))
(fun-idx (in-naturals)))
;; fun-idx corresponds to a function we want to compare typed/untyped
(define-values (u* t*)
(for/fold ([u* '()]
[t* '()])
([row (in-vector v)]
[row-idx (in-naturals)])
(define cfg (nat->bits row-idx))
(if (bit-high? cfg fun-idx)
(values u* (append row t*))
(values (append row u*) t*))))
(when (or (null? u*) (null? t*))
(define um (mean2 u*))
(define tm (mean2 t*))
(list f um tm (abs (- (string->number um) (string->number tm))))))
============================================================================= | #lang racket/base
ALOT
MAX-OVERHEAD
new-untyped-bars
)
(provide
benchmark->tex-file
count-benchmarks
count-new-oo-benchmarks
bits
bm
count-savings
( - > ( ) ( Values Natural Natural ) )
i.e. the number of data rows with 10 values rather than 30
count-all-configurations
get-lnm-table-data
render-table
tex-row
Low - level table builder
render-benchmark-descriptions
Render a list of Benchmark structures .
render-path-table
render-benchmarks-table
render-data-lattice
render-lnm-table
render-exact-plot
render-typed/untyped-plot
render-deliverable-plot
render-uncertainty
render-karst
render-srs-sound
render-srs-precise
render-delta
render-iterations-table
render-srs-single
render-exact-table
( - > * [ Symbol ] [ ] # : rest ( ) Lnm )
render-lnm-plot
( - > ( - > ( ) Any )
percent-diff
deliverable*
(rename-out
[ext:typed/untyped-ratio typed/untyped-ratio]
[ext:max-overhead max-overhead]
[ext:configuration->overhead configuration->overhead]
[ext:min-overhead min-overhead])
)
(require
benchmark-util/data-lattice
glob
gtp-summarize
(only-in gtp-summarize/bitstring natural->bitstring log2 bit-high?)
racket/match
(only-in pict blank hc-append vc-append)
(only-in "common.rkt" etal cite exact parag)
(only-in racket/file file->value)
(only-in racket/format ~r)
(only-in racket/list drop-right split-at last append*)
(only-in math/number-theory factorial)
(only-in racket/port with-input-from-string)
(only-in racket/string string-prefix? string-join)
scribble/core
scribble/base
version/utils
with-cache
racket/contract
"benchmark.rkt"
"util.rkt"
)
(require (only-in racket/serialize
serialize
deserialize
))
(define MAX-OVERHEAD
20)
250)
(define (count-benchmarks)
(*NUM-BENCHMARKS*))
(define (count-new-oo-benchmarks)
(*NUM-OO-BENCHMARKS*))
--- Syntax & Utils
( May be better off in libraries )
(define (count-all-configurations)
(*TOTAL-NUM-CONFIGURATIONS*))
(define (count-savings)
(with-cache (benchmark-savings-cache)
#:keys #false
#:read uncache-dataset
#:write cache-dataset
#:fasl? #false
new-count-savings))
(define (new-count-savings)
(define-values (skip total)
(for*/fold ([num-skip-runs 0]
[num-runs 0])
([rktd* (in-list (get-lnm-rktd**))]
[d (in-list rktd*)])
(with-input-from-file d
(lambda ()
(for/fold ([nsr num-skip-runs]
[nr num-runs])
([ln (in-lines)])
(define is-run? (eq? #\( (string-ref ln 0)))
(values
(+ nsr (if (and is-run? (= 10 (length (read-list ln)))) 1 0))
(+ nr (if is-run? 1 0))))))))
(list skip total))
(define (read-list str)
(with-handlers ([exn:fail? (lambda (e) #f)])
(let ([r (with-input-from-string str read)])
(and (list? r) r))))
(define (tex-row #:sep [sep #f] . x*)
(let loop ([x* x*])
(if (null? (cdr x*))
(list (car x*) (format " \\\\~a~n" (if sep (format "[~a]" sep) "")))
(list* (car x*) " & " (loop (cdr x*))))))
(define (percent-diff meas exp)
(/ (- meas exp) exp))
(define BENCHMARK-NAMES (map benchmark-name ALL-BENCHMARKS))
(define bits
tt)
(define (cache-table T)
(cons BENCHMARK-NAMES T))
(define (uncache-table tag+data)
(and (equal? (car tag+data) BENCHMARK-NAMES)
(cdr tag+data)))
(define (cache-dataset d)
(cons (get-lnm-rktd**) d))
(define (uncache-dataset fname+d)
(and (equal? (car fname+d) (get-lnm-rktd**))
(cdr fname+d)))
(define (render-table render-proc #:title title* #:cache cache-file #:sep [sep 0.2])
(exact
(format "\\setlength{\\tabcolsep}{~aem}" sep)
(format "\\begin{tabular}{l~a}" (make-string (sub1 (length title*)) #\r))
(list " \\toprule \n" (apply tex-row title*) " \\midrule \n")
(apply elem
(with-cache cache-file
#:fasl? #false
#:read uncache-table
#:write cache-table
render-proc))
"\\end{tabular}\n\n"))
(define ((list-cache-file tag) bm-or-bm*)
(ensure-dir CACHE)
(define bm* (if (list? bm-or-bm*) bm-or-bm* (list bm-or-bm*)))
(string-append
CACHE "/" tag
(string-join (map (compose1 symbol->string benchmark-name) bm*) "-")
".rktd"))
(define exact-cache-file
(list-cache-file "cache-exact-"))
(define typed/untyped-cache-file
(list-cache-file "cache-tu-"))
(define (deliverable-cache-file N)
(list-cache-file (format "cache-~a-deliverable-" N)))
(define (lattice-cache-file bm v)
(ensure-dir CACHE)
(string-append CACHE "/cache-lattice-" (symbol->string bm) "-" v ".rktd"))
(define (path-table-cache-file)
(ensure-dir CACHE)
(build-path CACHE "cache-path-table.rktd"))
(define (benchmarks-table-cache-file)
(ensure-dir CACHE)
(build-path CACHE (*BENCHMARK-TABLE-CACHE*)))
(define (benchmark-savings-cache)
(ensure-dir CACHE)
(build-path CACHE (*BENCHMARK-SAVINGS-CACHE*)))
(define (exact-table-cache)
(ensure-dir CACHE)
(build-path CACHE (*EXACT-TABLE-CACHE*)))
(define (lnm-table-cache)
(ensure-dir CACHE)
(build-path CACHE (*LNM-TABLE-CACHE*)))
(define (lnm-table-data-cache)
(ensure-dir CACHE)
(build-path CACHE (*LNM-TABLE-DATA-CACHE*)))
NOTE 2017 - 12 - 28 : can not use cache , the white rectangles do n't look right
(define (render-data-lattice bm v)
(parameterize ([*use-cache?* #false]
(with-cache (lattice-cache-file (benchmark-name bm) v)
#:read deserialize
#:write serialize
#:fasl? #false
(lambda () (file->performance-lattice (benchmark-rktd bm v))))))
(define (render-benchmark b+d)
(define b* (car b+d))
(define-values (b name)
(if (list? b*)
(values (car b*) (string-join (map (compose1 symbol->string benchmark-name) b*) ", "))
(values b* (symbol->string (benchmark-name b*)))))
(define d (cdr b+d))
(elem
"\\benchmark{"
name
"}{"
(benchmark-author b)
"}{"
(benchmark-origin b)
"}{"
(benchmark-purpose b)
"}{"
d
"}{"
(benchmark->tex-file b)
"}{"
(or (benchmark-lib* b) "N/A")
"}\n\n"))
(define (benchmark->tex-file b [scale 1])
(define M (benchmark-modulegraph b))
(define pn (modulegraph-project-name M))
(define mgd MODULE-GRAPH)
(ensure-dir mgd)
(define mgf (format "~a/~a.tex" mgd pn))
(unless (file-exists? mgf)
(WARNING "could not find modulegraph for project '~a', creating graph now." pn)
(call-with-output-file mgf
(lambda (p) (modulegraph->tex M p))))
(exact (format "\\modulegraph{~a}{~a}" mgf scale)))
(define (render-benchmark-descriptions . b+d*)
(define key (equal-hash-code (map cdr b+d*)))
(parameterize ([*current-cache-keys* (list (lambda () key))]
(with-cache (cachefile "benchmark-descriptions.rktd")
#:read deserialize
#:write serialize
#:fasl? #false
(lambda ()
( check - missing - benchmarks ( map ( compose1 benchmark - name car ) b+d * ) )
(define b+d*+ (sort b+d* benchmark<? #:key (lambda (x) (if (list? (car x)) (caar x) (car x)))))
(apply exact (map render-benchmark b+d*+))))))
(define PATH-D* '(1 3 5 10 20))
(define PATH-TABLE-TITLE*
(list* "Benchmark"
"\\# Mod."
(for/list ([d (in-list PATH-D*)])
(format "D = ~a" d))))
(define ITERATIONS-TABLE-TITLE*
(let ([row '("Benchmark" "v6.2" "v6.3" "v6.4")])
(append row '("") row)))
(define BENCHMARKS-TABLE-TITLE* '(
"Benchmark"
"\\twoline{Untyped}{LOC}"
"\\twoline{Annotation}{LOC}"
"\\# Mod."
"\\# Adp."
"\\# Bnd."
"\\# Exp."
))
(define EXACT-TABLE-TITLE* '(
"TBA"
))
(define (render-iterations-table)
(render-table new-iterations-table
#:title ITERATIONS-TABLE-TITLE*
#:cache (build-path CACHE "cache-iterations-table.rktd")))
(define (render-path-table)
(render-table new-path-table
#:title PATH-TABLE-TITLE*
#:cache (path-table-cache-file)))
(define (render-benchmarks-table)
(render-table new-benchmarks-table
#:title BENCHMARKS-TABLE-TITLE*
#:cache (benchmarks-table-cache-file)))
(define (new-benchmarks-table)
(for/list ([b (in-list ALL-BENCHMARKS)])
(define M (benchmark-modulegraph b))
(define num-adaptor (benchmark-num-adaptor b))
(define uloc (modulegraph->untyped-loc M))
(define tloc (modulegraph->typed-loc M))
TODO do n't pad last row
(format "{\\tt ~a}" (benchmark-name b))
(number->string uloc)
(if (zero? uloc) "0" (format-percent-diff tloc uloc))
(number->string (modulegraph->num-modules M))
(number->string num-adaptor)
(number->string (modulegraph->num-edges M))
(number->string (modulegraph->num-identifiers M)))))
(define (new-iterations-table)
(define version* (*RKT-VERSIONS*))
(two-column
(for/list ([bm (in-list ALL-BENCHMARKS)])
(cons
(format "{\\tt ~a}" (benchmark-name bm))
(for/list ([v (in-list version*)])
(number->string (benchmark->num-iterations bm v)))))))
(define (two-column x*)
(define-values (first-half second-half) (split-at x* (quotient (length x*) 2)))
(for/list ([a (in-list first-half)]
[b (in-list second-half)])
(apply tex-row (append a (list "~~~~~~") b))))
(define (deliverable-paths% S D)
(define num-deliv
(for*/sum ([c* (all-paths S)]
#:when (andmap (lambda (cfg) (<= (configuration->overhead S cfg) D))
(cdr (drop-right c* 1))))
1))
(define total-paths (factorial (get-num-modules S)))
(* 100 (/ num-deliv total-paths)))
(define (new-path-table)
(for/list ([bm (in-list ALL-BENCHMARKS)]
#:when (<= (benchmark->num-modules bm) 11))
(define S (from-rktd (benchmark-rktd bm "6.4")))
(apply tex-row
(format "{\\tt ~a}" (benchmark-name bm))
(format "~a" (benchmark->num-modules bm))
(for/list ([D (in-list PATH-D*)])
(number->string (deliverable-paths% S D))))))
( tex - row " { \\tt sieve } " " 2 " " 0 " " 0 " " 0 " " 0 " " 0.50 " )
( tex - row " { \\tt fsm } " " 4 " " 0 " " 0 " " 0 " " 0 " " 0 " )
( tex - row " { \\tt dungeon } " " 5 " " 0 " " 0 " " 0 " " 0.50 " " 1 " )
( tex - row " { \\tt zombie } " " 5 " " 0 " " 0 " " 0 " " 0 " " 0 " )
( tex - row " { \\tt zordoz } " " 5 " " 0 " " 1 " " 1 " " 1 " " 1 " )
( tex - row " { \\tt lnm } " " 6 " " 0.17 " " 1 " " 1 " " 1 " " 1 " )
( tex - row " { } " " 6 " " 0 " " 0 " " 0 " " 0 " " 0.17 " )
( tex - row " { \\tt kcfa } " " 7 " " 0 " " 0.20 " " 0.97 " " 1 " " 1 " )
( tex - row " { \\tt snake } " " 8 " " 0 " " 0 " " 0 " " 0.8 " " 0.50 " )
( tex - row " { \\tt acquire } " " 9 " " 0 " " 0.2 " " 0.83 " " 1 " " 1 " )
( tex - row " { \\tt synth } " " 10 " " 0 " " 0 " " 0 " " 0 " " 0 " )
(define (format-percent-diff meas exp)
(define diff (- meas exp))
(define pct (round (* 100 (percent-diff meas exp))))
(format "~a~~~~~a(~a\\%)"
diff
(if (< pct 10) "\\hphantom{0}" "")
pct))
(struct lnm (name description))
(define (make-lnm name . descr*)
(lnm name (apply elem descr*)))
( benchmark < ? ( lnm->benchmark l1 )
(define (render-lnm-description l)
(elem
(parag (symbol->string (lnm-name l)))
(elem (lnm-description l))))
(define (render-lnm-plot pict*->elem #:rktd*** [rktd*** #f] #:index [cache-offset 1])
Sort & make figures of with 6 plots each or whatever
(parameterize ([*AXIS-LABELS?* #f]
[*CACHE-PREFIX* "./cache/cache-lnm-"]
[*COLOR-OFFSET* 1]
[*L* '(0 1)]
[*L-LABELS?* #t]
[*LEGEND?* (or (not rktd***)
(for*/or ([rktd** (in-list rktd***)]
[rktd* (in-list rktd**)])
(< 1 (length rktd*))))]
[*LINE-LABELS?* #f]
[*LOG-TRANSFORM?* #t]
[*M* #f]
[*MAX-OVERHEAD* MAX-OVERHEAD]
[*N* #f]
[*NUM-SAMPLES* ALOT]
[*PLOT-FONT-SCALE* 0.04]
[*PLOT-HEIGHT* 100]
[*PLOT-WIDTH* 210]
[*SINGLE-PLOT?* #f]
[*X-MINOR-TICKS* (append (for/list ([i (in-range 12 MAX-OVERHEAD 2)]) (/ i 10))
(for/list ([i (in-range 4 MAX-OVERHEAD 2)]) i))]
[*X-TICK-LINES?* #t]
[*X-TICKS* '(1 2 20)]
[ * Y - MINOR - TICKS * ' ( 25 75 ) ]
[*Y-NUM-TICKS* 3]
[*Y-TICK-LINES?* #t]
[*Y-STYLE* '%])
(define cache? (*CACHE?*))
(pict*->elem
(for/list ([rktd** (in-list (or rktd*** (split-list 5 (get-lnm-rktd**))))]
[i (in-naturals cache-offset)])
(parameterize ([*CACHE-TAG* (if cache? (number->string i) #f)])
(collect-garbage 'major)
(render-lnm (list->vector (append* rktd**))))))))
(define (get-lnm-rktd**)
(for/list ([b (in-list ALL-BENCHMARKS)])
(for/list ([v->rktd (in-list (benchmark-rktd* b))])
(cdr v->rktd))))
(define LNM-TABLE-TITLE* '(
"Benchmark"
"\\twoline{Typed/Untyped}{Ratio}"
"Mean Overhead"
"Max Overhead"
( for / list ( [ over ( in - list LNM - OVERHEAD * ) ] )
))
(define (render-lnm-table)
(with-cache (lnm-table-cache)
#:read (lambda (tag+data)
(let ([d (uncache-table tag+data)])
(and d (deserialize d))))
#:write (compose1 cache-table serialize)
#:fasl? #false
new-lnm-bars))
(define (get-lnm-table-data)
(with-cache (lnm-table-data-cache)
#:read uncache-dataset
#:write cache-dataset
#:fasl? #false
(lambda ()
(call-with-values new-lnm-table-data list))))
(define (new-untyped-data)
(let loop ([rktd** (get-lnm-rktd**)])
(if (null? rktd**)
(values '() '())
(let-values ([(n* r**) (loop (cdr rktd**))]
[(_) (collect-garbage 'major)]
[(S*) (for/list ([rktd (in-list (car rktd**))])
(from-rktd rktd))])
(values
(cons (fname->title (caar rktd**)) n*)
(cons (map untyped-mean S*) r**))))))
(define (new-lnm-table-data)
(let loop ([rktd** (get-lnm-rktd**)])
(if (null? rktd**)
(values '() '() '() '())
(let-values ([(n* r** m** x**) (loop (cdr rktd**))]
[(_) (collect-garbage 'major)]
: ( Summary )
([rktd (in-list (car rktd**))])
(from-rktd rktd))])
(values
(cons (fname->title (caar rktd**)) n*)
(cons (map typed/untyped-ratio S*) r**)
(cons (map avg-overhead S*) m**)
(cons (map max-overhead S*) x**))))))
(define (new-untyped-bars)
(parameterize ([*PLOT-WIDTH* 420]
[*PLOT-HEIGHT* 140]
[*PLOT-FONT-SCALE* 0.04]
[*LOG-TRANSFORM?* #f])
(apply render-untyped-bars (call-with-values new-untyped-data list))))
(define (new-lnm-bars)
(parameterize ([*PLOT-WIDTH* 420]
[*PLOT-HEIGHT* 140]
[*PLOT-FONT-SCALE* 0.04]
[*LOG-TRANSFORM?* #t])
(apply render-bars (get-lnm-table-data))))
(define (new-lnm-dots)
(parameterize ([*PLOT-WIDTH* 300]
[*PLOT-HEIGHT* 20])
(render-dots (get-lnm-rktd**))))
(define (old-render-lnm-table)
(render-table new-lnm-table
#:title LNM-TABLE-TITLE*
#:cache (lnm-table-cache)))
(define (new-lnm-table)
(for/list ([rktd* (in-list (get-lnm-rktd**))])
(define name (fname->title (car rktd*)))
(collect-garbage 'major)
(define S* (map from-rktd rktd*))
(tex-row
name
(format-stat* typed/untyped-ratio S* #:precision 2)
(format-stat* avg-overhead S*)
(format-stat* max-overhead S*)
( for / list ( [ overhead ( in - list LNM - OVERHEAD * ) ] )
)))
TODO put these in sub - table
(define (format-stat* f S* #:precision [p 0])
(string-join
(for/list ((S (in-list S*)))
(~r (f S) #:precision p))
"~~"))
(define (benchmark->rktd* bm)
(for/list ([v (in-list (*RKT-VERSIONS*))])
(benchmark-rktd bm v)))
(define (render-exact-plot . bm*)
(with-cache (exact-cache-file bm*)
#:keys #false
#:read deserialize
#:write serialize
#:fasl? #false
(lambda ()
(parameterize ([*LEGEND?* #f]
[*PLOT-FONT-SCALE* 0.04]
[*PLOT-HEIGHT* 200]
[*PLOT-WIDTH* 430]
[*POINT-SIZE* 6]
[*POINT-ALPHA* 0.7])
(render-exact*
(for*/list ([bm (in-list bm*)])
(list->vector (benchmark->rktd* bm))))))))
(define (render-exact-table bm)
(render-table
new-exact-table
#:title EXACT-TABLE-TITLE*
#:cache (cachefile "exact-table")))
(define (new-exact-table)
(for/list ([b (in-list ALL-BENCHMARKS)])
(tex-row "?")))
(define (render-typed/untyped-plot . bm*)
(with-cache (typed/untyped-cache-file bm*)
#:read deserialize
#:write serialize
#:fasl? #false
#:keys #false
(lambda ()
(parameterize ([*LEGEND?* #f]
[*ERROR-BAR-WIDTH* 20]
[*ERROR-BAR-LINE-WIDTH* 1]
[*PLOT-FONT-SCALE* 0.04]
[*PLOT-HEIGHT* 320]
[*PLOT-WIDTH* 430]
[*POINT-SIZE* 5]
[*Y-NUM-TICKS* 4]
[*POINT-ALPHA* 0.7])
(render-typed/untyped
(for*/list ([bm (in-list bm*)])
(list->vector (benchmark->rktd* bm))))))))
(define (render-deliverable-plot D . bm*)
(with-cache ((deliverable-cache-file D) bm*)
#:read deserialize
#:write serialize
#:fasl? #false
#:keys #false
(lambda ()
(parameterize ([*LEGEND?* #f]
[*ERROR-BAR-WIDTH* (*RECTANGLE-WIDTH*)]
[*ERROR-BAR-LINE-WIDTH* (*RECTANGLE-WIDTH*)]
[*Y-NUM-TICKS* 3]
[*POINT-ALPHA* 0.7]
[*PLOT-FONT-SCALE* 0.04]
[*PLOT-HEIGHT* 180]
[*PLOT-WIDTH* 440])
(render-deliverable D
(for*/list ([bm (in-list bm*)])
(list->vector (benchmark->rktd* bm))))))))
(define (render-uncertainty bm*)
(vc-append 20
(apply render-typed/untyped-plot bm*)
( hc - append 0 ( blank 10 0 ) ( apply render - typed / untyped - plot bm * ) )
(render-bars-xlabels 33 (map (compose1 symbol->string benchmark-name) bm*))))
(define (render-karst csv)
(parameterize ([*current-cache-keys* (list (lambda () csv))])
[*LEGEND?* #f]
[*ERROR-BAR-WIDTH* 0.2]
[*ERROR-BAR-LINE-WIDTH* 1]
[*PLOT-FONT-SCALE* 0.04]
[*PLOT-HEIGHT* 140]
[*PLOT-WIDTH* 430]
[*POINT-SIZE* 5]
[*COLOR-OFFSET* 4]
[*Y-NUM-TICKS* 4]
[*POINT-ALPHA* 0.7])
(with-cache (cachefile "cache-karst.rktd")
#:read deserialize
#:write serialize
#:fasl? #false
(lambda ()
(render-karst-pict csv))))
(define (render-srs-sound bm* factor*)
(define rktd**
(for/list ([bm (in-list bm*)])
(for/list ([v (in-list (*RKT-VERSIONS*))])
(benchmark-rktd bm v))))
(with-cache (build-path "cache" "cache-srs-sound.rktd")
#:read deserialize
#:write serialize
#:fasl? #false
#:keys #false
(lambda ()
(render-srs-sound-pict rktd** factor*))))
(define (render-srs-precise bm* factor*)
(define rktd**
(for/list ([bm (in-list bm*)])
(for/list ([v (in-list (*RKT-VERSIONS*))])
(benchmark-rktd bm v))))
(with-cache ((list-cache-file "cache-srs-precise-") bm*)
#:read deserialize
#:write serialize
#:fasl? #false
#:keys #false
(lambda ()
(render-srs-precise-pict rktd** factor*))))
(define (render-srs-single bm sample-size-factor)
(define name (benchmark-name bm))
(parameterize ([*current-cache-keys* (list (lambda () sample-size-factor) (lambda () name))]
[*L* '(0)]
[*L-LABELS?* #t]
TODO fix width
[*NUM-SAMPLES* ALOT]
[*PLOT-HEIGHT* 100]
[*PLOT-WIDTH* 210]
[*PLOT-FONT-SCALE* 0.04]
[*SINGLE-PLOT?* #f]
[*X-MINOR-TICKS* (append (for/list ([i (in-range 12 20 2)]) (/ i 10))
(for/list ([i (in-range 4 20 2)]) i))]
[*X-TICK-LINES?* #t]
[*X-TICKS* '(1 2 20)]
[*Y-NUM-TICKS* 3]
[*Y-TICK-LINES?* #t]
[*Y-STYLE* '%]
[*AXIS-LABELS?* #f]
[*LEGEND?* #f]
[*LINE-LABELS?* #f]
[*LOG-TRANSFORM?* #t]
[*M* #f]
[*MAX-OVERHEAD* 20]
[*N* #f]
[*SINGLE-PLOT?* #f])
(hc-append (*GRAPH-HSPACE*)
(render-srs-sound (list bm) (list sample-size-factor))
(render-srs-precise (list bm) (list sample-size-factor)))))
(define (render-delta bm* #:sample-factor [sample-factor #f] #:sample-style [sample-style #f])
(define versions (*RKT-VERSIONS*))
(unless (= 2 (length versions))
(raise-user-error 'render-delta "Cannot compare more than 2 versions of Racket, got ~a~n" versions))
(parameterize ([*AXIS-LABELS?* #f]
[*LEGEND?* #f]
[*LINE-LABELS?* #f]
[*LNM-WIDTH* (+ 0.5 (*LNM-WIDTH*))]
[*MAX-OVERHEAD* 20]
[*NUM-SAMPLES* ALOT])
(define name*
(for/list ([bm (in-list bm*)])
(symbol->string (benchmark-name bm))))
(define rktd**
(for/list ([bm (in-list bm*)])
(for/list ([v (in-list versions)])
(benchmark-rktd bm v))))
(parameterize ([*current-cache-keys* (list (lambda () rktd**))])
(with-cache ((list-cache-file "cache-delta-") bm*)
#:read deserialize
#:write serialize
#:fasl? #false
(lambda ()
(render-delta-pict name* rktd** #:title (format "v~a - v~a" (cadr versions) (car versions)) #:sample-factor sample-factor #:sample-style sample-style))))))
(define (ext:max-overhead rktd)
(max-overhead (from-rktd rktd)))
(define (ext:typed/untyped-ratio rktd)
(typed/untyped-ratio rktd))
(define (ext:configuration->overhead rktd cfg)
(add-x (rnd (configuration->overhead rktd cfg))))
(define (add-x str)
(string-append str "x"))
(define (ext:min-overhead rktd)
(add-x (rnd (min-overhead (from-rktd rktd)))))
(define (deliverable* D v bm*)
(parameterize ([*current-cache-keys* (list (lambda () bm*))]
[*use-cache?* #f])
(with-cache (cachefile (format "cache-~a-deliverable-count" D))
(lambda ()
(for/sum ((bm (in-list bm*)))
(define rktd (benchmark-rktd bm v))
((D-deliverable D) (from-rktd rktd)))))))
( 2016 - 06 - 07 : unitless for now , but will eventually make this official )
( define ( last rktd * ) )
( define f * ( module - names ) )
( for ( [ w ( in - list ( get - weights f * ) ) ] )
( rnd ( call - with - values
( define ( get - weights f * )
( raise - user - error ' weigh " not good for ~a at ~a ~a ~a " ) )
(module+ test
(require rackunit rackunit-abbrevs)
(check-apply* read-list
["()" => '()]
["( 1 2 3 )" => '(1 2 3)]
["( 2 1 () 5)" => '(2 1 () 5)]
["yolo" => #f]
[")( " => #f])
(test-case "typed/untyped-ratio"
(let ([z6.2 (ext:typed/untyped-ratio (benchmark-rktd zordoz "6.2"))]
[z6.3 (ext:typed/untyped-ratio (benchmark-rktd zordoz "6.3"))])
(check-true (< z6.3 z6.2)))
(let ([fsm6.2 (ext:typed/untyped-ratio (benchmark-rktd fsm "6.2"))]
[fsm6.3 (ext:typed/untyped-ratio (benchmark-rktd fsm "6.3"))]
[fsmoo6.2 (ext:typed/untyped-ratio (benchmark-rktd fsmoo "6.2"))]
[fsmoo6.3 (ext:typed/untyped-ratio (benchmark-rktd fsmoo "6.3"))])
(check-true (> fsm6.3 fsm6.2))
(check-true (= fsmoo6.3 fsmoo6.2))))
)
|
7c5de9c8fcd5ae4f9041f4e1452d0572f267f378d5801e36234599f7fdf95840 | ruhler/smten | AST.hs |
# LANGUAGE MultiParamTypeClasses #
{-# LANGUAGE TypeSynonymInstances #-}
module Smten.Runtime.Yices2.AST (Yices2(..), YTerm) where
import Foreign
import Foreign.C.String
import Data.Char
import Data.Functor
import Data.Maybe
import qualified Data.HashTable.IO as H
import Numeric
import Smten.Runtime.Bit
import Smten.Runtime.Yices2.FFI
import Smten.Runtime.Formula.Type
import Smten.Runtime.FreeID
import Smten.Runtime.Model
import Smten.Runtime.SolverAST
type VarMap = H.BasicHashTable FreeID YTerm
data Yices2 = Yices2 {
y2_ctx :: Ptr YContext,
y2_vars :: VarMap
}
instance SolverAST Yices2 YTerm YTerm YTerm where
declare_bool y nm = do
ty <- c_yices_bool_type
term <- c_yices_new_uninterpreted_term ty
H.insert (y2_vars y) nm term
declare_integer y nm = do
ty <- c_yices_int_type
term <- c_yices_new_uninterpreted_term ty
H.insert (y2_vars y) nm term
declare_bit y w nm = do
ty <- c_yices_bv_type (fromInteger w)
term <- c_yices_new_uninterpreted_term ty
H.insert (y2_vars y) nm term
getBoolValue y nm = do
model <- c_yices_get_model (y2_ctx y) 1
r <- getBoolValueWithModel y nm model
c_yices_free_model model
return r
getIntegerValue y nm = do
model <- c_yices_get_model (y2_ctx y) 1
r <- getIntegerValueWithModel y nm model
c_yices_free_model model
return r
getBitVectorValue y w nm = do
model <- c_yices_get_model (y2_ctx y) 1
r <- getBitVectorValueWithModel y w nm model
c_yices_free_model model
return r
getModel y vars = do
model <- c_yices_get_model (y2_ctx y) 1
let getv (nm, BoolT) = BoolA <$> getBoolValueWithModel y nm model
getv (nm, IntegerT) = IntegerA <$> getIntegerValueWithModel y nm model
getv (nm, BitT w) = do
b <- getBitVectorValueWithModel y w nm model
return (BitA $ bv_make w b)
r <- mapM getv vars
c_yices_free_model model
return r
check y = do
st <- c_yices_check_context (y2_ctx y) nullPtr
return $! fromYSMTStatus st
cleanup y = do
c_yices_free_context (y2_ctx y)
c_yices_exit
assert y e = c_yices_assert_formula (y2_ctx y) e
bool _ p = if p then c_yices_true else c_yices_false
integer _ i = c_yices_int64 (fromInteger i)
bit _ w v = do
let w' = fromInteger w
v' = fromInteger v
base2 = showIntAtBase 2 (\x -> chr (x + ord '0')) v ""
binstr = replicate (fromInteger w - length base2) '0' ++ base2
if w <= 64
then c_yices_bvconst_uint64 w' v'
else withCString binstr $ \str -> c_yices_parse_bvbin str
var_bool y nm = fromJust <$> H.lookup (y2_vars y) nm
var_integer y nm = fromJust <$> H.lookup (y2_vars y) nm
var_bit y w nm = fromJust <$> H.lookup (y2_vars y) nm
and_bool _ = c_yices_and2
or_bool _ = c_yices_or2
not_bool _ = c_yices_not
ite_bool _ = c_yices_ite
ite_integer _ = c_yices_ite
ite_bit _ = c_yices_ite
eq_integer _ = c_yices_eq
leq_integer _ = c_yices_arith_leq_atom
add_integer _ = c_yices_add
sub_integer _ = c_yices_sub
eq_bit _ = c_yices_eq
leq_bit _ = c_yices_bvle_atom
add_bit _ = c_yices_bvadd
sub_bit _ = c_yices_bvsub
mul_bit _ = c_yices_bvmul
sdiv_bit _ = c_yices_bvsdiv
smod_bit _ = c_yices_bvsmod
srem_bit _ = c_yices_bvsrem
udiv_bit _ = c_yices_bvdiv
urem_bit _ = c_yices_bvrem
or_bit _ = c_yices_bvor
and_bit _ = c_yices_bvand
concat_bit _ = c_yices_bvconcat
shl_bit _ _ = c_yices_bvshl
lshr_bit _ _ = c_yices_bvlshr
not_bit _ = c_yices_bvnot
sign_extend_bit _ fr to a = c_yices_sign_extend a (fromInteger $ to - fr)
extract_bit _ hi lo x = c_yices_bvextract x (fromInteger lo) (fromInteger hi)
getBoolValueWithModel :: Yices2 -> FreeID -> YModel -> IO Bool
getBoolValueWithModel y nm model = do
x <- alloca $ \ptr -> do
term <- fromJust <$> H.lookup (y2_vars y) nm
ir <- c_yices_get_bool_value model term ptr
case ir of
_ | ir == (-1) -> do
-- -1 means we don't care, so just return the equivalent
-- of False.
return 0
0 -> do
v <- peek ptr
return v
_ -> error $ "yices2 get bool value returned: " ++ show ir
case x of
0 -> return False
1 -> return True
_ -> error $ "yices2 get bool value got: " ++ show x
getIntegerValueWithModel :: Yices2 -> FreeID -> YModel -> IO Integer
getIntegerValueWithModel y nm model = do
x <- alloca $ \ptr -> do
term <- fromJust <$> H.lookup (y2_vars y) nm
ir <- c_yices_get_int64_value model term ptr
if ir == 0
then do
v <- peek ptr
return $! v
else error $ "yices2 get int64 value returned: " ++ show ir
return $! toInteger x
getBitVectorValueWithModel :: Yices2 -> Integer -> FreeID -> YModel -> IO Integer
getBitVectorValueWithModel y w nm model = do
bits <- allocaArray (fromInteger w) $ \ptr -> do
term <- fromJust <$> H.lookup (y2_vars y) nm
ir <- c_yices_get_bv_value model term ptr
if ir == 0
then peekArray (fromInteger w) ptr
else error $ "yices2 get bit vector value returned: " ++ show ir
return $! bvInteger bits
Given a bit vector as a list of bits , where a bit is an Int32 with
value 0 or 1 , convert it to the integer value represented .
LSB is first .
bvInteger :: [Int32] -> Integer
bvInteger [] = 0
bvInteger (x:xs) = bvInteger xs * 2 + (fromIntegral x)
| null | https://raw.githubusercontent.com/ruhler/smten/16dd37fb0ee3809408803d4be20401211b6c4027/smten-lib/Smten/Runtime/Yices2/AST.hs | haskell | # LANGUAGE TypeSynonymInstances #
-1 means we don't care, so just return the equivalent
of False. |
# LANGUAGE MultiParamTypeClasses #
module Smten.Runtime.Yices2.AST (Yices2(..), YTerm) where
import Foreign
import Foreign.C.String
import Data.Char
import Data.Functor
import Data.Maybe
import qualified Data.HashTable.IO as H
import Numeric
import Smten.Runtime.Bit
import Smten.Runtime.Yices2.FFI
import Smten.Runtime.Formula.Type
import Smten.Runtime.FreeID
import Smten.Runtime.Model
import Smten.Runtime.SolverAST
type VarMap = H.BasicHashTable FreeID YTerm
data Yices2 = Yices2 {
y2_ctx :: Ptr YContext,
y2_vars :: VarMap
}
instance SolverAST Yices2 YTerm YTerm YTerm where
declare_bool y nm = do
ty <- c_yices_bool_type
term <- c_yices_new_uninterpreted_term ty
H.insert (y2_vars y) nm term
declare_integer y nm = do
ty <- c_yices_int_type
term <- c_yices_new_uninterpreted_term ty
H.insert (y2_vars y) nm term
declare_bit y w nm = do
ty <- c_yices_bv_type (fromInteger w)
term <- c_yices_new_uninterpreted_term ty
H.insert (y2_vars y) nm term
getBoolValue y nm = do
model <- c_yices_get_model (y2_ctx y) 1
r <- getBoolValueWithModel y nm model
c_yices_free_model model
return r
getIntegerValue y nm = do
model <- c_yices_get_model (y2_ctx y) 1
r <- getIntegerValueWithModel y nm model
c_yices_free_model model
return r
getBitVectorValue y w nm = do
model <- c_yices_get_model (y2_ctx y) 1
r <- getBitVectorValueWithModel y w nm model
c_yices_free_model model
return r
getModel y vars = do
model <- c_yices_get_model (y2_ctx y) 1
let getv (nm, BoolT) = BoolA <$> getBoolValueWithModel y nm model
getv (nm, IntegerT) = IntegerA <$> getIntegerValueWithModel y nm model
getv (nm, BitT w) = do
b <- getBitVectorValueWithModel y w nm model
return (BitA $ bv_make w b)
r <- mapM getv vars
c_yices_free_model model
return r
check y = do
st <- c_yices_check_context (y2_ctx y) nullPtr
return $! fromYSMTStatus st
cleanup y = do
c_yices_free_context (y2_ctx y)
c_yices_exit
assert y e = c_yices_assert_formula (y2_ctx y) e
bool _ p = if p then c_yices_true else c_yices_false
integer _ i = c_yices_int64 (fromInteger i)
bit _ w v = do
let w' = fromInteger w
v' = fromInteger v
base2 = showIntAtBase 2 (\x -> chr (x + ord '0')) v ""
binstr = replicate (fromInteger w - length base2) '0' ++ base2
if w <= 64
then c_yices_bvconst_uint64 w' v'
else withCString binstr $ \str -> c_yices_parse_bvbin str
var_bool y nm = fromJust <$> H.lookup (y2_vars y) nm
var_integer y nm = fromJust <$> H.lookup (y2_vars y) nm
var_bit y w nm = fromJust <$> H.lookup (y2_vars y) nm
and_bool _ = c_yices_and2
or_bool _ = c_yices_or2
not_bool _ = c_yices_not
ite_bool _ = c_yices_ite
ite_integer _ = c_yices_ite
ite_bit _ = c_yices_ite
eq_integer _ = c_yices_eq
leq_integer _ = c_yices_arith_leq_atom
add_integer _ = c_yices_add
sub_integer _ = c_yices_sub
eq_bit _ = c_yices_eq
leq_bit _ = c_yices_bvle_atom
add_bit _ = c_yices_bvadd
sub_bit _ = c_yices_bvsub
mul_bit _ = c_yices_bvmul
sdiv_bit _ = c_yices_bvsdiv
smod_bit _ = c_yices_bvsmod
srem_bit _ = c_yices_bvsrem
udiv_bit _ = c_yices_bvdiv
urem_bit _ = c_yices_bvrem
or_bit _ = c_yices_bvor
and_bit _ = c_yices_bvand
concat_bit _ = c_yices_bvconcat
shl_bit _ _ = c_yices_bvshl
lshr_bit _ _ = c_yices_bvlshr
not_bit _ = c_yices_bvnot
sign_extend_bit _ fr to a = c_yices_sign_extend a (fromInteger $ to - fr)
extract_bit _ hi lo x = c_yices_bvextract x (fromInteger lo) (fromInteger hi)
getBoolValueWithModel :: Yices2 -> FreeID -> YModel -> IO Bool
getBoolValueWithModel y nm model = do
x <- alloca $ \ptr -> do
term <- fromJust <$> H.lookup (y2_vars y) nm
ir <- c_yices_get_bool_value model term ptr
case ir of
_ | ir == (-1) -> do
return 0
0 -> do
v <- peek ptr
return v
_ -> error $ "yices2 get bool value returned: " ++ show ir
case x of
0 -> return False
1 -> return True
_ -> error $ "yices2 get bool value got: " ++ show x
getIntegerValueWithModel :: Yices2 -> FreeID -> YModel -> IO Integer
getIntegerValueWithModel y nm model = do
x <- alloca $ \ptr -> do
term <- fromJust <$> H.lookup (y2_vars y) nm
ir <- c_yices_get_int64_value model term ptr
if ir == 0
then do
v <- peek ptr
return $! v
else error $ "yices2 get int64 value returned: " ++ show ir
return $! toInteger x
getBitVectorValueWithModel :: Yices2 -> Integer -> FreeID -> YModel -> IO Integer
getBitVectorValueWithModel y w nm model = do
bits <- allocaArray (fromInteger w) $ \ptr -> do
term <- fromJust <$> H.lookup (y2_vars y) nm
ir <- c_yices_get_bv_value model term ptr
if ir == 0
then peekArray (fromInteger w) ptr
else error $ "yices2 get bit vector value returned: " ++ show ir
return $! bvInteger bits
Given a bit vector as a list of bits , where a bit is an Int32 with
value 0 or 1 , convert it to the integer value represented .
LSB is first .
bvInteger :: [Int32] -> Integer
bvInteger [] = 0
bvInteger (x:xs) = bvInteger xs * 2 + (fromIntegral x)
|
9df59ef64e40589668326a54026f09ab3b5b42b0eb99da756426638ba9f7058d | tmattio/spin | {{ project_snake }}.mli | (** {{ project_description }} *)
val greet : string -> string
* Returns a greeting message .
{ 4 Examples }
{ [ print_endline @@ greet " " ] }
{4 Examples}
{[ print_endline @@ greet "Jane" ]} *)
| null | https://raw.githubusercontent.com/tmattio/spin/e9955109659d5246a492b6b1312a4c3eb001e86b/template/bin/template/lib/%7B%7B%20project_snake%20%7D%7D.mli | ocaml | * {{ project_description }} |
val greet : string -> string
* Returns a greeting message .
{ 4 Examples }
{ [ print_endline @@ greet " " ] }
{4 Examples}
{[ print_endline @@ greet "Jane" ]} *)
|
91f670448901c746154fd8213662d64b869e9ad9bff8f6f903ccd1f64b695b21 | bhaskara/programmable-reinforcement-learning | crlm.lisp | ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; concurrent-alisp/crlm.lisp
;; Contains the main code that defines what it means to execute an calisp program
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(in-package calisp)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; definitions
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defclass <crlm> ()
(
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; the main components
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(env
:type env-user:<env>
:reader env
:initarg :env)
(partial-program
:type <calisp-program>
:reader part-prog
:initarg :part-prog)
(observers
:reader observers
:writer set-observers
:initarg :observers)
(debugging-observers
:reader debugging-observers
:writer set-debugging-observers
:initarg :debugging-observers
:initform nil)
(policy
:type policy:[policy]
:reader policy
:initarg :policy)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; parameters of current run
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(num-steps
:type fixnum
:reader num-steps
:initarg :num-steps
:initform nil)
(num-episodes
:type fixnum
:reader num-episodes
:initarg :num-episodes
:initform nil)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; local state while executing
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(elapsed-steps
:type fixnum
:accessor crlm-elapsed-steps)
(elapsed-episodes
:type fixnum
:accessor crlm-elapsed-episodes)
(joint-state
:reader joint-state
:writer set-joint-state
:initform (make-joint-state))
(part-prog-terminated?
:type boolean
:documentation "True iff the partial program has terminated without the environment terminating."
:accessor crlm-part-prog-terminated?)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; thread-related bookkeeping
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(num-running-threads
:type fixnum
:reader num-running-threads
:accessor crlm-num-running-threads)
(process-thread-ids
:documentation "maps lisp processes of each thread in the partial program to an ID"
:type hash-table
:initform (make-hash-table :test #'eq)
:reader process-thread-ids)
(thread-states
:documentation "maps thread ids to thread-state"
:type hash-table
:initform (make-hash-table :test #'equal)
:reader thread-states)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; actions and effectors
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(actions
:documentation "table that holds the joint action as it is built up. maps effector to individual action"
:type hash-table
:initform (make-hash-table :test #'eq)
:reader actions)
(effector-thread-ids
:documentation "table mapping effector to id of thread currently holding it."
:type hash-table
:initform (make-hash-table :test #'eq)
:reader effector-thread-ids)
(reassign-list
:documentation "list of effector-thread pairs that represent reassignments that must happen at the beginning of the next env step."
:type list :accessor reassign-list)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; choices
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(thread-choice-results
:documentation "table holding the joint choice made for a subset of the choice threads"
:type hash-table
:initform (make-hash-table :test #'equal)
:reader thread-choice-results)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; locks and condition variables
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(lock
:type process-lock
:initform (make-process-lock :name "CRLM Lock")
:reader lock)
(action-condition
:type <condition-variable>
:reader action-condition
:writer set-action-condition)
(choice-condition
:type <condition-variable>
:reader choice-condition
:writer set-choice-condition)
(wait-condition
:type <condition-variable>
:reader wait-condition
:writer set-wait-condition)
(step-condition
:type <condition-variable>
:reader step-condition
:writer set-step-condition)
(effector-condition
:type <condition-variable>
:reader effector-condition
:writer set-effector-condition)
)
(:documentation "Class that basically serves as a place to put all the relevant local state while running a concurrent ALisp program. Required initargs are
:env - <env>
:part-prog - <part-prog>
:policy - <calisp-policy>
:observers - either of type <calisp-observer> or a list of <calisp-observer>s" ))
(defmethod initialize-instance :after ((c <crlm>) &rest args)
(declare (ignore args))
(let ((observers (observers c)))
(if (listp observers)
(dolist (obs observers)
(check-type obs rl:<rl-observer>))
(progn
(check-type observers rl:<rl-observer>)
(set-observers (list observers) c))))
(let ((deb-observers (debugging-observers c)))
(unless (listp deb-observers)
(check-type deb-observers <calisp-debugging-observer>)
(set-debugging-observers (list deb-observers) c)))
(let ((lock (lock c)))
(set-action-condition (make-instance '<condition-variable> :lock lock :name "action-cv" ) c)
(set-choice-condition (make-instance '<condition-variable> :lock lock :name "choice-cv" ) c)
(set-wait-condition (make-instance '<condition-variable> :lock lock :name "wait-cv") c)
(set-effector-condition (make-instance '<condition-variable> :lock lock :name "effector-cv") c)
(set-step-condition (make-instance '<condition-variable> :lock lock :name "step-cv" ) c)
))
(define-condition crlm-last-step-reached ()
())
(define-condition env-terminated ()
())
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; macros
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defmacro notify-debugging-observers (crlm msg &rest args)
"notify-debugging-observers CRLM MSG &rest ARGS. Notify debugging observers of MSG. The joint state is also cloned and inserted before the ARGS."
(with-gensyms (observers obs cloned-state)
`(let ((,observers (debugging-observers ,crlm)))
(when ,observers
(let ((,cloned-state (clone (joint-state ,crlm))))
(dolist (,obs ,observers)
(,msg ,obs ,cloned-state ,@args)))))))
(defmacro notify-all-observers (crlm msg &rest args)
"notify-all-observers CRLM MSG &rest ARGS. Notify all observers (including debugging observers) of MSG with ARGS."
(with-gensyms (obs)
`(progn
(dolist (,obs (observers ,crlm))
(,msg ,obs ,@args))
(dolist (,obs (debugging-observers ,crlm))
(,msg ,obs ,@args)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; code that executes in the control thread
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; run and helpers
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defun run (c &aux (lock (lock c)))
"run CRLM. Repeatedly run the partial program in the environment."
;; during this run, dynamically bind the *crlm* special variable to crlm
for debugging purposes , for now just setf * crlm *
(setf *crlm* c
(crlm-elapsed-steps c) 0
(crlm-elapsed-episodes c) 0)
(notify-all-observers c inform-start-execution)
(with-process-lock (lock)
(handler-case
loop . One iteration per episode . Exited when a
;; crlm-last-step-reached condition is signalled.
(loop
(unwind-protect
;; protected form : start up episode, then loop, doing a crlm step each time.
;; Will exit when either an env-terminated error is signalled
;; (which is handled below), or the last step is reached
(progn
;; reset env, start part prog, set up bookkeeping vars
(start-episode c)
;; run episode
(handler-case
loop with one iteration per step . Exited
;; when env terminates, or crlm-last-step-reached signalled.
(loop
;; wait for step
(until (no-running-threads c)
(notify-debugging-observers c inform-main-thread-wait)
(wait (step-condition c)))
(notify-debugging-observers c inform-main-thread-wakeup)
;; take next step
(if (at-env-action c)
(joint-action c)
(joint-choice c)))
;; If we stopped because of env termination, check if this was the
;; last episode.
(env-terminated ()
(let ((elapsed-episodes (incf (crlm-elapsed-episodes c))))
(when (aand (num-episodes c) (>= elapsed-episodes it))
(error 'crlm-last-step-reached))))
;; Otherwise, we must have stopped because of reaching the last step
;; of the main loop. Set a flag, and pass on the condition.
(crlm-last-step-reached (c2)
(setf (crlm-part-prog-terminated? c) t)
(error c2))))
;; cleanup form : regardless of why we stopped, kill all threads.
;; This will cause each thread to unwind, and then stop.
(kill-all-threads c)))
;; when last step is reached, notify observers, then exit
(crlm-last-step-reached ()
(notify-all-observers c inform-finish-execution)))))
(defun start-episode (c &aux (root-thread-id (root-thread-id (part-prog c))))
"reset env state, create root thread, set up bookkeeping vars"
;; reset env
(env-user:reset (env c))
;; reset condition vars
(dolist (cv (list (action-condition c)
(choice-condition c)
(step-condition c)
(effector-condition c)
(wait-condition c)))
(remove-waiting-processes cv))
(let ((proc (make-process :name (format nil "~a" root-thread-id))) ;; root thread
(effectors (current-effectors c))
(actions (actions c))
(eff-t-ids (effector-thread-ids c)))
;; set up bookkeeping vars
(setf (crlm-num-running-threads c) 1
(crlm-part-prog-terminated? c) nil
(gethash proc (clrhash (process-thread-ids c))) root-thread-id
(gethash root-thread-id (clrhash (thread-states c)))
(make-thread-state :status 'running :effectors effectors)
(gethash root-thread-id (clrhash (thread-choice-results c)))
'choice-unassigned)
(let ((ts (gethash root-thread-id (thread-states c))))
(push (make-frame 'start) (ts-stack ts)))
(clrhash actions)
(clrhash eff-t-ids)
(setf (reassign-list c) nil)
(do-elements (eff effectors)
(setf (gethash eff actions) 'action-unassigned
(gethash eff eff-t-ids) root-thread-id))
(let ((s (env-user:get-state (env c))))
(set-joint-state
(make-joint-state :env-state (env-user:get-state (env c))
:global (make-frame 'global)
:thread-states (thread-states c))
c)
(notify-all-observers c inform-start-episode s))
;; start root thread
(initialize-thread c proc #'start (list (part-prog c)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; joint-action and helpers
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defun joint-action (c &aux (env (env c)))
(assert (am-holding-lock c) nil
"joint-action called while not holding lock.")
(let* ((actions (actions c))
(act (mapset 'list (lambda (eff) (cons eff (gethash eff actions))) (current-effectors c)))
(s (env-user:get-state env))
(old-effs (current-effectors c)))
;; check that env hasn't terminated
(assert (not (env-user:at-terminal-state env)) nil
"Tried to do action ~a but environment is at a terminal state ~a"
act s)
;; perform the action in the environment
(multiple-value-bind (r next-s term)
(env-user:do-action env act)
;; update the env state
(set-env-state next-s c)
;; inform all observers
(notify-all-observers c inform-env-step act r next-s term)
;; keep track of effectors that have been added or deleted
;; in the new state
(handle-effector-changes c old-effs (current-effectors c))
(handle-pending-reassigns c)
;; initialize action table to all unassigned
(let ((actions (actions c)))
(maphash
(lambda (k v)
(declare (ignore v))
(setf (gethash k actions) 'action-unassigned))
actions))
;; thread bookkeeping
(loop
for ts being each hash-value in (thread-states c)
when (eq (ts-status ts) 'waiting-to-act)
do (make-thread-state-internal ts))
;; Increment number of steps
(let ((steps (incf (crlm-elapsed-steps c))))
;; Has the env terminated?
(when (env-user:at-terminal-state env)
(error 'env-terminated))
;; Have we reached last step?
(when (aand (num-steps c) (>= steps it))
(error 'crlm-last-step-reached)))
;; If not, wake up threads waiting for an environment step
(wake-up-cpp-threads c (action-condition c))
;; return nothing
(values))))
(defun handle-pending-reassigns (c )
(assert (am-holding-lock c) nil
"handle-pending-reassigns called while not holding lock.")
(let ((eff-t-ids (effector-thread-ids c)))
(dolist (entry (reassign-list c))
(destructuring-bind (id . eff) entry
(let ((src-id (check-not-null (gethash eff eff-t-ids)
"Eff-t-id entry for ~a" eff))
(dest-state (check-not-null (gethash id (thread-states c))
"Thread state for ~a" id)))
(setf (gethash eff eff-t-ids) id)
(let* ((src-state (check-not-null (gethash src-id (thread-states c))
"Thread state for id ~a" src-id))
(src-effectors (ts-effectors src-state)))
(assert (member eff src-effectors :test #'equal) ()
"Unexpectedly, effector ~a did not belong to effector list ~a of thread ~a before reassign."
eff src-effectors src-id)
(setf (ts-effectors src-state) (delete eff src-effectors :test #'equal))
(push eff (ts-effectors dest-state)))))))
(setf (reassign-list c) nil))
(defun handle-effector-changes (c old-effs new-effs)
"handle-effector-changes CRLM OLD-EFFS NEW-EFFS. Do the necessary bookkeeping to figure what effectors are new/removed, and call the partial program's assign-new-effectors method to figure out which thread gets the new effectors."
(multiple-value-bind (added deleted)
(symmetric-difference new-effs old-effs)
(let ((eff-t-ids (effector-thread-ids c))
(actions (actions c))
(thread-states (thread-states c)))
(do-elements (e deleted)
(let* ((ts (gethash (gethash e eff-t-ids) thread-states))
(effs (ts-effectors ts)))
(assert (member e effs) ()
"Unexpectedly, effector ~a was not in effector list ~a of thread ~a"
e effs (gethash e eff-t-ids))
(setf (ts-effectors ts) (delete e effs))
)
(remhash e eff-t-ids)
(remhash e actions))
(let ((ids (assign-effectors (part-prog c) (joint-state c) added))
(t-states (thread-states c)))
(mapc (lambda (eff id)
(multiple-value-bind (t-state exists?)
(gethash id t-states)
(assert exists? ()
"Attempted to assign new effector ~a to nonexistent thread ~a. Actual set of threads is ~a."
eff id (hash-keys t-states))
(setf (gethash eff actions) 'newly-added
(gethash eff eff-t-ids) id)
(push eff (ts-effectors t-state))))
added ids)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; joint choice and helpers
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defun joint-choice (c)
(assert (am-holding-lock c) nil
"joint-choice called while not holding crlm lock.")
;; figure out which threads are actually choosing
(let* ((omega (joint-state c))
(choosing-thread-ids (setf (js-choosing-thread-ids omega)
(choosing-thread-ids (part-prog c) omega))))
(assert choosing-thread-ids nil "Empty list of labels of choosing threads at ~a" omega)
;; make sure threads exist and want to choose. set their status.
(dolist (id choosing-thread-ids)
(multiple-value-bind (ts present)
(gethash id (thread-states c))
(let ((stat (ts-status ts)))
(assert (and present (eq stat 'holding)) nil
"Invalid thread id ~a with status ~a" id stat))
(setf (ts-status ts) 'choosing)))
;; make fresh copy of joint state to pass to observers
(let ((fresh-omega (clone omega))
(choices (choice-set omega choosing-thread-ids))
(choice-res (thread-choice-results c)))
(setf (js-choices fresh-omega) choices)
;; inform observers that we have arrived at a choice
(notify-all-observers c inform-arrive-choice-state fresh-omega)
;; use policy to make the choice. If the policy declines, stop execution.
;; if the state is unknown to the policy, choose randomly instead.
(let ((choice
(handler-case
(policy:make-choice (policy c) fresh-omega)
(policy:choose-to-abort ()
(error 'crlm-last-step-reached))
(policy:unknown-state ()
(sample-uniformly choices)))))
;; make sure this choice is legal
(assert (set:member? choice choices)
(choice) "Choice ~a is not a member of ~a" choice choices)
;; store the choice that was made. Assumes choice is an
;; association list from thread-id to choice
(mapc #'(lambda (choice-entry)
(setf (gethash (car choice-entry) choice-res)
(cdr choice-entry)))
choice)
;; inform observers
(notify-all-observers c inform-calisp-step fresh-omega choice))
wake up threads
(wake-up-cpp-threads c (choice-condition c))
(wake-up-cpp-threads c (wait-condition c)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
Operations called in threads of the partial program
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; choices
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defmacro call (fn-name args &key (label fn-name))
"Macro call FN-NAME ARGS &key (LABEL FN-NAME)
FN-NAME (not evaluated) is the name of the function to be called.
ARGS (not evaluated) is a lambda list, in which some elements may be of the form (choose-arg CHOICE-LIST) where CHOICE-LIST is evaluated."
(let ((num-unspecified 0) ;; how many vars are unspecified
(num-params (length args))
(choice-lists nil) ;; list of choices for each unspecified param
(unspecified (make-array 0 :adjustable t :fill-pointer 0)) ;; list where nth element is t if nth param unspecified
(unspecified-param-nums (make-array 0 :adjustable t :fill-pointer 0)) ;; list of numbers of unspecified params
(exit-label (intern-compound-symbol label "-EXIT")) ;; label of exit point of this call
(arg-vars ;; avoid multiple evaluation of arguments
(loop repeat (length args) collect (gensym))))
;; preprocessing to figure out at compile-time which parameters are specified
(loop
for a in args
for i below num-params
for unspec = (and (listp a) (eq (first a) 'choose-arg))
do (vector-push-extend unspec unspecified)
when unspec
do (incf num-unspecified)
(push (second a) choice-lists)
(vector-push-extend i unspecified-param-nums))
(with-gensyms (c new-frame choice param-num param-choice lock current-thread-id
choice-list-vals ts var val param-names cloned-state)
;; this is where the expanded code begins
`(let ((,c *crlm*)
(,lock (lock *crlm*))
(,new-frame (make-frame ',fn-name))
,@(when choice-lists
`((,choice-list-vals (list ,@(reverse choice-lists)))))
;; bind vars for args to avoid multiple evaluation
,@(map 'list (lambda (a v u) `(,v ,(if u ''unspecified a))) args arg-vars unspecified)
)
(with-process-lock (,lock)
;; get thread state
(multiple-value-bind (,current-thread-id ,ts)
(lookup-process ,c)
;; update the program counter and state type
(update-program-counter ,ts ',label)
(setf (frame-label (first (ts-stack ,ts))) ',label)
;; add new frame
(setf (ts-next-frame ,ts) ,new-frame)
(let ((,param-names (lookup-calisp-subroutine #',fn-name)))
(mapc (lambda (,var ,val)
(set-frame-var-val ,new-frame ,var ,val nil))
,param-names (list ,@arg-vars))
;; set the choice list and state type
(setf (ts-choices ,ts)
,(cond ((= num-unspecified 1) `(first ,choice-list-vals))
((> num-unspecified 0) choice-list-vals)
(t `'(no-choice)))
(ts-type ,ts) 'call)
;; make choice
(let* ((,choice (choose-using-completion ,c)))
;; fill in unspecified parameters into frame
,(case num-unspecified
(0 `(declare (ignore ,choice)))
(1 `(set-frame-var-val ,new-frame (nth ,(aref unspecified-param-nums 0) ,param-names) ,choice t))
(t `(map nil (lambda (,param-num ,param-choice)
(set-frame-var-val ,new-frame (nth ,param-num ,param-names) ,param-choice t))
,unspecified-param-nums ,choice)))
;; move next frame to top of stack
(move-next-frame-to-stack ,ts)
;; fill in unspecified arguments of function call
,(cond ((= num-unspecified 1)
`(setf ,(nth (aref unspecified-param-nums 0) arg-vars) ,choice))
((> num-unspecified 1)
`(setf
,@(loop
for i across unspecified-param-nums
collect (nth i arg-vars)
collect `(nth ,i ,choice))))))
;; do the function call (and return this as the final return value)
(unwind-protect
(,fn-name ,@arg-vars)
;; cleanup forms
;; pop stack, set pc to exit point of this choice
(pop (ts-stack ,ts))
(update-program-counter ,ts ',exit-label)
(setf (ts-choices ,ts) '(no-choice)
(ts-type ,ts) 'call-exit)
(let ((,cloned-state (clone (joint-state ,c))))
(unless (crlm-part-prog-terminated? ,c)
(notify-all-observers ,c inform-end-choice-block
,current-thread-id ,cloned-state)))
;; update state again and exit the unwind-protect
(make-thread-state-internal ,ts)
)
)))))))
(defmacro choose (label &rest choices)
"macro choose LABEL &rest CHOICES
LABEL (not evaluated) : label for this choice point
CHOICES (not evaluated) : list, where either all choices are of the form (CHOICE-NAME CHOICE-FORMS) where CHOICE-NAME is not the symbol 'call, or all choices are of the form (CALL &rest ARGS) where ARGS would be the arguments to a CALL statement."
(let ((choice-labels (map 'vector
(lambda (x)
(if (eq (first x) 'call)
(caadr x)
(car x)))
choices))
(forms (mapcar (lambda (x) (if (eq (first x) 'call) (second x)
`(progn ,@(rest x)))) choices)))
(with-gensyms (c new-frame choice ts lock cloned-state current-thread-id)
;; expanded code starts here
`(let ((,c *crlm*)
(,lock (lock *crlm*))
(,new-frame (make-frame ',label)))
(with-process-lock (,lock)
;; get thread state
(multiple-value-bind (,current-thread-id ,ts)
(lookup-process ,c)
;; update program counter
(update-program-counter ,ts ',label)
(setf (frame-label (first (ts-stack ,ts))) ',label)
;; add new frame
(setf (ts-next-frame ,ts) ,new-frame)
;; add single entry to frame for choice-var
;; (set-frame-var-val ,new-frame 'choice 'unspecified nil)
;; set choice set, type
(setf (ts-choices ,ts) ',choice-labels
(ts-type ,ts) 'choose)
;; make choice and binding
(let ((,choice (choose-using-completion ,c)))
;; fill in unspecified parameter into frame
;; (set-frame-var-val ,new-frame 'choice ,choice t)
;; rename frame with label of the choice
(setf (frame-name ,new-frame) ,choice)
;; move next frame to top of stack
(move-next-frame-to-stack ,ts)
(make-thread-state-internal ,ts)
;; evaluate chosen form
(unwind-protect
(case ,choice
,@(loop
for f in forms
for ch across choice-labels
collect `(,ch ,f)))
;; cleanup forms
;; pop stack, set pc to exit point of this choice
(pop (ts-stack ,ts))
(update-program-counter ,ts ',(intern-compound-symbol label "-EXIT"))
(setf (ts-choices ,ts) '(no-choice)
(ts-type ,ts) 'choose-exit)
(let ((,cloned-state (clone (joint-state ,c))))
(unless (crlm-part-prog-terminated? ,c)
(notify-all-observers ,c inform-end-choice-block
,current-thread-id ,cloned-state)))
;; update state again and exit unwind-protect
(make-thread-state-internal ,ts)
)
)))))))
(defmacro dummy-choice (label)
"macro dummy-choice LABEL. Set up a dummy choice point with label LABEL with the single choice labelled 'no-choice that expands to nil."
`(choose ,label ((no-choice (nil)))))
(defmacro with-choice (label (var choices) &body body)
"with-choice LABEL (VAR CHOICES) &body BODY
LABEL (not evaluated) - label of this choice
VAR (not evaluated) - symbol that names the choice variable
CHOICES (evaluated) - set of choices
BODY (not evaluated) - set of forms enclosed by implicit progn
Bind VAR to a value chosen from CHOICES by the completion, then execute BODY."
(with-gensyms (c new-frame ts lock current-thread-id cloned-state actual-choices)
;; expanded code starts here
`(let ((,c *crlm*)
(,lock (lock *crlm*))
(,new-frame (make-frame ',label))
(,actual-choices ,choices)
)
(with-process-lock (,lock)
;; get current thread state
(multiple-value-bind (,current-thread-id ,ts)
(lookup-process ,c)
;; update the program counter
(update-program-counter ,ts ',label)
(setf (frame-label (first (ts-stack ,ts))) ',label)
;; add new frame
(setf (ts-next-frame ,ts) ,new-frame)
;; add a single entry to this frame for the choice variable
(set-frame-var-val ,new-frame ',var 'unspecified nil)
;; set the choice list and type
(setf (ts-choices ,ts) ,actual-choices
(ts-type ,ts) 'with-choice)
;; make choice and binding
(let ((,var (choose-using-completion ,c)))
;; fill in unspecified parameter into frame
(set-frame-var-val ,new-frame ',var ,var t)
;; move next frame to top of stack
(move-next-frame-to-stack ,ts)
;; do function call (and return this as final return value)
(unwind-protect
(progn ,@body)
;; cleanup forms
;; pop stack, set pc to exit point of this choice
(pop (ts-stack ,ts))
(update-program-counter ,ts ',(intern-compound-symbol label "-EXIT"))
(setf (ts-choices ,ts) '(no-choice)
(ts-type ,ts) 'with-choice-exit)
(let ((,cloned-state (clone (joint-state ,c))))
(unless (crlm-part-prog-terminated? ,c)
(notify-all-observers ,c inform-end-choice-block
,current-thread-id ,cloned-state)))
;; update state again and exit unwind protect
(make-thread-state-internal ,ts)
)
))))))
(defun choose-using-completion (c)
(assert (am-holding-lock c))
(let ((choice-res (thread-choice-results c)))
;; get relevant info about this thread
(multiple-value-bind (current-thread ts)
(lookup-process c)
(let ((pc (ts-pc ts))
(choices (ts-choices ts)))
;; thread bookkeeping
(setf (ts-status ts) 'holding
(gethash current-thread choice-res) 'choice-unassigned)
;; a loop is needed because not all threads will choose at a choice state
(while (eq (gethash current-thread choice-res) 'choice-unassigned)
;; wake up control thread if at step state
(dec-num-running-threads c)
(when (no-running-threads c)
(notify-all (step-condition c)))
;; go to sleep till choice is made
(notify-debugging-observers c inform-wait-choice current-thread pc)
(wait (choice-condition c)))
(notify-debugging-observers c inform-wakeup current-thread)
;; return the choice that was made
(multiple-value-bind (val present)
(gethash current-thread choice-res)
(assert (and present (member? val choices)) (val)
"Thread ~a received invalid choice ~a at choice point ~a"
current-thread val pc)
val)))))
(defun lookup-calisp-subroutine (f)
(let ((l (get-lambda-list f)))
(assert (notany
(lambda (x) (member x '(&optional &key &rest &aux)))
l)
() "Concurrent ALisp subroutines cannot have optional, key, rest, or aux arguments.")
l))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; actions
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defmacro action (&rest args)
"Macro action [LABEL] ACTION.
LABEL (not evaluated) - label for this point in the calisp program. Defaults to nil.
ACTION - any object.
Called by a thread to cause that thread's effectors to perform the given actions. ACTION is either a list of pairs, in which case it is treated as an association list from effectors to their individual actions, or not, in which case it is treated as an individual action that is done by each effector."
(if (= 1 (length args))
`(act-crlm *crlm* ,(first args) nil)
`(act-crlm *crlm* ,(second args) ',(first args))))
(defun act-crlm (c act label &aux (lock (lock c)))
(with-process-lock (lock)
(multiple-value-bind (id ts)
(lookup-process c)
(let* ((effectors (ts-effectors ts))
(actions (if (and (listp act) (every #'consp act)) act
(mapcar (lambda (e) (cons e act)) effectors))))
;; checks
(assert
(and (= (length effectors) (length actions))
(every (lambda (action) (member (first action) effectors))
actions))
nil
"Thread called action with action list ~a but the actual effector list is ~a"
actions effectors)
;; thread bookkeeping
(setf (ts-status ts) 'waiting-to-act)
(update-program-counter ts label)
(setf (frame-label (first (ts-stack ts))) label)
;; set actions for the effectors
(dolist (a actions)
(setf (gethash (car a) (actions c)) (cdr a)))
;; Wake up crlm thread either if all effectors have been assigned, or num-running-threads = 0
The second condition is for joint choices , and the first condition is necessary when
;; not all threads possess effectors
(dec-num-running-threads c)
(when (or (no-running-threads c)
(at-env-action c))
(notify-all (step-condition c)))
(notify-debugging-observers c inform-wait-action id label)
(setf (ts-type ts) 'action)
;; Wait for action to complete, then return
(wait (action-condition c))
(notify-debugging-observers c inform-wakeup id)
;; return nothing
(values)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; thread-related
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defmacro spawn (id func &rest a)
"spawn ID FUNC [LABEL] ARGS EFFECTORS.
ID (evaluated) - ID of new thread.
FUNC (not evaluated) - name of function to call
LABEL (not evaluated) - a symbol that is the label of this location in the program
ARGS (evaluated) - arg list
EFFECTORS (evaluated) - effector list of new thread."
(condlet
(((= (length a) 3)
(label (first a))
(args (second a))
(effectors (third a)))
((= (length a) 2)
(label func)
(args (first a))
(effectors (second a)))
(otherwise (assert nil nil "Incorrect argument list ~a to spawn"
(list* id func a))))
`(spawn-crlm *crlm* ',label ,id #',func ,args ,effectors (make-frame ',func))))
(defun spawn-crlm (c label id func args effectors new-frame &aux (lock (lock *crlm*)))
(with-process-lock (lock)
(multiple-value-bind (current-id current-ts)
(lookup-process c)
(declare (ignore current-id))
(let ((process-name (format nil "~a" id)) ; because process name must be a string
(thread-states (thread-states c)))
;; checks
(assert (not (hash-table-has-key thread-states id)) (id)
"Attempted to spawn a thread with id ~a, which already exists" id)
;; update the program counter and state type
(update-program-counter current-ts label)
(setf (frame-label (first (ts-stack current-ts))) label
(ts-choices current-ts) '(no-choice)
(ts-type current-ts) 'spawn)
;; wait for spawn to happen
(choose-using-completion c)
;; start the new thread
(let ((process (make-process :name process-name))
(t-state (make-thread-state :status 'internal)))
(push new-frame (ts-stack t-state))
(setf (gethash process (process-thread-ids c)) id
(gethash id thread-states) t-state)
(incf (crlm-num-running-threads c))
(multiple-value-bind (current-thread current-thread-state)
(lookup-process c)
(declare (ignore current-thread-state))
(notify-all-observers c inform-spawn-thread id current-thread effectors))
(reassign-crlm c id effectors)
(initialize-thread c process func args)
(values))))))
(defun get-new-thread-id (id)
"get-new-thread-id ID.
ID is a symbol.
Look in the thread table of *crlm*, and return a list of the form (ID N) which does not name an existing thread, where N is an integer."
(list id
(1+
(loop
for k being each hash-key in (thread-states *crlm*)
maximize
(if (and (listp k) (eq (first k) id))
(second k)
-1)))))
(defun reassign-crlm (c id eff
&aux (lock (lock c))
(effectors (if (listp eff) eff (list eff))))
(with-process-lock (lock)
(multiple-value-bind (src-thread src-thread-state)
(lookup-process c)
(let ((my-effectors (ts-effectors src-thread-state)))
(multiple-value-bind (dest-thread-state dest-thread-exists)
(gethash id (thread-states c))
;; checks
(assert dest-thread-exists nil
"Attempted to reassign ~a to unknown thread ~a" effectors id)
(assert (every (lambda (eff) (member eff my-effectors)) effectors) nil
"Not every effector in ~a is part of ~a's effector list ~a"
effectors src-thread my-effectors)
(let ((his-effectors (ts-effectors dest-thread-state)))
Reassign
(dolist (eff effectors)
(setf my-effectors (delete eff my-effectors)
(gethash eff (effector-thread-ids c)) id
his-effectors (insert-sorted-list eff his-effectors)))
(setf (ts-effectors src-thread-state) my-effectors
(ts-effectors dest-thread-state) his-effectors))
;; Notify threads who may be waiting for effectors
(wake-up-cpp-threads c (effector-condition c))
(wake-up-cpp-threads c (wait-condition c))
(notify-all-observers c inform-reassign effectors src-thread id)
(values))))))
(defun die (c &aux (lock (lock c)))
(with-process-lock (lock)
(multiple-value-bind (current-thread current-thread-state)
(lookup-process c)
;; remove this thread info from the tables
(remhash *current-process* (process-thread-ids c))
(remhash current-thread (thread-states c))
(remhash current-thread (thread-choice-results c))
(unless (crlm-part-prog-terminated? c)
(notify-all-observers c inform-die-thread current-thread)
(dec-num-running-threads c)
(unless (env-user:at-terminal-state (env c))
;; checks
(assert (null (ts-effectors current-thread-state))
nil "Thread ~a called die while still holding effectors ~a"
current-thread (ts-effectors current-thread-state))
(assert (> (hash-table-count (thread-states c)) 0) nil
"All threads died before environment terminated.")
if this thread dying causes us to be at a step state , notify crlm thread
(when (no-running-threads c)
(notify-all (step-condition c)))))
(values))))
(defmacro reassign (label &rest args)
"Macro reassign LABEL EFFECTORS DEST-THREAD-ID &key WAIT-ACTION
LABEL (not evaluated) - label of this point in the program
EFFECTORS (evaluated) - list of effectors to reassign
DEST-THREAD-ID (evaluated) - id of destination thread
WAIT-ACTION (evaluated) - when supplied, indicates that, if the destination thread has already committed to a joint action, then the effectors being reassigned will do this action (via a call to ACTION) on this step, and be reassigned at the beginning of the next step. If this argument is not supplied, assert in the above situation."
`(reassign-to-existing-thread *crlm* ',label ,@args))
(defun reassign-to-existing-thread (c label effectors id &key (wait-action nil wait-action-supplied)
&aux (lock (lock c)))
(with-process-lock (lock)
;; get state of dest thread
(multiple-value-bind (t-state exists)
(gethash id (thread-states c))
(assert exists () "Attempted to reassign effectors ~a to nonexistent thread ~a. Actual thread list is ~a."
effectors id (hash-keys (thread-states c)))
(case (ts-status t-state)
;; if dest is already at an action, wait for a step
(waiting-to-act
(assert wait-action-supplied ()
"Attempted to reassign effectors ~a to thread ~a which is already committed to an action, and the reassign call did not specify a default action." effectors id)
(dolist (eff effectors)
(push (cons id eff) (reassign-list c)))
(act-crlm c wait-action label)
)
;; otherwise assign immediately
(otherwise (reassign-crlm c id effectors))))))
(defmacro wait-for-effectors (label)
"wait-for-effectors LABEL
LABEL (not evaluated) is a symbol labelling this program state."
`(wait-effectors-crlm *crlm* ',label))
(defun wait-effectors-crlm (c label)
(let ((lock (lock *crlm*)))
(with-process-lock (lock)
(multiple-value-bind (id ts)
(lookup-process *crlm*)
(setf (ts-status ts) 'waiting-for-effector
(ts-type ts) 'internal
(ts-choices) 'not-choosing)
(update-program-counter ts label)
(until (my-effectors)
(dec-num-running-threads c)
(when (no-running-threads c)
(notify-all (step-condition c)))
(notify-debugging-observers c inform-wait-effectors id)
(wait (effector-condition c)))
(notify-debugging-observers c inform-wakeup id)
(make-thread-state-internal ts)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; accessing the joint state
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defun my-effectors ()
"my-effectors. Return the effector list of the calling thread."
(multiple-value-bind (id ts)
(lookup-process *crlm*)
(declare (ignore id))
(ts-effectors ts)))
(defun env-state ()
"env-state. Return environment state."
(get-env-state *crlm*))
(defun combined-state ()
"combined state. Return combined state. Called within partial programs. Returned value should not be modified in any way."
(joint-state *crlm*))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; miscellaneous helper functions
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; thread-related
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(declaim (inline am-holding-lock wake-up-cpp-threads dec-num-running-threads no-running-threads))
(defun dec-num-running-threads (c)
"Decrement num running threads."
(decf (crlm-num-running-threads c))
(values))
(defun no-running-threads (c)
"Return t iff there are no running threads."
;; Note reliance of spawn on the way this is implemented
(zerop (num-running-threads c)))
(defun wake-up-cpp-threads (c cond-var)
(incf (crlm-num-running-threads c) (num-waiting cond-var))
(notify-all cond-var))
(defun am-holding-lock (c)
"am-holding-lock CRLM. Is the current process holding the crlm lock?"
(eq *current-process* (process-lock-locker (lock c))))
(defun lookup-process (c &optional (p *current-process*))
"lookup-process CRLM &optional (PROCESS *CURRENT-PROCESS*). Return 1) the thread id associated with PROCESS 2) the associated thread-state object"
(multiple-value-bind (thread-id t-id-present)
(gethash p (process-thread-ids c))
(assert t-id-present nil "Process ~a not found in the thread ID table" p)
(multiple-value-bind (ts ts-present)
(gethash thread-id (thread-states c))
(assert ts-present nil "Thread ID ~a not found in the thread-state table" thread-id)
(values thread-id ts))))
(defun initialize-thread (c proc func args)
"initialize-thread CRLM PROCESS FUNC ARGS. Initialize the process object PROCESS, so that once it is enabled it will begin by calling FUNC with arguments ARGS, then call die. Then enable the process."
(process-preset proc #'establish-bindings (list '*standard-output* ) (list *standard-output*)
#'(lambda()
(unwind-protect
(apply func args)
(die c))) nil)
(process-enable proc))
(defun kill-all-threads (c)
"kill-all-threads CRLM. Kill all currently existing cpp threads. The stacks of the threads are unwound correctly."
(let ((killed-list
(loop
for p being each hash-key in (process-thread-ids c) using (hash-value id)
do (process-kill p)
necessary if p was at a wait
collect p)))
;; for the unix threading system - wait and make sure the threads are actually dead
(process-unlock (lock c))
(loop
for p in killed-list
do (process-wait "crlm-kill-whostate" (lambda (x) (not (member x *all-processes*))) p))
(process-lock (lock c))
)
(setf (crlm-num-running-threads c) 0)
(notify-all-observers c inform-part-prog-terminated))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; accessors for state
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(declaim (inline get-env-state set-env-state))
(defun get-env-state (c)
(js-env-state (joint-state c)))
(defun set-env-state (s c)
(setf (js-env-state (joint-state c)) s))
(defun update-program-counter (t-state label)
"update-program-counter T-STATE LABEL. Update the program counter of thread state to be at LABEL. Uses the value of *containing-subroutine-name* as the containing subroutine."
(setf (ts-pc t-state)
(make-pc *containing-subroutine-name* label)))
(defun at-env-action (c)
"at-env-action C. Is every effector assigned an action?"
(loop
for a being each hash-value in (actions c)
never (equal a 'action-unassigned)))
(defun current-effectors (c)
"current-effectors C. return a copy of the effector set of current environment state."
(mapset 'list #'identity (env-user:current-effectors (env c))))
| null | https://raw.githubusercontent.com/bhaskara/programmable-reinforcement-learning/8afc98116a8f78163b3f86076498d84b3f596217/lisp/concurrent-alisp/crlm.lisp | lisp |
concurrent-alisp/crlm.lisp
Contains the main code that defines what it means to execute an calisp program
definitions
the main components
parameters of current run
local state while executing
thread-related bookkeeping
actions and effectors
choices
locks and condition variables
macros
code that executes in the control thread
run and helpers
during this run, dynamically bind the *crlm* special variable to crlm
crlm-last-step-reached condition is signalled.
protected form : start up episode, then loop, doing a crlm step each time.
Will exit when either an env-terminated error is signalled
(which is handled below), or the last step is reached
reset env, start part prog, set up bookkeeping vars
run episode
when env terminates, or crlm-last-step-reached signalled.
wait for step
take next step
If we stopped because of env termination, check if this was the
last episode.
Otherwise, we must have stopped because of reaching the last step
of the main loop. Set a flag, and pass on the condition.
cleanup form : regardless of why we stopped, kill all threads.
This will cause each thread to unwind, and then stop.
when last step is reached, notify observers, then exit
reset env
reset condition vars
root thread
set up bookkeeping vars
start root thread
joint-action and helpers
check that env hasn't terminated
perform the action in the environment
update the env state
inform all observers
keep track of effectors that have been added or deleted
in the new state
initialize action table to all unassigned
thread bookkeeping
Increment number of steps
Has the env terminated?
Have we reached last step?
If not, wake up threads waiting for an environment step
return nothing
joint choice and helpers
figure out which threads are actually choosing
make sure threads exist and want to choose. set their status.
make fresh copy of joint state to pass to observers
inform observers that we have arrived at a choice
use policy to make the choice. If the policy declines, stop execution.
if the state is unknown to the policy, choose randomly instead.
make sure this choice is legal
store the choice that was made. Assumes choice is an
association list from thread-id to choice
inform observers
choices
how many vars are unspecified
list of choices for each unspecified param
list where nth element is t if nth param unspecified
list of numbers of unspecified params
label of exit point of this call
avoid multiple evaluation of arguments
preprocessing to figure out at compile-time which parameters are specified
this is where the expanded code begins
bind vars for args to avoid multiple evaluation
get thread state
update the program counter and state type
add new frame
set the choice list and state type
make choice
fill in unspecified parameters into frame
move next frame to top of stack
fill in unspecified arguments of function call
do the function call (and return this as the final return value)
cleanup forms
pop stack, set pc to exit point of this choice
update state again and exit the unwind-protect
expanded code starts here
get thread state
update program counter
add new frame
add single entry to frame for choice-var
(set-frame-var-val ,new-frame 'choice 'unspecified nil)
set choice set, type
make choice and binding
fill in unspecified parameter into frame
(set-frame-var-val ,new-frame 'choice ,choice t)
rename frame with label of the choice
move next frame to top of stack
evaluate chosen form
cleanup forms
pop stack, set pc to exit point of this choice
update state again and exit unwind-protect
expanded code starts here
get current thread state
update the program counter
add new frame
add a single entry to this frame for the choice variable
set the choice list and type
make choice and binding
fill in unspecified parameter into frame
move next frame to top of stack
do function call (and return this as final return value)
cleanup forms
pop stack, set pc to exit point of this choice
update state again and exit unwind protect
get relevant info about this thread
thread bookkeeping
a loop is needed because not all threads will choose at a choice state
wake up control thread if at step state
go to sleep till choice is made
return the choice that was made
actions
checks
thread bookkeeping
set actions for the effectors
Wake up crlm thread either if all effectors have been assigned, or num-running-threads = 0
not all threads possess effectors
Wait for action to complete, then return
return nothing
thread-related
because process name must be a string
checks
update the program counter and state type
wait for spawn to happen
start the new thread
checks
Notify threads who may be waiting for effectors
remove this thread info from the tables
checks
get state of dest thread
if dest is already at an action, wait for a step
otherwise assign immediately
accessing the joint state
miscellaneous helper functions
thread-related
Note reliance of spawn on the way this is implemented
for the unix threading system - wait and make sure the threads are actually dead
accessors for state
|
(in-package calisp)
(defclass <crlm> ()
(
(env
:type env-user:<env>
:reader env
:initarg :env)
(partial-program
:type <calisp-program>
:reader part-prog
:initarg :part-prog)
(observers
:reader observers
:writer set-observers
:initarg :observers)
(debugging-observers
:reader debugging-observers
:writer set-debugging-observers
:initarg :debugging-observers
:initform nil)
(policy
:type policy:[policy]
:reader policy
:initarg :policy)
(num-steps
:type fixnum
:reader num-steps
:initarg :num-steps
:initform nil)
(num-episodes
:type fixnum
:reader num-episodes
:initarg :num-episodes
:initform nil)
(elapsed-steps
:type fixnum
:accessor crlm-elapsed-steps)
(elapsed-episodes
:type fixnum
:accessor crlm-elapsed-episodes)
(joint-state
:reader joint-state
:writer set-joint-state
:initform (make-joint-state))
(part-prog-terminated?
:type boolean
:documentation "True iff the partial program has terminated without the environment terminating."
:accessor crlm-part-prog-terminated?)
(num-running-threads
:type fixnum
:reader num-running-threads
:accessor crlm-num-running-threads)
(process-thread-ids
:documentation "maps lisp processes of each thread in the partial program to an ID"
:type hash-table
:initform (make-hash-table :test #'eq)
:reader process-thread-ids)
(thread-states
:documentation "maps thread ids to thread-state"
:type hash-table
:initform (make-hash-table :test #'equal)
:reader thread-states)
(actions
:documentation "table that holds the joint action as it is built up. maps effector to individual action"
:type hash-table
:initform (make-hash-table :test #'eq)
:reader actions)
(effector-thread-ids
:documentation "table mapping effector to id of thread currently holding it."
:type hash-table
:initform (make-hash-table :test #'eq)
:reader effector-thread-ids)
(reassign-list
:documentation "list of effector-thread pairs that represent reassignments that must happen at the beginning of the next env step."
:type list :accessor reassign-list)
(thread-choice-results
:documentation "table holding the joint choice made for a subset of the choice threads"
:type hash-table
:initform (make-hash-table :test #'equal)
:reader thread-choice-results)
(lock
:type process-lock
:initform (make-process-lock :name "CRLM Lock")
:reader lock)
(action-condition
:type <condition-variable>
:reader action-condition
:writer set-action-condition)
(choice-condition
:type <condition-variable>
:reader choice-condition
:writer set-choice-condition)
(wait-condition
:type <condition-variable>
:reader wait-condition
:writer set-wait-condition)
(step-condition
:type <condition-variable>
:reader step-condition
:writer set-step-condition)
(effector-condition
:type <condition-variable>
:reader effector-condition
:writer set-effector-condition)
)
(:documentation "Class that basically serves as a place to put all the relevant local state while running a concurrent ALisp program. Required initargs are
:env - <env>
:part-prog - <part-prog>
:policy - <calisp-policy>
:observers - either of type <calisp-observer> or a list of <calisp-observer>s" ))
(defmethod initialize-instance :after ((c <crlm>) &rest args)
(declare (ignore args))
(let ((observers (observers c)))
(if (listp observers)
(dolist (obs observers)
(check-type obs rl:<rl-observer>))
(progn
(check-type observers rl:<rl-observer>)
(set-observers (list observers) c))))
(let ((deb-observers (debugging-observers c)))
(unless (listp deb-observers)
(check-type deb-observers <calisp-debugging-observer>)
(set-debugging-observers (list deb-observers) c)))
(let ((lock (lock c)))
(set-action-condition (make-instance '<condition-variable> :lock lock :name "action-cv" ) c)
(set-choice-condition (make-instance '<condition-variable> :lock lock :name "choice-cv" ) c)
(set-wait-condition (make-instance '<condition-variable> :lock lock :name "wait-cv") c)
(set-effector-condition (make-instance '<condition-variable> :lock lock :name "effector-cv") c)
(set-step-condition (make-instance '<condition-variable> :lock lock :name "step-cv" ) c)
))
(define-condition crlm-last-step-reached ()
())
(define-condition env-terminated ()
())
(defmacro notify-debugging-observers (crlm msg &rest args)
"notify-debugging-observers CRLM MSG &rest ARGS. Notify debugging observers of MSG. The joint state is also cloned and inserted before the ARGS."
(with-gensyms (observers obs cloned-state)
`(let ((,observers (debugging-observers ,crlm)))
(when ,observers
(let ((,cloned-state (clone (joint-state ,crlm))))
(dolist (,obs ,observers)
(,msg ,obs ,cloned-state ,@args)))))))
(defmacro notify-all-observers (crlm msg &rest args)
"notify-all-observers CRLM MSG &rest ARGS. Notify all observers (including debugging observers) of MSG with ARGS."
(with-gensyms (obs)
`(progn
(dolist (,obs (observers ,crlm))
(,msg ,obs ,@args))
(dolist (,obs (debugging-observers ,crlm))
(,msg ,obs ,@args)))))
(defun run (c &aux (lock (lock c)))
"run CRLM. Repeatedly run the partial program in the environment."
for debugging purposes , for now just setf * crlm *
(setf *crlm* c
(crlm-elapsed-steps c) 0
(crlm-elapsed-episodes c) 0)
(notify-all-observers c inform-start-execution)
(with-process-lock (lock)
(handler-case
loop . One iteration per episode . Exited when a
(loop
(unwind-protect
(progn
(start-episode c)
(handler-case
loop with one iteration per step . Exited
(loop
(until (no-running-threads c)
(notify-debugging-observers c inform-main-thread-wait)
(wait (step-condition c)))
(notify-debugging-observers c inform-main-thread-wakeup)
(if (at-env-action c)
(joint-action c)
(joint-choice c)))
(env-terminated ()
(let ((elapsed-episodes (incf (crlm-elapsed-episodes c))))
(when (aand (num-episodes c) (>= elapsed-episodes it))
(error 'crlm-last-step-reached))))
(crlm-last-step-reached (c2)
(setf (crlm-part-prog-terminated? c) t)
(error c2))))
(kill-all-threads c)))
(crlm-last-step-reached ()
(notify-all-observers c inform-finish-execution)))))
(defun start-episode (c &aux (root-thread-id (root-thread-id (part-prog c))))
"reset env state, create root thread, set up bookkeeping vars"
(env-user:reset (env c))
(dolist (cv (list (action-condition c)
(choice-condition c)
(step-condition c)
(effector-condition c)
(wait-condition c)))
(remove-waiting-processes cv))
(effectors (current-effectors c))
(actions (actions c))
(eff-t-ids (effector-thread-ids c)))
(setf (crlm-num-running-threads c) 1
(crlm-part-prog-terminated? c) nil
(gethash proc (clrhash (process-thread-ids c))) root-thread-id
(gethash root-thread-id (clrhash (thread-states c)))
(make-thread-state :status 'running :effectors effectors)
(gethash root-thread-id (clrhash (thread-choice-results c)))
'choice-unassigned)
(let ((ts (gethash root-thread-id (thread-states c))))
(push (make-frame 'start) (ts-stack ts)))
(clrhash actions)
(clrhash eff-t-ids)
(setf (reassign-list c) nil)
(do-elements (eff effectors)
(setf (gethash eff actions) 'action-unassigned
(gethash eff eff-t-ids) root-thread-id))
(let ((s (env-user:get-state (env c))))
(set-joint-state
(make-joint-state :env-state (env-user:get-state (env c))
:global (make-frame 'global)
:thread-states (thread-states c))
c)
(notify-all-observers c inform-start-episode s))
(initialize-thread c proc #'start (list (part-prog c)))))
(defun joint-action (c &aux (env (env c)))
(assert (am-holding-lock c) nil
"joint-action called while not holding lock.")
(let* ((actions (actions c))
(act (mapset 'list (lambda (eff) (cons eff (gethash eff actions))) (current-effectors c)))
(s (env-user:get-state env))
(old-effs (current-effectors c)))
(assert (not (env-user:at-terminal-state env)) nil
"Tried to do action ~a but environment is at a terminal state ~a"
act s)
(multiple-value-bind (r next-s term)
(env-user:do-action env act)
(set-env-state next-s c)
(notify-all-observers c inform-env-step act r next-s term)
(handle-effector-changes c old-effs (current-effectors c))
(handle-pending-reassigns c)
(let ((actions (actions c)))
(maphash
(lambda (k v)
(declare (ignore v))
(setf (gethash k actions) 'action-unassigned))
actions))
(loop
for ts being each hash-value in (thread-states c)
when (eq (ts-status ts) 'waiting-to-act)
do (make-thread-state-internal ts))
(let ((steps (incf (crlm-elapsed-steps c))))
(when (env-user:at-terminal-state env)
(error 'env-terminated))
(when (aand (num-steps c) (>= steps it))
(error 'crlm-last-step-reached)))
(wake-up-cpp-threads c (action-condition c))
(values))))
(defun handle-pending-reassigns (c )
(assert (am-holding-lock c) nil
"handle-pending-reassigns called while not holding lock.")
(let ((eff-t-ids (effector-thread-ids c)))
(dolist (entry (reassign-list c))
(destructuring-bind (id . eff) entry
(let ((src-id (check-not-null (gethash eff eff-t-ids)
"Eff-t-id entry for ~a" eff))
(dest-state (check-not-null (gethash id (thread-states c))
"Thread state for ~a" id)))
(setf (gethash eff eff-t-ids) id)
(let* ((src-state (check-not-null (gethash src-id (thread-states c))
"Thread state for id ~a" src-id))
(src-effectors (ts-effectors src-state)))
(assert (member eff src-effectors :test #'equal) ()
"Unexpectedly, effector ~a did not belong to effector list ~a of thread ~a before reassign."
eff src-effectors src-id)
(setf (ts-effectors src-state) (delete eff src-effectors :test #'equal))
(push eff (ts-effectors dest-state)))))))
(setf (reassign-list c) nil))
(defun handle-effector-changes (c old-effs new-effs)
"handle-effector-changes CRLM OLD-EFFS NEW-EFFS. Do the necessary bookkeeping to figure what effectors are new/removed, and call the partial program's assign-new-effectors method to figure out which thread gets the new effectors."
(multiple-value-bind (added deleted)
(symmetric-difference new-effs old-effs)
(let ((eff-t-ids (effector-thread-ids c))
(actions (actions c))
(thread-states (thread-states c)))
(do-elements (e deleted)
(let* ((ts (gethash (gethash e eff-t-ids) thread-states))
(effs (ts-effectors ts)))
(assert (member e effs) ()
"Unexpectedly, effector ~a was not in effector list ~a of thread ~a"
e effs (gethash e eff-t-ids))
(setf (ts-effectors ts) (delete e effs))
)
(remhash e eff-t-ids)
(remhash e actions))
(let ((ids (assign-effectors (part-prog c) (joint-state c) added))
(t-states (thread-states c)))
(mapc (lambda (eff id)
(multiple-value-bind (t-state exists?)
(gethash id t-states)
(assert exists? ()
"Attempted to assign new effector ~a to nonexistent thread ~a. Actual set of threads is ~a."
eff id (hash-keys t-states))
(setf (gethash eff actions) 'newly-added
(gethash eff eff-t-ids) id)
(push eff (ts-effectors t-state))))
added ids)))))
(defun joint-choice (c)
(assert (am-holding-lock c) nil
"joint-choice called while not holding crlm lock.")
(let* ((omega (joint-state c))
(choosing-thread-ids (setf (js-choosing-thread-ids omega)
(choosing-thread-ids (part-prog c) omega))))
(assert choosing-thread-ids nil "Empty list of labels of choosing threads at ~a" omega)
(dolist (id choosing-thread-ids)
(multiple-value-bind (ts present)
(gethash id (thread-states c))
(let ((stat (ts-status ts)))
(assert (and present (eq stat 'holding)) nil
"Invalid thread id ~a with status ~a" id stat))
(setf (ts-status ts) 'choosing)))
(let ((fresh-omega (clone omega))
(choices (choice-set omega choosing-thread-ids))
(choice-res (thread-choice-results c)))
(setf (js-choices fresh-omega) choices)
(notify-all-observers c inform-arrive-choice-state fresh-omega)
(let ((choice
(handler-case
(policy:make-choice (policy c) fresh-omega)
(policy:choose-to-abort ()
(error 'crlm-last-step-reached))
(policy:unknown-state ()
(sample-uniformly choices)))))
(assert (set:member? choice choices)
(choice) "Choice ~a is not a member of ~a" choice choices)
(mapc #'(lambda (choice-entry)
(setf (gethash (car choice-entry) choice-res)
(cdr choice-entry)))
choice)
(notify-all-observers c inform-calisp-step fresh-omega choice))
wake up threads
(wake-up-cpp-threads c (choice-condition c))
(wake-up-cpp-threads c (wait-condition c)))))
Operations called in threads of the partial program
(defmacro call (fn-name args &key (label fn-name))
"Macro call FN-NAME ARGS &key (LABEL FN-NAME)
FN-NAME (not evaluated) is the name of the function to be called.
ARGS (not evaluated) is a lambda list, in which some elements may be of the form (choose-arg CHOICE-LIST) where CHOICE-LIST is evaluated."
(num-params (length args))
(loop repeat (length args) collect (gensym))))
(loop
for a in args
for i below num-params
for unspec = (and (listp a) (eq (first a) 'choose-arg))
do (vector-push-extend unspec unspecified)
when unspec
do (incf num-unspecified)
(push (second a) choice-lists)
(vector-push-extend i unspecified-param-nums))
(with-gensyms (c new-frame choice param-num param-choice lock current-thread-id
choice-list-vals ts var val param-names cloned-state)
`(let ((,c *crlm*)
(,lock (lock *crlm*))
(,new-frame (make-frame ',fn-name))
,@(when choice-lists
`((,choice-list-vals (list ,@(reverse choice-lists)))))
,@(map 'list (lambda (a v u) `(,v ,(if u ''unspecified a))) args arg-vars unspecified)
)
(with-process-lock (,lock)
(multiple-value-bind (,current-thread-id ,ts)
(lookup-process ,c)
(update-program-counter ,ts ',label)
(setf (frame-label (first (ts-stack ,ts))) ',label)
(setf (ts-next-frame ,ts) ,new-frame)
(let ((,param-names (lookup-calisp-subroutine #',fn-name)))
(mapc (lambda (,var ,val)
(set-frame-var-val ,new-frame ,var ,val nil))
,param-names (list ,@arg-vars))
(setf (ts-choices ,ts)
,(cond ((= num-unspecified 1) `(first ,choice-list-vals))
((> num-unspecified 0) choice-list-vals)
(t `'(no-choice)))
(ts-type ,ts) 'call)
(let* ((,choice (choose-using-completion ,c)))
,(case num-unspecified
(0 `(declare (ignore ,choice)))
(1 `(set-frame-var-val ,new-frame (nth ,(aref unspecified-param-nums 0) ,param-names) ,choice t))
(t `(map nil (lambda (,param-num ,param-choice)
(set-frame-var-val ,new-frame (nth ,param-num ,param-names) ,param-choice t))
,unspecified-param-nums ,choice)))
(move-next-frame-to-stack ,ts)
,(cond ((= num-unspecified 1)
`(setf ,(nth (aref unspecified-param-nums 0) arg-vars) ,choice))
((> num-unspecified 1)
`(setf
,@(loop
for i across unspecified-param-nums
collect (nth i arg-vars)
collect `(nth ,i ,choice))))))
(unwind-protect
(,fn-name ,@arg-vars)
(pop (ts-stack ,ts))
(update-program-counter ,ts ',exit-label)
(setf (ts-choices ,ts) '(no-choice)
(ts-type ,ts) 'call-exit)
(let ((,cloned-state (clone (joint-state ,c))))
(unless (crlm-part-prog-terminated? ,c)
(notify-all-observers ,c inform-end-choice-block
,current-thread-id ,cloned-state)))
(make-thread-state-internal ,ts)
)
)))))))
(defmacro choose (label &rest choices)
"macro choose LABEL &rest CHOICES
LABEL (not evaluated) : label for this choice point
CHOICES (not evaluated) : list, where either all choices are of the form (CHOICE-NAME CHOICE-FORMS) where CHOICE-NAME is not the symbol 'call, or all choices are of the form (CALL &rest ARGS) where ARGS would be the arguments to a CALL statement."
(let ((choice-labels (map 'vector
(lambda (x)
(if (eq (first x) 'call)
(caadr x)
(car x)))
choices))
(forms (mapcar (lambda (x) (if (eq (first x) 'call) (second x)
`(progn ,@(rest x)))) choices)))
(with-gensyms (c new-frame choice ts lock cloned-state current-thread-id)
`(let ((,c *crlm*)
(,lock (lock *crlm*))
(,new-frame (make-frame ',label)))
(with-process-lock (,lock)
(multiple-value-bind (,current-thread-id ,ts)
(lookup-process ,c)
(update-program-counter ,ts ',label)
(setf (frame-label (first (ts-stack ,ts))) ',label)
(setf (ts-next-frame ,ts) ,new-frame)
(setf (ts-choices ,ts) ',choice-labels
(ts-type ,ts) 'choose)
(let ((,choice (choose-using-completion ,c)))
(setf (frame-name ,new-frame) ,choice)
(move-next-frame-to-stack ,ts)
(make-thread-state-internal ,ts)
(unwind-protect
(case ,choice
,@(loop
for f in forms
for ch across choice-labels
collect `(,ch ,f)))
(pop (ts-stack ,ts))
(update-program-counter ,ts ',(intern-compound-symbol label "-EXIT"))
(setf (ts-choices ,ts) '(no-choice)
(ts-type ,ts) 'choose-exit)
(let ((,cloned-state (clone (joint-state ,c))))
(unless (crlm-part-prog-terminated? ,c)
(notify-all-observers ,c inform-end-choice-block
,current-thread-id ,cloned-state)))
(make-thread-state-internal ,ts)
)
)))))))
(defmacro dummy-choice (label)
"macro dummy-choice LABEL. Set up a dummy choice point with label LABEL with the single choice labelled 'no-choice that expands to nil."
`(choose ,label ((no-choice (nil)))))
(defmacro with-choice (label (var choices) &body body)
"with-choice LABEL (VAR CHOICES) &body BODY
LABEL (not evaluated) - label of this choice
VAR (not evaluated) - symbol that names the choice variable
CHOICES (evaluated) - set of choices
BODY (not evaluated) - set of forms enclosed by implicit progn
Bind VAR to a value chosen from CHOICES by the completion, then execute BODY."
(with-gensyms (c new-frame ts lock current-thread-id cloned-state actual-choices)
`(let ((,c *crlm*)
(,lock (lock *crlm*))
(,new-frame (make-frame ',label))
(,actual-choices ,choices)
)
(with-process-lock (,lock)
(multiple-value-bind (,current-thread-id ,ts)
(lookup-process ,c)
(update-program-counter ,ts ',label)
(setf (frame-label (first (ts-stack ,ts))) ',label)
(setf (ts-next-frame ,ts) ,new-frame)
(set-frame-var-val ,new-frame ',var 'unspecified nil)
(setf (ts-choices ,ts) ,actual-choices
(ts-type ,ts) 'with-choice)
(let ((,var (choose-using-completion ,c)))
(set-frame-var-val ,new-frame ',var ,var t)
(move-next-frame-to-stack ,ts)
(unwind-protect
(progn ,@body)
(pop (ts-stack ,ts))
(update-program-counter ,ts ',(intern-compound-symbol label "-EXIT"))
(setf (ts-choices ,ts) '(no-choice)
(ts-type ,ts) 'with-choice-exit)
(let ((,cloned-state (clone (joint-state ,c))))
(unless (crlm-part-prog-terminated? ,c)
(notify-all-observers ,c inform-end-choice-block
,current-thread-id ,cloned-state)))
(make-thread-state-internal ,ts)
)
))))))
(defun choose-using-completion (c)
(assert (am-holding-lock c))
(let ((choice-res (thread-choice-results c)))
(multiple-value-bind (current-thread ts)
(lookup-process c)
(let ((pc (ts-pc ts))
(choices (ts-choices ts)))
(setf (ts-status ts) 'holding
(gethash current-thread choice-res) 'choice-unassigned)
(while (eq (gethash current-thread choice-res) 'choice-unassigned)
(dec-num-running-threads c)
(when (no-running-threads c)
(notify-all (step-condition c)))
(notify-debugging-observers c inform-wait-choice current-thread pc)
(wait (choice-condition c)))
(notify-debugging-observers c inform-wakeup current-thread)
(multiple-value-bind (val present)
(gethash current-thread choice-res)
(assert (and present (member? val choices)) (val)
"Thread ~a received invalid choice ~a at choice point ~a"
current-thread val pc)
val)))))
(defun lookup-calisp-subroutine (f)
(let ((l (get-lambda-list f)))
(assert (notany
(lambda (x) (member x '(&optional &key &rest &aux)))
l)
() "Concurrent ALisp subroutines cannot have optional, key, rest, or aux arguments.")
l))
(defmacro action (&rest args)
"Macro action [LABEL] ACTION.
LABEL (not evaluated) - label for this point in the calisp program. Defaults to nil.
ACTION - any object.
Called by a thread to cause that thread's effectors to perform the given actions. ACTION is either a list of pairs, in which case it is treated as an association list from effectors to their individual actions, or not, in which case it is treated as an individual action that is done by each effector."
(if (= 1 (length args))
`(act-crlm *crlm* ,(first args) nil)
`(act-crlm *crlm* ,(second args) ',(first args))))
(defun act-crlm (c act label &aux (lock (lock c)))
(with-process-lock (lock)
(multiple-value-bind (id ts)
(lookup-process c)
(let* ((effectors (ts-effectors ts))
(actions (if (and (listp act) (every #'consp act)) act
(mapcar (lambda (e) (cons e act)) effectors))))
(assert
(and (= (length effectors) (length actions))
(every (lambda (action) (member (first action) effectors))
actions))
nil
"Thread called action with action list ~a but the actual effector list is ~a"
actions effectors)
(setf (ts-status ts) 'waiting-to-act)
(update-program-counter ts label)
(setf (frame-label (first (ts-stack ts))) label)
(dolist (a actions)
(setf (gethash (car a) (actions c)) (cdr a)))
The second condition is for joint choices , and the first condition is necessary when
(dec-num-running-threads c)
(when (or (no-running-threads c)
(at-env-action c))
(notify-all (step-condition c)))
(notify-debugging-observers c inform-wait-action id label)
(setf (ts-type ts) 'action)
(wait (action-condition c))
(notify-debugging-observers c inform-wakeup id)
(values)))))
(defmacro spawn (id func &rest a)
"spawn ID FUNC [LABEL] ARGS EFFECTORS.
ID (evaluated) - ID of new thread.
FUNC (not evaluated) - name of function to call
LABEL (not evaluated) - a symbol that is the label of this location in the program
ARGS (evaluated) - arg list
EFFECTORS (evaluated) - effector list of new thread."
(condlet
(((= (length a) 3)
(label (first a))
(args (second a))
(effectors (third a)))
((= (length a) 2)
(label func)
(args (first a))
(effectors (second a)))
(otherwise (assert nil nil "Incorrect argument list ~a to spawn"
(list* id func a))))
`(spawn-crlm *crlm* ',label ,id #',func ,args ,effectors (make-frame ',func))))
(defun spawn-crlm (c label id func args effectors new-frame &aux (lock (lock *crlm*)))
(with-process-lock (lock)
(multiple-value-bind (current-id current-ts)
(lookup-process c)
(declare (ignore current-id))
(thread-states (thread-states c)))
(assert (not (hash-table-has-key thread-states id)) (id)
"Attempted to spawn a thread with id ~a, which already exists" id)
(update-program-counter current-ts label)
(setf (frame-label (first (ts-stack current-ts))) label
(ts-choices current-ts) '(no-choice)
(ts-type current-ts) 'spawn)
(choose-using-completion c)
(let ((process (make-process :name process-name))
(t-state (make-thread-state :status 'internal)))
(push new-frame (ts-stack t-state))
(setf (gethash process (process-thread-ids c)) id
(gethash id thread-states) t-state)
(incf (crlm-num-running-threads c))
(multiple-value-bind (current-thread current-thread-state)
(lookup-process c)
(declare (ignore current-thread-state))
(notify-all-observers c inform-spawn-thread id current-thread effectors))
(reassign-crlm c id effectors)
(initialize-thread c process func args)
(values))))))
(defun get-new-thread-id (id)
"get-new-thread-id ID.
ID is a symbol.
Look in the thread table of *crlm*, and return a list of the form (ID N) which does not name an existing thread, where N is an integer."
(list id
(1+
(loop
for k being each hash-key in (thread-states *crlm*)
maximize
(if (and (listp k) (eq (first k) id))
(second k)
-1)))))
(defun reassign-crlm (c id eff
&aux (lock (lock c))
(effectors (if (listp eff) eff (list eff))))
(with-process-lock (lock)
(multiple-value-bind (src-thread src-thread-state)
(lookup-process c)
(let ((my-effectors (ts-effectors src-thread-state)))
(multiple-value-bind (dest-thread-state dest-thread-exists)
(gethash id (thread-states c))
(assert dest-thread-exists nil
"Attempted to reassign ~a to unknown thread ~a" effectors id)
(assert (every (lambda (eff) (member eff my-effectors)) effectors) nil
"Not every effector in ~a is part of ~a's effector list ~a"
effectors src-thread my-effectors)
(let ((his-effectors (ts-effectors dest-thread-state)))
Reassign
(dolist (eff effectors)
(setf my-effectors (delete eff my-effectors)
(gethash eff (effector-thread-ids c)) id
his-effectors (insert-sorted-list eff his-effectors)))
(setf (ts-effectors src-thread-state) my-effectors
(ts-effectors dest-thread-state) his-effectors))
(wake-up-cpp-threads c (effector-condition c))
(wake-up-cpp-threads c (wait-condition c))
(notify-all-observers c inform-reassign effectors src-thread id)
(values))))))
(defun die (c &aux (lock (lock c)))
(with-process-lock (lock)
(multiple-value-bind (current-thread current-thread-state)
(lookup-process c)
(remhash *current-process* (process-thread-ids c))
(remhash current-thread (thread-states c))
(remhash current-thread (thread-choice-results c))
(unless (crlm-part-prog-terminated? c)
(notify-all-observers c inform-die-thread current-thread)
(dec-num-running-threads c)
(unless (env-user:at-terminal-state (env c))
(assert (null (ts-effectors current-thread-state))
nil "Thread ~a called die while still holding effectors ~a"
current-thread (ts-effectors current-thread-state))
(assert (> (hash-table-count (thread-states c)) 0) nil
"All threads died before environment terminated.")
if this thread dying causes us to be at a step state , notify crlm thread
(when (no-running-threads c)
(notify-all (step-condition c)))))
(values))))
(defmacro reassign (label &rest args)
"Macro reassign LABEL EFFECTORS DEST-THREAD-ID &key WAIT-ACTION
LABEL (not evaluated) - label of this point in the program
EFFECTORS (evaluated) - list of effectors to reassign
DEST-THREAD-ID (evaluated) - id of destination thread
WAIT-ACTION (evaluated) - when supplied, indicates that, if the destination thread has already committed to a joint action, then the effectors being reassigned will do this action (via a call to ACTION) on this step, and be reassigned at the beginning of the next step. If this argument is not supplied, assert in the above situation."
`(reassign-to-existing-thread *crlm* ',label ,@args))
(defun reassign-to-existing-thread (c label effectors id &key (wait-action nil wait-action-supplied)
&aux (lock (lock c)))
(with-process-lock (lock)
(multiple-value-bind (t-state exists)
(gethash id (thread-states c))
(assert exists () "Attempted to reassign effectors ~a to nonexistent thread ~a. Actual thread list is ~a."
effectors id (hash-keys (thread-states c)))
(case (ts-status t-state)
(waiting-to-act
(assert wait-action-supplied ()
"Attempted to reassign effectors ~a to thread ~a which is already committed to an action, and the reassign call did not specify a default action." effectors id)
(dolist (eff effectors)
(push (cons id eff) (reassign-list c)))
(act-crlm c wait-action label)
)
(otherwise (reassign-crlm c id effectors))))))
(defmacro wait-for-effectors (label)
"wait-for-effectors LABEL
LABEL (not evaluated) is a symbol labelling this program state."
`(wait-effectors-crlm *crlm* ',label))
(defun wait-effectors-crlm (c label)
(let ((lock (lock *crlm*)))
(with-process-lock (lock)
(multiple-value-bind (id ts)
(lookup-process *crlm*)
(setf (ts-status ts) 'waiting-for-effector
(ts-type ts) 'internal
(ts-choices) 'not-choosing)
(update-program-counter ts label)
(until (my-effectors)
(dec-num-running-threads c)
(when (no-running-threads c)
(notify-all (step-condition c)))
(notify-debugging-observers c inform-wait-effectors id)
(wait (effector-condition c)))
(notify-debugging-observers c inform-wakeup id)
(make-thread-state-internal ts)))))
(defun my-effectors ()
"my-effectors. Return the effector list of the calling thread."
(multiple-value-bind (id ts)
(lookup-process *crlm*)
(declare (ignore id))
(ts-effectors ts)))
(defun env-state ()
"env-state. Return environment state."
(get-env-state *crlm*))
(defun combined-state ()
"combined state. Return combined state. Called within partial programs. Returned value should not be modified in any way."
(joint-state *crlm*))
(declaim (inline am-holding-lock wake-up-cpp-threads dec-num-running-threads no-running-threads))
(defun dec-num-running-threads (c)
"Decrement num running threads."
(decf (crlm-num-running-threads c))
(values))
(defun no-running-threads (c)
"Return t iff there are no running threads."
(zerop (num-running-threads c)))
(defun wake-up-cpp-threads (c cond-var)
(incf (crlm-num-running-threads c) (num-waiting cond-var))
(notify-all cond-var))
(defun am-holding-lock (c)
"am-holding-lock CRLM. Is the current process holding the crlm lock?"
(eq *current-process* (process-lock-locker (lock c))))
(defun lookup-process (c &optional (p *current-process*))
"lookup-process CRLM &optional (PROCESS *CURRENT-PROCESS*). Return 1) the thread id associated with PROCESS 2) the associated thread-state object"
(multiple-value-bind (thread-id t-id-present)
(gethash p (process-thread-ids c))
(assert t-id-present nil "Process ~a not found in the thread ID table" p)
(multiple-value-bind (ts ts-present)
(gethash thread-id (thread-states c))
(assert ts-present nil "Thread ID ~a not found in the thread-state table" thread-id)
(values thread-id ts))))
(defun initialize-thread (c proc func args)
"initialize-thread CRLM PROCESS FUNC ARGS. Initialize the process object PROCESS, so that once it is enabled it will begin by calling FUNC with arguments ARGS, then call die. Then enable the process."
(process-preset proc #'establish-bindings (list '*standard-output* ) (list *standard-output*)
#'(lambda()
(unwind-protect
(apply func args)
(die c))) nil)
(process-enable proc))
(defun kill-all-threads (c)
"kill-all-threads CRLM. Kill all currently existing cpp threads. The stacks of the threads are unwound correctly."
(let ((killed-list
(loop
for p being each hash-key in (process-thread-ids c) using (hash-value id)
do (process-kill p)
necessary if p was at a wait
collect p)))
(process-unlock (lock c))
(loop
for p in killed-list
do (process-wait "crlm-kill-whostate" (lambda (x) (not (member x *all-processes*))) p))
(process-lock (lock c))
)
(setf (crlm-num-running-threads c) 0)
(notify-all-observers c inform-part-prog-terminated))
(declaim (inline get-env-state set-env-state))
(defun get-env-state (c)
(js-env-state (joint-state c)))
(defun set-env-state (s c)
(setf (js-env-state (joint-state c)) s))
(defun update-program-counter (t-state label)
"update-program-counter T-STATE LABEL. Update the program counter of thread state to be at LABEL. Uses the value of *containing-subroutine-name* as the containing subroutine."
(setf (ts-pc t-state)
(make-pc *containing-subroutine-name* label)))
(defun at-env-action (c)
"at-env-action C. Is every effector assigned an action?"
(loop
for a being each hash-value in (actions c)
never (equal a 'action-unassigned)))
(defun current-effectors (c)
"current-effectors C. return a copy of the effector set of current environment state."
(mapset 'list #'identity (env-user:current-effectors (env c))))
|
e1b8b8538738badfecd9e7217480eab4aa18eac00c3fbc6d5a7b786796ada3f0 | mbj/mhs | Bounded.hs | module Data.Bounded (module Exports) where
import Data.Bounded.Integral as Exports
import Data.Bounded.Text as Exports
import Data.Bounded.TypeLevel as Exports
import Data.Conversions as Exports
import Data.Conversions.FromType as Exports
| null | https://raw.githubusercontent.com/mbj/mhs/3c0fe9e28c24ba633ed51ccbeeb154d6f2f82292/bounded/src/Data/Bounded.hs | haskell | module Data.Bounded (module Exports) where
import Data.Bounded.Integral as Exports
import Data.Bounded.Text as Exports
import Data.Bounded.TypeLevel as Exports
import Data.Conversions as Exports
import Data.Conversions.FromType as Exports
| |
9b8f99f8fd9af7d8a9591babf607f743f1db760f823d60ce04448774f9a77747 | robert-strandh/Second-Climacs | buffer.lisp | (cl:in-package #:second-climacs-syntax-common-lisp-test)
(defun buffer-from-string (string)
(let* ((line (make-instance 'cluffer-standard-line:open-line))
(buffer (make-instance 'cluffer-standard-buffer:buffer
:initial-line line)))
(loop with line-number = 0
with item-number = 0
for char across string
for line = (cluffer:find-line buffer line-number)
do (if (eql char #\Newline)
(progn (cluffer:split-line-at-position line item-number)
(setf item-number 0)
(incf line-number))
(progn (cluffer:insert-item-at-position line char item-number)
(incf item-number))))
buffer))
(defun analyzer-from-buffer (buffer)
(let ((cache (make-instance 'cl-syntax::cache)))
(make-instance 'cl-syntax::analyzer
:buffer buffer)))
:folio cache))
(defun forms-from-cache (cache)
(append (reverse (mapcar #'cl-syntax::expression
(cl-syntax::prefix cache)))
(mapcar #'cl-syntax::expression
(cl-syntax::suffix cache))))
;;; Mark a buffer line as modified without really modifying it by
inserting an item in the first position and then immediately
;;; deleting that item again.
(defun mark-buffer-line-as-modified (buffer-line)
(cluffer:insert-item-at-position buffer-line #\Space 0)
(cluffer:delete-item-at-position buffer-line 0))
;;; Given a buffer, return a random line in that buffer.
(defun random-buffer-line (buffer)
(let* ((line-count (cluffer:line-count buffer))
(line-number (random line-count)))
(cluffer:find-line buffer line-number)))
| null | https://raw.githubusercontent.com/robert-strandh/Second-Climacs/1d1bc30f4431d8ea7893aea58a63464e216377a4/Code/Syntax/Common-Lisp/Test/buffer.lisp | lisp | Mark a buffer line as modified without really modifying it by
deleting that item again.
Given a buffer, return a random line in that buffer. | (cl:in-package #:second-climacs-syntax-common-lisp-test)
(defun buffer-from-string (string)
(let* ((line (make-instance 'cluffer-standard-line:open-line))
(buffer (make-instance 'cluffer-standard-buffer:buffer
:initial-line line)))
(loop with line-number = 0
with item-number = 0
for char across string
for line = (cluffer:find-line buffer line-number)
do (if (eql char #\Newline)
(progn (cluffer:split-line-at-position line item-number)
(setf item-number 0)
(incf line-number))
(progn (cluffer:insert-item-at-position line char item-number)
(incf item-number))))
buffer))
(defun analyzer-from-buffer (buffer)
(let ((cache (make-instance 'cl-syntax::cache)))
(make-instance 'cl-syntax::analyzer
:buffer buffer)))
:folio cache))
(defun forms-from-cache (cache)
(append (reverse (mapcar #'cl-syntax::expression
(cl-syntax::prefix cache)))
(mapcar #'cl-syntax::expression
(cl-syntax::suffix cache))))
inserting an item in the first position and then immediately
(defun mark-buffer-line-as-modified (buffer-line)
(cluffer:insert-item-at-position buffer-line #\Space 0)
(cluffer:delete-item-at-position buffer-line 0))
(defun random-buffer-line (buffer)
(let* ((line-count (cluffer:line-count buffer))
(line-number (random line-count)))
(cluffer:find-line buffer line-number)))
|
a5033cc3558d3fcd5b4e2656447f98c08504165c8ace43b4d82dfb1e10eba0a8 | jmbr/cl-buchberger | ring-element.lisp | (in-package :com.superadditive.cl-buchberger)
Copyright ( C ) 2007 < >
;;
;; 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 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 General Public License for more details.
;;
You should have received a copy of the GNU General Public License
;; along with this program. If not, see </>.
(defclass ring-element ()
(base-ring)
(:documentation "Base class for ring elements."))
(define-condition ring-division-by-zero (error)
((operands
:initarg :operands
:reader operands)))
(defgeneric ring-copy (element)
(:documentation "Returns a deep copy of an element"))
(defgeneric ring-zero-p (element)
(:documentation "Returns t if element is zero, nil otherwise"))
(defgeneric ring-equal-p (e1 e2)
(:documentation "Returns t if e1 equals e2, nil otherwise"))
(defgeneric ring-identity-p (element)
(:documentation "Returns t if element is the multiplicative
identity, nil otherwise"))
(defgeneric ring+ (element &rest more-elements))
(defgeneric ring- (element &rest more-elements))
(defgeneric ring* (element &rest more-elements))
(defgeneric ring/ (element &rest more-elements))
(defgeneric ring-mod (element &rest more-elements))
(defgeneric add (e1 e2)
(:documentation "Adds ring elements"))
(defgeneric sub (e1 e2)
(:documentation "Subtracts ring elements"))
(defgeneric mul (e1 e2)
(:documentation "Multiplies ring elements"))
(defgeneric divides-p (e1 e2)
(:documentation "Returns t if e1 divides e2 in the base ring"))
(defgeneric div (e1 e2)
(:documentation "Divides ring elements"))
(defgeneric divmod (element divisors)
(:documentation "Returns quotient(s) and remainder if we are working
in an Euclidean ring."))
(defgeneric element->string (element &key &allow-other-keys)
(:documentation "Returns a human-readable string representation of
an element"))
(defgeneric ring-lcm (e1 e2)
(:documentation "Returns the LCM of e1 and e2"))
| null | https://raw.githubusercontent.com/jmbr/cl-buchberger/4503216b4f2e3372daf4c9cca7b2e978cbc8256b/ring-element.lisp | lisp |
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
GNU General Public License for more details.
along with this program. If not, see </>. | (in-package :com.superadditive.cl-buchberger)
Copyright ( C ) 2007 < >
it under the terms of the GNU General Public License as published by
the Free Software Foundation , either version 3 of the License , or
You should have received a copy of the GNU General Public License
(defclass ring-element ()
(base-ring)
(:documentation "Base class for ring elements."))
(define-condition ring-division-by-zero (error)
((operands
:initarg :operands
:reader operands)))
(defgeneric ring-copy (element)
(:documentation "Returns a deep copy of an element"))
(defgeneric ring-zero-p (element)
(:documentation "Returns t if element is zero, nil otherwise"))
(defgeneric ring-equal-p (e1 e2)
(:documentation "Returns t if e1 equals e2, nil otherwise"))
(defgeneric ring-identity-p (element)
(:documentation "Returns t if element is the multiplicative
identity, nil otherwise"))
(defgeneric ring+ (element &rest more-elements))
(defgeneric ring- (element &rest more-elements))
(defgeneric ring* (element &rest more-elements))
(defgeneric ring/ (element &rest more-elements))
(defgeneric ring-mod (element &rest more-elements))
(defgeneric add (e1 e2)
(:documentation "Adds ring elements"))
(defgeneric sub (e1 e2)
(:documentation "Subtracts ring elements"))
(defgeneric mul (e1 e2)
(:documentation "Multiplies ring elements"))
(defgeneric divides-p (e1 e2)
(:documentation "Returns t if e1 divides e2 in the base ring"))
(defgeneric div (e1 e2)
(:documentation "Divides ring elements"))
(defgeneric divmod (element divisors)
(:documentation "Returns quotient(s) and remainder if we are working
in an Euclidean ring."))
(defgeneric element->string (element &key &allow-other-keys)
(:documentation "Returns a human-readable string representation of
an element"))
(defgeneric ring-lcm (e1 e2)
(:documentation "Returns the LCM of e1 and e2"))
|
eff4dd9aa137387579a4a094021c42c87dae3ee89d7920153212cc1b66b29e57 | chetmurthy/ensemble | util.mli | (**************************************************************)
(* UTIL.MLI *)
Author : , 4/95
(**************************************************************)
open Trans
(**************************************************************)
type ('a,'b,'c) fun2arg = 'a -> 'b -> 'c
type ('a,'b,'c,'d) fun3arg = 'a -> 'b -> 'c -> 'd
external : ( ' a,'b,'c ) fun2arg - > ( ' a,'b,'c ) fun2arg = " % arity2 "
external arity3 : ( ' a,'b,'c,'d ) fun3arg - > ( ' a,'b,'c,'d ) fun3arg = " % arity3 "
external arity2 : ('a,'b,'c) fun2arg -> ('a,'b,'c) fun2arg = "%arity2"
external arity3 : ('a,'b,'c,'d) fun3arg -> ('a,'b,'c,'d) fun3arg = "%arity3"
*)
val arity2 : ('a,'b,'c) fun2arg -> ('a,'b,'c) fun2arg
val arity3 : ('a,'b,'c,'d) fun3arg -> ('a,'b,'c,'d) fun3arg
(**************************************************************)
external (=|) : int -> int -> bool = "%eq"
external (<>|) : int -> int -> bool = "%noteq"
external (>=|) : int -> int -> bool = "%geint"
external (<=|) : int -> int -> bool = "%leint"
external (>|) : int -> int -> bool = "%gtint"
external (<|) : int -> int -> bool = "%ltint"
val int_max : int -> int -> int
val int_min : int -> int -> int
(**************************************************************)
(* Really basic things.
*)
The first application creates a counter . Each time the
* second unit is applied the next integer ( starting from 0 )
* is returned .
* second unit is applied the next integer (starting from 0)
* is returned.
*)
val counter : unit -> unit -> int
(* The identity function.
*)
val ident : 'a -> 'a
(* This is used to discard non-unit return values from
* functions so that the compiler does not generate a
* warning.
*)
val unit : ' a - > unit
val : ' a - > ' b - > unit
val unit : 'a -> unit
val unit2 : 'a -> 'b -> unit
*)
val ignore2 : 'a -> 'b -> unit
val info : string -> string -> string
(* The string sanity.
*)
val sanity : string
val sanityn : int -> string
(**************************************************************)
(* Debugging stuff.
*)
val verbose : bool ref
val quiet : bool ref
val addinfo : string -> string -> string
val failmsg : string -> string -> string
(**************************************************************)
(* Export printf and sprintf.
*)
val printf : ('a, unit, unit) format -> 'a
val eprintf : ('a, unit, unit) format -> 'a
val sprintf : ('a, unit, string) format -> 'a
(**************************************************************)
val fprintf_override : (out_channel -> string -> unit) -> unit
(**************************************************************)
(* Some list/array operations.
*)
val sequence : int -> int array
val index : 'a -> 'a list -> int
val except : 'a -> 'a list -> 'a list
val array_is_empty : 'a array -> bool
val array_filter : ('a -> bool) -> 'a array -> 'a array
val array_index : 'a -> 'a array -> int
val array_mem : 'a -> 'a array -> bool
val array_filter_nones : 'a option array -> 'a array
val array_exists : (int -> 'a -> bool) -> 'a array -> bool
val array_incr : int array -> int -> unit
val array_decr : int array -> int -> unit
val array_add : int array -> int -> int -> unit
val array_sub : int array -> int -> int -> unit
val array_for_all : ('a -> bool) -> 'a array -> bool
val array_flatten : 'a array array -> 'a array
val matrix_incr : int array array -> int -> int -> unit
val do_once : (unit -> 'a) -> (unit -> 'a)
val hashtbl_size : ('a,'b) Hashtbl.t -> int
val hashtbl_to_list : ('a,'b) Hashtbl.t -> ('a * 'b) list
val string_check : debug -> string -> int(*ofs*) -> int(*len*) -> unit
val deepcopy : 'a -> 'a
(**************************************************************)
(* Some string conversion functions.
*)
val string_of_unit : unit -> string
val string_map : (char -> char) -> string -> string
val string_of_pair :
('a -> string) -> ('b -> string) -> ('a * 'b -> string)
val string_of_list : ('a -> string) -> 'a list -> string
val string_of_array : ('a -> string) -> 'a array -> string
val string_of_int_list : int list -> string
val string_of_int_array : int array -> string
val bool_of_string : string -> bool
val string_of_bool : bool -> string
val string_of_bool_list : bool list -> string
val string_of_bool_array : bool array -> string
val string_split : string -> string -> string list
val hex_to_string : string -> string
val hex_of_string : string -> string
val string_uppercase : string -> string
val strchr : char -> string -> int
(**************************************************************)
(* Some additional option operations.
*)
(* Calls the function if the option is a Some()
*)
val if_some : 'a option -> ('a -> unit) -> unit
(* Call the function if the option is None.
*)
val if_none : 'a option -> (unit -> 'a option) -> 'a option
(* Extract the contents of an option. Fails on None.
*)
val some_of : debug -> 'a option -> 'a
(* Returns true if the option is None.
*)
val is_none : 'a option -> bool
(* String representation of an option.
*)
val string_of_option : ('a -> string) -> 'a option -> string
val option_map : ('a -> 'b) -> 'a option -> 'b option
val filter_nones : 'a option list -> 'a list
val once : debug -> 'a option list -> 'a
(**************************************************************)
val make_magic : unit -> (('a -> Obj.t ) * (Obj.t -> 'a))
(**************************************************************)
val disable_sigpipe : unit -> unit
(**************************************************************)
val average : int - > unit
val gc_profile : string - > ( ' a - > ' b ) - > ' a - > ' b
: string - > ( ' a - > ' b - > ' c - > 'd ) - > ' a - > ' b - > ' c - > 'd
val average : int -> unit
val gc_profile : string -> ('a -> 'b) -> 'a -> 'b
val gc_profile3 : string -> ('a -> 'b -> 'c -> 'd) -> 'a -> 'b -> 'c -> 'd
*)
(**************************************************************)
val strtok : string -> string -> string * string
(**************************************************************)
val string_of_id : debug -> (string * 'a) array -> 'a -> string
val id_of_string : debug -> (string * 'a) array -> string -> 'a
(**************************************************************)
val string_list_of_gc_stat : Gc.stat -> string list
(**************************************************************)
(* Get the tag value of an object's representation.
*)
val tag : 'a -> int
(**************************************************************)
val sample : int -> 'a array -> 'a array
(**************************************************************)
(* Generate a string representation of an exception.
*)
val error : exn -> string
(* Same as Printexc.catch.
*)
val catch : ('a -> 'b) -> 'a -> 'b
val count_true : bool array -> int
(* Called to set a function for logging information about
* this module.
*)
val set_error_log : ((unit -> string) -> unit) -> unit
val install_error : (exn -> string) -> unit
(**************************************************************)
| null | https://raw.githubusercontent.com/chetmurthy/ensemble/8266a89e68be24a4aaa5d594662e211eeaa6dc89/ensemble/server/util/util.mli | ocaml | ************************************************************
UTIL.MLI
************************************************************
************************************************************
************************************************************
************************************************************
Really basic things.
The identity function.
This is used to discard non-unit return values from
* functions so that the compiler does not generate a
* warning.
The string sanity.
************************************************************
Debugging stuff.
************************************************************
Export printf and sprintf.
************************************************************
************************************************************
Some list/array operations.
ofs
len
************************************************************
Some string conversion functions.
************************************************************
Some additional option operations.
Calls the function if the option is a Some()
Call the function if the option is None.
Extract the contents of an option. Fails on None.
Returns true if the option is None.
String representation of an option.
************************************************************
************************************************************
************************************************************
************************************************************
************************************************************
************************************************************
************************************************************
Get the tag value of an object's representation.
************************************************************
************************************************************
Generate a string representation of an exception.
Same as Printexc.catch.
Called to set a function for logging information about
* this module.
************************************************************ | Author : , 4/95
open Trans
type ('a,'b,'c) fun2arg = 'a -> 'b -> 'c
type ('a,'b,'c,'d) fun3arg = 'a -> 'b -> 'c -> 'd
external : ( ' a,'b,'c ) fun2arg - > ( ' a,'b,'c ) fun2arg = " % arity2 "
external arity3 : ( ' a,'b,'c,'d ) fun3arg - > ( ' a,'b,'c,'d ) fun3arg = " % arity3 "
external arity2 : ('a,'b,'c) fun2arg -> ('a,'b,'c) fun2arg = "%arity2"
external arity3 : ('a,'b,'c,'d) fun3arg -> ('a,'b,'c,'d) fun3arg = "%arity3"
*)
val arity2 : ('a,'b,'c) fun2arg -> ('a,'b,'c) fun2arg
val arity3 : ('a,'b,'c,'d) fun3arg -> ('a,'b,'c,'d) fun3arg
external (=|) : int -> int -> bool = "%eq"
external (<>|) : int -> int -> bool = "%noteq"
external (>=|) : int -> int -> bool = "%geint"
external (<=|) : int -> int -> bool = "%leint"
external (>|) : int -> int -> bool = "%gtint"
external (<|) : int -> int -> bool = "%ltint"
val int_max : int -> int -> int
val int_min : int -> int -> int
The first application creates a counter . Each time the
* second unit is applied the next integer ( starting from 0 )
* is returned .
* second unit is applied the next integer (starting from 0)
* is returned.
*)
val counter : unit -> unit -> int
val ident : 'a -> 'a
val unit : ' a - > unit
val : ' a - > ' b - > unit
val unit : 'a -> unit
val unit2 : 'a -> 'b -> unit
*)
val ignore2 : 'a -> 'b -> unit
val info : string -> string -> string
val sanity : string
val sanityn : int -> string
val verbose : bool ref
val quiet : bool ref
val addinfo : string -> string -> string
val failmsg : string -> string -> string
val printf : ('a, unit, unit) format -> 'a
val eprintf : ('a, unit, unit) format -> 'a
val sprintf : ('a, unit, string) format -> 'a
val fprintf_override : (out_channel -> string -> unit) -> unit
val sequence : int -> int array
val index : 'a -> 'a list -> int
val except : 'a -> 'a list -> 'a list
val array_is_empty : 'a array -> bool
val array_filter : ('a -> bool) -> 'a array -> 'a array
val array_index : 'a -> 'a array -> int
val array_mem : 'a -> 'a array -> bool
val array_filter_nones : 'a option array -> 'a array
val array_exists : (int -> 'a -> bool) -> 'a array -> bool
val array_incr : int array -> int -> unit
val array_decr : int array -> int -> unit
val array_add : int array -> int -> int -> unit
val array_sub : int array -> int -> int -> unit
val array_for_all : ('a -> bool) -> 'a array -> bool
val array_flatten : 'a array array -> 'a array
val matrix_incr : int array array -> int -> int -> unit
val do_once : (unit -> 'a) -> (unit -> 'a)
val hashtbl_size : ('a,'b) Hashtbl.t -> int
val hashtbl_to_list : ('a,'b) Hashtbl.t -> ('a * 'b) list
val deepcopy : 'a -> 'a
val string_of_unit : unit -> string
val string_map : (char -> char) -> string -> string
val string_of_pair :
('a -> string) -> ('b -> string) -> ('a * 'b -> string)
val string_of_list : ('a -> string) -> 'a list -> string
val string_of_array : ('a -> string) -> 'a array -> string
val string_of_int_list : int list -> string
val string_of_int_array : int array -> string
val bool_of_string : string -> bool
val string_of_bool : bool -> string
val string_of_bool_list : bool list -> string
val string_of_bool_array : bool array -> string
val string_split : string -> string -> string list
val hex_to_string : string -> string
val hex_of_string : string -> string
val string_uppercase : string -> string
val strchr : char -> string -> int
val if_some : 'a option -> ('a -> unit) -> unit
val if_none : 'a option -> (unit -> 'a option) -> 'a option
val some_of : debug -> 'a option -> 'a
val is_none : 'a option -> bool
val string_of_option : ('a -> string) -> 'a option -> string
val option_map : ('a -> 'b) -> 'a option -> 'b option
val filter_nones : 'a option list -> 'a list
val once : debug -> 'a option list -> 'a
val make_magic : unit -> (('a -> Obj.t ) * (Obj.t -> 'a))
val disable_sigpipe : unit -> unit
val average : int - > unit
val gc_profile : string - > ( ' a - > ' b ) - > ' a - > ' b
: string - > ( ' a - > ' b - > ' c - > 'd ) - > ' a - > ' b - > ' c - > 'd
val average : int -> unit
val gc_profile : string -> ('a -> 'b) -> 'a -> 'b
val gc_profile3 : string -> ('a -> 'b -> 'c -> 'd) -> 'a -> 'b -> 'c -> 'd
*)
val strtok : string -> string -> string * string
val string_of_id : debug -> (string * 'a) array -> 'a -> string
val id_of_string : debug -> (string * 'a) array -> string -> 'a
val string_list_of_gc_stat : Gc.stat -> string list
val tag : 'a -> int
val sample : int -> 'a array -> 'a array
val error : exn -> string
val catch : ('a -> 'b) -> 'a -> 'b
val count_true : bool array -> int
val set_error_log : ((unit -> string) -> unit) -> unit
val install_error : (exn -> string) -> unit
|
b2eefe00dcf338be3d782f5ecd5d68d39db0c4e42e43c2fde181f161d2540eaa | kindista/kindista | utilities.lisp | Copyright 2012 - 2021 CommonGoods Network , Inc.
;;;
This file is part of Kindista .
;;;
Kindista 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.
;;;
Kindista 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 Kindista . If not , see < / > .
(in-package :kindista)
; number of active users (&key date location distance)
; number of offers (&key date location distance)
; number of requests (&key date location distance)
; number of gratitudes (&key date location distance)
; number of conversations (&key date location distance)
; number of users who have commented on a conversation (&key period-start period-end)
number of users who have used kindista ( & key period - start period - end )
(defun get-admin-active-accounts-png ()
(setf (content-type*) "image/png")
(with-chart (:line 600 600)
(add-series "Active Kindista Accounts"
(active-kindista-accounts-over-time))
(set-axis :y "Accounts" :data-interval 20)
(set-axis :x "Date"
:label-formatter #'chart-date-labels
:angle 90)
(save-stream (send-headers))))
(defun get-admin-metrics-chart-png ()
(handle-static-file (merge-pathnames *metrics-path* "kindista-metrics-chart.png")
"image/png"))
(defun chart-date-labels (timecode)
(multiple-value-bind (time date-name formatted-date)
(humanize-exact-time timecode)
(declare (ignore time date-name))
formatted-date))
(defun active-kindista-accounts-over-time ()
(let ((day nil))
(loop for i
from (floor (/ (parse-datetime "05/01/2013") +day-in-seconds+))
to (floor (/ (get-universal-time) +day-in-seconds+))
do (setf day (* i +day-in-seconds+))
collect (list day (active-people day)))))
(defun most-active-users (&key (count 20) time-period &aux users active-users)
(dolist (userid *active-people-index*)
(push (cons userid
(length (remove-if-not (lambda (type) (eq type :gratitude))
(gethash userid *profile-activity-index*)
:key #'result-type)))
users))
(setf users (sort (copy-list users) #'> :key #'cdr))
(setf active-users (mapcar (lambda (user) (list (db (car user) :name) :userid (car user) :total-gratitudes (cdr user)))
(subseq users 0 (- count 1))))
active-users)
(defun basic-chart ()
(with-open-file (file (s+ *metrics-path* "active-accounts")
:direction :output
:if-exists :supersede)
(with-standard-io-syntax
(let ((*print-pretty* t))
(prin1
(active-kindista-accounts-over-time)
file)))))
(defun active-people (&optional date)
"Returns number of active accounts on Kindista.
When a date is specified, returns the number of people who are active now
and had signed up before midnight on that date."
(if date
(let ((time (cond
((integerp date) date)
((stringp date)
(+ +day-in-seconds+ (parse-datetime date))))))
(length
(loop for person in *active-people-index*
when (< (db person :created) time)
collect person)))
(length *active-people-index*)))
(defun sharing-items-count (&optional date)
"Returns number of current offers, requests, and gratitudes.
When a date is specified, returns the number of current offers, requests,
and gratitudes that had been posted before midnight on that date."
(let ((offers 0)
(requests 0)
(gratitudes 0))
(if date
(let ((time (cond
((integerp date) date)
((stringp date)
(+ +day-in-seconds+ (parse-datetime date))))))
(dolist (result (hash-table-values *db-results*))
(let* ((data (db (result-id result)))
(active-p (getf data :active)))
(case (result-type result)
(:offer (when (and active-p
(< (db (result-id result) :created) time))
(incf offers)))
(:request (when (and active-p
(< (db (result-id result) :created) time))
(incf requests)))
(:gratitude (when (< (db (result-id result) :created) time)
(incf gratitudes)))))))
(dolist (result (hash-table-values *db-results*))
(let* ((data (db (result-id result)))
(active-p (getf data :active)))
(case (result-type result)
(:offer (when active-p (incf offers)))
(:request (when active-p (incf requests)))
(:gratitude (incf gratitudes))))))
(values offers requests gratitudes)))
(defun transactions-report ()
(with-standard-io-syntax
(with-open-file (s (merge-pathnames *metrics-path* "transaction-report")
:direction :output
:if-exists :supersede
:if-does-not-exist :create)
(let ((*print-readably* nil))
(format s "######### Completed Transactions #########~%" ))
(dolist (transaction *completed-transactions-index*)
(let* ((gratitude-id (getf transaction :gratitude))
(gratitude (db gratitude-id))
(recipient-id (getf gratitude :author))
(recipient (db recipient-id))
(item-id (getf transaction :on))
(item (db item-id)))
(format s "~A~%" (strcat "DATE: " (humanize-exact-time (getf transaction :time)
:detailed t))
)
(format s "~A~%" (strcat "LOCATION: " (getf recipient :address)))
(format s "~A~%" (strcat "RECIPIENT: " (getf recipient :name)
" (" recipient-id ")")
)
(format s "~A~%" (strcat "GIFT GIVER(S): "
(format nil
*english-list*
(loop for id in (getf gratitude :subjects)
collect (strcat (db id :name)
" ("
id
")"))))
)
(format s "~A~%" (strcat (symbol-name (getf item :type))
" TITLE: "
(getf item :title))
)
(format s "~A~%" (strcat (symbol-name (getf item :type)) " DETAILS: ") )
(format s "~A~%" (getf item :details))
(format s "~A~%" (strcat (symbol-name (getf gratitude :type)) " TEXT:") )
(format s "~A~%" (getf gratitude :text))
(format s "~A~%" "------------------" ))))))
(defun outstanding-invitations-count ()
(hash-table-count *invitation-index*))
(defun gratitude-texts ()
(loop for result in (hash-table-values *db-results*)
when (eq (result-type result) :gratitude)
collect (cons (result-id result) (db (result-id result) :text))))
(defun completed-transactions-report
(&optional (start (- (get-universal-time) (* +day-in-seconds+ 365)))
(end (get-universal-time))
&aux (transactions))
(dolist (transaction (safe-sort *completed-transactions-index*
#'<
:key #'(lambda (transaction) (getf transaction :time))))
(when (and (< (getf transaction :time) end)
(> (getf transaction :time) start))
(push transaction transactions)))
;; if we want to include gratitudes w/o transactions
( setf transaction - gratitude - ids
( mapcar ( lambda ( transaction ) ( getf transaction : gratitude ) ) transactions ) )
( setf orphan - gratitudes
; (loop for result in (hash-table-values *db-results*)
; when (and (eq (result-type result) :gratitude)
; (< (result-time result) end)
; (> (result-time result) start)
; (not (find (result-id result) transaction-gratitude-ids)))
; collect result))
(with-open-file (s (s+ +db-path+ "/metrics/transactions-report")
:direction :output
:if-exists :supersede)
(with-standard-io-syntax
(prin1 "######### Completed Transactions #########" s)
(fresh-line s)
(prin1 (strcat (length transactions) " completed transactions"))
(fresh-line s)
(dolist (transaction transactions)
(let* ((gratitude (db (getf transaction :gratitude)))
(recipient (db (getf gratitude :author))))
(format s "DATE: ~A" (humanize-exact-time (getf transaction :time) :detailed t))
(fresh-line s)
(format s "LOCATION: ~A" (getf recipient :address))
(fresh-line s)
(format s "RECIPIENT: ~A (~A)"
(getf recipient :name)
(getf gratitude :author))
(fresh-line s)
(format s "GIFT GIVER(S): ")
(format s *english-list*
(mapcar (lambda (subject)
(strcat (db subject :name) " (" subject ")"))
(getf gratitude :subjects)))
(fresh-line s)
(let ((inventory-item (db (getf transaction :on))))
(format s "~A text:" (symbol-name (getf inventory-item :type)))
(fresh-line s)
(prin1 (getf inventory-item :details) s)
(fresh-line s))
(let ((gratitude (db (getf transaction :gratitude))))
(format s "GRATITUDE TEXT:")
(fresh-line s)
(prin1 (getf gratitude :text) s)))
(fresh-line s)
(format s "------------------------")
(fresh-line s)
))))
(defun user-email-subscriptions-analysis
(&aux (active-users 0)
(message 0)
(reminders 0)
(expired-invites 0)
(blog 0)
(kindista 0)
(all 0)
(any 0))
(dolist (userid *active-people-index*)
(let ((user (db userid)))
(incf active-users)
(when (getf user :notify-message) (incf message))
(when (getf user :notify-reminders) (incf reminders))
(when (getf user :notify-expired-invites) (incf expired-invites))
(when (getf user :notify-blog) (incf blog))
(when (getf user :notify-kindista) (incf kindista))
(when (and (getf user :notify-reminders)
(getf user :notify-blog)
(getf user :notify-kindista))
(incf all))
(when (or (getf user :notify-reminders)
(getf user :notify-blog)
(getf user :notify-kindista))
(incf any))))
(list :active active-users
:message message
:reminders reminders
:expired-invites expired-invites
:blog blog
:kindista kindista
:all all
:any any
))
(defun local-members (&key focal-point-id (distance 25))
"Provides values for a list of people within :distance (default=25 miles)
of a given :focal-point-id (default=Eugene OR), followed by the length of that list.
Any id can be used as long as (getf id :lat/long) provides meaningful result."
(let* ((focal-point-data (if (db focal-point-id :lat)
(db focal-point-id)
(db +kindista-id+)))
(lat (getf focal-point-data :lat))
(long (getf focal-point-data :long))
(people (mapcar #'result-id
(geo-index-query *people-geo-index* lat long distance))))
(values people (length people))))
(defun update-metrics-chart
(&key (start-month 1)
(start-year (- (current-year) 3))
&aux (chart-data)
(now (local-time:now))
(current-year (timestamp-year now))
(current-month (timestamp-month now)))
(loop for year from start-year to current-year
do (dolist (month '("01" "02" "03" "04" "05" "06" "07" "08" "09" "10" "11" "12"))
(let ((file (pathname (strcat *metrics-path* year "/" month "/monthly-summary")))
(time (encode-universal-time 0 0 1 15 (parse-integer month) year))
(file-data))
(when (and (file-exists-p file)
(or (and (= year start-year)
(>= (parse-integer month) start-month))
(> year start-year))
(or (< year current-year)
(< (parse-integer month) current-month)
(and (= (parse-integer month) current-month)
(= (local-time:timestamp-day now)
(days-in-month now)))))
(with-standard-io-syntax
(with-open-file (summary file :direction :input)
(setf file-data (read summary)))) (flet ((record-data (data-type &aux (data (getf file-data data-type)))
(push (list time (if (listp data)
(length data)
data))
(getf chart-data data-type))))
(mapcar #'record-data (list :active-users
:used-search
:new-offers
:new-requests
:got-offers
:got-requests
;:messages-sent
:completed-transactions)))))))
(with-open-file (s (strcat *metrics-path* "/kindista-metrics-chart.png")
:direction :output
:if-does-not-exist :create
:if-exists :supersede
:element-type '(unsigned-byte 8))
(with-chart (:line 1200 600)
(doplist (key val chart-data)
(add-series (string-capitalize
(string-downcase
(ppcre:regex-replace-all "-" (symbol-name key) " ")))
val))
(set-axis :y "" :data-interval 10)
(set-axis :x "Month"
:label-formatter #'format-month-for-activity-charts
)
( add - title " Kindista Usage over time " )
;(add-feature :label)
(save-stream s))
(finish-output s)))
(defun monthly-statistic
(year month statistic
&key (return-list nil)
&aux dir summary-file)
(setf month (if (< (/ month 10) 1)
(strcat "0" month)
(strcat month)))
(setf dir (strcat *metrics-path* year "/" month "/"))
(setf summary-file (merge-pathnames dir "/monthly-summary"))
(when (file-exists-p summary-file)
(with-standard-io-syntax
(with-open-file (s summary-file)
(let* ((data (read s))
(stat (getf data statistic)))
(cond
((and (listp stat) return-list)
stat)
((listp stat)
(length stat))
(t stat)))))))
(defun transactions-completed-in-year (year)
(average-statistic-in-year year :completed-transactions))
(defun average-statistic-in-year
(year statistic
&key (total-annual-count nil)
&aux (return-value)
(monthly-counts))
(unless total-annual-count (setf return-value 0))
(loop for month from 1 to 12
do (asetf return-value
(if total-annual-count
(let ((monthly-statistic (monthly-statistic year
month
statistic
:return-list t)))
(setf monthly-counts
(append monthly-counts
(list (length monthly-statistic))))
(remove-duplicates
(append it monthly-statistic)))
(+ it
(or (monthly-statistic year
month
statistic) 0)))))
(when total-annual-count (asetf return-value (length it)))
(values (list :monthly-counts monthly-counts)
(list :total return-value)
(list :average (coerce (if monthly-counts
(/ (apply '+ monthly-counts)
(length monthly-counts))
(/ return-value 12))
'float))))
(defun create-past-monthly-activity-reports (years)
(dolist (year years)
(loop for month from 1 to 12
for dir = (strcat *metrics-path* year
"/"
(if (< (/ month 10) 1)
(strcat "0" month)
(strcat month))
"/")
when (cl-fad::directory-exists-p dir)
do (monthly-activity-report month year))))
(defun send-progress-report-email (title)
(cl-smtp:send-email
+mail-server+
"Kindista <>"
(if *productionp*
"Progress Reports <>"
*error-message-email*)
title
(strcat
"Please see the attached file for a chart of various metrics we are collecting for Kindista usage. "
#\linefeed #\linefeed
"Please note: Due to a bug in the graphing library we are using, some of the dates may be repeated on the x-axis. "
"The data points should be correct and there is one data point per month for each metric . "
"Also, we didn't start collecting metrics for new offers/requests until July/2015.")
:attachments (merge-pathnames *metrics-path* "kindista-metrics-chart.png")))
| null | https://raw.githubusercontent.com/kindista/kindista/b67cd5975247f633c74a9299539de7b66d202011/src/analytics/utilities.lisp | lisp |
(at your option) any later version.
without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public
License for more details.
number of active users (&key date location distance)
number of offers (&key date location distance)
number of requests (&key date location distance)
number of gratitudes (&key date location distance)
number of conversations (&key date location distance)
number of users who have commented on a conversation (&key period-start period-end)
if we want to include gratitudes w/o transactions
(loop for result in (hash-table-values *db-results*)
when (and (eq (result-type result) :gratitude)
(< (result-time result) end)
(> (result-time result) start)
(not (find (result-id result) transaction-gratitude-ids)))
collect result))
:messages-sent
(add-feature :label) | Copyright 2012 - 2021 CommonGoods Network , Inc.
This file is part of Kindista .
Kindista 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
Kindista is distributed in the hope that it will be useful , but WITHOUT
You should have received a copy of the GNU Affero General Public License
along with Kindista . If not , see < / > .
(in-package :kindista)
number of users who have used kindista ( & key period - start period - end )
(defun get-admin-active-accounts-png ()
(setf (content-type*) "image/png")
(with-chart (:line 600 600)
(add-series "Active Kindista Accounts"
(active-kindista-accounts-over-time))
(set-axis :y "Accounts" :data-interval 20)
(set-axis :x "Date"
:label-formatter #'chart-date-labels
:angle 90)
(save-stream (send-headers))))
(defun get-admin-metrics-chart-png ()
(handle-static-file (merge-pathnames *metrics-path* "kindista-metrics-chart.png")
"image/png"))
(defun chart-date-labels (timecode)
(multiple-value-bind (time date-name formatted-date)
(humanize-exact-time timecode)
(declare (ignore time date-name))
formatted-date))
(defun active-kindista-accounts-over-time ()
(let ((day nil))
(loop for i
from (floor (/ (parse-datetime "05/01/2013") +day-in-seconds+))
to (floor (/ (get-universal-time) +day-in-seconds+))
do (setf day (* i +day-in-seconds+))
collect (list day (active-people day)))))
(defun most-active-users (&key (count 20) time-period &aux users active-users)
(dolist (userid *active-people-index*)
(push (cons userid
(length (remove-if-not (lambda (type) (eq type :gratitude))
(gethash userid *profile-activity-index*)
:key #'result-type)))
users))
(setf users (sort (copy-list users) #'> :key #'cdr))
(setf active-users (mapcar (lambda (user) (list (db (car user) :name) :userid (car user) :total-gratitudes (cdr user)))
(subseq users 0 (- count 1))))
active-users)
(defun basic-chart ()
(with-open-file (file (s+ *metrics-path* "active-accounts")
:direction :output
:if-exists :supersede)
(with-standard-io-syntax
(let ((*print-pretty* t))
(prin1
(active-kindista-accounts-over-time)
file)))))
(defun active-people (&optional date)
"Returns number of active accounts on Kindista.
When a date is specified, returns the number of people who are active now
and had signed up before midnight on that date."
(if date
(let ((time (cond
((integerp date) date)
((stringp date)
(+ +day-in-seconds+ (parse-datetime date))))))
(length
(loop for person in *active-people-index*
when (< (db person :created) time)
collect person)))
(length *active-people-index*)))
(defun sharing-items-count (&optional date)
"Returns number of current offers, requests, and gratitudes.
When a date is specified, returns the number of current offers, requests,
and gratitudes that had been posted before midnight on that date."
(let ((offers 0)
(requests 0)
(gratitudes 0))
(if date
(let ((time (cond
((integerp date) date)
((stringp date)
(+ +day-in-seconds+ (parse-datetime date))))))
(dolist (result (hash-table-values *db-results*))
(let* ((data (db (result-id result)))
(active-p (getf data :active)))
(case (result-type result)
(:offer (when (and active-p
(< (db (result-id result) :created) time))
(incf offers)))
(:request (when (and active-p
(< (db (result-id result) :created) time))
(incf requests)))
(:gratitude (when (< (db (result-id result) :created) time)
(incf gratitudes)))))))
(dolist (result (hash-table-values *db-results*))
(let* ((data (db (result-id result)))
(active-p (getf data :active)))
(case (result-type result)
(:offer (when active-p (incf offers)))
(:request (when active-p (incf requests)))
(:gratitude (incf gratitudes))))))
(values offers requests gratitudes)))
(defun transactions-report ()
(with-standard-io-syntax
(with-open-file (s (merge-pathnames *metrics-path* "transaction-report")
:direction :output
:if-exists :supersede
:if-does-not-exist :create)
(let ((*print-readably* nil))
(format s "######### Completed Transactions #########~%" ))
(dolist (transaction *completed-transactions-index*)
(let* ((gratitude-id (getf transaction :gratitude))
(gratitude (db gratitude-id))
(recipient-id (getf gratitude :author))
(recipient (db recipient-id))
(item-id (getf transaction :on))
(item (db item-id)))
(format s "~A~%" (strcat "DATE: " (humanize-exact-time (getf transaction :time)
:detailed t))
)
(format s "~A~%" (strcat "LOCATION: " (getf recipient :address)))
(format s "~A~%" (strcat "RECIPIENT: " (getf recipient :name)
" (" recipient-id ")")
)
(format s "~A~%" (strcat "GIFT GIVER(S): "
(format nil
*english-list*
(loop for id in (getf gratitude :subjects)
collect (strcat (db id :name)
" ("
id
")"))))
)
(format s "~A~%" (strcat (symbol-name (getf item :type))
" TITLE: "
(getf item :title))
)
(format s "~A~%" (strcat (symbol-name (getf item :type)) " DETAILS: ") )
(format s "~A~%" (getf item :details))
(format s "~A~%" (strcat (symbol-name (getf gratitude :type)) " TEXT:") )
(format s "~A~%" (getf gratitude :text))
(format s "~A~%" "------------------" ))))))
(defun outstanding-invitations-count ()
(hash-table-count *invitation-index*))
(defun gratitude-texts ()
(loop for result in (hash-table-values *db-results*)
when (eq (result-type result) :gratitude)
collect (cons (result-id result) (db (result-id result) :text))))
(defun completed-transactions-report
(&optional (start (- (get-universal-time) (* +day-in-seconds+ 365)))
(end (get-universal-time))
&aux (transactions))
(dolist (transaction (safe-sort *completed-transactions-index*
#'<
:key #'(lambda (transaction) (getf transaction :time))))
(when (and (< (getf transaction :time) end)
(> (getf transaction :time) start))
(push transaction transactions)))
( setf transaction - gratitude - ids
( mapcar ( lambda ( transaction ) ( getf transaction : gratitude ) ) transactions ) )
( setf orphan - gratitudes
(with-open-file (s (s+ +db-path+ "/metrics/transactions-report")
:direction :output
:if-exists :supersede)
(with-standard-io-syntax
(prin1 "######### Completed Transactions #########" s)
(fresh-line s)
(prin1 (strcat (length transactions) " completed transactions"))
(fresh-line s)
(dolist (transaction transactions)
(let* ((gratitude (db (getf transaction :gratitude)))
(recipient (db (getf gratitude :author))))
(format s "DATE: ~A" (humanize-exact-time (getf transaction :time) :detailed t))
(fresh-line s)
(format s "LOCATION: ~A" (getf recipient :address))
(fresh-line s)
(format s "RECIPIENT: ~A (~A)"
(getf recipient :name)
(getf gratitude :author))
(fresh-line s)
(format s "GIFT GIVER(S): ")
(format s *english-list*
(mapcar (lambda (subject)
(strcat (db subject :name) " (" subject ")"))
(getf gratitude :subjects)))
(fresh-line s)
(let ((inventory-item (db (getf transaction :on))))
(format s "~A text:" (symbol-name (getf inventory-item :type)))
(fresh-line s)
(prin1 (getf inventory-item :details) s)
(fresh-line s))
(let ((gratitude (db (getf transaction :gratitude))))
(format s "GRATITUDE TEXT:")
(fresh-line s)
(prin1 (getf gratitude :text) s)))
(fresh-line s)
(format s "------------------------")
(fresh-line s)
))))
(defun user-email-subscriptions-analysis
(&aux (active-users 0)
(message 0)
(reminders 0)
(expired-invites 0)
(blog 0)
(kindista 0)
(all 0)
(any 0))
(dolist (userid *active-people-index*)
(let ((user (db userid)))
(incf active-users)
(when (getf user :notify-message) (incf message))
(when (getf user :notify-reminders) (incf reminders))
(when (getf user :notify-expired-invites) (incf expired-invites))
(when (getf user :notify-blog) (incf blog))
(when (getf user :notify-kindista) (incf kindista))
(when (and (getf user :notify-reminders)
(getf user :notify-blog)
(getf user :notify-kindista))
(incf all))
(when (or (getf user :notify-reminders)
(getf user :notify-blog)
(getf user :notify-kindista))
(incf any))))
(list :active active-users
:message message
:reminders reminders
:expired-invites expired-invites
:blog blog
:kindista kindista
:all all
:any any
))
(defun local-members (&key focal-point-id (distance 25))
"Provides values for a list of people within :distance (default=25 miles)
of a given :focal-point-id (default=Eugene OR), followed by the length of that list.
Any id can be used as long as (getf id :lat/long) provides meaningful result."
(let* ((focal-point-data (if (db focal-point-id :lat)
(db focal-point-id)
(db +kindista-id+)))
(lat (getf focal-point-data :lat))
(long (getf focal-point-data :long))
(people (mapcar #'result-id
(geo-index-query *people-geo-index* lat long distance))))
(values people (length people))))
(defun update-metrics-chart
(&key (start-month 1)
(start-year (- (current-year) 3))
&aux (chart-data)
(now (local-time:now))
(current-year (timestamp-year now))
(current-month (timestamp-month now)))
(loop for year from start-year to current-year
do (dolist (month '("01" "02" "03" "04" "05" "06" "07" "08" "09" "10" "11" "12"))
(let ((file (pathname (strcat *metrics-path* year "/" month "/monthly-summary")))
(time (encode-universal-time 0 0 1 15 (parse-integer month) year))
(file-data))
(when (and (file-exists-p file)
(or (and (= year start-year)
(>= (parse-integer month) start-month))
(> year start-year))
(or (< year current-year)
(< (parse-integer month) current-month)
(and (= (parse-integer month) current-month)
(= (local-time:timestamp-day now)
(days-in-month now)))))
(with-standard-io-syntax
(with-open-file (summary file :direction :input)
(setf file-data (read summary)))) (flet ((record-data (data-type &aux (data (getf file-data data-type)))
(push (list time (if (listp data)
(length data)
data))
(getf chart-data data-type))))
(mapcar #'record-data (list :active-users
:used-search
:new-offers
:new-requests
:got-offers
:got-requests
:completed-transactions)))))))
(with-open-file (s (strcat *metrics-path* "/kindista-metrics-chart.png")
:direction :output
:if-does-not-exist :create
:if-exists :supersede
:element-type '(unsigned-byte 8))
(with-chart (:line 1200 600)
(doplist (key val chart-data)
(add-series (string-capitalize
(string-downcase
(ppcre:regex-replace-all "-" (symbol-name key) " ")))
val))
(set-axis :y "" :data-interval 10)
(set-axis :x "Month"
:label-formatter #'format-month-for-activity-charts
)
( add - title " Kindista Usage over time " )
(save-stream s))
(finish-output s)))
(defun monthly-statistic
(year month statistic
&key (return-list nil)
&aux dir summary-file)
(setf month (if (< (/ month 10) 1)
(strcat "0" month)
(strcat month)))
(setf dir (strcat *metrics-path* year "/" month "/"))
(setf summary-file (merge-pathnames dir "/monthly-summary"))
(when (file-exists-p summary-file)
(with-standard-io-syntax
(with-open-file (s summary-file)
(let* ((data (read s))
(stat (getf data statistic)))
(cond
((and (listp stat) return-list)
stat)
((listp stat)
(length stat))
(t stat)))))))
(defun transactions-completed-in-year (year)
(average-statistic-in-year year :completed-transactions))
(defun average-statistic-in-year
(year statistic
&key (total-annual-count nil)
&aux (return-value)
(monthly-counts))
(unless total-annual-count (setf return-value 0))
(loop for month from 1 to 12
do (asetf return-value
(if total-annual-count
(let ((monthly-statistic (monthly-statistic year
month
statistic
:return-list t)))
(setf monthly-counts
(append monthly-counts
(list (length monthly-statistic))))
(remove-duplicates
(append it monthly-statistic)))
(+ it
(or (monthly-statistic year
month
statistic) 0)))))
(when total-annual-count (asetf return-value (length it)))
(values (list :monthly-counts monthly-counts)
(list :total return-value)
(list :average (coerce (if monthly-counts
(/ (apply '+ monthly-counts)
(length monthly-counts))
(/ return-value 12))
'float))))
(defun create-past-monthly-activity-reports (years)
(dolist (year years)
(loop for month from 1 to 12
for dir = (strcat *metrics-path* year
"/"
(if (< (/ month 10) 1)
(strcat "0" month)
(strcat month))
"/")
when (cl-fad::directory-exists-p dir)
do (monthly-activity-report month year))))
(defun send-progress-report-email (title)
(cl-smtp:send-email
+mail-server+
"Kindista <>"
(if *productionp*
"Progress Reports <>"
*error-message-email*)
title
(strcat
"Please see the attached file for a chart of various metrics we are collecting for Kindista usage. "
#\linefeed #\linefeed
"Please note: Due to a bug in the graphing library we are using, some of the dates may be repeated on the x-axis. "
"The data points should be correct and there is one data point per month for each metric . "
"Also, we didn't start collecting metrics for new offers/requests until July/2015.")
:attachments (merge-pathnames *metrics-path* "kindista-metrics-chart.png")))
|
9627897d40ead996d3c312d3c8c4fdd02c534770d4da1efb26016ece2d241578 | pfdietz/ansi-test | revappend.lsp | ;-*- Mode: Lisp -*-
Author :
Created : Sat Apr 19 22:37:43 2003
;;;; Contains: Tests of REVAPPEND
(deftest revappend.1
(let* ((x (list 'a 'b 'c))
(y (list 'd 'e 'f))
(xcopy (make-scaffold-copy x))
(ycopy (make-scaffold-copy y))
)
(let ((result (revappend x y)))
(and
(check-scaffold-copy x xcopy)
(check-scaffold-copy y ycopy)
(eqt (cdddr result) y)
result)))
(c b a d e f))
(deftest revappend.2
(revappend (copy-tree '(a b c d e)) 10)
(e d c b a . 10))
(deftest revappend.3
(revappend nil 'a)
a)
(deftest revappend.4
(revappend (copy-tree '(a (b c) d)) nil)
(d (b c) a))
(deftest revappend.order.1
(let ((i 0) x y)
(values
(revappend (progn (setf x (incf i)) (copy-list '(a b c)))
(progn (setf y (incf i)) (copy-list '(d e f))))
i x y))
(c b a d e f) 2 1 2)
(def-fold-test revappend.fold.1 (revappend '(x) nil))
(def-fold-test revappend.fold.2 (revappend '(x y z) nil))
;;; Error tests
(deftest revappend.error.1
(signals-error (revappend) program-error)
t)
(deftest revappend.error.2
(signals-error (revappend nil) program-error)
t)
(deftest revappend.error.3
(signals-error (revappend nil nil nil) program-error)
t)
(deftest revappend.error.4
(signals-error (revappend '(a . b) '(z)) type-error)
t)
| null | https://raw.githubusercontent.com/pfdietz/ansi-test/3f4b9d31c3408114f0467eaeca4fd13b28e2ce31/cons/revappend.lsp | lisp | -*- Mode: Lisp -*-
Contains: Tests of REVAPPEND
Error tests | Author :
Created : Sat Apr 19 22:37:43 2003
(deftest revappend.1
(let* ((x (list 'a 'b 'c))
(y (list 'd 'e 'f))
(xcopy (make-scaffold-copy x))
(ycopy (make-scaffold-copy y))
)
(let ((result (revappend x y)))
(and
(check-scaffold-copy x xcopy)
(check-scaffold-copy y ycopy)
(eqt (cdddr result) y)
result)))
(c b a d e f))
(deftest revappend.2
(revappend (copy-tree '(a b c d e)) 10)
(e d c b a . 10))
(deftest revappend.3
(revappend nil 'a)
a)
(deftest revappend.4
(revappend (copy-tree '(a (b c) d)) nil)
(d (b c) a))
(deftest revappend.order.1
(let ((i 0) x y)
(values
(revappend (progn (setf x (incf i)) (copy-list '(a b c)))
(progn (setf y (incf i)) (copy-list '(d e f))))
i x y))
(c b a d e f) 2 1 2)
(def-fold-test revappend.fold.1 (revappend '(x) nil))
(def-fold-test revappend.fold.2 (revappend '(x y z) nil))
(deftest revappend.error.1
(signals-error (revappend) program-error)
t)
(deftest revappend.error.2
(signals-error (revappend nil) program-error)
t)
(deftest revappend.error.3
(signals-error (revappend nil nil nil) program-error)
t)
(deftest revappend.error.4
(signals-error (revappend '(a . b) '(z)) type-error)
t)
|
bd1c73f97c9d51c7612bbbcdd93cd6a39b027433b38485f34d152e10e85e34b4 | argp/bap | sequence.ml | (* ocamlbuild benchsuite/sequence.native -- snoc_front | tee >(./plot) *)
module type SIG = sig
type 'a t
val empty : 'a t
val cons : 'a t -> 'a -> 'a t
val front : 'a t -> ('a t * 'a) option
val map : ('a -> 'b) -> 'a t -> 'b t
val snoc : 'a t -> 'a -> 'a t
val rear : 'a t -> ('a t * 'a) option
val of_enum : 'a BatEnum.t -> 'a t
val enum : 'a t -> 'a BatEnum.t
val of_backwards : 'a BatEnum.t -> 'a t
val backwards : 'a t -> 'a BatEnum.t
val fold_left : ('acc -> 'a -> 'acc) -> 'acc -> 'a t -> 'acc
val fold_right : ('acc -> 'a -> 'acc) -> 'acc -> 'a t -> 'acc
val reverse : 'a t -> 'a t
val get : 'a t -> int -> 'a
val set : 'a t -> int -> 'a -> 'a t
val append : 'a t -> 'a t -> 'a t
val split_at : 'a t -> int -> 'a t * 'a t
(* take, drop *)
val generate_of_enum : 'a BatEnum.t -> 'a t
end
module Vect : SIG =
struct
type 'a t = 'a BatVect.t
let empty = BatVect.empty
let cons t x = BatVect.prepend x t
let snoc t x = BatVect.append x t
let map = BatVect.map
let front t =
if BatVect.is_empty t then None
else
let n = BatVect.length t in
Some (BatVect.sub t 0 (n - 1), BatVect.get t 0)
let rear t =
if BatVect.is_empty t then None
else
let n = BatVect.length t in
Some (BatVect.sub t 1 (n - 1), BatVect.get t (n - 1))
let of_enum = BatVect.of_enum
let enum = BatVect.enum
let of_backwards = BatVect.of_backwards
let backwards = BatVect.backwards
let fold_left = BatVect.fold_left
let fold_right f acc t = BatVect.fold_right (fun acc elt -> f elt acc) t acc
let reverse _ = assert false
let get = BatVect.get
let set = BatVect.set
let append = BatVect.concat
let split_at t n =
(BatVect.sub t 0 n, BatVect.sub t n (BatVect.length t - n))
let generate_of_enum = of_enum
end
module ListOverflow : SIG with type 'a t = 'a list =
struct
type 'a t = 'a list
let empty = []
let length l =
let rec aux acc = function
| [] -> acc
| _ :: t -> aux (acc + 1) t in
aux 0 l
let cons t x = x :: t
let front = function
| [] -> None
| h :: t -> Some (t, h)
let rec map f = function
| [] -> []
| h :: t ->
let h = f h in
let t = map f t in
h :: t
let rec rev_append l1 l2 =
match l1 with
| [] -> l2
| h1 :: t1 -> rev_append t1 (h1 :: l2)
let reverse l = rev_append l []
let rec snoc t x =
match t with
| [] -> [x]
| h :: t -> h :: snoc t x
let rear = function
| [] -> None
| h :: t ->
let rec aux acc prev = function
| [] -> Some (reverse acc, prev)
| h :: t -> aux (h :: acc) h t in
aux [h] h t
let rec of_enum e =
match BatEnum.get e with
| None -> []
| Some h -> h :: of_enum e
let generate_of_enum = of_enum
let of_backwards e =
let rec aux acc e =
match BatEnum.get e with
| None -> acc
| Some h -> aux (h :: acc) e in
aux [] e
let enum l =
let rec make lr count =
BatEnum.make
~next:(fun () ->
match !lr with
| [] -> raise BatEnum.No_more_elements
| h :: t ->
decr count;
lr := t;
h
)
~count:(fun () ->
if !count < 0 then count := length !lr;
!count
)
~clone:(fun () ->
make (ref !lr) (ref !count)
) in
make (ref l) (ref (-1))
let backwards l = enum (reverse l)
let rec fold_left f acc = function
| [] -> acc
| h :: t -> fold_left f (f acc h) t
let rec fold_right f acc l =
match l with
| [] -> acc
| h :: t -> f (fold_right f acc t) h
let rec get t i =
match i, t with
| _, [] -> invalid_arg "Index out of bounds"
| 0, h :: _ -> h
| _, _ :: t -> get t (i - 1)
let rec set t i v =
match i, t with
| _, [] -> invalid_arg "Index out of bounds"
| 0, h :: t -> v :: t
| _, h :: t -> h :: set t (i - 1) v
let rec append l1 l2 =
match l1 with
| [] -> l2
| h :: t -> h :: append t l2
let split_at l i =
let rec aux acc i l =
match i, l with
| 0, _ -> reverse acc, l
| _, [] -> invalid_arg "Index out of bounds"
| _, h :: t -> aux (h :: acc) (i - 1) t in
aux [] 0 l
end
module ListTail : sig
include SIG with type 'a t = 'a list
val map2 : ('a -> 'b) -> 'a list -> 'b list
end =
struct
type 'a t = 'a list
let empty = []
let length l =
let rec aux acc = function
| [] -> acc
| _ :: t -> aux (acc + 1) t in
aux 0 l
let cons t x = x :: t
let front = function
| [] -> None
| h :: t -> Some (t, h)
let rec rev_append l1 l2 =
match l1 with
| [] -> l2
| h1 :: t1 -> rev_append t1 (h1 :: l2)
let reverse l = rev_append l []
let map f l =
let rec aux f acc = function
| [] -> reverse acc
| h :: t -> aux f (f h :: acc) t in
aux f [] l
(* copy pasted from core lib *)
let rec count_map ~f l ctr =
match l with
| [] -> []
| [x1] ->
let f1 = f x1 in
[f1]
| [x1; x2] ->
let f1 = f x1 in
let f2 = f x2 in
[f1; f2]
| [x1; x2; x3] ->
let f1 = f x1 in
let f2 = f x2 in
let f3 = f x3 in
[f1; f2; f3]
| [x1; x2; x3; x4] ->
let f1 = f x1 in
let f2 = f x2 in
let f3 = f x3 in
let f4 = f x4 in
[f1; f2; f3; f4]
| x1 :: x2 :: x3 :: x4 :: x5 :: tl ->
let f1 = f x1 in
let f2 = f x2 in
let f3 = f x3 in
let f4 = f x4 in
let f5 = f x5 in
f1 :: f2 :: f3 :: f4 :: f5 ::
(if ctr > 1000
then map f tl
else count_map ~f tl (ctr + 1))
let map2 f l = count_map ~f l 0
let snoc t x =
let rec aux x acc = function
| [] -> reverse (x :: acc)
| h :: t -> aux x (h :: acc) t in
aux x [] t
let rear = function
| [] -> None
| h :: t ->
let rec aux acc prev = function
| [] -> Some (reverse acc, prev)
| h :: t -> aux (h :: acc) h t in
aux [h] h t
let of_backwards e =
let rec aux acc e =
match BatEnum.get e with
| None -> acc
| Some h -> aux (h :: acc) e in
aux [] e
let of_enum e = reverse (of_backwards e)
let generate_of_enum = of_enum
let enum l =
let rec make lr count =
BatEnum.make
~next:(fun () ->
match !lr with
| [] -> raise BatEnum.No_more_elements
| h :: t ->
decr count;
lr := t;
h
)
~count:(fun () ->
if !count < 0 then count := length !lr;
!count
)
~clone:(fun () ->
make (ref !lr) (ref !count)
) in
make (ref l) (ref (-1))
let backwards l = enum (reverse l)
let rec fold_left f acc = function
| [] -> acc
| h :: t -> fold_left f (f acc h) t
let rec fold_right f acc l =
fold_left f acc (reverse l)
let rec get t i =
match i, t with
| _, [] -> invalid_arg "Index out of bounds"
| 0, h :: _ -> h
| _, _ :: t -> get t (i - 1)
let set t i v =
let rec aux i v acc t =
match i, t with
| _, [] -> invalid_arg "Index out of bounds"
| 0, h :: t -> rev_append acc (v :: t)
| _, h :: t -> aux (i - 1) v (h :: acc) t in
aux i v [] t
let append l1 l2 =
rev_append (reverse l1) l2
let split_at l i =
let rec aux acc i l =
match i, l with
| 0, _ -> reverse acc, l
| _, [] -> invalid_arg "Index out of bounds"
| _, h :: t -> aux (h :: acc) (i - 1) t in
aux [] 0 l
end
module ListTailModCons : sig
include SIG with type 'a t = 'a list
val map2 : ('a -> 'b) -> 'a list -> 'b list
end = struct
type 'a t = 'a BatList.t
let empty = []
let cons t x = x :: t
let snoc t x = BatList.append t [x]
let map = BatList.map
let set_tail (l : 'a list) (v : 'a list) =
Obj.set_field (Obj.repr l) 1 (Obj.repr v)
let map2 f = function
| [] -> []
| h :: t ->
let rec loop f dst = function
| [] -> ()
| [a] ->
let a = f a in
set_tail dst (a :: [])
| [a; b] ->
let a = f a in
let b = f b in
set_tail dst (a :: b :: [])
| [a; b; c] ->
let a = f a in
let b = f b in
let c = f c in
set_tail dst (a :: b :: c :: [])
| [a; b; c; d] ->
let a = f a in
let b = f b in
let c = f c in
let d = f d in
set_tail dst (a :: b :: c :: d :: [])
| [a; b; c; d; e] ->
let a = f a in
let b = f b in
let c = f c in
let d = f d in
let e = f e in
set_tail dst (a :: b :: c :: d :: e :: [])
| a :: b :: c :: d :: e :: t ->
let a = f a in
let b = f b in
let c = f c in
let d = f d in
let e = f e in
let last = e :: [] in
set_tail dst (a :: b :: c :: d :: last);
loop f last t in
let r = f h :: [] in
loop f r t;
Obj.magic r
let rec count_map ~f l ctr =
match l with
| [] -> []
| [x1] ->
let f1 = f x1 in
[f1]
| [x1; x2] ->
let f1 = f x1 in
let f2 = f x2 in
[f1; f2]
| [x1; x2; x3] ->
let f1 = f x1 in
let f2 = f x2 in
let f3 = f x3 in
[f1; f2; f3]
| [x1; x2; x3; x4] ->
let f1 = f x1 in
let f2 = f x2 in
let f3 = f x3 in
let f4 = f x4 in
[f1; f2; f3; f4]
| x1 :: x2 :: x3 :: x4 :: x5 :: tl ->
let f1 = f x1 in
let f2 = f x2 in
let f3 = f x3 in
let f4 = f x4 in
let f5 = f x5 in
f1 :: f2 :: f3 :: f4 :: f5 ::
(if ctr > 1000
then map2 f tl
else count_map ~f tl (ctr + 1))
let map2 f l =
count_map ~f l 0
let append = BatList.append
let get = BatList.nth
let split_at i t = BatList.split_at t i
FIXME
let l1, l2 = split_at t i in
match l2 with
| [] -> invalid_arg "aze"
| _ :: t -> append l1 (v :: t)
let reverse = BatList.rev
let fold_left = BatList.fold_left
let fold_right f init l =
let rec tail_loop acc = function
| [] -> acc
| h :: t -> tail_loop (f acc h) t
in
let rec loop n = function
| [] -> init
| h :: t ->
if n < 1000 then
f (loop (n+1) t) h
else
f (tail_loop init (reverse t)) h
in
loop 0 l
let enum = BatList.enum
let backwards = BatList.backwards
let of_enum = BatList.of_enum
let generate_of_enum = of_enum
let of_backwards = BatList.of_backwards
let front = function
| [] -> None
| h :: t -> Some (t, h)
FIXME
| [] -> None
| h :: t ->
let rec aux acc prev = function
| [] -> Some (reverse acc, prev)
| h :: t -> aux (h :: acc) h t in
aux [h] h t
end
module Deque : SIG =
struct
type 'a t = {front : 'a list; len : int; rear : 'a list}
let empty = {front = []; rear = []; len = 0}
let split_at _ _ = assert false
let append _ _ = assert false
let set _ _ _ = assert false
let get _ _ = assert false
let reverse {front; len; rear} = {front = rear; rear = front; len}
let fold_left f acc {front; rear; len = _} =
let acc = ListTailModCons.fold_left f acc front in
ListTailModCons.fold_right f acc rear
let fold_right f acc {front; rear; len = _} =
let acc = ListTailModCons.fold_left f acc rear in
ListTailModCons.fold_right f acc front
let enum {front; rear} =
BatEnum.append (ListTailModCons.enum front) (ListTailModCons.backwards rear)
let backwards {front; rear} =
BatEnum.append (ListTailModCons.enum rear) (ListTailModCons.backwards front)
let of_enum e =
let l = ListTailModCons.of_backwards e in
{front = []; rear = l; len = List.length l}
let of_backwards e =
let l = ListTailModCons.of_backwards e in
{front = l; rear = []; len = List.length l}
let front q =
match q with
| {front = h :: front; len = len} ->
Some ({ q with front = front ; len = len - 1 }, h)
| {rear = rear; len = len} ->
let rear, rev_front = BatList.split_at (len / 2) rear in
let front = List.rev rev_front in
match front with
| [] -> None
| h :: t ->
Some ({ front = t ;
len = len - 1 ;
rear = rear ;
}, h)
let rear q =
match q with
| {rear = h :: rear; len = len} ->
Some ({ q with rear = rear ; len = len - 1 }, h)
| {front = front; len = len} ->
let front, rev_rear = BatList.split_at (len / 2) front in
let rear = List.rev rev_rear in
match rear with
| [] -> None
| h :: t ->
Some ({ rear = t ;
len = len - 1 ;
front = front ;
}, h)
let cons {front; len; rear} x =
{front = x :: front; len = len + 1; rear = rear}
let snoc {front; len; rear} x =
{front = front; len = len + 1; rear = x :: rear}
let map f {front; rear; len} =
let front = ListTailModCons.map f front in
let rear = List.rev (ListTailModCons.map f (List.rev rear)) in
{front; rear; len}
let generate_of_enum e =
let l = of_enum e in
match front l with
| None -> l
| Some (t, x) -> cons t x
end
module GenFingerTree = struct
type 'a monoid = {
zero : 'a;
combine : 'a -> 'a -> 'a ;
}
exception Empty
type ('a, 'm) node =
| Node2 of 'm * 'a * 'a
| Node3 of 'm * 'a * 'a * 'a
type ('a, 'm) digit =
| One of 'm * 'a
| Two of 'm * 'a * 'a
| Three of 'm * 'a * 'a * 'a
| Four of 'm * 'a * 'a * 'a * 'a
type ('a, 'm) fg =
| Nil
| Single of 'a
| Deep of 'm * ('a, 'm) digit * (('a, 'm) node, 'm) fg * ('a, 'm) digit
let empty = Nil
let singleton a = Single a
let is_empty = function
| Nil -> true
| Single _ | Deep _ -> false
let fold_right_node f acc = function
| Node2 (_, a, b) -> f (f acc b) a
| Node3 (_, a, b, c) -> f (f (f acc c) b) a
let fold_left_node f acc = function
| Node2 (_, a, b) -> f (f acc a) b
| Node3 (_, a, b, c) -> f (f (f acc a) b) c
let fold_right_digit f acc = function
| One (_, a) -> f acc a
| Two (_, a, b) -> f (f acc b) a
| Three (_, a, b, c) -> f (f (f acc c) b) a
| Four (_, a, b, c, d) -> f (f (f (f acc d) c) b) a
let fold_left_digit f acc = function
| One (_, a) -> f acc a
| Two (_, a, b) -> f (f acc a) b
| Three (_, a, b, c) -> f (f (f acc a) b) c
| Four (_, a, b, c, d) -> f (f (f (f acc a) b) c) d
let rec fold_right : 'acc 'a 'm. ('acc -> 'a -> 'acc) -> 'acc -> ('a, 'm) fg -> 'acc = fun f acc -> function
| Nil -> acc
| Single x -> f acc x
| Deep (_, pr, m, sf) ->
let acc = fold_right_digit f acc sf in
let acc = fold_right (fun acc elt -> fold_right_node f acc elt) acc m in
let acc = fold_right_digit f acc pr in
acc
let rec fold_left : 'acc 'a 'm. ('acc -> 'a -> 'acc) -> 'acc -> ('a, 'm) fg -> 'acc = fun f acc -> function
| Nil -> acc
| Single x -> f acc x
| Deep (_, pr, m, sf) ->
let acc = fold_left_digit f acc pr in
let acc = fold_left (fun acc elt -> fold_left_node f acc elt) acc m in
let acc = fold_left_digit f acc sf in
acc
type ('wrapped_type, 'a, 'm) wrap = monoid:'m monoid -> measure:('a -> 'm) -> 'wrapped_type
let measure_node = function
| Node2 (v, _, _)
| Node3 (v, _, _, _) -> v
let measure_digit = function
| One (v, _)
| Two (v, _, _)
| Three (v, _, _, _)
| Four (v, _, _, _, _) -> v
let measure_t_node ~monoid = function
| Nil -> monoid.zero
| Single x -> measure_node x
| Deep (v, _, _, _) -> v
let measure_t ~monoid ~measure = function
| Nil -> monoid.zero
| Single x -> measure x
| Deep (v, _, _, _) -> v
let node2 ~monoid ~measure a b =
Node2 (monoid.combine (measure a) (measure b), a, b)
let node2_node ~monoid a b =
Node2 (monoid.combine (measure_node a) (measure_node b), a, b)
let node3 ~monoid ~measure a b c =
Node3 (monoid.combine (measure a) (monoid.combine (measure b) (measure c)), a, b, c)
let node3_node ~monoid a b c =
Node3 (monoid.combine (measure_node a) (monoid.combine (measure_node b) (measure_node c)), a, b, c)
let deep ~monoid pr m sf =
let v = measure_digit pr in
let v = monoid.combine v (measure_t_node ~monoid m) in
let v = monoid.combine v (measure_digit sf) in
Deep (v, pr, m, sf)
let one_node a =
One (measure_node a, a)
let one ~measure a =
One (measure a, a)
let two_node ~monoid a b =
Two (monoid.combine (measure_node a) (measure_node b), a, b)
let two ~monoid ~measure a b =
Two (monoid.combine (measure a) (measure b), a, b)
let three_node ~monoid a b c =
Three (monoid.combine (monoid.combine (measure_node a) (measure_node b)) (measure_node c), a, b, c)
let three ~monoid ~measure a b c =
Three (monoid.combine (monoid.combine (measure a) (measure b)) (measure c), a, b, c)
let four_node ~monoid a b c d =
Four (monoid.combine (monoid.combine (measure_node a) (measure_node b)) (monoid.combine (measure_node c) (measure_node d)), a, b, c, d)
let four ~monoid ~measure a b c d =
Four (monoid.combine (monoid.combine (measure a) (measure b)) (monoid.combine (measure c) (measure d)), a, b, c, d)
let cons_digit_node ~monoid d x =
match d with
| One (v, a) -> Two (monoid.combine (measure_node x) v, x, a)
| Two (v, a, b) -> Three (monoid.combine (measure_node x) v, x, a, b)
| Three (v, a, b, c) -> Four (monoid.combine (measure_node x) v, x, a, b, c)
| Four _ -> assert false
let cons_digit ~monoid ~measure d x =
match d with
| One (v, a) -> Two (monoid.combine (measure x) v, x, a)
| Two (v, a, b) -> Three (monoid.combine (measure x) v, x, a, b)
| Three (v, a, b, c) -> Four (monoid.combine (measure x) v, x, a, b, c)
| Four _ -> assert false
let snoc_digit_node ~monoid d x =
match d with
| One (v, a) -> Two (monoid.combine v (measure_node x), a, x)
| Two (v, a, b) -> Three (monoid.combine v (measure_node x), a, b, x)
| Three (v, a, b, c) -> Four (monoid.combine v (measure_node x), a, b, c, x)
| Four _ -> assert false
let snoc_digit ~monoid ~measure d x =
match d with
| One (v, a) -> Two (monoid.combine v (measure x), a, x)
| Two (v, a, b) -> Three (monoid.combine v (measure x), a, b, x)
| Three (v, a, b, c) -> Four (monoid.combine v (measure x), a, b, c, x)
| Four _ -> assert false
let rec cons_aux : 'a 'm.
monoid:'m monoid -> (('a, 'm) node, 'm) fg -> ('a, 'm) node -> (('a, 'm) node, 'm) fg =
fun ~monoid t a ->
match t with
| Nil ->
Single a
| Single b ->
deep ~monoid (one_node a) Nil (one_node b)
| Deep (_, Four (_, b, c, d, e), m, sf) ->
deep ~monoid (two_node ~monoid a b) (cons_aux ~monoid m (node3_node ~monoid c d e)) sf
| Deep (v, pr, m, sf) ->
Deep (monoid.combine (measure_node a) v, cons_digit_node ~monoid pr a, m, sf)
let cons ~monoid ~measure t a =
match t with
| Nil ->
Single a
| Single b ->
deep ~monoid (one measure a) Nil (one measure b)
| Deep (_, Four (_, b, c, d, e), m, sf) ->
deep ~monoid (two ~monoid ~measure a b) (cons_aux ~monoid m (node3 ~monoid ~measure c d e)) sf
| Deep (v, pr, m, sf) ->
Deep (monoid.combine (measure a) v, cons_digit ~monoid ~measure pr a, m, sf)
let rec snoc_aux : 'a 'm.
monoid:'m monoid -> (('a, 'm) node, 'm) fg -> ('a, 'm) node -> (('a, 'm) node, 'm) fg =
fun ~monoid t a ->
match t with
| Nil ->
Single a
| Single b ->
deep ~monoid (one_node b) Nil (one_node a)
| Deep (_, pr, m, Four (_, b, c, d, e)) ->
deep ~monoid pr (snoc_aux ~monoid m (node3_node ~monoid b c d)) (two_node ~monoid e a)
| Deep (v, pr, m, sf) ->
Deep (monoid.combine v (measure_node a), pr, m, snoc_digit_node ~monoid sf a)
let snoc ~monoid ~measure t a =
match t with
| Nil ->
Single a
| Single b ->
deep ~monoid (one ~measure b) Nil (one ~measure a)
| Deep (_, pr, m, Four (_, b, c, d, e)) ->
deep ~monoid pr (snoc_aux ~monoid m (node3 ~monoid ~measure b c d)) (two ~measure ~monoid e a)
| Deep (v, pr, m, sf) ->
Deep (monoid.combine v (measure a), pr, m, snoc_digit ~monoid ~measure sf a)
let to_tree_digit_node ~monoid d =
match d with
| One (_, a) -> Single a
| Two (v, a, b) -> Deep (v, one_node a, Nil, one_node b)
| Three (v, a, b, c) -> Deep (v, two_node ~monoid a b, Nil, one_node c)
| Four (v, a, b, c, d) -> Deep (v, three_node ~monoid a b c, Nil, one_node d)
let to_tree_digit ~monoid ~measure d =
match d with
| One (_, a) -> Single a
| Two (v, a, b) -> Deep (v, one ~measure a, Nil, one ~measure b)
| Three (v, a, b, c) -> Deep (v, two ~monoid ~measure a b, Nil, one ~measure c)
| Four (v, a, b, c, d) -> Deep (v, three ~monoid ~measure a b c, Nil, one ~measure d)
let to_tree_list ~monoid ~measure = function
| [] -> Nil
| [a] -> Single a
| [a; b] -> deep ~monoid (one ~measure a) Nil (one ~measure b)
| [a; b; c] -> deep ~monoid (two ~monoid ~measure a b) Nil (one ~measure c)
| [a; b; c; d] -> deep ~monoid (three ~monoid ~measure a b c) Nil (one ~measure d)
| _ -> assert false
let to_digit_node = function
| Node2 (v, a, b) -> Two (v, a, b)
| Node3 (v, a, b, c) -> Three (v, a, b, c)
let to_digit_list ~monoid ~measure = function
| [a] -> one ~measure a
| [a; b] -> two ~monoid ~measure a b
| [a; b; c] -> three ~monoid ~measure a b c
| [a; b; c; d] -> four ~monoid ~measure a b c d
| _ -> assert false
let to_digit_list_node ~monoid = function
| [a] -> one_node a
| [a; b] -> two_node ~monoid a b
| [a; b; c] -> three_node ~monoid a b c
| [a; b; c; d] -> four_node ~monoid a b c d
| _ -> assert false
let head_digit = function
| One (_, a)
| Two (_, a, _)
| Three (_, a, _, _)
| Four (_, a, _, _, _) -> a
let last_digit = function
| One (_, a)
| Two (_, _, a)
| Three (_, _, _, a)
| Four (_, _, _, _, a) -> a
let tail_digit_node ~monoid = function
| One _ -> assert false
| Two (_, _, a) -> one_node a
| Three (_, _, a, b) -> two_node ~monoid a b
| Four (_, _, a, b, c) -> three_node ~monoid a b c
let tail_digit ~monoid ~measure = function
| One _ -> assert false
| Two (_, _, a) -> one ~measure a
| Three (_, _, a, b) -> two ~monoid ~measure a b
| Four (_, _, a, b, c) -> three ~monoid ~measure a b c
let init_digit_node ~monoid = function
| One _ -> assert false
| Two (_, a, _) -> one_node a
| Three (_, a, b, _) -> two_node ~monoid a b
| Four (_, a, b, c, _) -> three_node ~monoid a b c
let init_digit ~monoid ~measure = function
| One _ -> assert false
| Two (_, a, _) -> one ~measure a
| Three (_, a, b, _) -> two ~monoid ~measure a b
| Four (_, a, b, c, _) -> three ~monoid ~measure a b c
type ('a, 'rest) view =
| Vnil
| Vcons of 'a * 'rest
let rec view_left_aux : 'a 'm.
monoid:'m monoid -> (('a, 'm) node, 'm) fg -> (('a, 'm) node, (('a, 'm) node, 'm) fg) view =
fun ~monoid -> function
| Nil -> Vnil
| Single x -> Vcons (x, Nil)
| Deep (_, One (_, a), m, sf) ->
let vcons =
match view_left_aux ~monoid m with
| Vnil -> to_tree_digit_node ~monoid sf
| Vcons (a, m') -> deep ~monoid (to_digit_node a) m' sf in
Vcons (a, vcons)
| Deep (_, pr, m, sf) ->
let vcons = deep ~monoid (tail_digit_node ~monoid pr) m sf in
Vcons (head_digit pr, vcons)
let view_left ~monoid ~measure = function
| Nil -> Vnil
| Single x -> Vcons (x, Nil)
| Deep (_, One (_, a), m, sf) ->
let vcons =
match view_left_aux ~monoid m with
| Vnil -> to_tree_digit ~monoid ~measure sf
| Vcons (a, m') -> deep ~monoid (to_digit_node a) m' sf in
Vcons (a, vcons)
| Deep (_, pr, m, sf) ->
let vcons = deep ~monoid (tail_digit ~monoid ~measure pr) m sf in
Vcons (head_digit pr, vcons)
let rec view_right_aux : 'a 'm.
monoid:'m monoid -> (('a, 'm) node, 'm) fg -> (('a, 'm) node, (('a, 'm) node, 'm) fg) view =
fun ~monoid -> function
| Nil -> Vnil
| Single x -> Vcons (x, Nil)
| Deep (_, pr, m, One (_, a)) ->
let vcons =
match view_right_aux ~monoid m with
| Vnil -> to_tree_digit_node ~monoid pr
| Vcons (a, m') -> deep ~monoid pr m' (to_digit_node a) in
Vcons (a, vcons)
| Deep (_, pr, m, sf) ->
let vcons = deep ~monoid pr m (init_digit_node ~monoid sf) in
Vcons (last_digit sf, vcons)
let view_right ~monoid ~measure = function
| Nil -> Vnil
| Single x -> Vcons (x, Nil)
| Deep (_, pr, m, One (_, a)) ->
let vcons =
match view_right_aux ~monoid m with
| Vnil -> to_tree_digit ~monoid ~measure pr
| Vcons (a, m') -> deep ~monoid pr m' (to_digit_node a) in
Vcons (a, vcons)
| Deep (_, pr, m, sf) ->
let vcons = deep ~monoid pr m (init_digit ~monoid ~measure sf) in
Vcons (last_digit sf, vcons)
let head_exn = function
| Nil -> raise Empty
| Single a -> a
| Deep (_, pr, _, _) -> head_digit pr
let head = function
| Nil -> None
| Single a -> Some a
| Deep (_, pr, _, _) -> Some (head_digit pr)
let last_exn = function
| Nil -> raise Empty
| Single a -> a
| Deep (_, _, _, sf) -> last_digit sf
let last = function
| Nil -> None
| Single a -> Some a
| Deep (_, _, _, sf) -> Some (last_digit sf)
let tail ~monoid ~measure t =
match view_left ~monoid ~measure t with
| Vnil -> None
| Vcons (_, tl) -> Some tl
let tail_exn ~monoid ~measure t =
match view_left ~monoid ~measure t with
| Vnil -> raise Empty
| Vcons (_, tl) -> tl
let front ~monoid ~measure t =
match view_left ~monoid ~measure t with
| Vnil -> None
| Vcons (hd, tl) -> Some (tl, hd)
let front_exn ~monoid ~measure t =
match view_left ~monoid ~measure t with
| Vnil -> raise Empty
| Vcons (hd, tl) -> (tl, hd)
let init ~monoid ~measure t =
match view_right ~monoid ~measure t with
| Vnil -> None
| Vcons (_, tl) -> Some tl
let init_exn ~monoid ~measure t =
match view_right ~monoid ~measure t with
| Vnil -> raise Empty
| Vcons (_, tl) -> tl
let rear ~monoid ~measure t =
match view_right ~monoid ~measure t with
| Vnil -> None
| Vcons (hd, tl) -> Some (tl, hd)
let rear_exn ~monoid ~measure t =
match view_right ~monoid ~measure t with
| Vnil -> raise Empty
| Vcons (hd, tl) -> (tl, hd)
let nodes =
let add_digit_to digit l =
match digit with
| One (_, a) -> a :: l
| Two (_, a, b) -> a :: b :: l
| Three (_, a, b, c) -> a :: b :: c :: l
| Four (_, a, b, c, d) -> a :: b :: c :: d :: l in
let rec nodes_aux ~monoid ~measure ts sf2 =
match ts, sf2 with
| [], One _ -> assert false
| [], Two (_, a, b)
| [a], One (_, b) -> [node2 ~monoid ~measure a b]
| [], Three (_, a, b, c)
| [a], Two (_, b, c)
| [a; b], One (_, c) -> [node3 ~monoid ~measure a b c]
| [], Four (_, a, b, c, d)
| [a], Three (_, b, c, d)
| [a; b], Two (_, c, d)
| [a; b; c], One (_, d) -> [node2 ~monoid ~measure a b; node2 ~monoid ~measure c d]
| a :: b :: c :: ts, _ -> node3 ~monoid ~measure a b c :: nodes_aux ~monoid ~measure ts sf2
| [a], Four (_, b, c, d, e)
| [a; b], Three (_, c, d, e) -> [node3 ~monoid ~measure a b c; node2 ~monoid ~measure d e]
| [a; b], Four (_, c, d, e, f) -> [node3 ~monoid ~measure a b c; node3 ~monoid ~measure d e f] in
fun ~monoid ~measure sf1 ts sf2 ->
let ts = add_digit_to sf1 ts in
nodes_aux ~monoid ~measure ts sf2
let rec app3 : 'a 'm.
monoid:'m monoid -> measure:('a -> 'm) -> ('a, 'm) fg -> 'a list -> ('a, 'm) fg -> ('a, 'm) fg =
fun ~monoid ~measure t1 elts t2 ->
match t1, t2 with
| Nil, _ ->
List.fold_right (fun elt acc -> cons ~monoid ~measure acc elt) elts t2
| _, Nil ->
List.fold_left (fun acc elt -> snoc ~monoid ~measure acc elt) t1 elts
| Single x1, _ ->
cons ~monoid ~measure (List.fold_right (fun elt acc -> cons ~monoid ~measure acc elt) elts t2) x1
| _, Single x2 ->
snoc ~monoid ~measure (List.fold_left (fun acc elt -> snoc ~monoid ~measure acc elt) t1 elts) x2
| Deep (_, pr1, m1, sf1), Deep (_, pr2, m2, sf2) ->
deep ~monoid pr1 (app3 ~monoid ~measure:measure_node m1 (nodes ~monoid ~measure sf1 elts pr2) m2) sf2
let append ~monoid ~measure t1 t2 = app3 ~monoid ~measure t1 [] t2
let reverse_digit_node ~monoid rev_a = function
| One (_, a) -> one_node (rev_a a)
| Two (_, a, b) -> two_node ~monoid (rev_a b) (rev_a a)
| Three (_, a, b, c) -> three_node ~monoid (rev_a c) (rev_a b) (rev_a a)
| Four (_, a, b, c, d) -> four_node ~monoid (rev_a d) (rev_a c) (rev_a b) (rev_a a)
let reverse_digit ~monoid ~measure = function
| One _ as d -> d
| Two (_, a, b) -> two ~monoid ~measure b a
| Three (_, a, b, c) -> three ~monoid ~measure c b a
| Four (_, a, b, c, d) -> four ~monoid ~measure d c b a
let reverse_node_node ~monoid rev_a = function
| Node2 (_, a, b) -> node2_node ~monoid (rev_a b) (rev_a a)
| Node3 (_, a, b, c) -> node3_node ~monoid (rev_a c) (rev_a b) (rev_a a)
let reverse_node ~monoid ~measure = function
| Node2 (_, a, b) -> node2 ~monoid ~measure b a
| Node3 (_, a, b, c) -> node3 ~monoid ~measure c b a
let rec reverse_aux : 'a 'm.
monoid:'m monoid -> (('a, 'm) node -> ('a, 'm) node) -> (('a, 'm) node, 'm) fg -> (('a, 'm) node, 'm) fg =
fun ~monoid reverse_a -> function
| Nil -> Nil
| Single a -> Single (reverse_a a)
| Deep (_, pr, m, sf) ->
let rev_pr = reverse_digit_node ~monoid reverse_a pr in
let rev_sf = reverse_digit_node ~monoid reverse_a sf in
let rev_m = reverse_aux ~monoid (reverse_node_node ~monoid (reverse_a)) m in
deep ~monoid rev_sf rev_m rev_pr
let reverse ~monoid ~measure = function
| Nil
| Single _ as t -> t
| Deep (_, pr, m, sf) ->
let rev_pr = reverse_digit ~monoid ~measure pr in
let rev_sf = reverse_digit ~monoid ~measure sf in
let rev_m = reverse_aux ~monoid (reverse_node ~monoid ~measure) m in
deep ~monoid rev_sf rev_m rev_pr
type ('a, 'rest) split = Split of 'rest * 'a * 'rest
let split_digit ~monoid ~measure p i = function
| One (_, a) -> Split ([], a, [])
| Two (_, a, b) ->
let i' = monoid.combine i (measure a) in
if p i' then Split ([], a, [b]) else
Split ([a], b, [])
| Three (_, a, b, c) ->
let i' = monoid.combine i (measure a) in
if p i' then Split ([], a, [b; c]) else
let i'' = monoid.combine i' (measure b) in
if p i'' then Split ([a], b, [c]) else
Split ([a; b], c, [])
| Four (_, a, b, c, d) ->
let i' = monoid.combine i (measure a) in
if p i' then Split ([], a, [b; c; d]) else
let i'' = monoid.combine i' (measure b) in
if p i'' then Split ([a], b, [c; d]) else
let i''' = monoid.combine i'' (measure c) in
if p i''' then Split ([a; b], c, [d]) else
Split ([a; b; c], d, [])
let deep_left ~monoid ~measure pr m sf =
match pr with
| [] -> (
match view_left ~monoid ~measure:measure_node m with
| Vnil -> to_tree_digit ~monoid ~measure sf
| Vcons (a, m') -> deep ~monoid (to_digit_node a) m' sf
)
| _ ->
deep ~monoid (to_digit_list ~monoid ~measure pr) m sf
let deep_right ~monoid ~measure pr m sf =
match sf with
| [] -> (
match view_right ~monoid ~measure:measure_node m with
| Vnil -> to_tree_digit ~monoid ~measure pr
| Vcons (a, m') -> deep ~monoid pr m' (to_digit_node a)
)
| _ ->
deep ~monoid pr m (to_digit_list ~monoid ~measure sf)
let rec split_tree : 'a 'm.
monoid:'m monoid -> measure:('a -> 'm) -> ('m -> bool) -> 'm -> ('a, 'm) fg -> ('a, ('a, 'm) fg) split =
fun ~monoid ~measure p i -> function
| Nil -> raise Empty
| Single x -> Split (Nil, x, Nil)
| Deep (_, pr, m, sf) ->
let vpr = monoid.combine i (measure_digit pr) in
if p vpr then
let Split (l, x, r) = split_digit ~monoid ~measure p i pr in
Split (to_tree_list ~monoid ~measure l, x, deep_left ~monoid ~measure r m sf)
else
let vm = monoid.combine vpr (measure_t_node ~monoid m) in
if p vm then
let Split (ml, xs, mr) = split_tree ~monoid ~measure:measure_node p vpr m in
let Split (l, x, r) = split_digit ~monoid ~measure p (monoid.combine vpr (measure_t_node ~monoid ml)) (to_digit_node xs) in
Split (deep_right ~monoid ~measure pr ml l, x, deep_left ~monoid ~measure r mr sf)
else
let Split (l, x, r) = split_digit ~monoid ~measure p vm sf in
Split (deep_right ~monoid ~measure pr m l, x, to_tree_list ~monoid ~measure r)
let split ~monoid ~measure f t =
match t with
| Nil -> (Nil, Nil)
| _ ->
if f (measure_t ~monoid ~measure t) then
let Split (l, x, r) = split_tree ~monoid ~measure f monoid.zero t in
(l, cons ~monoid ~measure r x)
else
(t, Nil)
let lookup_digit ~monoid ~measure p i = function
| One (_, a) -> monoid.zero, a
| Two (_, a, b) ->
let m_a = measure a in
let i' = monoid.combine i m_a in
if p i' then monoid.zero, a else m_a, b
| Three (_, a, b, c) ->
let m_a = measure a in
let i' = monoid.combine i m_a in
if p i' then monoid.zero, a else
let m_b = measure b in
let i'' = monoid.combine i' m_b in
if p i'' then m_a, b else monoid.combine m_a m_b, c
| Four (_, a, b, c, d) ->
let m_a = measure a in
let i' = monoid.combine i m_a in
if p i' then monoid.zero, a else
let m_b = measure b in
let i'' = monoid.combine i' m_b in
if p i'' then m_a, b else
let m_c = measure c in
let i''' = monoid.combine i'' m_c in
if p i''' then monoid.combine m_a m_b, c else monoid.combine (monoid.combine m_a m_b) m_c, d
let lookup_node ~monoid ~measure p i = function
| Node2 (_, a, b) ->
let m_a = measure a in
let i' = monoid.combine i m_a in
if p i' then monoid.zero, a else m_a, b
| Node3 (_, a, b, c) ->
let m_a = measure a in
let i' = monoid.combine i m_a in
if p i' then monoid.zero, a else
let m_b = measure b in
let i'' = monoid.combine i' m_b in
if p i'' then m_a, b else monoid.combine m_a m_b, c
let rec lookup_tree : 'a 'm. monoid:'m monoid -> measure:('a -> 'm) -> ('m -> bool) -> 'm -> ('a, 'm) fg -> 'm * 'a =
fun ~monoid ~measure p i -> function
| Nil -> raise Empty
| Single x -> monoid.zero, x
| Deep (_, pr, m, sf) ->
let m_pr = measure_digit pr in
let vpr = monoid.combine i m_pr in
if p vpr then lookup_digit ~monoid ~measure p i pr else
let m_m = measure_t_node ~monoid m in
let vm = monoid.combine vpr m_m in
if p vm then
let v_left, node = lookup_tree ~monoid ~measure:measure_node p vpr m in
let v, x = lookup_node ~monoid ~measure p (monoid.combine vpr v_left) node in
monoid.combine (monoid.combine m_pr v_left) v, x
else
let v, x = lookup_digit ~monoid ~measure p vm sf in
monoid.combine (monoid.combine m_pr m_m) v, x
let lookup ~monoid ~measure p t =
snd (lookup_tree ~monoid ~measure p monoid.zero t)
let enum_digit enum_a d k =
match d with
| One (_, a) ->
enum_a a k
| Two (_, a, b) ->
enum_a a (fun () -> enum_a b k)
| Three (_, a, b, c) ->
enum_a a (fun () -> enum_a b (fun () -> enum_a c k))
| Four (_, a, b, c, d) ->
enum_a a (fun () -> enum_a b (fun () -> enum_a c (fun () -> enum_a d k)))
let enum_digit_backwards enum_a d k =
match d with
| One (_, a) ->
enum_a a k
| Two (_, a, b) ->
enum_a b (fun () -> enum_a a k)
| Three (_, a, b, c) ->
enum_a c (fun () -> enum_a b (fun () -> enum_a a k))
| Four (_, a, b, c, d) ->
enum_a d (fun () -> enum_a c (fun () -> enum_a b (fun () -> enum_a a k)))
let enum_node enum_a n k =
match n with
| Node2 (_, a, b) ->
enum_a a (fun () -> enum_a b k)
| Node3 (_, a, b, c) ->
enum_a a (fun () -> enum_a b (fun () -> enum_a c k))
let enum_node_backwards enum_a n k =
match n with
| Node2 (_, a, b) ->
enum_a b (fun () -> enum_a a k)
| Node3 (_, a, b, c) ->
enum_a c (fun () -> enum_a b (fun () -> enum_a a k))
let enum_base a k = a, k
type 'a iter = unit -> 'a ret
and 'a ret = 'a * 'a iter
type ('input, 'output) iter_into = 'input -> 'output iter -> 'output ret
let rec enum_aux : 'v 'a 'm. ('a, 'v) iter_into -> (('a, 'm) fg, 'v) iter_into =
fun enum_a t k ->
match t with
| Nil -> k ()
| Single a -> enum_a a k
| Deep (_, pr, m, sf) ->
enum_digit enum_a pr (fun () ->
enum_aux (enum_node enum_a) m (fun () ->
enum_digit enum_a sf k
)
)
let enum_cps t = enum_aux enum_base t (fun () -> raise BatEnum.No_more_elements)
let rec enum_aux_backwards : 'v 'a 'm. ('a, 'v) iter_into -> (('a, 'm) fg, 'v) iter_into =
fun enum_a t k ->
match t with
| Nil -> k ()
| Single a -> enum_a a k
| Deep (_, pr, m, sf) ->
enum_digit_backwards enum_a sf (fun () ->
enum_aux_backwards (enum_node_backwards enum_a) m (fun () ->
enum_digit_backwards enum_a pr k
)
)
let enum_cps_backwards t = enum_aux_backwards enum_base t (fun () -> raise BatEnum.No_more_elements)
let enum t =
BatEnum.from_loop
(fun () -> enum_cps t)
(fun k -> k ())
let backwards t =
BatEnum.from_loop
(fun () -> enum_cps_backwards t)
(fun k -> k ())
let of_enum ~monoid ~measure enum =
BatEnum.fold (fun t elt -> snoc ~monoid ~measure t elt) empty enum
let of_backwards ~monoid ~measure enum =
BatEnum.fold (fun t elt -> cons ~monoid ~measure t elt) empty enum
let measure = measure_t
let map ~monoid ~measure f t = (* suboptimal when the measure does not depend on 'a *)
fold_left (fun acc elt -> snoc ~monoid ~measure acc (f elt)) empty t
end
module Sequence : sig
include SIG
val enum2 : 'a t -> 'a BatEnum.t
val fold_left2 : ('acc -> 'a -> 'acc) -> 'acc -> 'a t -> 'acc
val fold_right2 : ('acc -> 'a -> 'acc) -> 'acc -> 'a t -> 'acc
val reverse2 : 'a t -> 'a t
val update2 : 'a t -> int -> ('a -> 'a) -> 'a t
val set2 : 'a t -> int -> 'a -> 'a t
val get2 : 'a t -> int -> 'a
val of_enum2 : 'a BatEnum.t -> 'a t
val map2 : ('a -> 'b) -> 'a t -> 'b t
end =
struct
type nat = int
let nat_plus_monoid = { GenFingerTree.
zero = 0;
combine = (+);
}
let size_measurer = fun _ -> 1
type ('a, 'm) fg = ('a, nat) GenFingerTree.fg
type 'a t = ('a, nat) fg
let empty = GenFingerTree.empty
let fold_left = GenFingerTree.fold_left
let fold_right = GenFingerTree.fold_right
let cons t x = GenFingerTree.cons ~monoid:nat_plus_monoid ~measure:size_measurer t x
let snoc t x = GenFingerTree.snoc ~monoid:nat_plus_monoid ~measure:size_measurer t x
let front t = GenFingerTree.front ~monoid:nat_plus_monoid ~measure:size_measurer t
let rear t = GenFingerTree.rear ~monoid:nat_plus_monoid ~measure:size_measurer t
let append t1 t2 = GenFingerTree.append ~monoid:nat_plus_monoid ~measure:size_measurer t1 t2
let reverse t = GenFingerTree.reverse ~monoid:nat_plus_monoid ~measure:size_measurer t
let measure t = GenFingerTree.measure ~monoid:nat_plus_monoid ~measure:size_measurer t
let size = measure
let split f t = GenFingerTree.split ~monoid:nat_plus_monoid ~measure:size_measurer f t
let split_at t i =
if i < 0 || i >= size t then invalid_arg "Index out of bounds";
split (fun index -> i < index) t
let lookup f t = GenFingerTree.lookup ~monoid:nat_plus_monoid ~measure:size_measurer f t
let get t i =
if i < 0 || i >= size t then invalid_arg "Index out of bounds";
lookup (fun index -> i < index) t
let tail_exn t = GenFingerTree.tail_exn ~monoid:nat_plus_monoid ~measure:size_measurer t
let set t i v =
if i < 0 || i >= size t then invalid_arg "Index out of bounds";
let left, right = split_at t i in
append (snoc left v) (tail_exn right)
let update t i f =
set t i (f (get t i))
let of_enum e = GenFingerTree.of_enum ~monoid:nat_plus_monoid ~measure:size_measurer e
let generate_of_enum = of_enum
let of_backwards e = GenFingerTree.of_backwards ~monoid:nat_plus_monoid ~measure:size_measurer e
let map f t = GenFingerTree.map ~monoid:nat_plus_monoid ~measure:size_measurer f t
let enum = GenFingerTree.enum
let backwards = GenFingerTree.backwards
module Opt = (* optimized *)
struct
open GenFingerTree
let rec height : 'a. int -> ('a, 'm) fg -> int = fun acc -> function
| Nil
| Single _ -> acc
| Deep (_, _, m, _) -> height (acc + 1) m
let height t = height 0 t
let tdigit = 0
let tfg = 1
let telt = 2
type 'a iter = int array
let rec aux_elt stack index depth elt =
if depth = 0 then (
stack.(0) <- index - 2;
stack.(index - 1) <- 42; (*gc*)
Obj.magic elt
) else (
match Obj.magic elt with
| Node2 (_, a, b) ->
stack.(index - 1) <- Obj.magic b;
stack.(index + 0) <- telt lor ((depth - 1) lsl 2);
aux_elt stack (index + 2) (depth - 1) a
| Node3 (_, a, b, c) ->
stack.(index - 1) <- Obj.magic c;
stack.(index + 0) <- telt lor ((depth - 1) lsl 2);
stack.(index + 1) <- Obj.magic b;
stack.(index + 2) <- telt lor ((depth - 1) lsl 2);
aux_elt stack (index + 4) (depth - 1) a
)
let aux_digit stack index depth = function
| One (_, a) ->
aux_elt stack index depth a
| Two (_, a, b) ->
stack.(index - 1) <- Obj.magic b;
stack.(index + 0) <- telt lor (depth lsl 2);
aux_elt stack (index + 2) depth a
| Three (_, a, b, c) ->
stack.(index - 1) <- Obj.magic c;
stack.(index + 0) <- telt lor (depth lsl 2);
stack.(index + 1) <- Obj.magic b;
stack.(index + 2) <- telt lor (depth lsl 2);
aux_elt stack (index + 4) depth a
| Four (_, a, b, c, d) ->
stack.(index - 1) <- Obj.magic d;
stack.(index + 0) <- telt lor (depth lsl 2);
stack.(index + 1) <- Obj.magic c;
stack.(index + 2) <- telt lor (depth lsl 2);
stack.(index + 3) <- Obj.magic b;
stack.(index + 4) <- telt lor (depth lsl 2);
aux_elt stack (index + 6) depth a
let rec aux stack index =
if index = 0 then (
stack.(0) <- 0;
raise BatEnum.No_more_elements
);
let type_ = stack.(index) land 3 in
let depth = stack.(index) lsr 2 in
let value = Obj.magic stack.(index - 1) in
this test comes first because it is
* the one most likely to be true
* making it last results in a 20 % slow down
* the one most likely to be true
* making it last results in a 20% slow down *)
aux_elt stack index depth value
else if type_ = tfg then
match value with
| Nil -> stack.(index - 1) <- 0(*gc*); aux stack (index - 2)
| Single x -> aux_elt stack index depth x
| Deep (_, pr, m, sf) ->
stack.(index - 1) <- Obj.magic sf;
stack.(index + 0) <- tdigit lor (depth lsl 2);
stack.(index + 1) <- Obj.magic m;
stack.(index + 2) <- tfg lor ((depth + 1) lsl 2);
aux_digit stack (index + 4) depth pr
else
aux_digit stack index depth value
let enum_next (stack : int array) =
aux stack stack.(0)
let enum_stack t : _ array =
let stack = Obj.obj (Obj.new_block 0 ((3 * height t + 3 + 1) * 2 + 1)) in
stack.(0) <- 2;
stack.(1) <- Obj.magic t;
stack.(2) <- tfg;
stack
let enum t =
let stack = enum_stack t in
BatEnum.make
~next:(fun () -> enum_next stack)
~count:(fun _ -> assert false)
~clone:(fun () -> assert false)
let rec fold_left_a f depth acc a =
if depth = 0 then
f acc a
else
Obj.magic (
match Obj.magic a with
| Node2 (_, a, b) ->
let acc = fold_left_a f (depth - 1) acc a in
let acc = fold_left_a f (depth - 1) acc b in
acc
| Node3 (_, a, b, c) ->
let acc = fold_left_a f (depth - 1) acc a in
let acc = fold_left_a f (depth - 1) acc b in
let acc = fold_left_a f (depth - 1) acc c in
acc
)
let fold_left_digit f depth acc = function
| One (_, a) ->
fold_left_a f depth acc a
| Two (_, a, b) ->
let acc = fold_left_a f depth acc a in
let acc = fold_left_a f depth acc b in
acc
| Three (_, a, b, c) ->
let acc = fold_left_a f depth acc a in
let acc = fold_left_a f depth acc b in
let acc = fold_left_a f depth acc c in
acc
| Four (_, a, b, c, d) ->
let acc = fold_left_a f depth acc a in
let acc = fold_left_a f depth acc b in
let acc = fold_left_a f depth acc c in
let acc = fold_left_a f depth acc d in
acc
let rec fold_left f depth acc = function
| Nil ->
acc
| Single a ->
fold_left_a f depth acc a
| Deep (_, pr, m, sf) ->
let acc = fold_left_digit f depth acc pr in
let acc = fold_left f (depth + 1) acc (Obj.magic m) in
let acc = fold_left_digit f depth acc sf in
acc
let fold_left f acc t =
fold_left f 0 acc t
let rec fold_right_a f depth acc a =
if depth = 0 then
f acc a
else
Obj.magic (
match Obj.magic a with
| Node2 (_, a, b) ->
let acc = fold_right_a f (depth - 1) acc b in
let acc = fold_right_a f (depth - 1) acc a in
acc
| Node3 (_, a, b, c) ->
let acc = fold_right_a f (depth - 1) acc c in
let acc = fold_right_a f (depth - 1) acc b in
let acc = fold_right_a f (depth - 1) acc a in
acc
)
let fold_right_digit f depth acc = function
| One (_, a) ->
fold_right_a f depth acc a
| Two (_, a, b) ->
let acc = fold_right_a f depth acc b in
let acc = fold_right_a f depth acc a in
acc
| Three (_, a, b, c) ->
let acc = fold_right_a f depth acc c in
let acc = fold_right_a f depth acc b in
let acc = fold_right_a f depth acc a in
acc
| Four (_, a, b, c, d) ->
let acc = fold_right_a f depth acc d in
let acc = fold_right_a f depth acc c in
let acc = fold_right_a f depth acc b in
let acc = fold_right_a f depth acc a in
acc
let rec fold_right f depth acc = function
| Nil ->
acc
| Single a ->
fold_right_a f depth acc a
| Deep (_, pr, m, sf) ->
let acc = fold_right_digit f depth acc sf in
let acc = fold_right f (depth + 1) acc (Obj.magic m) in
let acc = fold_right_digit f depth acc pr in
acc
let fold_right f acc t =
fold_right f 0 acc t
end
let enum2 = Opt.enum
let fold_left2 = Opt.fold_left
let fold_right2 = Opt.fold_right
specialized for int
struct
open GenFingerTree
let measure_t_node = function
| Nil -> 0
| Single x -> measure_node x
| Deep (v, _, _, _) -> v
let measure_t = function
| Nil -> 0
| Single _ -> 1
| Deep (v, _, _, _) -> v
let node2 a b =
Node2 (2, a, b)
let node2_node a b =
Node2 (measure_node a + measure_node b, a, b)
let node3 a b c =
Node3 (3, a, b, c)
let node3_node a b c =
Node3 (measure_node a + measure_node b + measure_node c, a, b, c)
let deep pr m sf =
Deep (measure_digit pr + measure_t_node m + measure_digit sf, pr, m, sf)
let one a =
One (1, a)
let one_node a =
One (measure_node a, a)
let two a b =
Two (2, a, b)
let two_node a b =
Two (measure_node a + measure_node b, a, b)
let three a b c =
Three (3, a, b, c)
let three_node a b c =
Three (measure_node a + measure_node b + measure_node c, a, b, c)
let four a b c d =
Four (4, a, b, c, d)
let four_node a b c d =
Four (measure_node a + measure_node b + measure_node c + measure_node d, a, b, c, d)
let rec reverse_a depth a =
if depth = 0 then a else
Obj.magic (
match Obj.magic a with
| Node2 (v, a, b) ->
Node2 (v, reverse_a (depth - 1) b, reverse_a (depth - 1) a)
| Node3 (v, a, b, c) ->
Node3 (v, reverse_a (depth - 1) c, reverse_a (depth - 1) b, reverse_a (depth - 1) a)
)
let reverse_digit depth = function
| One (v, a) ->
One (v, reverse_a depth a)
| Two (v, a, b) ->
Two (v, reverse_a depth b, reverse_a depth a)
| Three (v, a, b, c) ->
Three (v, reverse_a depth c, reverse_a depth b, reverse_a depth a)
| Four (v, a, b, c, d) ->
Four (v, reverse_a depth d, reverse_a depth c, reverse_a depth b, reverse_a depth a)
let rec reverse depth = function
| Nil -> Nil
| Single a -> Single (reverse_a depth a)
| Deep (v, pr, m, sf) ->
let rev_pr = reverse_digit depth pr in
let rev_sf = reverse_digit depth sf in
let rev_m = Obj.magic (reverse (depth + 1) (Obj.magic m)) in
Deep (v, rev_sf, rev_m, rev_pr)
let reverse t = reverse 0 t
let get_digit d i =
match d with
| One (_, a) -> a
| Two (_, a, b) -> if i = 0 then a else b
| Three (_, a, b, c) -> if i = 0 then a else if i = 1 then b else c
| Four (_, a, b, c, d) -> if i < 2 then (if i = 0 then a else b) else (if i = 2 then c else d)
let rec get_a depth a i =
if depth = 1 then (
match Obj.magic a with
| Node2 (_, a, b) -> if i = 0 then a else b
| Node3 (_, a, b, c) -> if i = 0 then a else if i = 1 then b else c
) else (
match Obj.magic a with
| Node2 (_, a, b) ->
if i < measure_node a then get_a (depth - 1) a i else
let i = i - measure_node a in
get_a (depth - 1) b i
| Node3 (_, a, b, c) ->
if i < measure_node a then get_a (depth - 1) a i else
let i = i - measure_node a in
if i < measure_node b then get_a (depth - 1) b i else
let i = i - measure_node b in
get_a (depth - 1) c i
)
let get_digit_node depth d i =
match d with
| One (_, a) ->
get_a depth a i
| Two (_, a, b) ->
if i < measure_node a then get_a depth a i else
let i = i - measure_node a in
get_a depth b i
| Three (_, a, b, c) ->
if i < measure_node a then get_a depth a i else
let i = i - measure_node a in
if i < measure_node b then get_a depth b i else
let i = i - measure_node b in
get_a depth c i
| Four (_, a, b, c, d) ->
if i < measure_node a then get_a depth a i else
let i = i - measure_node a in
if i < measure_node b then get_a depth b i else
let i = i - measure_node b in
if i < measure_node c then get_a depth c i else
let i = i - measure_node c in
get_a depth d i
let rec get_aux depth t i =
match t with
| Nil -> assert false
| Single v -> get_a depth v i
| Deep (_, pr, m, sf) ->
if i < measure_digit pr then
get_digit_node depth pr i
else
let i = i - measure_digit pr in
if i < measure_t_node m then
get_aux (depth + 1) (Obj.magic m) i
else
let i = i - measure_t_node m in
get_digit_node depth sf i
let check_bounds t i =
if i < 0 || i >= size t then invalid_arg "Index out of bounds"
let get t i =
check_bounds t i;
match t with
| Nil -> assert false
| Single v -> v
| Deep (_, pr, m, sf) ->
if i < measure_digit pr then
get_digit pr i
else
let i = i - measure_digit pr in
if i < measure_t_node m then
get_aux 1 m i
else
let i = i - measure_t_node m in
get_digit sf i
let update_digit d i f =
match d with
| One (v, a) ->
One (v, f a)
| Two (v, a, b) ->
if i = 0 then Two (v, f a, b) else
Two (v, a, f b)
| Three (v, a, b, c) ->
if i = 0 then Three (v, f a, b, c) else
if i = 1 then Three (v, a, f b, c) else
Three (v, a, b, f c)
| Four (v, a, b, c, d) ->
if i < 2 then (
if i = 0 then Four (v, f a, b, c, d) else Four (v, a, f b, c, d)
) else (
if i = 2 then Four (v, a, b, f c, d) else Four (v, a, b, c, f d)
)
let rec update_a depth a i f =
if depth = 1 then
Obj.magic (
match Obj.magic a with
| Node2 (v, a, b) ->
if i = 0 then Node2 (v, f a, b) else
Node2 (v, a, f b)
| Node3 (v, a, b, c) ->
if i = 0 then Node3 (v, f a, b, c) else
if i = 1 then Node3 (v, a, f b, c) else
Node3 (v, a, b, f c)
)
else
Obj.magic (
match Obj.magic a with
| Node2 (v, a, b) ->
if i < measure_node a then Node2 (v, update_a (depth - 1) a i f, b) else
let i = i - measure_node a in
Node2 (v, a, update_a (depth - 1) b i f)
| Node3 (v, a, b, c) ->
if i < measure_node a then Node3 (v, update_a (depth - 1) a i f, b, c) else
let i = i - measure_node a in
if i < measure_node b then Node3 (v, a, update_a (depth - 1) b i f, c) else
let i = i - measure_node b in
Node3 (v, a, b, update_a (depth - 1) c i f)
)
let update_digit_node depth d i f =
match d with
| One (v, a) ->
One (v, update_a depth a i f)
| Two (v, a, b) ->
if i < measure_node a then Two (v, update_a depth a i f, b) else
let i = i - measure_node a in
Two (v, a, update_a depth b i f)
| Three (v, a, b, c) ->
if i < measure_node a then Three (v, update_a depth a i f, b, c) else
let i = i - measure_node a in
if i < measure_node b then Three (v, a, update_a depth b i f, c) else
let i = i - measure_node b in
Three (v, a, b, update_a depth c i f)
| Four (v, a, b, c, d) ->
if i < measure_node a then Four (v, update_a depth a i f, b, c, d) else
let i = i - measure_node a in
if i < measure_node b then Four (v, a, update_a depth b i f, c, d) else
let i = i - measure_node b in
if i < measure_node c then Four (v, a, b, update_a depth c i f, d) else
let i = i - measure_node c in
Four (v, a, b, c, update_a depth d i f)
let rec update_aux depth t i f =
match t with
| Nil -> assert false
| Single v -> Single (update_a depth v i f)
| Deep (v, pr, m, sf) ->
if i < measure_digit pr then
Deep (v, update_digit_node depth pr i f, m, sf)
else
let i = i - measure_digit pr in
if i < measure_t_node m then
Deep (v, pr, Obj.magic (update_aux (depth + 1) (Obj.magic m) i f), sf)
else
let i = i - measure_t_node m in
Deep (v, pr, m, update_digit_node depth sf i f)
let update t i f =
check_bounds t i;
match t with
| Nil -> assert false
| Single v -> Single (f v)
| Deep (v, pr, m, sf) ->
if i < measure_digit pr then
Deep (v, update_digit pr i f, m, sf)
else
let i = i - measure_digit pr in
if i < measure_t_node m then
Deep (v, pr, update_aux 1 m i f, sf)
else
let i = i - measure_t_node m in
Deep (v, pr, m, update_digit sf i f)
let set t i v =
update t i (fun _ -> v)
let rec get_node depth enum =
if depth = 1 then
let v1 = BatEnum.get_exn enum in
let v2 = BatEnum.get_exn enum in
let v3 = BatEnum.get_exn enum in
Obj.magic (node3 v1 v2 v3)
else
let v1 = get_node (depth - 1) enum in
let v2 = get_node (depth - 1) enum in
let v3 = get_node (depth - 1) enum in
Obj.magic (node3_node v1 v2 v3)
let rec get_digit_node depth enum n =
match n with
| 1 ->
let v1 = get_node depth enum in
one_node v1
| 2 ->
let v1 = get_node depth enum in
let v2 = get_node depth enum in
two_node v1 v2
| 3 ->
let v1 = get_node depth enum in
let v2 = get_node depth enum in
let v3 = get_node depth enum in
three_node v1 v2 v3
| 4 ->
let v1 = get_node depth enum in
let v2 = get_node depth enum in
let v3 = get_node depth enum in
let v4 = get_node depth enum in
four_node v1 v2 v3 v4
| _ -> assert false
let rec fast_of_enum_aux depth enum n =
if n = 0 then Nil else
if n = 1 then Single (get_node depth enum) else
let n_rec = if n <= 8 then 0 else (n - 8 + 3 - 1) / 3 in
let n_left = (n - n_rec * 3) / 2 in
let n_right = (n - n_rec * 3 + 1) / 2 in
let pr = get_digit_node depth enum n_left in
let m = Obj.magic (fast_of_enum_aux (depth + 1) enum n_rec) in
let sf = get_digit_node depth enum n_right in
deep pr m sf
let rec get_digit enum n =
match n with
| 1 ->
let v1 = BatEnum.get_exn enum in
one v1
| 2 ->
let v1 = BatEnum.get_exn enum in
let v2 = BatEnum.get_exn enum in
two v1 v2
| 3 ->
let v1 = BatEnum.get_exn enum in
let v2 = BatEnum.get_exn enum in
let v3 = BatEnum.get_exn enum in
three v1 v2 v3
| 4 ->
let v1 = BatEnum.get_exn enum in
let v2 = BatEnum.get_exn enum in
let v3 = BatEnum.get_exn enum in
let v4 = BatEnum.get_exn enum in
four v1 v2 v3 v4
| _ -> assert false
let fast_of_enum enum n =
if n = 0 then Nil else
if n = 1 then Single (BatEnum.get_exn enum) else
let n_rec = if n <= 8 then 0 else (n - 8 + 3 - 1) / 3 in
let n_left = (n - n_rec * 3) / 2 in
let n_right = (n - n_rec * 3 + 1) / 2 in
let pr = get_digit enum n_left in
let m = fast_of_enum_aux 1 enum n_rec in
let sf = get_digit enum n_right in
Deep (n, pr, m, sf)
let rec get_node depth a i =
if depth = 1 then
let v1 = BatDynArray.unsafe_get a !i in
let v2 = BatDynArray.unsafe_get a (!i + 1) in
let v3 = BatDynArray.unsafe_get a (!i + 2) in
i := !i + 3;
Obj.magic (node3 v1 v2 v3)
else
let v1 = get_node (depth - 1) a i in
let v2 = get_node (depth - 1) a i in
let v3 = get_node (depth - 1) a i in
Obj.magic (node3_node v1 v2 v3)
let rec get_digit_node depth a i n =
match n with
| 1 ->
let v1 = get_node depth a i in
one_node v1
| 2 ->
let v1 = get_node depth a i in
let v2 = get_node depth a i in
two_node v1 v2
| 3 ->
let v1 = get_node depth a i in
let v2 = get_node depth a i in
let v3 = get_node depth a i in
three_node v1 v2 v3
| 4 ->
let v1 = get_node depth a i in
let v2 = get_node depth a i in
let v3 = get_node depth a i in
let v4 = get_node depth a i in
four_node v1 v2 v3 v4
| _ -> assert false
let rec fast_of_enum_aux depth a i n =
if n = 0 then Nil else
if n = 1 then Single (get_node depth a i) else
let n_rec = if n <= 8 then 0 else (n - 8 + 3 - 1) / 3 in
let n_left = (n - n_rec * 3) / 2 in
let n_right = (n - n_rec * 3 + 1) / 2 in
let pr = get_digit_node depth a i n_left in
let m = Obj.magic (fast_of_enum_aux (depth + 1) a i n_rec) in
let sf = get_digit_node depth a i n_right in
deep pr m sf
let rec get_digit a i n =
match n with
| 1 ->
let v1 = BatDynArray.unsafe_get a !i in
i := !i + 1;
one v1
| 2 ->
let v1 = BatDynArray.unsafe_get a !i in
let v2 = BatDynArray.unsafe_get a (!i + 1) in
i := !i + 2;
two v1 v2
| 3 ->
let v1 = BatDynArray.unsafe_get a !i in
let v2 = BatDynArray.unsafe_get a (!i + 1) in
let v3 = BatDynArray.unsafe_get a (!i + 2) in
i := !i + 3;
three v1 v2 v3
| 4 ->
let v1 = BatDynArray.unsafe_get a !i in
let v2 = BatDynArray.unsafe_get a (!i + 1) in
let v3 = BatDynArray.unsafe_get a (!i + 2) in
let v4 = BatDynArray.unsafe_get a (!i + 3) in
i := !i + 4;
four v1 v2 v3 v4
| _ -> assert false
let fast_of_enum_array a i n =
if n = 0 then Nil else
if n = 1 then Single (BatDynArray.unsafe_get a 0) else
let n_rec = if n <= 8 then 0 else (n - 8 + 3 - 1) / 3 in
let n_left = (n - n_rec * 3) / 2 in
let n_right = (n - n_rec * 3 + 1) / 2 in
let pr = get_digit a i n_left in
let m = fast_of_enum_aux 1 a i n_rec in
let sf = get_digit a i n_right in
Deep (n, pr, m, sf)
let of_enum enum =
if BatEnum.fast_count enum then
fast_of_enum enum (BatEnum.count enum)
else
let a = BatDynArray.make 10 in
try while true do BatDynArray.add a (BatEnum.get_exn enum) done;
assert false
with BatEnum.No_more_elements ->
fast_of_enum_array a (ref 0) (BatDynArray.length a)
let rec map_a f depth a =
if depth = 0 then
f a
else
Obj.magic (
match Obj.magic a with
| Node2 (v, a, b) ->
let a = map_a f (depth - 1) a in
let b = map_a f (depth - 1) b in
Node2 (v, a, b)
| Node3 (v, a, b, c) ->
let a = map_a f (depth - 1) a in
let b = map_a f (depth - 1) b in
let c = map_a f (depth - 1) c in
Node3 (v, a, b, c)
)
let map_digit f depth = function
| One (v, a) ->
let a = map_a f depth a in
One (v, a)
| Two (v, a, b) ->
let a = map_a f depth a in
let b = map_a f depth b in
Two (v, a, b)
| Three (v, a, b, c) ->
let a = map_a f depth a in
let b = map_a f depth b in
let c = map_a f depth c in
Three (v, a, b, c)
| Four (v, a, b, c, d) ->
let a = map_a f depth a in
let b = map_a f depth b in
let c = map_a f depth c in
let d = map_a f depth d in
Four (v, a, b, c, d)
let rec map f depth = function
| Nil ->
Nil
| Single a ->
let a = map_a f depth a in
Single a
| Deep (v, pr, m, sf) ->
let pr = map_digit f depth pr in
let m = Obj.magic (map f (depth + 1) (Obj.magic m)) in
let sf = map_digit f depth sf in
Deep (v, pr, m, sf)
let map f t =
map f 0 t
end
let reverse2 = Spec.reverse
let update2 = Spec.update
let set2 = Spec.set
let get2 = Spec.get
let of_enum2 = Spec.of_enum
let map2 = Spec.map
end
SEARCHME
let rec memory_size acc t =
let tag = Obj.tag t in
if tag = Obj.int_tag then acc
else if tag < Obj.no_scan_tag &&
tag <> Obj.lazy_tag &&
tag <> Obj.closure_tag &&
tag <> Obj.object_tag &&
tag <> Obj.infix_tag &&
tag <> Obj.forward_tag &&
tag <> Obj.abstract_tag &&
tag <> Obj.string_tag &&
tag <> Obj.double_tag &&
tag <> Obj.double_array_tag &&
tag <> Obj.custom_tag &&
tag <> Obj.final_tag &&
tag <> Obj.out_of_heap_tag &&
tag <> Obj.unaligned_tag then
let size = Obj.size t in
let acc = ref (acc + size + 1) in
for i = 0 to size - 2 do
acc := memory_size !acc (Obj.field t i)
done;
memory_size !acc (Obj.field t (size - 1))
else
assert false
let memory_size a = memory_size 0 (Obj.repr a)
let bench_size size s =
let module M = (val s : SIG) in
let rec aux stack = function
| 0 -> stack
| n -> aux (M.cons stack n) (n - 1) in
let s = aux M.empty size in
memory_size s
let bench_cons_front size s n =
for i = 0 to n do
let module M = (val s : SIG) in
let rec aux stack = function
| 0 -> stack
| n -> aux (M.cons stack n) (n - 1) in
let s = aux M.empty size in
let rec aux stack =
match M.front stack with
| None -> ()
| Some (stack, _) -> aux stack in
aux s
done
let bench_map size s =
(* not benching the construction time, just the mapping time *)
let module M = (val s : SIG) in
let rec aux stack = function
| 0 -> stack
| n -> aux (M.cons stack n) (n - 1) in
let s = aux M.empty size in
fun n ->
for i = 0 to n do
ignore (M.map (fun x -> x + 1) s)
done
let bench_snoc_front size s n =
for i = 0 to n do
let module M = (val s : SIG) in
let rec aux stack = function
| 0 -> stack
| n -> aux (M.snoc stack n) (n - 1) in
let s = aux M.empty size in
let rec aux stack =
match M.front stack with
| None -> ()
| Some (stack, _) -> aux stack in
aux s
done
let bench_snoc_front_rear size s n =
for i = 0 to n do
let module M = (val s : SIG) in
let rec aux stack = function
| 0 -> stack
| n -> aux (M.snoc stack n) (n - 1) in
let s = aux M.empty size in
let rec aux stack =
match M.front stack with
| None -> ()
| Some (stack, _) ->
match M.rear stack with
| None -> ()
| Some (stack, _) -> aux stack in
aux s
done
let bench_enum1 size s =
let a = BatArray.Labels.init size ~f:(fun i -> i) in
let e = BatArray.enum a in
let module M = (val s : SIG) in
let t = M.generate_of_enum e in
fun n ->
for i = 0 to n do
let e = M.enum t in
try while true; do ignore (BatEnum.get_exn e); done
with BatEnum.No_more_elements -> ()
done
let bench_of_enum1 size s n =
let a = BatArray.Labels.init size ~f:(fun i -> i) in
for i = 0 to n do
let e = BatArray.enum a in
let module M = (val s : SIG) in
ignore (M.of_enum e)
done
let bench_fold_left size s =
let a = BatArray.Labels.init size ~f:(fun i -> i) in
let e = BatArray.enum a in
let module M = (val s : SIG) in
let t = M.generate_of_enum e in
fun n ->
for i = 0 to n do
M.fold_left (fun () _ -> ()) () t;
done
let bench_fold_right size s =
let a = BatArray.Labels.init size ~f:(fun i -> i) in
let e = BatArray.enum a in
let module M = (val s : SIG) in
let t = M.generate_of_enum e in
fun n ->
for i = 0 to n do
M.fold_right (fun () _ -> ()) () t;
done
let bench_reverse size s =
let a = BatArray.Labels.init size ~f:(fun i -> i) in
let e = BatArray.enum a in
let module M = (val s : SIG) in
let t = M.generate_of_enum e in
fun n ->
for i = 0 to n do
ignore (M.reverse t)
done
let bench_append size s =
let a = BatArray.Labels.init size ~f:(fun i -> i) in
let e = BatArray.enum a in
let module M = (val s : SIG) in
let t = M.generate_of_enum e in
fun n ->
for i = 0 to n do
ignore (M.append t t)
done
let bench_get size s =
let a = BatArray.Labels.init size ~f:(fun i -> i) in
let e = BatArray.enum a in
let module M = (val s : SIG) in
let t = M.generate_of_enum e in
fun n ->
for i = 0 to n do
for i = 0 to size - 1 do
ignore (M.get t i)
done
done
let bench_set size s =
let a = BatArray.Labels.init size ~f:(fun i -> i) in
let e = BatArray.enum a in
let module M = (val s : SIG) in
let t = M.generate_of_enum e in
fun n ->
for i = 0 to n do
let t = ref t in
for i = 0 to size - 1 do
t := M.set !t i 0
done
done
module ListTailCore : SIG = struct include ListTail let map = map2 end
module ListTailModConsOpt : SIG = struct include ListTailModCons let map = map2 end
module FgGen : SIG = Sequence
module FgGenOpt : SIG = struct include Sequence let enum = enum2 let fold_left = fold_left2 let fold_right = fold_right2 end
module FgSpec : SIG = struct include Sequence let reverse = reverse2 let update = update2 let set = set2 let get = get2 let of_enum = of_enum2 let map = map2 end
let sizes = [
1; 10; 100; 1_000; 10_000; 100_000;
]
let print_readings ~title size l =
if size = BatList.hd sizes then (
Printf.printf "#%s size" title;
BatList.iter (fun r ->
Printf.printf "\t%s" r.Bench.desc;
) l;
Printf.printf "\n"
);
Printf.printf "%d" size;
BatList.iter (fun r ->
Printf.printf "\t%.3f" (1_000_000_000. *. r.Bench.mean.Bench.Bootstrap.point /. float size)
) l;
Printf.printf "\n"
let bench ~title ?(deque=false) ?(list=false) ?(map=false) bench =
fun size ->
let core = if map then [
"ListTailModConsOpt", bench size (module ListTailModConsOpt : SIG);
"ListTailCore", bench size (module ListTailCore : SIG);
] else [] in
let lists = if list then [
"ListOverflow", bench size (module ListOverflow : SIG);
"ListTail", bench size (module ListTail : SIG);
"ListTailModCons", bench size (module ListTailModCons : SIG);
] @ core else [
] in
let deque = if deque then [
"Deque", bench size (module Deque : SIG);
] else [] in
let readings =
Bench.bench_n (lists @ deque @ [
"FgGen", bench size (module FgGen : SIG);
"FgGenOpt", bench size (module FgGenOpt : SIG);
"FgSpec", bench size (module FgSpec : SIG);
"Vect", bench size (module Vect : SIG);
]) in
fun () -> print_readings ~title size readings
let heap_size ~title size =
let assoc = [
"ListOverflow", bench_size size (module ListOverflow : SIG);
"Deque", bench_size size (module Deque : SIG);
"FgGen", bench_size size (module FgGen : SIG);
"Vect", bench_size size (module Vect : SIG);
] in
fun () ->
if size = BatList.hd sizes then (
Printf.printf "#%s size" title;
BatList.iter (fun (name,_) -> Printf.printf "\t%s" name) assoc;
Printf.printf "\n"
);
Printf.printf "%d" size;
BatList.iter (fun (_,size) -> Printf.printf "\t%d" size) assoc;
Printf.printf "\n"
let benches = [
"cons_front", bench ~list:true ~deque:true bench_cons_front;
"snoc_front", bench ~deque:true bench_snoc_front;
"snoc_front_rear", bench ~deque:true bench_snoc_front_rear;
"size", heap_size;
"map", bench ~deque:true ~list:true ~map:true bench_map;
"of_enum", bench ~list:true ~deque:true bench_of_enum1;
"enum", bench ~list:true ~deque:true bench_enum1;
"fold_left", bench ~list:true ~deque:true bench_fold_left;
"fold_right", bench ~list:true ~deque:true bench_fold_right;
"reverse", bench ~list:true bench_reverse;
"append", bench bench_append;
"set", bench bench_set;
"get", bench bench_get;
]
let () =
Bench.config.Bench.samples <- 100;
Array.iter (fun s ->
try
let f = BatList.assoc s benches in
let printers = BatList.map (f ~title:s) sizes in
BatList.iter (fun f -> f ()) printers;
Printf.printf "\n"
with Not_found ->
Printf.printf "`%s' is not a valid bench name\nThe possibilities are: " s;
BatList.iter (fun (name,_) -> Printf.printf "%s, " name) benches;
Printf.printf "\n";
exit 1
) (Array.sub Sys.argv 1 (Array.length Sys.argv - 1))
| null | https://raw.githubusercontent.com/argp/bap/2f60a35e822200a1ec50eea3a947a322b45da363/batteries/benchsuite/sequence.ml | ocaml | ocamlbuild benchsuite/sequence.native -- snoc_front | tee >(./plot)
take, drop
copy pasted from core lib
suboptimal when the measure does not depend on 'a
optimized
gc
gc
not benching the construction time, just the mapping time |
module type SIG = sig
type 'a t
val empty : 'a t
val cons : 'a t -> 'a -> 'a t
val front : 'a t -> ('a t * 'a) option
val map : ('a -> 'b) -> 'a t -> 'b t
val snoc : 'a t -> 'a -> 'a t
val rear : 'a t -> ('a t * 'a) option
val of_enum : 'a BatEnum.t -> 'a t
val enum : 'a t -> 'a BatEnum.t
val of_backwards : 'a BatEnum.t -> 'a t
val backwards : 'a t -> 'a BatEnum.t
val fold_left : ('acc -> 'a -> 'acc) -> 'acc -> 'a t -> 'acc
val fold_right : ('acc -> 'a -> 'acc) -> 'acc -> 'a t -> 'acc
val reverse : 'a t -> 'a t
val get : 'a t -> int -> 'a
val set : 'a t -> int -> 'a -> 'a t
val append : 'a t -> 'a t -> 'a t
val split_at : 'a t -> int -> 'a t * 'a t
val generate_of_enum : 'a BatEnum.t -> 'a t
end
module Vect : SIG =
struct
type 'a t = 'a BatVect.t
let empty = BatVect.empty
let cons t x = BatVect.prepend x t
let snoc t x = BatVect.append x t
let map = BatVect.map
let front t =
if BatVect.is_empty t then None
else
let n = BatVect.length t in
Some (BatVect.sub t 0 (n - 1), BatVect.get t 0)
let rear t =
if BatVect.is_empty t then None
else
let n = BatVect.length t in
Some (BatVect.sub t 1 (n - 1), BatVect.get t (n - 1))
let of_enum = BatVect.of_enum
let enum = BatVect.enum
let of_backwards = BatVect.of_backwards
let backwards = BatVect.backwards
let fold_left = BatVect.fold_left
let fold_right f acc t = BatVect.fold_right (fun acc elt -> f elt acc) t acc
let reverse _ = assert false
let get = BatVect.get
let set = BatVect.set
let append = BatVect.concat
let split_at t n =
(BatVect.sub t 0 n, BatVect.sub t n (BatVect.length t - n))
let generate_of_enum = of_enum
end
module ListOverflow : SIG with type 'a t = 'a list =
struct
type 'a t = 'a list
let empty = []
let length l =
let rec aux acc = function
| [] -> acc
| _ :: t -> aux (acc + 1) t in
aux 0 l
let cons t x = x :: t
let front = function
| [] -> None
| h :: t -> Some (t, h)
let rec map f = function
| [] -> []
| h :: t ->
let h = f h in
let t = map f t in
h :: t
let rec rev_append l1 l2 =
match l1 with
| [] -> l2
| h1 :: t1 -> rev_append t1 (h1 :: l2)
let reverse l = rev_append l []
let rec snoc t x =
match t with
| [] -> [x]
| h :: t -> h :: snoc t x
let rear = function
| [] -> None
| h :: t ->
let rec aux acc prev = function
| [] -> Some (reverse acc, prev)
| h :: t -> aux (h :: acc) h t in
aux [h] h t
let rec of_enum e =
match BatEnum.get e with
| None -> []
| Some h -> h :: of_enum e
let generate_of_enum = of_enum
let of_backwards e =
let rec aux acc e =
match BatEnum.get e with
| None -> acc
| Some h -> aux (h :: acc) e in
aux [] e
let enum l =
let rec make lr count =
BatEnum.make
~next:(fun () ->
match !lr with
| [] -> raise BatEnum.No_more_elements
| h :: t ->
decr count;
lr := t;
h
)
~count:(fun () ->
if !count < 0 then count := length !lr;
!count
)
~clone:(fun () ->
make (ref !lr) (ref !count)
) in
make (ref l) (ref (-1))
let backwards l = enum (reverse l)
let rec fold_left f acc = function
| [] -> acc
| h :: t -> fold_left f (f acc h) t
let rec fold_right f acc l =
match l with
| [] -> acc
| h :: t -> f (fold_right f acc t) h
let rec get t i =
match i, t with
| _, [] -> invalid_arg "Index out of bounds"
| 0, h :: _ -> h
| _, _ :: t -> get t (i - 1)
let rec set t i v =
match i, t with
| _, [] -> invalid_arg "Index out of bounds"
| 0, h :: t -> v :: t
| _, h :: t -> h :: set t (i - 1) v
let rec append l1 l2 =
match l1 with
| [] -> l2
| h :: t -> h :: append t l2
let split_at l i =
let rec aux acc i l =
match i, l with
| 0, _ -> reverse acc, l
| _, [] -> invalid_arg "Index out of bounds"
| _, h :: t -> aux (h :: acc) (i - 1) t in
aux [] 0 l
end
module ListTail : sig
include SIG with type 'a t = 'a list
val map2 : ('a -> 'b) -> 'a list -> 'b list
end =
struct
type 'a t = 'a list
let empty = []
let length l =
let rec aux acc = function
| [] -> acc
| _ :: t -> aux (acc + 1) t in
aux 0 l
let cons t x = x :: t
let front = function
| [] -> None
| h :: t -> Some (t, h)
let rec rev_append l1 l2 =
match l1 with
| [] -> l2
| h1 :: t1 -> rev_append t1 (h1 :: l2)
let reverse l = rev_append l []
let map f l =
let rec aux f acc = function
| [] -> reverse acc
| h :: t -> aux f (f h :: acc) t in
aux f [] l
let rec count_map ~f l ctr =
match l with
| [] -> []
| [x1] ->
let f1 = f x1 in
[f1]
| [x1; x2] ->
let f1 = f x1 in
let f2 = f x2 in
[f1; f2]
| [x1; x2; x3] ->
let f1 = f x1 in
let f2 = f x2 in
let f3 = f x3 in
[f1; f2; f3]
| [x1; x2; x3; x4] ->
let f1 = f x1 in
let f2 = f x2 in
let f3 = f x3 in
let f4 = f x4 in
[f1; f2; f3; f4]
| x1 :: x2 :: x3 :: x4 :: x5 :: tl ->
let f1 = f x1 in
let f2 = f x2 in
let f3 = f x3 in
let f4 = f x4 in
let f5 = f x5 in
f1 :: f2 :: f3 :: f4 :: f5 ::
(if ctr > 1000
then map f tl
else count_map ~f tl (ctr + 1))
let map2 f l = count_map ~f l 0
let snoc t x =
let rec aux x acc = function
| [] -> reverse (x :: acc)
| h :: t -> aux x (h :: acc) t in
aux x [] t
let rear = function
| [] -> None
| h :: t ->
let rec aux acc prev = function
| [] -> Some (reverse acc, prev)
| h :: t -> aux (h :: acc) h t in
aux [h] h t
let of_backwards e =
let rec aux acc e =
match BatEnum.get e with
| None -> acc
| Some h -> aux (h :: acc) e in
aux [] e
let of_enum e = reverse (of_backwards e)
let generate_of_enum = of_enum
let enum l =
let rec make lr count =
BatEnum.make
~next:(fun () ->
match !lr with
| [] -> raise BatEnum.No_more_elements
| h :: t ->
decr count;
lr := t;
h
)
~count:(fun () ->
if !count < 0 then count := length !lr;
!count
)
~clone:(fun () ->
make (ref !lr) (ref !count)
) in
make (ref l) (ref (-1))
let backwards l = enum (reverse l)
let rec fold_left f acc = function
| [] -> acc
| h :: t -> fold_left f (f acc h) t
let rec fold_right f acc l =
fold_left f acc (reverse l)
let rec get t i =
match i, t with
| _, [] -> invalid_arg "Index out of bounds"
| 0, h :: _ -> h
| _, _ :: t -> get t (i - 1)
let set t i v =
let rec aux i v acc t =
match i, t with
| _, [] -> invalid_arg "Index out of bounds"
| 0, h :: t -> rev_append acc (v :: t)
| _, h :: t -> aux (i - 1) v (h :: acc) t in
aux i v [] t
let append l1 l2 =
rev_append (reverse l1) l2
let split_at l i =
let rec aux acc i l =
match i, l with
| 0, _ -> reverse acc, l
| _, [] -> invalid_arg "Index out of bounds"
| _, h :: t -> aux (h :: acc) (i - 1) t in
aux [] 0 l
end
module ListTailModCons : sig
include SIG with type 'a t = 'a list
val map2 : ('a -> 'b) -> 'a list -> 'b list
end = struct
type 'a t = 'a BatList.t
let empty = []
let cons t x = x :: t
let snoc t x = BatList.append t [x]
let map = BatList.map
let set_tail (l : 'a list) (v : 'a list) =
Obj.set_field (Obj.repr l) 1 (Obj.repr v)
let map2 f = function
| [] -> []
| h :: t ->
let rec loop f dst = function
| [] -> ()
| [a] ->
let a = f a in
set_tail dst (a :: [])
| [a; b] ->
let a = f a in
let b = f b in
set_tail dst (a :: b :: [])
| [a; b; c] ->
let a = f a in
let b = f b in
let c = f c in
set_tail dst (a :: b :: c :: [])
| [a; b; c; d] ->
let a = f a in
let b = f b in
let c = f c in
let d = f d in
set_tail dst (a :: b :: c :: d :: [])
| [a; b; c; d; e] ->
let a = f a in
let b = f b in
let c = f c in
let d = f d in
let e = f e in
set_tail dst (a :: b :: c :: d :: e :: [])
| a :: b :: c :: d :: e :: t ->
let a = f a in
let b = f b in
let c = f c in
let d = f d in
let e = f e in
let last = e :: [] in
set_tail dst (a :: b :: c :: d :: last);
loop f last t in
let r = f h :: [] in
loop f r t;
Obj.magic r
let rec count_map ~f l ctr =
match l with
| [] -> []
| [x1] ->
let f1 = f x1 in
[f1]
| [x1; x2] ->
let f1 = f x1 in
let f2 = f x2 in
[f1; f2]
| [x1; x2; x3] ->
let f1 = f x1 in
let f2 = f x2 in
let f3 = f x3 in
[f1; f2; f3]
| [x1; x2; x3; x4] ->
let f1 = f x1 in
let f2 = f x2 in
let f3 = f x3 in
let f4 = f x4 in
[f1; f2; f3; f4]
| x1 :: x2 :: x3 :: x4 :: x5 :: tl ->
let f1 = f x1 in
let f2 = f x2 in
let f3 = f x3 in
let f4 = f x4 in
let f5 = f x5 in
f1 :: f2 :: f3 :: f4 :: f5 ::
(if ctr > 1000
then map2 f tl
else count_map ~f tl (ctr + 1))
let map2 f l =
count_map ~f l 0
let append = BatList.append
let get = BatList.nth
let split_at i t = BatList.split_at t i
FIXME
let l1, l2 = split_at t i in
match l2 with
| [] -> invalid_arg "aze"
| _ :: t -> append l1 (v :: t)
let reverse = BatList.rev
let fold_left = BatList.fold_left
let fold_right f init l =
let rec tail_loop acc = function
| [] -> acc
| h :: t -> tail_loop (f acc h) t
in
let rec loop n = function
| [] -> init
| h :: t ->
if n < 1000 then
f (loop (n+1) t) h
else
f (tail_loop init (reverse t)) h
in
loop 0 l
let enum = BatList.enum
let backwards = BatList.backwards
let of_enum = BatList.of_enum
let generate_of_enum = of_enum
let of_backwards = BatList.of_backwards
let front = function
| [] -> None
| h :: t -> Some (t, h)
FIXME
| [] -> None
| h :: t ->
let rec aux acc prev = function
| [] -> Some (reverse acc, prev)
| h :: t -> aux (h :: acc) h t in
aux [h] h t
end
module Deque : SIG =
struct
type 'a t = {front : 'a list; len : int; rear : 'a list}
let empty = {front = []; rear = []; len = 0}
let split_at _ _ = assert false
let append _ _ = assert false
let set _ _ _ = assert false
let get _ _ = assert false
let reverse {front; len; rear} = {front = rear; rear = front; len}
let fold_left f acc {front; rear; len = _} =
let acc = ListTailModCons.fold_left f acc front in
ListTailModCons.fold_right f acc rear
let fold_right f acc {front; rear; len = _} =
let acc = ListTailModCons.fold_left f acc rear in
ListTailModCons.fold_right f acc front
let enum {front; rear} =
BatEnum.append (ListTailModCons.enum front) (ListTailModCons.backwards rear)
let backwards {front; rear} =
BatEnum.append (ListTailModCons.enum rear) (ListTailModCons.backwards front)
let of_enum e =
let l = ListTailModCons.of_backwards e in
{front = []; rear = l; len = List.length l}
let of_backwards e =
let l = ListTailModCons.of_backwards e in
{front = l; rear = []; len = List.length l}
let front q =
match q with
| {front = h :: front; len = len} ->
Some ({ q with front = front ; len = len - 1 }, h)
| {rear = rear; len = len} ->
let rear, rev_front = BatList.split_at (len / 2) rear in
let front = List.rev rev_front in
match front with
| [] -> None
| h :: t ->
Some ({ front = t ;
len = len - 1 ;
rear = rear ;
}, h)
let rear q =
match q with
| {rear = h :: rear; len = len} ->
Some ({ q with rear = rear ; len = len - 1 }, h)
| {front = front; len = len} ->
let front, rev_rear = BatList.split_at (len / 2) front in
let rear = List.rev rev_rear in
match rear with
| [] -> None
| h :: t ->
Some ({ rear = t ;
len = len - 1 ;
front = front ;
}, h)
let cons {front; len; rear} x =
{front = x :: front; len = len + 1; rear = rear}
let snoc {front; len; rear} x =
{front = front; len = len + 1; rear = x :: rear}
let map f {front; rear; len} =
let front = ListTailModCons.map f front in
let rear = List.rev (ListTailModCons.map f (List.rev rear)) in
{front; rear; len}
let generate_of_enum e =
let l = of_enum e in
match front l with
| None -> l
| Some (t, x) -> cons t x
end
module GenFingerTree = struct
type 'a monoid = {
zero : 'a;
combine : 'a -> 'a -> 'a ;
}
exception Empty
type ('a, 'm) node =
| Node2 of 'm * 'a * 'a
| Node3 of 'm * 'a * 'a * 'a
type ('a, 'm) digit =
| One of 'm * 'a
| Two of 'm * 'a * 'a
| Three of 'm * 'a * 'a * 'a
| Four of 'm * 'a * 'a * 'a * 'a
type ('a, 'm) fg =
| Nil
| Single of 'a
| Deep of 'm * ('a, 'm) digit * (('a, 'm) node, 'm) fg * ('a, 'm) digit
let empty = Nil
let singleton a = Single a
let is_empty = function
| Nil -> true
| Single _ | Deep _ -> false
let fold_right_node f acc = function
| Node2 (_, a, b) -> f (f acc b) a
| Node3 (_, a, b, c) -> f (f (f acc c) b) a
let fold_left_node f acc = function
| Node2 (_, a, b) -> f (f acc a) b
| Node3 (_, a, b, c) -> f (f (f acc a) b) c
let fold_right_digit f acc = function
| One (_, a) -> f acc a
| Two (_, a, b) -> f (f acc b) a
| Three (_, a, b, c) -> f (f (f acc c) b) a
| Four (_, a, b, c, d) -> f (f (f (f acc d) c) b) a
let fold_left_digit f acc = function
| One (_, a) -> f acc a
| Two (_, a, b) -> f (f acc a) b
| Three (_, a, b, c) -> f (f (f acc a) b) c
| Four (_, a, b, c, d) -> f (f (f (f acc a) b) c) d
let rec fold_right : 'acc 'a 'm. ('acc -> 'a -> 'acc) -> 'acc -> ('a, 'm) fg -> 'acc = fun f acc -> function
| Nil -> acc
| Single x -> f acc x
| Deep (_, pr, m, sf) ->
let acc = fold_right_digit f acc sf in
let acc = fold_right (fun acc elt -> fold_right_node f acc elt) acc m in
let acc = fold_right_digit f acc pr in
acc
let rec fold_left : 'acc 'a 'm. ('acc -> 'a -> 'acc) -> 'acc -> ('a, 'm) fg -> 'acc = fun f acc -> function
| Nil -> acc
| Single x -> f acc x
| Deep (_, pr, m, sf) ->
let acc = fold_left_digit f acc pr in
let acc = fold_left (fun acc elt -> fold_left_node f acc elt) acc m in
let acc = fold_left_digit f acc sf in
acc
type ('wrapped_type, 'a, 'm) wrap = monoid:'m monoid -> measure:('a -> 'm) -> 'wrapped_type
let measure_node = function
| Node2 (v, _, _)
| Node3 (v, _, _, _) -> v
let measure_digit = function
| One (v, _)
| Two (v, _, _)
| Three (v, _, _, _)
| Four (v, _, _, _, _) -> v
let measure_t_node ~monoid = function
| Nil -> monoid.zero
| Single x -> measure_node x
| Deep (v, _, _, _) -> v
let measure_t ~monoid ~measure = function
| Nil -> monoid.zero
| Single x -> measure x
| Deep (v, _, _, _) -> v
let node2 ~monoid ~measure a b =
Node2 (monoid.combine (measure a) (measure b), a, b)
let node2_node ~monoid a b =
Node2 (monoid.combine (measure_node a) (measure_node b), a, b)
let node3 ~monoid ~measure a b c =
Node3 (monoid.combine (measure a) (monoid.combine (measure b) (measure c)), a, b, c)
let node3_node ~monoid a b c =
Node3 (monoid.combine (measure_node a) (monoid.combine (measure_node b) (measure_node c)), a, b, c)
let deep ~monoid pr m sf =
let v = measure_digit pr in
let v = monoid.combine v (measure_t_node ~monoid m) in
let v = monoid.combine v (measure_digit sf) in
Deep (v, pr, m, sf)
let one_node a =
One (measure_node a, a)
let one ~measure a =
One (measure a, a)
let two_node ~monoid a b =
Two (monoid.combine (measure_node a) (measure_node b), a, b)
let two ~monoid ~measure a b =
Two (monoid.combine (measure a) (measure b), a, b)
let three_node ~monoid a b c =
Three (monoid.combine (monoid.combine (measure_node a) (measure_node b)) (measure_node c), a, b, c)
let three ~monoid ~measure a b c =
Three (monoid.combine (monoid.combine (measure a) (measure b)) (measure c), a, b, c)
let four_node ~monoid a b c d =
Four (monoid.combine (monoid.combine (measure_node a) (measure_node b)) (monoid.combine (measure_node c) (measure_node d)), a, b, c, d)
let four ~monoid ~measure a b c d =
Four (monoid.combine (monoid.combine (measure a) (measure b)) (monoid.combine (measure c) (measure d)), a, b, c, d)
let cons_digit_node ~monoid d x =
match d with
| One (v, a) -> Two (monoid.combine (measure_node x) v, x, a)
| Two (v, a, b) -> Three (monoid.combine (measure_node x) v, x, a, b)
| Three (v, a, b, c) -> Four (monoid.combine (measure_node x) v, x, a, b, c)
| Four _ -> assert false
let cons_digit ~monoid ~measure d x =
match d with
| One (v, a) -> Two (monoid.combine (measure x) v, x, a)
| Two (v, a, b) -> Three (monoid.combine (measure x) v, x, a, b)
| Three (v, a, b, c) -> Four (monoid.combine (measure x) v, x, a, b, c)
| Four _ -> assert false
let snoc_digit_node ~monoid d x =
match d with
| One (v, a) -> Two (monoid.combine v (measure_node x), a, x)
| Two (v, a, b) -> Three (monoid.combine v (measure_node x), a, b, x)
| Three (v, a, b, c) -> Four (monoid.combine v (measure_node x), a, b, c, x)
| Four _ -> assert false
let snoc_digit ~monoid ~measure d x =
match d with
| One (v, a) -> Two (monoid.combine v (measure x), a, x)
| Two (v, a, b) -> Three (monoid.combine v (measure x), a, b, x)
| Three (v, a, b, c) -> Four (monoid.combine v (measure x), a, b, c, x)
| Four _ -> assert false
let rec cons_aux : 'a 'm.
monoid:'m monoid -> (('a, 'm) node, 'm) fg -> ('a, 'm) node -> (('a, 'm) node, 'm) fg =
fun ~monoid t a ->
match t with
| Nil ->
Single a
| Single b ->
deep ~monoid (one_node a) Nil (one_node b)
| Deep (_, Four (_, b, c, d, e), m, sf) ->
deep ~monoid (two_node ~monoid a b) (cons_aux ~monoid m (node3_node ~monoid c d e)) sf
| Deep (v, pr, m, sf) ->
Deep (monoid.combine (measure_node a) v, cons_digit_node ~monoid pr a, m, sf)
let cons ~monoid ~measure t a =
match t with
| Nil ->
Single a
| Single b ->
deep ~monoid (one measure a) Nil (one measure b)
| Deep (_, Four (_, b, c, d, e), m, sf) ->
deep ~monoid (two ~monoid ~measure a b) (cons_aux ~monoid m (node3 ~monoid ~measure c d e)) sf
| Deep (v, pr, m, sf) ->
Deep (monoid.combine (measure a) v, cons_digit ~monoid ~measure pr a, m, sf)
let rec snoc_aux : 'a 'm.
monoid:'m monoid -> (('a, 'm) node, 'm) fg -> ('a, 'm) node -> (('a, 'm) node, 'm) fg =
fun ~monoid t a ->
match t with
| Nil ->
Single a
| Single b ->
deep ~monoid (one_node b) Nil (one_node a)
| Deep (_, pr, m, Four (_, b, c, d, e)) ->
deep ~monoid pr (snoc_aux ~monoid m (node3_node ~monoid b c d)) (two_node ~monoid e a)
| Deep (v, pr, m, sf) ->
Deep (monoid.combine v (measure_node a), pr, m, snoc_digit_node ~monoid sf a)
let snoc ~monoid ~measure t a =
match t with
| Nil ->
Single a
| Single b ->
deep ~monoid (one ~measure b) Nil (one ~measure a)
| Deep (_, pr, m, Four (_, b, c, d, e)) ->
deep ~monoid pr (snoc_aux ~monoid m (node3 ~monoid ~measure b c d)) (two ~measure ~monoid e a)
| Deep (v, pr, m, sf) ->
Deep (monoid.combine v (measure a), pr, m, snoc_digit ~monoid ~measure sf a)
let to_tree_digit_node ~monoid d =
match d with
| One (_, a) -> Single a
| Two (v, a, b) -> Deep (v, one_node a, Nil, one_node b)
| Three (v, a, b, c) -> Deep (v, two_node ~monoid a b, Nil, one_node c)
| Four (v, a, b, c, d) -> Deep (v, three_node ~monoid a b c, Nil, one_node d)
let to_tree_digit ~monoid ~measure d =
match d with
| One (_, a) -> Single a
| Two (v, a, b) -> Deep (v, one ~measure a, Nil, one ~measure b)
| Three (v, a, b, c) -> Deep (v, two ~monoid ~measure a b, Nil, one ~measure c)
| Four (v, a, b, c, d) -> Deep (v, three ~monoid ~measure a b c, Nil, one ~measure d)
let to_tree_list ~monoid ~measure = function
| [] -> Nil
| [a] -> Single a
| [a; b] -> deep ~monoid (one ~measure a) Nil (one ~measure b)
| [a; b; c] -> deep ~monoid (two ~monoid ~measure a b) Nil (one ~measure c)
| [a; b; c; d] -> deep ~monoid (three ~monoid ~measure a b c) Nil (one ~measure d)
| _ -> assert false
let to_digit_node = function
| Node2 (v, a, b) -> Two (v, a, b)
| Node3 (v, a, b, c) -> Three (v, a, b, c)
let to_digit_list ~monoid ~measure = function
| [a] -> one ~measure a
| [a; b] -> two ~monoid ~measure a b
| [a; b; c] -> three ~monoid ~measure a b c
| [a; b; c; d] -> four ~monoid ~measure a b c d
| _ -> assert false
let to_digit_list_node ~monoid = function
| [a] -> one_node a
| [a; b] -> two_node ~monoid a b
| [a; b; c] -> three_node ~monoid a b c
| [a; b; c; d] -> four_node ~monoid a b c d
| _ -> assert false
let head_digit = function
| One (_, a)
| Two (_, a, _)
| Three (_, a, _, _)
| Four (_, a, _, _, _) -> a
let last_digit = function
| One (_, a)
| Two (_, _, a)
| Three (_, _, _, a)
| Four (_, _, _, _, a) -> a
let tail_digit_node ~monoid = function
| One _ -> assert false
| Two (_, _, a) -> one_node a
| Three (_, _, a, b) -> two_node ~monoid a b
| Four (_, _, a, b, c) -> three_node ~monoid a b c
let tail_digit ~monoid ~measure = function
| One _ -> assert false
| Two (_, _, a) -> one ~measure a
| Three (_, _, a, b) -> two ~monoid ~measure a b
| Four (_, _, a, b, c) -> three ~monoid ~measure a b c
let init_digit_node ~monoid = function
| One _ -> assert false
| Two (_, a, _) -> one_node a
| Three (_, a, b, _) -> two_node ~monoid a b
| Four (_, a, b, c, _) -> three_node ~monoid a b c
let init_digit ~monoid ~measure = function
| One _ -> assert false
| Two (_, a, _) -> one ~measure a
| Three (_, a, b, _) -> two ~monoid ~measure a b
| Four (_, a, b, c, _) -> three ~monoid ~measure a b c
type ('a, 'rest) view =
| Vnil
| Vcons of 'a * 'rest
let rec view_left_aux : 'a 'm.
monoid:'m monoid -> (('a, 'm) node, 'm) fg -> (('a, 'm) node, (('a, 'm) node, 'm) fg) view =
fun ~monoid -> function
| Nil -> Vnil
| Single x -> Vcons (x, Nil)
| Deep (_, One (_, a), m, sf) ->
let vcons =
match view_left_aux ~monoid m with
| Vnil -> to_tree_digit_node ~monoid sf
| Vcons (a, m') -> deep ~monoid (to_digit_node a) m' sf in
Vcons (a, vcons)
| Deep (_, pr, m, sf) ->
let vcons = deep ~monoid (tail_digit_node ~monoid pr) m sf in
Vcons (head_digit pr, vcons)
let view_left ~monoid ~measure = function
| Nil -> Vnil
| Single x -> Vcons (x, Nil)
| Deep (_, One (_, a), m, sf) ->
let vcons =
match view_left_aux ~monoid m with
| Vnil -> to_tree_digit ~monoid ~measure sf
| Vcons (a, m') -> deep ~monoid (to_digit_node a) m' sf in
Vcons (a, vcons)
| Deep (_, pr, m, sf) ->
let vcons = deep ~monoid (tail_digit ~monoid ~measure pr) m sf in
Vcons (head_digit pr, vcons)
let rec view_right_aux : 'a 'm.
monoid:'m monoid -> (('a, 'm) node, 'm) fg -> (('a, 'm) node, (('a, 'm) node, 'm) fg) view =
fun ~monoid -> function
| Nil -> Vnil
| Single x -> Vcons (x, Nil)
| Deep (_, pr, m, One (_, a)) ->
let vcons =
match view_right_aux ~monoid m with
| Vnil -> to_tree_digit_node ~monoid pr
| Vcons (a, m') -> deep ~monoid pr m' (to_digit_node a) in
Vcons (a, vcons)
| Deep (_, pr, m, sf) ->
let vcons = deep ~monoid pr m (init_digit_node ~monoid sf) in
Vcons (last_digit sf, vcons)
let view_right ~monoid ~measure = function
| Nil -> Vnil
| Single x -> Vcons (x, Nil)
| Deep (_, pr, m, One (_, a)) ->
let vcons =
match view_right_aux ~monoid m with
| Vnil -> to_tree_digit ~monoid ~measure pr
| Vcons (a, m') -> deep ~monoid pr m' (to_digit_node a) in
Vcons (a, vcons)
| Deep (_, pr, m, sf) ->
let vcons = deep ~monoid pr m (init_digit ~monoid ~measure sf) in
Vcons (last_digit sf, vcons)
let head_exn = function
| Nil -> raise Empty
| Single a -> a
| Deep (_, pr, _, _) -> head_digit pr
let head = function
| Nil -> None
| Single a -> Some a
| Deep (_, pr, _, _) -> Some (head_digit pr)
let last_exn = function
| Nil -> raise Empty
| Single a -> a
| Deep (_, _, _, sf) -> last_digit sf
let last = function
| Nil -> None
| Single a -> Some a
| Deep (_, _, _, sf) -> Some (last_digit sf)
let tail ~monoid ~measure t =
match view_left ~monoid ~measure t with
| Vnil -> None
| Vcons (_, tl) -> Some tl
let tail_exn ~monoid ~measure t =
match view_left ~monoid ~measure t with
| Vnil -> raise Empty
| Vcons (_, tl) -> tl
let front ~monoid ~measure t =
match view_left ~monoid ~measure t with
| Vnil -> None
| Vcons (hd, tl) -> Some (tl, hd)
let front_exn ~monoid ~measure t =
match view_left ~monoid ~measure t with
| Vnil -> raise Empty
| Vcons (hd, tl) -> (tl, hd)
let init ~monoid ~measure t =
match view_right ~monoid ~measure t with
| Vnil -> None
| Vcons (_, tl) -> Some tl
let init_exn ~monoid ~measure t =
match view_right ~monoid ~measure t with
| Vnil -> raise Empty
| Vcons (_, tl) -> tl
let rear ~monoid ~measure t =
match view_right ~monoid ~measure t with
| Vnil -> None
| Vcons (hd, tl) -> Some (tl, hd)
let rear_exn ~monoid ~measure t =
match view_right ~monoid ~measure t with
| Vnil -> raise Empty
| Vcons (hd, tl) -> (tl, hd)
let nodes =
let add_digit_to digit l =
match digit with
| One (_, a) -> a :: l
| Two (_, a, b) -> a :: b :: l
| Three (_, a, b, c) -> a :: b :: c :: l
| Four (_, a, b, c, d) -> a :: b :: c :: d :: l in
let rec nodes_aux ~monoid ~measure ts sf2 =
match ts, sf2 with
| [], One _ -> assert false
| [], Two (_, a, b)
| [a], One (_, b) -> [node2 ~monoid ~measure a b]
| [], Three (_, a, b, c)
| [a], Two (_, b, c)
| [a; b], One (_, c) -> [node3 ~monoid ~measure a b c]
| [], Four (_, a, b, c, d)
| [a], Three (_, b, c, d)
| [a; b], Two (_, c, d)
| [a; b; c], One (_, d) -> [node2 ~monoid ~measure a b; node2 ~monoid ~measure c d]
| a :: b :: c :: ts, _ -> node3 ~monoid ~measure a b c :: nodes_aux ~monoid ~measure ts sf2
| [a], Four (_, b, c, d, e)
| [a; b], Three (_, c, d, e) -> [node3 ~monoid ~measure a b c; node2 ~monoid ~measure d e]
| [a; b], Four (_, c, d, e, f) -> [node3 ~monoid ~measure a b c; node3 ~monoid ~measure d e f] in
fun ~monoid ~measure sf1 ts sf2 ->
let ts = add_digit_to sf1 ts in
nodes_aux ~monoid ~measure ts sf2
let rec app3 : 'a 'm.
monoid:'m monoid -> measure:('a -> 'm) -> ('a, 'm) fg -> 'a list -> ('a, 'm) fg -> ('a, 'm) fg =
fun ~monoid ~measure t1 elts t2 ->
match t1, t2 with
| Nil, _ ->
List.fold_right (fun elt acc -> cons ~monoid ~measure acc elt) elts t2
| _, Nil ->
List.fold_left (fun acc elt -> snoc ~monoid ~measure acc elt) t1 elts
| Single x1, _ ->
cons ~monoid ~measure (List.fold_right (fun elt acc -> cons ~monoid ~measure acc elt) elts t2) x1
| _, Single x2 ->
snoc ~monoid ~measure (List.fold_left (fun acc elt -> snoc ~monoid ~measure acc elt) t1 elts) x2
| Deep (_, pr1, m1, sf1), Deep (_, pr2, m2, sf2) ->
deep ~monoid pr1 (app3 ~monoid ~measure:measure_node m1 (nodes ~monoid ~measure sf1 elts pr2) m2) sf2
let append ~monoid ~measure t1 t2 = app3 ~monoid ~measure t1 [] t2
let reverse_digit_node ~monoid rev_a = function
| One (_, a) -> one_node (rev_a a)
| Two (_, a, b) -> two_node ~monoid (rev_a b) (rev_a a)
| Three (_, a, b, c) -> three_node ~monoid (rev_a c) (rev_a b) (rev_a a)
| Four (_, a, b, c, d) -> four_node ~monoid (rev_a d) (rev_a c) (rev_a b) (rev_a a)
let reverse_digit ~monoid ~measure = function
| One _ as d -> d
| Two (_, a, b) -> two ~monoid ~measure b a
| Three (_, a, b, c) -> three ~monoid ~measure c b a
| Four (_, a, b, c, d) -> four ~monoid ~measure d c b a
let reverse_node_node ~monoid rev_a = function
| Node2 (_, a, b) -> node2_node ~monoid (rev_a b) (rev_a a)
| Node3 (_, a, b, c) -> node3_node ~monoid (rev_a c) (rev_a b) (rev_a a)
let reverse_node ~monoid ~measure = function
| Node2 (_, a, b) -> node2 ~monoid ~measure b a
| Node3 (_, a, b, c) -> node3 ~monoid ~measure c b a
let rec reverse_aux : 'a 'm.
monoid:'m monoid -> (('a, 'm) node -> ('a, 'm) node) -> (('a, 'm) node, 'm) fg -> (('a, 'm) node, 'm) fg =
fun ~monoid reverse_a -> function
| Nil -> Nil
| Single a -> Single (reverse_a a)
| Deep (_, pr, m, sf) ->
let rev_pr = reverse_digit_node ~monoid reverse_a pr in
let rev_sf = reverse_digit_node ~monoid reverse_a sf in
let rev_m = reverse_aux ~monoid (reverse_node_node ~monoid (reverse_a)) m in
deep ~monoid rev_sf rev_m rev_pr
let reverse ~monoid ~measure = function
| Nil
| Single _ as t -> t
| Deep (_, pr, m, sf) ->
let rev_pr = reverse_digit ~monoid ~measure pr in
let rev_sf = reverse_digit ~monoid ~measure sf in
let rev_m = reverse_aux ~monoid (reverse_node ~monoid ~measure) m in
deep ~monoid rev_sf rev_m rev_pr
type ('a, 'rest) split = Split of 'rest * 'a * 'rest
let split_digit ~monoid ~measure p i = function
| One (_, a) -> Split ([], a, [])
| Two (_, a, b) ->
let i' = monoid.combine i (measure a) in
if p i' then Split ([], a, [b]) else
Split ([a], b, [])
| Three (_, a, b, c) ->
let i' = monoid.combine i (measure a) in
if p i' then Split ([], a, [b; c]) else
let i'' = monoid.combine i' (measure b) in
if p i'' then Split ([a], b, [c]) else
Split ([a; b], c, [])
| Four (_, a, b, c, d) ->
let i' = monoid.combine i (measure a) in
if p i' then Split ([], a, [b; c; d]) else
let i'' = monoid.combine i' (measure b) in
if p i'' then Split ([a], b, [c; d]) else
let i''' = monoid.combine i'' (measure c) in
if p i''' then Split ([a; b], c, [d]) else
Split ([a; b; c], d, [])
let deep_left ~monoid ~measure pr m sf =
match pr with
| [] -> (
match view_left ~monoid ~measure:measure_node m with
| Vnil -> to_tree_digit ~monoid ~measure sf
| Vcons (a, m') -> deep ~monoid (to_digit_node a) m' sf
)
| _ ->
deep ~monoid (to_digit_list ~monoid ~measure pr) m sf
let deep_right ~monoid ~measure pr m sf =
match sf with
| [] -> (
match view_right ~monoid ~measure:measure_node m with
| Vnil -> to_tree_digit ~monoid ~measure pr
| Vcons (a, m') -> deep ~monoid pr m' (to_digit_node a)
)
| _ ->
deep ~monoid pr m (to_digit_list ~monoid ~measure sf)
let rec split_tree : 'a 'm.
monoid:'m monoid -> measure:('a -> 'm) -> ('m -> bool) -> 'm -> ('a, 'm) fg -> ('a, ('a, 'm) fg) split =
fun ~monoid ~measure p i -> function
| Nil -> raise Empty
| Single x -> Split (Nil, x, Nil)
| Deep (_, pr, m, sf) ->
let vpr = monoid.combine i (measure_digit pr) in
if p vpr then
let Split (l, x, r) = split_digit ~monoid ~measure p i pr in
Split (to_tree_list ~monoid ~measure l, x, deep_left ~monoid ~measure r m sf)
else
let vm = monoid.combine vpr (measure_t_node ~monoid m) in
if p vm then
let Split (ml, xs, mr) = split_tree ~monoid ~measure:measure_node p vpr m in
let Split (l, x, r) = split_digit ~monoid ~measure p (monoid.combine vpr (measure_t_node ~monoid ml)) (to_digit_node xs) in
Split (deep_right ~monoid ~measure pr ml l, x, deep_left ~monoid ~measure r mr sf)
else
let Split (l, x, r) = split_digit ~monoid ~measure p vm sf in
Split (deep_right ~monoid ~measure pr m l, x, to_tree_list ~monoid ~measure r)
let split ~monoid ~measure f t =
match t with
| Nil -> (Nil, Nil)
| _ ->
if f (measure_t ~monoid ~measure t) then
let Split (l, x, r) = split_tree ~monoid ~measure f monoid.zero t in
(l, cons ~monoid ~measure r x)
else
(t, Nil)
let lookup_digit ~monoid ~measure p i = function
| One (_, a) -> monoid.zero, a
| Two (_, a, b) ->
let m_a = measure a in
let i' = monoid.combine i m_a in
if p i' then monoid.zero, a else m_a, b
| Three (_, a, b, c) ->
let m_a = measure a in
let i' = monoid.combine i m_a in
if p i' then monoid.zero, a else
let m_b = measure b in
let i'' = monoid.combine i' m_b in
if p i'' then m_a, b else monoid.combine m_a m_b, c
| Four (_, a, b, c, d) ->
let m_a = measure a in
let i' = monoid.combine i m_a in
if p i' then monoid.zero, a else
let m_b = measure b in
let i'' = monoid.combine i' m_b in
if p i'' then m_a, b else
let m_c = measure c in
let i''' = monoid.combine i'' m_c in
if p i''' then monoid.combine m_a m_b, c else monoid.combine (monoid.combine m_a m_b) m_c, d
let lookup_node ~monoid ~measure p i = function
| Node2 (_, a, b) ->
let m_a = measure a in
let i' = monoid.combine i m_a in
if p i' then monoid.zero, a else m_a, b
| Node3 (_, a, b, c) ->
let m_a = measure a in
let i' = monoid.combine i m_a in
if p i' then monoid.zero, a else
let m_b = measure b in
let i'' = monoid.combine i' m_b in
if p i'' then m_a, b else monoid.combine m_a m_b, c
let rec lookup_tree : 'a 'm. monoid:'m monoid -> measure:('a -> 'm) -> ('m -> bool) -> 'm -> ('a, 'm) fg -> 'm * 'a =
fun ~monoid ~measure p i -> function
| Nil -> raise Empty
| Single x -> monoid.zero, x
| Deep (_, pr, m, sf) ->
let m_pr = measure_digit pr in
let vpr = monoid.combine i m_pr in
if p vpr then lookup_digit ~monoid ~measure p i pr else
let m_m = measure_t_node ~monoid m in
let vm = monoid.combine vpr m_m in
if p vm then
let v_left, node = lookup_tree ~monoid ~measure:measure_node p vpr m in
let v, x = lookup_node ~monoid ~measure p (monoid.combine vpr v_left) node in
monoid.combine (monoid.combine m_pr v_left) v, x
else
let v, x = lookup_digit ~monoid ~measure p vm sf in
monoid.combine (monoid.combine m_pr m_m) v, x
let lookup ~monoid ~measure p t =
snd (lookup_tree ~monoid ~measure p monoid.zero t)
let enum_digit enum_a d k =
match d with
| One (_, a) ->
enum_a a k
| Two (_, a, b) ->
enum_a a (fun () -> enum_a b k)
| Three (_, a, b, c) ->
enum_a a (fun () -> enum_a b (fun () -> enum_a c k))
| Four (_, a, b, c, d) ->
enum_a a (fun () -> enum_a b (fun () -> enum_a c (fun () -> enum_a d k)))
let enum_digit_backwards enum_a d k =
match d with
| One (_, a) ->
enum_a a k
| Two (_, a, b) ->
enum_a b (fun () -> enum_a a k)
| Three (_, a, b, c) ->
enum_a c (fun () -> enum_a b (fun () -> enum_a a k))
| Four (_, a, b, c, d) ->
enum_a d (fun () -> enum_a c (fun () -> enum_a b (fun () -> enum_a a k)))
let enum_node enum_a n k =
match n with
| Node2 (_, a, b) ->
enum_a a (fun () -> enum_a b k)
| Node3 (_, a, b, c) ->
enum_a a (fun () -> enum_a b (fun () -> enum_a c k))
let enum_node_backwards enum_a n k =
match n with
| Node2 (_, a, b) ->
enum_a b (fun () -> enum_a a k)
| Node3 (_, a, b, c) ->
enum_a c (fun () -> enum_a b (fun () -> enum_a a k))
let enum_base a k = a, k
type 'a iter = unit -> 'a ret
and 'a ret = 'a * 'a iter
type ('input, 'output) iter_into = 'input -> 'output iter -> 'output ret
let rec enum_aux : 'v 'a 'm. ('a, 'v) iter_into -> (('a, 'm) fg, 'v) iter_into =
fun enum_a t k ->
match t with
| Nil -> k ()
| Single a -> enum_a a k
| Deep (_, pr, m, sf) ->
enum_digit enum_a pr (fun () ->
enum_aux (enum_node enum_a) m (fun () ->
enum_digit enum_a sf k
)
)
let enum_cps t = enum_aux enum_base t (fun () -> raise BatEnum.No_more_elements)
let rec enum_aux_backwards : 'v 'a 'm. ('a, 'v) iter_into -> (('a, 'm) fg, 'v) iter_into =
fun enum_a t k ->
match t with
| Nil -> k ()
| Single a -> enum_a a k
| Deep (_, pr, m, sf) ->
enum_digit_backwards enum_a sf (fun () ->
enum_aux_backwards (enum_node_backwards enum_a) m (fun () ->
enum_digit_backwards enum_a pr k
)
)
let enum_cps_backwards t = enum_aux_backwards enum_base t (fun () -> raise BatEnum.No_more_elements)
let enum t =
BatEnum.from_loop
(fun () -> enum_cps t)
(fun k -> k ())
let backwards t =
BatEnum.from_loop
(fun () -> enum_cps_backwards t)
(fun k -> k ())
let of_enum ~monoid ~measure enum =
BatEnum.fold (fun t elt -> snoc ~monoid ~measure t elt) empty enum
let of_backwards ~monoid ~measure enum =
BatEnum.fold (fun t elt -> cons ~monoid ~measure t elt) empty enum
let measure = measure_t
fold_left (fun acc elt -> snoc ~monoid ~measure acc (f elt)) empty t
end
module Sequence : sig
include SIG
val enum2 : 'a t -> 'a BatEnum.t
val fold_left2 : ('acc -> 'a -> 'acc) -> 'acc -> 'a t -> 'acc
val fold_right2 : ('acc -> 'a -> 'acc) -> 'acc -> 'a t -> 'acc
val reverse2 : 'a t -> 'a t
val update2 : 'a t -> int -> ('a -> 'a) -> 'a t
val set2 : 'a t -> int -> 'a -> 'a t
val get2 : 'a t -> int -> 'a
val of_enum2 : 'a BatEnum.t -> 'a t
val map2 : ('a -> 'b) -> 'a t -> 'b t
end =
struct
type nat = int
let nat_plus_monoid = { GenFingerTree.
zero = 0;
combine = (+);
}
let size_measurer = fun _ -> 1
type ('a, 'm) fg = ('a, nat) GenFingerTree.fg
type 'a t = ('a, nat) fg
let empty = GenFingerTree.empty
let fold_left = GenFingerTree.fold_left
let fold_right = GenFingerTree.fold_right
let cons t x = GenFingerTree.cons ~monoid:nat_plus_monoid ~measure:size_measurer t x
let snoc t x = GenFingerTree.snoc ~monoid:nat_plus_monoid ~measure:size_measurer t x
let front t = GenFingerTree.front ~monoid:nat_plus_monoid ~measure:size_measurer t
let rear t = GenFingerTree.rear ~monoid:nat_plus_monoid ~measure:size_measurer t
let append t1 t2 = GenFingerTree.append ~monoid:nat_plus_monoid ~measure:size_measurer t1 t2
let reverse t = GenFingerTree.reverse ~monoid:nat_plus_monoid ~measure:size_measurer t
let measure t = GenFingerTree.measure ~monoid:nat_plus_monoid ~measure:size_measurer t
let size = measure
let split f t = GenFingerTree.split ~monoid:nat_plus_monoid ~measure:size_measurer f t
let split_at t i =
if i < 0 || i >= size t then invalid_arg "Index out of bounds";
split (fun index -> i < index) t
let lookup f t = GenFingerTree.lookup ~monoid:nat_plus_monoid ~measure:size_measurer f t
let get t i =
if i < 0 || i >= size t then invalid_arg "Index out of bounds";
lookup (fun index -> i < index) t
let tail_exn t = GenFingerTree.tail_exn ~monoid:nat_plus_monoid ~measure:size_measurer t
let set t i v =
if i < 0 || i >= size t then invalid_arg "Index out of bounds";
let left, right = split_at t i in
append (snoc left v) (tail_exn right)
let update t i f =
set t i (f (get t i))
let of_enum e = GenFingerTree.of_enum ~monoid:nat_plus_monoid ~measure:size_measurer e
let generate_of_enum = of_enum
let of_backwards e = GenFingerTree.of_backwards ~monoid:nat_plus_monoid ~measure:size_measurer e
let map f t = GenFingerTree.map ~monoid:nat_plus_monoid ~measure:size_measurer f t
let enum = GenFingerTree.enum
let backwards = GenFingerTree.backwards
struct
open GenFingerTree
let rec height : 'a. int -> ('a, 'm) fg -> int = fun acc -> function
| Nil
| Single _ -> acc
| Deep (_, _, m, _) -> height (acc + 1) m
let height t = height 0 t
let tdigit = 0
let tfg = 1
let telt = 2
type 'a iter = int array
let rec aux_elt stack index depth elt =
if depth = 0 then (
stack.(0) <- index - 2;
Obj.magic elt
) else (
match Obj.magic elt with
| Node2 (_, a, b) ->
stack.(index - 1) <- Obj.magic b;
stack.(index + 0) <- telt lor ((depth - 1) lsl 2);
aux_elt stack (index + 2) (depth - 1) a
| Node3 (_, a, b, c) ->
stack.(index - 1) <- Obj.magic c;
stack.(index + 0) <- telt lor ((depth - 1) lsl 2);
stack.(index + 1) <- Obj.magic b;
stack.(index + 2) <- telt lor ((depth - 1) lsl 2);
aux_elt stack (index + 4) (depth - 1) a
)
let aux_digit stack index depth = function
| One (_, a) ->
aux_elt stack index depth a
| Two (_, a, b) ->
stack.(index - 1) <- Obj.magic b;
stack.(index + 0) <- telt lor (depth lsl 2);
aux_elt stack (index + 2) depth a
| Three (_, a, b, c) ->
stack.(index - 1) <- Obj.magic c;
stack.(index + 0) <- telt lor (depth lsl 2);
stack.(index + 1) <- Obj.magic b;
stack.(index + 2) <- telt lor (depth lsl 2);
aux_elt stack (index + 4) depth a
| Four (_, a, b, c, d) ->
stack.(index - 1) <- Obj.magic d;
stack.(index + 0) <- telt lor (depth lsl 2);
stack.(index + 1) <- Obj.magic c;
stack.(index + 2) <- telt lor (depth lsl 2);
stack.(index + 3) <- Obj.magic b;
stack.(index + 4) <- telt lor (depth lsl 2);
aux_elt stack (index + 6) depth a
let rec aux stack index =
if index = 0 then (
stack.(0) <- 0;
raise BatEnum.No_more_elements
);
let type_ = stack.(index) land 3 in
let depth = stack.(index) lsr 2 in
let value = Obj.magic stack.(index - 1) in
this test comes first because it is
* the one most likely to be true
* making it last results in a 20 % slow down
* the one most likely to be true
* making it last results in a 20% slow down *)
aux_elt stack index depth value
else if type_ = tfg then
match value with
| Single x -> aux_elt stack index depth x
| Deep (_, pr, m, sf) ->
stack.(index - 1) <- Obj.magic sf;
stack.(index + 0) <- tdigit lor (depth lsl 2);
stack.(index + 1) <- Obj.magic m;
stack.(index + 2) <- tfg lor ((depth + 1) lsl 2);
aux_digit stack (index + 4) depth pr
else
aux_digit stack index depth value
let enum_next (stack : int array) =
aux stack stack.(0)
let enum_stack t : _ array =
let stack = Obj.obj (Obj.new_block 0 ((3 * height t + 3 + 1) * 2 + 1)) in
stack.(0) <- 2;
stack.(1) <- Obj.magic t;
stack.(2) <- tfg;
stack
let enum t =
let stack = enum_stack t in
BatEnum.make
~next:(fun () -> enum_next stack)
~count:(fun _ -> assert false)
~clone:(fun () -> assert false)
let rec fold_left_a f depth acc a =
if depth = 0 then
f acc a
else
Obj.magic (
match Obj.magic a with
| Node2 (_, a, b) ->
let acc = fold_left_a f (depth - 1) acc a in
let acc = fold_left_a f (depth - 1) acc b in
acc
| Node3 (_, a, b, c) ->
let acc = fold_left_a f (depth - 1) acc a in
let acc = fold_left_a f (depth - 1) acc b in
let acc = fold_left_a f (depth - 1) acc c in
acc
)
let fold_left_digit f depth acc = function
| One (_, a) ->
fold_left_a f depth acc a
| Two (_, a, b) ->
let acc = fold_left_a f depth acc a in
let acc = fold_left_a f depth acc b in
acc
| Three (_, a, b, c) ->
let acc = fold_left_a f depth acc a in
let acc = fold_left_a f depth acc b in
let acc = fold_left_a f depth acc c in
acc
| Four (_, a, b, c, d) ->
let acc = fold_left_a f depth acc a in
let acc = fold_left_a f depth acc b in
let acc = fold_left_a f depth acc c in
let acc = fold_left_a f depth acc d in
acc
let rec fold_left f depth acc = function
| Nil ->
acc
| Single a ->
fold_left_a f depth acc a
| Deep (_, pr, m, sf) ->
let acc = fold_left_digit f depth acc pr in
let acc = fold_left f (depth + 1) acc (Obj.magic m) in
let acc = fold_left_digit f depth acc sf in
acc
let fold_left f acc t =
fold_left f 0 acc t
let rec fold_right_a f depth acc a =
if depth = 0 then
f acc a
else
Obj.magic (
match Obj.magic a with
| Node2 (_, a, b) ->
let acc = fold_right_a f (depth - 1) acc b in
let acc = fold_right_a f (depth - 1) acc a in
acc
| Node3 (_, a, b, c) ->
let acc = fold_right_a f (depth - 1) acc c in
let acc = fold_right_a f (depth - 1) acc b in
let acc = fold_right_a f (depth - 1) acc a in
acc
)
let fold_right_digit f depth acc = function
| One (_, a) ->
fold_right_a f depth acc a
| Two (_, a, b) ->
let acc = fold_right_a f depth acc b in
let acc = fold_right_a f depth acc a in
acc
| Three (_, a, b, c) ->
let acc = fold_right_a f depth acc c in
let acc = fold_right_a f depth acc b in
let acc = fold_right_a f depth acc a in
acc
| Four (_, a, b, c, d) ->
let acc = fold_right_a f depth acc d in
let acc = fold_right_a f depth acc c in
let acc = fold_right_a f depth acc b in
let acc = fold_right_a f depth acc a in
acc
let rec fold_right f depth acc = function
| Nil ->
acc
| Single a ->
fold_right_a f depth acc a
| Deep (_, pr, m, sf) ->
let acc = fold_right_digit f depth acc sf in
let acc = fold_right f (depth + 1) acc (Obj.magic m) in
let acc = fold_right_digit f depth acc pr in
acc
let fold_right f acc t =
fold_right f 0 acc t
end
let enum2 = Opt.enum
let fold_left2 = Opt.fold_left
let fold_right2 = Opt.fold_right
specialized for int
struct
open GenFingerTree
let measure_t_node = function
| Nil -> 0
| Single x -> measure_node x
| Deep (v, _, _, _) -> v
let measure_t = function
| Nil -> 0
| Single _ -> 1
| Deep (v, _, _, _) -> v
let node2 a b =
Node2 (2, a, b)
let node2_node a b =
Node2 (measure_node a + measure_node b, a, b)
let node3 a b c =
Node3 (3, a, b, c)
let node3_node a b c =
Node3 (measure_node a + measure_node b + measure_node c, a, b, c)
let deep pr m sf =
Deep (measure_digit pr + measure_t_node m + measure_digit sf, pr, m, sf)
let one a =
One (1, a)
let one_node a =
One (measure_node a, a)
let two a b =
Two (2, a, b)
let two_node a b =
Two (measure_node a + measure_node b, a, b)
let three a b c =
Three (3, a, b, c)
let three_node a b c =
Three (measure_node a + measure_node b + measure_node c, a, b, c)
let four a b c d =
Four (4, a, b, c, d)
let four_node a b c d =
Four (measure_node a + measure_node b + measure_node c + measure_node d, a, b, c, d)
let rec reverse_a depth a =
if depth = 0 then a else
Obj.magic (
match Obj.magic a with
| Node2 (v, a, b) ->
Node2 (v, reverse_a (depth - 1) b, reverse_a (depth - 1) a)
| Node3 (v, a, b, c) ->
Node3 (v, reverse_a (depth - 1) c, reverse_a (depth - 1) b, reverse_a (depth - 1) a)
)
let reverse_digit depth = function
| One (v, a) ->
One (v, reverse_a depth a)
| Two (v, a, b) ->
Two (v, reverse_a depth b, reverse_a depth a)
| Three (v, a, b, c) ->
Three (v, reverse_a depth c, reverse_a depth b, reverse_a depth a)
| Four (v, a, b, c, d) ->
Four (v, reverse_a depth d, reverse_a depth c, reverse_a depth b, reverse_a depth a)
let rec reverse depth = function
| Nil -> Nil
| Single a -> Single (reverse_a depth a)
| Deep (v, pr, m, sf) ->
let rev_pr = reverse_digit depth pr in
let rev_sf = reverse_digit depth sf in
let rev_m = Obj.magic (reverse (depth + 1) (Obj.magic m)) in
Deep (v, rev_sf, rev_m, rev_pr)
let reverse t = reverse 0 t
let get_digit d i =
match d with
| One (_, a) -> a
| Two (_, a, b) -> if i = 0 then a else b
| Three (_, a, b, c) -> if i = 0 then a else if i = 1 then b else c
| Four (_, a, b, c, d) -> if i < 2 then (if i = 0 then a else b) else (if i = 2 then c else d)
let rec get_a depth a i =
if depth = 1 then (
match Obj.magic a with
| Node2 (_, a, b) -> if i = 0 then a else b
| Node3 (_, a, b, c) -> if i = 0 then a else if i = 1 then b else c
) else (
match Obj.magic a with
| Node2 (_, a, b) ->
if i < measure_node a then get_a (depth - 1) a i else
let i = i - measure_node a in
get_a (depth - 1) b i
| Node3 (_, a, b, c) ->
if i < measure_node a then get_a (depth - 1) a i else
let i = i - measure_node a in
if i < measure_node b then get_a (depth - 1) b i else
let i = i - measure_node b in
get_a (depth - 1) c i
)
let get_digit_node depth d i =
match d with
| One (_, a) ->
get_a depth a i
| Two (_, a, b) ->
if i < measure_node a then get_a depth a i else
let i = i - measure_node a in
get_a depth b i
| Three (_, a, b, c) ->
if i < measure_node a then get_a depth a i else
let i = i - measure_node a in
if i < measure_node b then get_a depth b i else
let i = i - measure_node b in
get_a depth c i
| Four (_, a, b, c, d) ->
if i < measure_node a then get_a depth a i else
let i = i - measure_node a in
if i < measure_node b then get_a depth b i else
let i = i - measure_node b in
if i < measure_node c then get_a depth c i else
let i = i - measure_node c in
get_a depth d i
let rec get_aux depth t i =
match t with
| Nil -> assert false
| Single v -> get_a depth v i
| Deep (_, pr, m, sf) ->
if i < measure_digit pr then
get_digit_node depth pr i
else
let i = i - measure_digit pr in
if i < measure_t_node m then
get_aux (depth + 1) (Obj.magic m) i
else
let i = i - measure_t_node m in
get_digit_node depth sf i
let check_bounds t i =
if i < 0 || i >= size t then invalid_arg "Index out of bounds"
let get t i =
check_bounds t i;
match t with
| Nil -> assert false
| Single v -> v
| Deep (_, pr, m, sf) ->
if i < measure_digit pr then
get_digit pr i
else
let i = i - measure_digit pr in
if i < measure_t_node m then
get_aux 1 m i
else
let i = i - measure_t_node m in
get_digit sf i
let update_digit d i f =
match d with
| One (v, a) ->
One (v, f a)
| Two (v, a, b) ->
if i = 0 then Two (v, f a, b) else
Two (v, a, f b)
| Three (v, a, b, c) ->
if i = 0 then Three (v, f a, b, c) else
if i = 1 then Three (v, a, f b, c) else
Three (v, a, b, f c)
| Four (v, a, b, c, d) ->
if i < 2 then (
if i = 0 then Four (v, f a, b, c, d) else Four (v, a, f b, c, d)
) else (
if i = 2 then Four (v, a, b, f c, d) else Four (v, a, b, c, f d)
)
let rec update_a depth a i f =
if depth = 1 then
Obj.magic (
match Obj.magic a with
| Node2 (v, a, b) ->
if i = 0 then Node2 (v, f a, b) else
Node2 (v, a, f b)
| Node3 (v, a, b, c) ->
if i = 0 then Node3 (v, f a, b, c) else
if i = 1 then Node3 (v, a, f b, c) else
Node3 (v, a, b, f c)
)
else
Obj.magic (
match Obj.magic a with
| Node2 (v, a, b) ->
if i < measure_node a then Node2 (v, update_a (depth - 1) a i f, b) else
let i = i - measure_node a in
Node2 (v, a, update_a (depth - 1) b i f)
| Node3 (v, a, b, c) ->
if i < measure_node a then Node3 (v, update_a (depth - 1) a i f, b, c) else
let i = i - measure_node a in
if i < measure_node b then Node3 (v, a, update_a (depth - 1) b i f, c) else
let i = i - measure_node b in
Node3 (v, a, b, update_a (depth - 1) c i f)
)
let update_digit_node depth d i f =
match d with
| One (v, a) ->
One (v, update_a depth a i f)
| Two (v, a, b) ->
if i < measure_node a then Two (v, update_a depth a i f, b) else
let i = i - measure_node a in
Two (v, a, update_a depth b i f)
| Three (v, a, b, c) ->
if i < measure_node a then Three (v, update_a depth a i f, b, c) else
let i = i - measure_node a in
if i < measure_node b then Three (v, a, update_a depth b i f, c) else
let i = i - measure_node b in
Three (v, a, b, update_a depth c i f)
| Four (v, a, b, c, d) ->
if i < measure_node a then Four (v, update_a depth a i f, b, c, d) else
let i = i - measure_node a in
if i < measure_node b then Four (v, a, update_a depth b i f, c, d) else
let i = i - measure_node b in
if i < measure_node c then Four (v, a, b, update_a depth c i f, d) else
let i = i - measure_node c in
Four (v, a, b, c, update_a depth d i f)
let rec update_aux depth t i f =
match t with
| Nil -> assert false
| Single v -> Single (update_a depth v i f)
| Deep (v, pr, m, sf) ->
if i < measure_digit pr then
Deep (v, update_digit_node depth pr i f, m, sf)
else
let i = i - measure_digit pr in
if i < measure_t_node m then
Deep (v, pr, Obj.magic (update_aux (depth + 1) (Obj.magic m) i f), sf)
else
let i = i - measure_t_node m in
Deep (v, pr, m, update_digit_node depth sf i f)
let update t i f =
check_bounds t i;
match t with
| Nil -> assert false
| Single v -> Single (f v)
| Deep (v, pr, m, sf) ->
if i < measure_digit pr then
Deep (v, update_digit pr i f, m, sf)
else
let i = i - measure_digit pr in
if i < measure_t_node m then
Deep (v, pr, update_aux 1 m i f, sf)
else
let i = i - measure_t_node m in
Deep (v, pr, m, update_digit sf i f)
let set t i v =
update t i (fun _ -> v)
let rec get_node depth enum =
if depth = 1 then
let v1 = BatEnum.get_exn enum in
let v2 = BatEnum.get_exn enum in
let v3 = BatEnum.get_exn enum in
Obj.magic (node3 v1 v2 v3)
else
let v1 = get_node (depth - 1) enum in
let v2 = get_node (depth - 1) enum in
let v3 = get_node (depth - 1) enum in
Obj.magic (node3_node v1 v2 v3)
let rec get_digit_node depth enum n =
match n with
| 1 ->
let v1 = get_node depth enum in
one_node v1
| 2 ->
let v1 = get_node depth enum in
let v2 = get_node depth enum in
two_node v1 v2
| 3 ->
let v1 = get_node depth enum in
let v2 = get_node depth enum in
let v3 = get_node depth enum in
three_node v1 v2 v3
| 4 ->
let v1 = get_node depth enum in
let v2 = get_node depth enum in
let v3 = get_node depth enum in
let v4 = get_node depth enum in
four_node v1 v2 v3 v4
| _ -> assert false
let rec fast_of_enum_aux depth enum n =
if n = 0 then Nil else
if n = 1 then Single (get_node depth enum) else
let n_rec = if n <= 8 then 0 else (n - 8 + 3 - 1) / 3 in
let n_left = (n - n_rec * 3) / 2 in
let n_right = (n - n_rec * 3 + 1) / 2 in
let pr = get_digit_node depth enum n_left in
let m = Obj.magic (fast_of_enum_aux (depth + 1) enum n_rec) in
let sf = get_digit_node depth enum n_right in
deep pr m sf
let rec get_digit enum n =
match n with
| 1 ->
let v1 = BatEnum.get_exn enum in
one v1
| 2 ->
let v1 = BatEnum.get_exn enum in
let v2 = BatEnum.get_exn enum in
two v1 v2
| 3 ->
let v1 = BatEnum.get_exn enum in
let v2 = BatEnum.get_exn enum in
let v3 = BatEnum.get_exn enum in
three v1 v2 v3
| 4 ->
let v1 = BatEnum.get_exn enum in
let v2 = BatEnum.get_exn enum in
let v3 = BatEnum.get_exn enum in
let v4 = BatEnum.get_exn enum in
four v1 v2 v3 v4
| _ -> assert false
let fast_of_enum enum n =
if n = 0 then Nil else
if n = 1 then Single (BatEnum.get_exn enum) else
let n_rec = if n <= 8 then 0 else (n - 8 + 3 - 1) / 3 in
let n_left = (n - n_rec * 3) / 2 in
let n_right = (n - n_rec * 3 + 1) / 2 in
let pr = get_digit enum n_left in
let m = fast_of_enum_aux 1 enum n_rec in
let sf = get_digit enum n_right in
Deep (n, pr, m, sf)
let rec get_node depth a i =
if depth = 1 then
let v1 = BatDynArray.unsafe_get a !i in
let v2 = BatDynArray.unsafe_get a (!i + 1) in
let v3 = BatDynArray.unsafe_get a (!i + 2) in
i := !i + 3;
Obj.magic (node3 v1 v2 v3)
else
let v1 = get_node (depth - 1) a i in
let v2 = get_node (depth - 1) a i in
let v3 = get_node (depth - 1) a i in
Obj.magic (node3_node v1 v2 v3)
let rec get_digit_node depth a i n =
match n with
| 1 ->
let v1 = get_node depth a i in
one_node v1
| 2 ->
let v1 = get_node depth a i in
let v2 = get_node depth a i in
two_node v1 v2
| 3 ->
let v1 = get_node depth a i in
let v2 = get_node depth a i in
let v3 = get_node depth a i in
three_node v1 v2 v3
| 4 ->
let v1 = get_node depth a i in
let v2 = get_node depth a i in
let v3 = get_node depth a i in
let v4 = get_node depth a i in
four_node v1 v2 v3 v4
| _ -> assert false
let rec fast_of_enum_aux depth a i n =
if n = 0 then Nil else
if n = 1 then Single (get_node depth a i) else
let n_rec = if n <= 8 then 0 else (n - 8 + 3 - 1) / 3 in
let n_left = (n - n_rec * 3) / 2 in
let n_right = (n - n_rec * 3 + 1) / 2 in
let pr = get_digit_node depth a i n_left in
let m = Obj.magic (fast_of_enum_aux (depth + 1) a i n_rec) in
let sf = get_digit_node depth a i n_right in
deep pr m sf
let rec get_digit a i n =
match n with
| 1 ->
let v1 = BatDynArray.unsafe_get a !i in
i := !i + 1;
one v1
| 2 ->
let v1 = BatDynArray.unsafe_get a !i in
let v2 = BatDynArray.unsafe_get a (!i + 1) in
i := !i + 2;
two v1 v2
| 3 ->
let v1 = BatDynArray.unsafe_get a !i in
let v2 = BatDynArray.unsafe_get a (!i + 1) in
let v3 = BatDynArray.unsafe_get a (!i + 2) in
i := !i + 3;
three v1 v2 v3
| 4 ->
let v1 = BatDynArray.unsafe_get a !i in
let v2 = BatDynArray.unsafe_get a (!i + 1) in
let v3 = BatDynArray.unsafe_get a (!i + 2) in
let v4 = BatDynArray.unsafe_get a (!i + 3) in
i := !i + 4;
four v1 v2 v3 v4
| _ -> assert false
let fast_of_enum_array a i n =
if n = 0 then Nil else
if n = 1 then Single (BatDynArray.unsafe_get a 0) else
let n_rec = if n <= 8 then 0 else (n - 8 + 3 - 1) / 3 in
let n_left = (n - n_rec * 3) / 2 in
let n_right = (n - n_rec * 3 + 1) / 2 in
let pr = get_digit a i n_left in
let m = fast_of_enum_aux 1 a i n_rec in
let sf = get_digit a i n_right in
Deep (n, pr, m, sf)
let of_enum enum =
if BatEnum.fast_count enum then
fast_of_enum enum (BatEnum.count enum)
else
let a = BatDynArray.make 10 in
try while true do BatDynArray.add a (BatEnum.get_exn enum) done;
assert false
with BatEnum.No_more_elements ->
fast_of_enum_array a (ref 0) (BatDynArray.length a)
let rec map_a f depth a =
if depth = 0 then
f a
else
Obj.magic (
match Obj.magic a with
| Node2 (v, a, b) ->
let a = map_a f (depth - 1) a in
let b = map_a f (depth - 1) b in
Node2 (v, a, b)
| Node3 (v, a, b, c) ->
let a = map_a f (depth - 1) a in
let b = map_a f (depth - 1) b in
let c = map_a f (depth - 1) c in
Node3 (v, a, b, c)
)
let map_digit f depth = function
| One (v, a) ->
let a = map_a f depth a in
One (v, a)
| Two (v, a, b) ->
let a = map_a f depth a in
let b = map_a f depth b in
Two (v, a, b)
| Three (v, a, b, c) ->
let a = map_a f depth a in
let b = map_a f depth b in
let c = map_a f depth c in
Three (v, a, b, c)
| Four (v, a, b, c, d) ->
let a = map_a f depth a in
let b = map_a f depth b in
let c = map_a f depth c in
let d = map_a f depth d in
Four (v, a, b, c, d)
let rec map f depth = function
| Nil ->
Nil
| Single a ->
let a = map_a f depth a in
Single a
| Deep (v, pr, m, sf) ->
let pr = map_digit f depth pr in
let m = Obj.magic (map f (depth + 1) (Obj.magic m)) in
let sf = map_digit f depth sf in
Deep (v, pr, m, sf)
let map f t =
map f 0 t
end
let reverse2 = Spec.reverse
let update2 = Spec.update
let set2 = Spec.set
let get2 = Spec.get
let of_enum2 = Spec.of_enum
let map2 = Spec.map
end
SEARCHME
let rec memory_size acc t =
let tag = Obj.tag t in
if tag = Obj.int_tag then acc
else if tag < Obj.no_scan_tag &&
tag <> Obj.lazy_tag &&
tag <> Obj.closure_tag &&
tag <> Obj.object_tag &&
tag <> Obj.infix_tag &&
tag <> Obj.forward_tag &&
tag <> Obj.abstract_tag &&
tag <> Obj.string_tag &&
tag <> Obj.double_tag &&
tag <> Obj.double_array_tag &&
tag <> Obj.custom_tag &&
tag <> Obj.final_tag &&
tag <> Obj.out_of_heap_tag &&
tag <> Obj.unaligned_tag then
let size = Obj.size t in
let acc = ref (acc + size + 1) in
for i = 0 to size - 2 do
acc := memory_size !acc (Obj.field t i)
done;
memory_size !acc (Obj.field t (size - 1))
else
assert false
let memory_size a = memory_size 0 (Obj.repr a)
let bench_size size s =
let module M = (val s : SIG) in
let rec aux stack = function
| 0 -> stack
| n -> aux (M.cons stack n) (n - 1) in
let s = aux M.empty size in
memory_size s
let bench_cons_front size s n =
for i = 0 to n do
let module M = (val s : SIG) in
let rec aux stack = function
| 0 -> stack
| n -> aux (M.cons stack n) (n - 1) in
let s = aux M.empty size in
let rec aux stack =
match M.front stack with
| None -> ()
| Some (stack, _) -> aux stack in
aux s
done
let bench_map size s =
let module M = (val s : SIG) in
let rec aux stack = function
| 0 -> stack
| n -> aux (M.cons stack n) (n - 1) in
let s = aux M.empty size in
fun n ->
for i = 0 to n do
ignore (M.map (fun x -> x + 1) s)
done
let bench_snoc_front size s n =
for i = 0 to n do
let module M = (val s : SIG) in
let rec aux stack = function
| 0 -> stack
| n -> aux (M.snoc stack n) (n - 1) in
let s = aux M.empty size in
let rec aux stack =
match M.front stack with
| None -> ()
| Some (stack, _) -> aux stack in
aux s
done
let bench_snoc_front_rear size s n =
for i = 0 to n do
let module M = (val s : SIG) in
let rec aux stack = function
| 0 -> stack
| n -> aux (M.snoc stack n) (n - 1) in
let s = aux M.empty size in
let rec aux stack =
match M.front stack with
| None -> ()
| Some (stack, _) ->
match M.rear stack with
| None -> ()
| Some (stack, _) -> aux stack in
aux s
done
let bench_enum1 size s =
let a = BatArray.Labels.init size ~f:(fun i -> i) in
let e = BatArray.enum a in
let module M = (val s : SIG) in
let t = M.generate_of_enum e in
fun n ->
for i = 0 to n do
let e = M.enum t in
try while true; do ignore (BatEnum.get_exn e); done
with BatEnum.No_more_elements -> ()
done
let bench_of_enum1 size s n =
let a = BatArray.Labels.init size ~f:(fun i -> i) in
for i = 0 to n do
let e = BatArray.enum a in
let module M = (val s : SIG) in
ignore (M.of_enum e)
done
let bench_fold_left size s =
let a = BatArray.Labels.init size ~f:(fun i -> i) in
let e = BatArray.enum a in
let module M = (val s : SIG) in
let t = M.generate_of_enum e in
fun n ->
for i = 0 to n do
M.fold_left (fun () _ -> ()) () t;
done
let bench_fold_right size s =
let a = BatArray.Labels.init size ~f:(fun i -> i) in
let e = BatArray.enum a in
let module M = (val s : SIG) in
let t = M.generate_of_enum e in
fun n ->
for i = 0 to n do
M.fold_right (fun () _ -> ()) () t;
done
let bench_reverse size s =
let a = BatArray.Labels.init size ~f:(fun i -> i) in
let e = BatArray.enum a in
let module M = (val s : SIG) in
let t = M.generate_of_enum e in
fun n ->
for i = 0 to n do
ignore (M.reverse t)
done
let bench_append size s =
let a = BatArray.Labels.init size ~f:(fun i -> i) in
let e = BatArray.enum a in
let module M = (val s : SIG) in
let t = M.generate_of_enum e in
fun n ->
for i = 0 to n do
ignore (M.append t t)
done
let bench_get size s =
let a = BatArray.Labels.init size ~f:(fun i -> i) in
let e = BatArray.enum a in
let module M = (val s : SIG) in
let t = M.generate_of_enum e in
fun n ->
for i = 0 to n do
for i = 0 to size - 1 do
ignore (M.get t i)
done
done
let bench_set size s =
let a = BatArray.Labels.init size ~f:(fun i -> i) in
let e = BatArray.enum a in
let module M = (val s : SIG) in
let t = M.generate_of_enum e in
fun n ->
for i = 0 to n do
let t = ref t in
for i = 0 to size - 1 do
t := M.set !t i 0
done
done
module ListTailCore : SIG = struct include ListTail let map = map2 end
module ListTailModConsOpt : SIG = struct include ListTailModCons let map = map2 end
module FgGen : SIG = Sequence
module FgGenOpt : SIG = struct include Sequence let enum = enum2 let fold_left = fold_left2 let fold_right = fold_right2 end
module FgSpec : SIG = struct include Sequence let reverse = reverse2 let update = update2 let set = set2 let get = get2 let of_enum = of_enum2 let map = map2 end
let sizes = [
1; 10; 100; 1_000; 10_000; 100_000;
]
let print_readings ~title size l =
if size = BatList.hd sizes then (
Printf.printf "#%s size" title;
BatList.iter (fun r ->
Printf.printf "\t%s" r.Bench.desc;
) l;
Printf.printf "\n"
);
Printf.printf "%d" size;
BatList.iter (fun r ->
Printf.printf "\t%.3f" (1_000_000_000. *. r.Bench.mean.Bench.Bootstrap.point /. float size)
) l;
Printf.printf "\n"
let bench ~title ?(deque=false) ?(list=false) ?(map=false) bench =
fun size ->
let core = if map then [
"ListTailModConsOpt", bench size (module ListTailModConsOpt : SIG);
"ListTailCore", bench size (module ListTailCore : SIG);
] else [] in
let lists = if list then [
"ListOverflow", bench size (module ListOverflow : SIG);
"ListTail", bench size (module ListTail : SIG);
"ListTailModCons", bench size (module ListTailModCons : SIG);
] @ core else [
] in
let deque = if deque then [
"Deque", bench size (module Deque : SIG);
] else [] in
let readings =
Bench.bench_n (lists @ deque @ [
"FgGen", bench size (module FgGen : SIG);
"FgGenOpt", bench size (module FgGenOpt : SIG);
"FgSpec", bench size (module FgSpec : SIG);
"Vect", bench size (module Vect : SIG);
]) in
fun () -> print_readings ~title size readings
let heap_size ~title size =
let assoc = [
"ListOverflow", bench_size size (module ListOverflow : SIG);
"Deque", bench_size size (module Deque : SIG);
"FgGen", bench_size size (module FgGen : SIG);
"Vect", bench_size size (module Vect : SIG);
] in
fun () ->
if size = BatList.hd sizes then (
Printf.printf "#%s size" title;
BatList.iter (fun (name,_) -> Printf.printf "\t%s" name) assoc;
Printf.printf "\n"
);
Printf.printf "%d" size;
BatList.iter (fun (_,size) -> Printf.printf "\t%d" size) assoc;
Printf.printf "\n"
let benches = [
"cons_front", bench ~list:true ~deque:true bench_cons_front;
"snoc_front", bench ~deque:true bench_snoc_front;
"snoc_front_rear", bench ~deque:true bench_snoc_front_rear;
"size", heap_size;
"map", bench ~deque:true ~list:true ~map:true bench_map;
"of_enum", bench ~list:true ~deque:true bench_of_enum1;
"enum", bench ~list:true ~deque:true bench_enum1;
"fold_left", bench ~list:true ~deque:true bench_fold_left;
"fold_right", bench ~list:true ~deque:true bench_fold_right;
"reverse", bench ~list:true bench_reverse;
"append", bench bench_append;
"set", bench bench_set;
"get", bench bench_get;
]
let () =
Bench.config.Bench.samples <- 100;
Array.iter (fun s ->
try
let f = BatList.assoc s benches in
let printers = BatList.map (f ~title:s) sizes in
BatList.iter (fun f -> f ()) printers;
Printf.printf "\n"
with Not_found ->
Printf.printf "`%s' is not a valid bench name\nThe possibilities are: " s;
BatList.iter (fun (name,_) -> Printf.printf "%s, " name) benches;
Printf.printf "\n";
exit 1
) (Array.sub Sys.argv 1 (Array.length Sys.argv - 1))
|
a9b6f7d75bfa5ed9ab46f2f088c63786cf6a54a9f88df00969d429437451503d | zxymike93/SICP | 340.rkt | (define x 10)
(parallel-execute
(lambda () (set! x (* x x)))
(lambda () (set! x (* x x x))))
;; 所有可能的结果为
( * 10 10 ) - > ( set ! x 100 ) - > ( * 100 100 100 ) - > ( set ! x 1000000 ) - > 1000000
( * 10 10 ) - > ( * 10 10 10 ) - > ( set ! x 100 ) - > ( set ! x 1000 ) - > 1000
( * 10 10 ) - > ( * 10 10 10 ) - > ( set ! x 1000 ) - > ( set ! x 100 ) - > 100
( * 10 x ) - > ( * 10 10 10 ) - > ( set ! x 1000 ) - > ( * 10 1000 ) - > ( set ! 10 1000 ) - > 10000
( * 10 10 10 ) - > ( set ! x 1000 ) - > ( * 1000 1000 ) - > ( set ! x 1000000 ) - > 1000000
( * 10 10 10 ) - > ( * 10 10 ) - > ( set ! x 1000 ) - > ( set ! x 100 ) - > 100
( * 10 10 10 ) - > ( * 10 10 ) - > ( set ! x 100 ) - > ( set ! x 1000 ) - > 1000
( * 10 10 x ) - > ( * 10 10 ) - > ( set ! x 100 ) - > ( * 10 10 100 ) - > ( set ! x 10000 ) - > 10000
( * 10 x x ) - > ( * 10 10 ) - > ( set ! x 100 ) - > ( * 10 100 100 ) - > ( set ! x 100000 ) - > 100000
(parallel-execute
(s (lambda () (set! x (* x x))))
(s (lambda () (set! x (* x x x)))))
;; 所有的可能为
( set ! x ( * 10 10 ) ) - > ( set ! x ( * 100 100 100 ) ) - > 1000000
( set ! x ( * 10 10 10 ) ) - > ( set ! x ( * 1000 1000 ) ) - > 1000000
| null | https://raw.githubusercontent.com/zxymike93/SICP/9d8e84d6a185bf4d7f28c414fc3359741384beb5/chapter3/340.rkt | racket | 所有可能的结果为
所有的可能为 | (define x 10)
(parallel-execute
(lambda () (set! x (* x x)))
(lambda () (set! x (* x x x))))
( * 10 10 ) - > ( set ! x 100 ) - > ( * 100 100 100 ) - > ( set ! x 1000000 ) - > 1000000
( * 10 10 ) - > ( * 10 10 10 ) - > ( set ! x 100 ) - > ( set ! x 1000 ) - > 1000
( * 10 10 ) - > ( * 10 10 10 ) - > ( set ! x 1000 ) - > ( set ! x 100 ) - > 100
( * 10 x ) - > ( * 10 10 10 ) - > ( set ! x 1000 ) - > ( * 10 1000 ) - > ( set ! 10 1000 ) - > 10000
( * 10 10 10 ) - > ( set ! x 1000 ) - > ( * 1000 1000 ) - > ( set ! x 1000000 ) - > 1000000
( * 10 10 10 ) - > ( * 10 10 ) - > ( set ! x 1000 ) - > ( set ! x 100 ) - > 100
( * 10 10 10 ) - > ( * 10 10 ) - > ( set ! x 100 ) - > ( set ! x 1000 ) - > 1000
( * 10 10 x ) - > ( * 10 10 ) - > ( set ! x 100 ) - > ( * 10 10 100 ) - > ( set ! x 10000 ) - > 10000
( * 10 x x ) - > ( * 10 10 ) - > ( set ! x 100 ) - > ( * 10 100 100 ) - > ( set ! x 100000 ) - > 100000
(parallel-execute
(s (lambda () (set! x (* x x))))
(s (lambda () (set! x (* x x x)))))
( set ! x ( * 10 10 ) ) - > ( set ! x ( * 100 100 100 ) ) - > 1000000
( set ! x ( * 10 10 10 ) ) - > ( set ! x ( * 1000 1000 ) ) - > 1000000
|
c4a8930d1f89a8392e12869b0bb25303aa3b141479e91d1b4c0b9ce61ab481ae | solita/mnt-teet | navigation_logo.cljs | (ns teet.navigation.navigation-logo
(:require [teet.navigation.navigation-style :as navigation-style]
[herb.core :as herb :refer [<class]]))
(defn logo-shield
[{:keys [width height]
:or {width "100%"
height "100%"}}]
[:svg#Layer_1 {:class (<class navigation-style/logo-shield-style)
:height height
:width width
:version "1.1" :xmlns ""
:x "0px" :y "0px"
:viewBox "0 0 170.079 90.709"}
[:g
[:path.st0 {:style {:fill "#222221"}
:d "M156.76,42.142h-4.988v0.962h1.844v6.319h1.263v-6.319h1.881V42.142z M150.029,45.154h-2.681v-2.05h3.137
v-0.962h-4.4v7.281h4.4v-0.962h-3.137v-2.344h2.681V45.154z M139.173,42.142h-1.594v7.281h1.263v-4.806l0.037-0.006l1.569,4.812
h0.856l1.563-4.781l0.037,0.006v4.775h1.269v-7.281h-1.588l-1.693,5.725h-0.038L139.173,42.142z M133.217,43.917h0.037l0.919,2.9
h-1.869L133.217,43.917z M134.998,49.423h1.325l-2.425-7.281h-1.306l-2.438,7.281h1.332l0.518-1.644h2.469L134.998,49.423z
M128.873,42.142h-1.262v7.281h1.262V42.142z M123.242,43.104c0.409,0,0.748,0.193,1.019,0.577
c0.271,0.385,0.406,0.864,0.406,1.437v1.316c0,0.586-0.135,1.07-0.406,1.453c-0.271,0.382-0.61,0.574-1.019,0.574h-1.05v-5.357
H123.242z M123.242,49.423c0.767,0,1.407-0.278,1.919-0.834c0.513-0.557,0.769-1.272,0.769-2.147v-1.313
c0-0.875-0.256-1.591-0.769-2.15c-0.512-0.558-1.152-0.837-1.919-0.837h-2.312v7.281H123.242z M115.549,43.104h1.169
c0.366,0,0.641,0.111,0.825,0.332c0.183,0.22,0.275,0.518,0.275,0.893c0,0.379-0.091,0.671-0.272,0.875
c-0.181,0.204-0.457,0.306-0.828,0.306h-1.169V43.104z M116.824,46.473c0.333,0,0.59,0.106,0.769,0.319
c0.179,0.212,0.268,0.51,0.268,0.894v0.656c0,0.216,0.006,0.429,0.016,0.637c0.01,0.209,0.037,0.357,0.078,0.444h1.306v-0.106
c-0.054-0.088-0.09-0.225-0.109-0.413c-0.019-0.187-0.028-0.373-0.028-0.556v-0.669c0-0.437-0.088-0.805-0.263-1.103
c-0.175-0.298-0.458-0.507-0.85-0.628c0.35-0.162,0.617-0.385,0.8-0.669c0.184-0.283,0.275-0.618,0.275-1.006
c0-0.671-0.209-1.194-0.628-1.569c-0.418-0.375-0.999-0.562-1.74-0.562h-2.432v7.281h1.263v-2.95H116.824z M111.362,46.534
c0,0.636-0.126,1.134-0.378,1.493c-0.253,0.36-0.599,0.54-1.041,0.54c-0.454,0-0.807-0.18-1.059-0.54
c-0.253-0.359-0.379-0.857-0.379-1.493v-1.522c0-0.623,0.125-1.114,0.375-1.471c0.25-0.358,0.6-0.537,1.05-0.537
c0.446,0,0.796,0.179,1.05,0.537c0.255,0.357,0.382,0.848,0.382,1.471V46.534z M112.624,45.023c0-0.887-0.25-1.606-0.75-2.156
s-1.148-0.825-1.944-0.825c-0.8,0-1.447,0.275-1.943,0.825s-0.744,1.269-0.744,2.156v1.519c0,0.896,0.249,1.618,0.747,2.165
c0.498,0.548,1.149,0.822,1.953,0.822c0.796,0,1.442-0.274,1.937-0.822c0.496-0.547,0.744-1.269,0.744-2.165V45.023z
M102.455,43.104h1.294c0.375,0,0.665,0.139,0.869,0.416s0.306,0.611,0.306,1.003c0,0.383-0.102,0.708-0.306,0.975
c-0.204,0.267-0.494,0.4-0.869,0.4h-1.294V43.104z M103.749,46.861c0.746,0,1.34-0.219,1.781-0.656
c0.442-0.437,0.663-1.003,0.663-1.698c0-0.69-0.221-1.257-0.663-1.7c-0.441-0.444-1.035-0.665-1.781-0.665h-2.556v7.281h1.262
v-2.562H103.749z M98.037,48.274c-0.213,0.195-0.527,0.293-0.944,0.293c-0.387,0-0.705-0.102-0.953-0.304
c-0.248-0.203-0.372-0.534-0.372-0.993h-1.212l-0.019,0.037c-0.021,0.747,0.206,1.304,0.681,1.671
c0.475,0.368,1.1,0.551,1.875,0.551c0.771,0,1.385-0.18,1.841-0.539c0.456-0.36,0.684-0.854,0.684-1.481
c0-0.611-0.181-1.078-0.544-1.4c-0.362-0.322-0.925-0.594-1.687-0.816c-0.567-0.173-0.941-0.347-1.122-0.522
c-0.181-0.176-0.272-0.418-0.272-0.727c0-0.301,0.093-0.55,0.278-0.746c0.186-0.196,0.47-0.294,0.853-0.294
c0.38,0,0.666,0.117,0.86,0.352c0.194,0.234,0.29,0.544,0.29,0.93h1.213l0.012-0.037c0.017-0.692-0.186-1.233-0.609-1.623
c-0.423-0.389-1.011-0.584-1.766-0.584c-0.733,0-1.315,0.185-1.746,0.555c-0.432,0.371-0.647,0.858-0.647,1.461
c0,0.62,0.18,1.087,0.54,1.399c0.361,0.312,0.937,0.578,1.728,0.799c0.517,0.17,0.872,0.348,1.066,0.532
c0.194,0.185,0.291,0.427,0.291,0.726C98.356,47.826,98.249,48.079,98.037,48.274 M92.912,42.142h-1.269v5.025l-0.037,0.012
l-2.794-5.037H87.55v7.281h1.262v-5.031l0.038-0.013l2.793,5.044h1.269V42.142z M83.187,43.917h0.038l0.919,2.9h-1.869
L83.187,43.917z M84.969,49.423h1.325l-2.425-7.281h-1.307l-2.437,7.281h1.331l0.519-1.644h2.469L84.969,49.423z M75.35,43.104
h1.169c0.367,0,0.642,0.111,0.825,0.332c0.183,0.22,0.275,0.518,0.275,0.893c0,0.379-0.091,0.671-0.272,0.875
c-0.181,0.204-0.457,0.306-0.828,0.306H75.35V43.104z M76.625,46.473c0.334,0,0.59,0.106,0.769,0.319
c0.179,0.212,0.269,0.51,0.269,0.894v0.656c0,0.216,0.005,0.429,0.015,0.637c0.011,0.209,0.037,0.357,0.078,0.444h1.307v-0.106
c-0.054-0.088-0.091-0.225-0.11-0.413c-0.018-0.187-0.028-0.373-0.028-0.556v-0.669c0-0.437-0.087-0.805-0.262-1.103
c-0.175-0.298-0.459-0.507-0.85-0.628c0.35-0.162,0.616-0.385,0.8-0.669c0.183-0.283,0.275-0.618,0.275-1.006
c0-0.671-0.21-1.194-0.628-1.569c-0.419-0.375-0.999-0.562-1.741-0.562h-2.431v7.281h1.262v-2.95H76.625z M73.263,40.323h-5.931
v0.963h2.325v8.137h1.268v-8.137h2.338V40.323z"}]]
[:g
[:g
[:path.st1 {:style {:fill "#006EB5"}
:d "M26.221,66.786c0,0.135,0.037,0.262,0.101,0.371c0.245-0.249,0.556-0.434,0.904-0.528
c0.146-0.516,0.62-0.893,1.182-0.893c0.048,0,0.095,0.002,0.141,0.008c-0.468,0.135-0.846,0.484-1.021,0.934
c-0.291,0.096-0.501,0.371-0.501,0.694c0,0.151,0.046,0.291,0.124,0.407c0.253-0.283,0.585-0.493,0.962-0.595
c0.108-0.542,0.559-0.96,1.117-1.019c-0.487,0.204-0.829,0.686-0.829,1.247c0,0.198,0.043,0.387,0.12,0.557
c0.086-0.309,0.369-0.536,0.705-0.536c0.085,0,0.166,0.014,0.24,0.041c0.105,0.038,0.218,0.058,0.334,0.058
c0.541,0,0.98-0.439,0.98-0.981c0-0.108-0.017-0.212-0.049-0.31c0.257,0.075,0.445,0.313,0.445,0.595
c0,0.129-0.039,0.248-0.106,0.347c0.072,0.013,0.146,0.02,0.222,0.02c0.637,0,1.163-0.479,1.236-1.097
c0.32-0.173,0.601-0.407,0.843-0.699l0.17,0.829c0.012,0.057,0.008,0.115-0.007,0.167c-0.015,0.053-0.043,0.103-0.084,0.145
l0.703-0.722c0.041-0.042,0.069-0.092,0.083-0.145c0.016-0.053,0.019-0.11,0.007-0.168l-0.207-1.011
c-0.012-0.057-0.009-0.115,0.007-0.167c0.015-0.053,0.043-0.103,0.084-0.145l0.553-0.564c-0.041,0.042-0.069,0.092-0.084,0.145
s-0.018,0.11-0.006,0.167l0.207,1.013c0.012,0.058,0.009,0.115-0.006,0.168c-0.015,0.052-0.042,0.101-0.082,0.143l0.627-0.652
c0.04-0.042,0.068-0.092,0.083-0.145c0.016-0.052,0.019-0.11,0.006-0.167l-0.206-1.01c-0.012-0.057-0.009-0.115,0.007-0.167
c0.015-0.053,0.043-0.103,0.084-0.145l0.553-0.564c-0.041,0.042-0.069,0.092-0.084,0.145c-0.015,0.052-0.018,0.11-0.006,0.167
l0.208,1.013c0.012,0.057,0.008,0.115-0.007,0.167s-0.042,0.101-0.082,0.143l0.627-0.651c0.041-0.042,0.068-0.093,0.083-0.145
c0.016-0.053,0.019-0.11,0.007-0.168l-0.101-0.494c-0.106-0.559,0.471-1.202,0.929-1.267c0.055-0.106,0.085-0.221,0.085-0.34
c0-0.567-0.675-1.027-1.509-1.027c-0.407,0-0.777,0.11-1.049,0.289c0.109,0.323,0.132,0.651-0.937,0.803
c-0.848,0.12-1.594,0.285-2.161,0.766c-0.874,0.741-0.803,1.732-1.3,2.107c0.221,0.054,0.502,0.054,0.803-0.011
c0.19-0.041,0.366-0.104,0.521-0.182c-0.093,0.179-0.306,0.348-0.586,0.468c-0.092,0.35-0.403,0.684-0.823,0.84
c-0.265,0.098-0.528,0.108-0.746,0.045l-1.023-0.296c-0.126-0.036-0.257-0.055-0.394-0.055c-0.754,0-1.376,0.581-1.468,1.332
C26.494,66.111,26.221,66.417,26.221,66.786 M36.335,26.328c0.589-0.576,1.27-1.057,2.019-1.42
c-0.022-0.088-0.034-0.178-0.034-0.269v-0.006c-3.126,0.513-5.939,2.118-8.479,2.104c-0.712-0.003-1.27-0.275-1.36-0.726
c-0.018-0.089-0.016-0.181,0.003-0.273c0.038-0.175,0.194-0.308,0.382-0.308c0.216,0,0.39,0.175,0.39,0.39
c0,0.104-0.04,0.198-0.105,0.268c0.073,0.007,0.148,0.011,0.226,0.011c0.201,0,0.392-0.025,0.56-0.071
c0.275-0.073,0.477-0.324,0.477-0.623c0-0.355-0.289-0.643-0.645-0.643c-0.019,0-0.039,0.001-0.058,0.002
c0.089-0.038,0.189-0.059,0.293-0.059c0.413,0,0.749,0.335,0.749,0.749c0,0.022-0.001,0.043-0.003,0.064
c1.116-0.025,2.374-1.043,2.649-1.431c-0.35,0.08-0.729,0.124-1.125,0.124c-0.449,0-0.878-0.056-1.266-0.158
c-0.549-0.145-1.089-0.226-1.504-0.226c-1.37,0-2.479,0.893-2.479,1.994c0,0.91,0.752,1.705,1.794,1.918
C31.19,28.225,33.979,26.815,36.335,26.328 M22.967,29.571c0.063-0.334,0.089-0.657,0.077-0.969l-0.299,0.35
c-0.059-0.139-0.098-0.225-0.138-0.294c-0.033-0.057-0.061-0.096-0.1-0.103c-0.02,0.01-0.05,0.027-0.083,0.034
c-0.038,0.009-0.09,0.006-0.123,0.006c-0.03,0-0.082,0.003-0.121-0.006c-0.032-0.007-0.062-0.024-0.082-0.034
c-0.04,0.007-0.067,0.046-0.1,0.103c-0.04,0.069-0.079,0.155-0.138,0.294l-0.3-0.35c-0.011,0.312,0.014,0.635,0.077,0.969
c0.221-0.048,0.449-0.065,0.664-0.065C22.518,29.506,22.746,29.523,22.967,29.571 M23.101,30.471
c0.033-0.379-0.397-0.514-0.8-0.514c-0.401,0-0.831,0.135-0.798,0.514c0.041,0.462,0.473,0.242,0.798,0.244
C22.628,30.713,23.06,30.933,23.101,30.471 M24.249,27.742c-0.079,0.021-0.122,0.067-0.131,0.15
c-0.047,0.446-0.228,0.626-0.517,0.727c-0.004,0.449-0.066,0.79-0.188,1.212c0.343,0.717,0.08,1.218-0.198,1.326
c-0.265,0.102-0.607-0.036-0.91-0.036s-0.65,0.138-0.915,0.036c-0.279-0.108-0.541-0.609-0.199-1.326
c-0.121-0.422-0.184-0.763-0.187-1.212c-0.289-0.101-0.471-0.281-0.518-0.727c-0.009-0.083-0.052-0.129-0.13-0.15
c-1.14-0.313-1.248-1.729-0.671-2.131c-0.052,0.635-0.106,1.53,1.19,1.649c-0.021,0.744,0.3,0.943,0.632,0.943
c0.271,0.001,0.426-0.086,0.494-0.122c0.241-0.128,0.075-0.324,0.013-0.382c-0.166-0.155-0.25-0.374-0.21-0.594
c0.007-0.04,0.022-0.06,0.059-0.06h0.438h0.44c0.037,0,0.053,0.02,0.059,0.06c0.04,0.22-0.044,0.439-0.209,0.594
c-0.062,0.058-0.228,0.254,0.013,0.382c0.067,0.036,0.223,0.123,0.494,0.122c0.331,0,0.653-0.199,0.632-0.943
c1.296-0.119,1.241-1.014,1.19-1.649C25.497,26.013,25.388,27.429,24.249,27.742 M24.6,25.271c0,0.325-0.238,0.687-0.509,0.687
h-0.249c0.063,0.075,0.101,0.172,0.101,0.276c0,0.241-0.195,0.436-0.435,0.436c-0.241,0-0.436-0.195-0.436-0.436
c0-0.104,0.038-0.201,0.1-0.276h-0.26c-0.089,0-0.158,0.037-0.213,0.141c-0.018-0.141-0.036-0.286-0.004-0.381
c0.044-0.132,0.146-0.21,0.248-0.21h1.142C24.296,25.508,24.453,25.436,24.6,25.271 M24.449,24.73H24.05
c-0.198,0-0.335-0.082-0.451-0.215l-0.455-0.594c-0.075-0.094-0.135-0.16-0.232-0.203h0.45c0.135,0,0.255,0.057,0.349,0.178
l0.474,0.603C24.291,24.627,24.324,24.713,24.449,24.73 M22.368,23.749l0.582,0.817c0.092,0.135,0.179,0.209,0.304,0.261h-0.533
c-0.205,0-0.328-0.095-0.418-0.242l-0.458-0.702c-0.175-0.263-0.244-0.328-0.445-0.401h0.495
C22.09,23.482,22.272,23.609,22.368,23.749 M21.049,23.896l0.474,0.603c0.106,0.128,0.139,0.214,0.264,0.231h-0.398
c-0.199,0-0.336-0.082-0.452-0.215l-0.455-0.594c-0.075-0.094-0.134-0.16-0.232-0.203h0.45
C20.835,23.718,20.955,23.775,21.049,23.896 M20.762,25.958h-0.249c-0.27,0-0.509-0.362-0.509-0.687
c0.148,0.165,0.304,0.237,0.516,0.237h1.142c0.102,0,0.204,0.078,0.248,0.21c0.032,0.095,0.014,0.24-0.004,0.381
c-0.055-0.104-0.124-0.141-0.213-0.141h-0.26c0.062,0.075,0.099,0.172,0.099,0.276c0,0.241-0.195,0.436-0.435,0.436
s-0.435-0.195-0.435-0.436C20.662,26.13,20.699,26.033,20.762,25.958 M19.354,31.399l0.138-0.27
c0.027-0.052,0.038-0.108,0.037-0.163c-0.001-0.054-0.015-0.111-0.043-0.16l0.379,0.681c0.028,0.052,0.042,0.108,0.043,0.161
c0.002,0.056-0.01,0.113-0.037,0.165l-0.034,0.067c-0.233,0.452-0.45,1.299-0.209,1.79c-0.562-0.209-0.747-0.701-0.687-1.11
c-1.058-1.002-1.324-2.019-0.569-2.872l0.387-0.453c0.04-0.044,0.065-0.095,0.076-0.148c0.013-0.053,0.013-0.11-0.002-0.166
l0.202,0.753c0.014,0.056,0.015,0.114,0.003,0.168c-0.012,0.053-0.037,0.104-0.075,0.149l-0.118,0.138
c-0.395,0.46-0.289,1.083,0.329,1.642C19.239,31.613,19.281,31.533,19.354,31.399 M45.29,34.227
c0.041-0.101,0.064-0.212,0.064-0.329c0-0.472-0.383-0.857-0.856-0.857h-0.866c-0.059,0.001-0.114-0.015-0.163-0.04
c-0.048-0.025-0.092-0.063-0.125-0.111l-0.434-0.641c0.033,0.049,0.076,0.086,0.125,0.11c0.048,0.027,0.104,0.041,0.163,0.04
l1.141,0.001c0.059,0,0.115,0.015,0.163,0.04c0.048,0.026,0.092,0.064,0.125,0.112l-0.524-0.767
c-0.033-0.05-0.077-0.086-0.126-0.111c-0.048-0.027-0.104-0.041-0.162-0.041l-1.132,0.001c-0.058,0-0.114-0.014-0.162-0.04
c-0.049-0.027-0.093-0.064-0.126-0.112l-0.492-0.724c0.033,0.049,0.077,0.086,0.125,0.111c0.049,0.026,0.104,0.041,0.163,0.041
l1.136-0.001c0.059,0,0.115,0.014,0.163,0.04c0.049,0.025,0.092,0.063,0.125,0.111l-0.524-0.768
c-0.033-0.048-0.077-0.085-0.126-0.111c-0.048-0.026-0.104-0.04-0.162-0.04H41.9c-0.059,0-0.114-0.015-0.163-0.04
c-0.048-0.026-0.092-0.063-0.125-0.113l-0.607-0.889c1.227-0.147,2.217-0.812,2.414-1.728c0.255-1.188-0.926-2.342-2.636-2.593
c-0.288-0.042-0.508-0.289-0.508-0.588c0-0.253,0.16-0.471,0.385-0.555c-0.182-0.079-0.386-0.123-0.602-0.123
c-0.757,0-1.37,0.542-1.37,1.211c0,0.12,0.021,0.237,0.058,0.346c-0.848,0.367-1.62,1.016-2.211,1.717
c0.632-0.168,1.296-0.259,1.981-0.259c-0.003-0.031-0.005-0.063-0.005-0.096c0-0.512,0.414-0.928,0.928-0.928h0.013
c-0.35,0.154-0.52,0.49-0.52,0.712c0,0.265,0.215,0.479,0.479,0.479c0.103,0,0.199-0.032,0.277-0.088
c-0.018-0.059-0.028-0.124-0.028-0.19c0-0.367,0.297-0.664,0.665-0.664c0.032,0,0.065,0.002,0.096,0.007
c-0.253,0.118-0.429,0.376-0.429,0.674c0,0.411,0.333,0.744,0.744,0.744c0.044,0,0.086-0.003,0.128-0.01
c-0.012-0.044-0.018-0.089-0.018-0.137c0-0.295,0.239-0.532,0.533-0.532c0.295,0,0.534,0.237,0.534,0.532
c0,0.642-0.712,0.7-1.231,0.552c-1.478-0.427-2.862-0.617-4.201-0.43c-1.718,0.242-4.532,1.403-7.519,1.306
c-0.668-0.021-1.397-0.132-2.131-0.333c0.09,0.099,0.148,0.167,0.186,0.225c0.291,0.453,0.391,0.927,0.134,1.522
c0.007-0.666-0.543-1.214-1.004-1.551c-0.186-0.134-0.261-0.263-0.23-0.436l0.136-0.768c-0.01,0.057-0.005,0.113,0.012,0.166
c0.017,0.052,0.046,0.101,0.088,0.142l0.287,0.281c0.109-0.777-0.067-1.502-0.53-2.173c0.205-0.536,0.233-1.128,0.096-1.682
c-0.054,0.42-0.26,0.6-0.456,0.721c-0.363,0.229-0.423,0.612-0.235,0.868c-0.307-0.155-0.73-0.724-0.485-1.057
c0.264-0.36,0.987-0.191,1.076-0.806c-0.469-0.149-0.952-0.044-1.099-0.005c-0.278-0.318-0.647-0.476-1.106-0.473
c-0.363-0.329-0.829-0.466-1.4-0.41c-0.568-0.056-1.034,0.081-1.397,0.41c-0.459-0.003-0.828,0.155-1.106,0.473
c-0.148-0.039-0.63-0.144-1.1,0.005c0.089,0.615,0.811,0.446,1.076,0.806c0.245,0.333-0.178,0.902-0.485,1.057
c0.189-0.256,0.128-0.639-0.236-0.868c-0.194-0.121-0.401-0.301-0.455-0.721c-0.137,0.554-0.108,1.146,0.096,1.682
c-0.463,0.671-0.639,1.396-0.53,2.173l0.288-0.281c0.042-0.041,0.071-0.09,0.088-0.142c0.017-0.053,0.021-0.109,0.01-0.166
l0.137,0.768c0.03,0.173-0.043,0.302-0.229,0.436c-0.462,0.337-1.012,0.885-1.005,1.551c-0.256-0.595-0.153-1.089,0.135-1.522
c-0.876-0.473-1.543-1.25-1.666-1.392c-0.265-0.309-0.23-0.701,0.01-1.045c0.463-0.662,0.573-1.368-0.008-1.851
c0.004-0.036,0.006-0.071,0.006-0.107c0-0.439-0.312-0.806-0.727-0.888c0.077,0.12,0.122,0.263,0.122,0.415
c0,0.176-0.058,0.336-0.157,0.467c0.082,0.107,0.131,0.241,0.131,0.388c0,0.196-0.088,0.371-0.227,0.488
c0.014-0.067,0.02-0.137,0.02-0.209c0-0.452-0.279-0.83-0.658-0.934c-0.061-0.328-0.349-0.577-0.695-0.577
c-0.201,0-0.381,0.083-0.51,0.216c0.268,0.022,0.484,0.232,0.513,0.497c-0.128,0.097-0.231,0.23-0.298,0.385h0.017
c0.463,0,0.838,0.375,0.838,0.838c0,0.052-0.005,0.104-0.014,0.153c-0.035-0.189-0.121-0.365-0.26-0.501
c-0.26-0.254-0.638-0.306-0.984-0.174c-0.13-0.164-0.33-0.268-0.554-0.268c-0.254,0-0.476,0.133-0.601,0.333
c0.256,0.011,0.481,0.14,0.622,0.335c-0.364,0.466-0.368,1.109,0.004,1.473c0.252,0.246,0.613,0.302,0.95,0.187
c0.022-0.008,0.046-0.012,0.071-0.012c0.124,0,0.224,0.101,0.224,0.224s-0.1,0.223-0.224,0.223c-0.054,0-0.104-0.019-0.142-0.051
c-0.085-0.071-0.195-0.113-0.314-0.113c-0.27,0-0.49,0.218-0.49,0.49c0,0.02,0.001,0.041,0.004,0.06
c-0.046,0.015-0.095,0.023-0.146,0.023c-0.132,0-0.252-0.054-0.34-0.14c-0.014,0.053-0.021,0.109-0.021,0.167
c0,0.345,0.266,0.628,0.605,0.654c0.152,0.377,0.523,0.644,0.955,0.644c0.222,0,0.427-0.07,0.595-0.188
c0.074-0.051,0.162-0.082,0.258-0.082c0.249,0,0.451,0.202,0.451,0.451c0,0.215-0.15,0.393-0.351,0.44l-0.351,0.076
c-0.057,0.014-0.115,0.011-0.168-0.005c-0.053-0.013-0.103-0.041-0.145-0.081l0.803,0.763c0.043,0.04,0.093,0.067,0.146,0.082
c0.053,0.015,0.11,0.018,0.167,0.005l0.658-0.146c0.057-0.013,0.115-0.01,0.167,0.004c0.052,0.015,0.104,0.042,0.146,0.082
l0.551,0.525c-0.043-0.04-0.093-0.069-0.147-0.082c-0.052-0.015-0.109-0.018-0.166-0.005l-0.657,0.144
c-0.057,0.014-0.115,0.011-0.167-0.004c-0.053-0.014-0.104-0.041-0.146-0.081l0.736,0.698c0.042,0.04,0.093,0.067,0.145,0.082
c0.053,0.014,0.111,0.016,0.168,0.004l0.658-0.144c0.058-0.013,0.115-0.011,0.168,0.005c0.053,0.014,0.103,0.042,0.146,0.082
l0.551,0.523c-0.043-0.04-0.093-0.066-0.146-0.082c-0.053-0.014-0.11-0.016-0.168-0.004l-0.656,0.145
c-0.058,0.013-0.115,0.01-0.168-0.005c-0.053-0.014-0.103-0.041-0.146-0.082l0.736,0.697c0.043,0.041,0.093,0.069,0.146,0.082
c0.053,0.016,0.11,0.019,0.168,0.005l0.795-0.173c-0.772,0.436-1.594,0.93-2.465,1.481c-0.515,0.325-1.078,0.386-1.725,0.138
c-0.348-0.133-0.725-0.156-0.963-0.115c-0.31,0.054-0.573,0.242-0.726,0.502c0.12-0.047,0.251-0.074,0.389-0.074
c0.289,0,0.55,0.116,0.74,0.305c-0.301-0.126-0.675-0.139-1.038-0.006c-0.65,0.235-1.029,0.849-0.881,1.397
c-0.243,0.094-0.413,0.329-0.413,0.603c0,0.181,0.074,0.345,0.194,0.462c0.064-0.288,0.316-0.505,0.621-0.517
c0.127,0.084,0.275,0.144,0.434,0.176c0.048-0.083,0.109-0.157,0.179-0.222c-0.008-0.051-0.011-0.104-0.011-0.158
c0-0.594,0.48-1.074,1.073-1.074c0.049,0,0.097,0.003,0.145,0.01c-0.471,0.113-0.822,0.537-0.822,1.044
c0,0.064,0.006,0.127,0.017,0.188c-0.254,0.098-0.433,0.343-0.433,0.631c0,0.165,0.059,0.315,0.158,0.434
c0.182-0.356,0.537-0.608,0.954-0.648c0.157,0.046,0.323,0.07,0.494,0.07c0.108,0,0.213-0.009,0.315-0.027
c-0.092-0.135-0.146-0.297-0.146-0.473c0-0.46,0.373-0.834,0.835-0.834c0.04,0,0.078,0.002,0.118,0.008
c-0.441,0.188-0.711,0.571-0.618,0.92c0.066,0.246,0.299,0.418,0.6,0.475c-0.004,0.184-0.055,0.359-0.142,0.51
c0.387-0.028,0.718-0.261,0.883-0.592c0.456-0.183,0.737-0.574,0.643-0.929c-0.034-0.127-0.113-0.234-0.22-0.315
c-0.001-0.012-0.002-0.025-0.002-0.037c0-0.245,0.199-0.443,0.442-0.443c0.246,0,0.444,0.198,0.444,0.443
c0,0.116-0.044,0.221-0.117,0.299h0.927c0.058,0,0.114-0.014,0.162-0.041c0.049-0.024,0.092-0.062,0.125-0.111l0.595-0.882
c0.022-0.033,0.052-0.058,0.085-0.076c0.033-0.018,0.07-0.028,0.111-0.028h0.728c-0.04,0-0.078,0.01-0.111,0.028
c-0.033,0.018-0.063,0.043-0.085,0.076l-0.597,0.882c-0.033,0.049-0.076,0.087-0.125,0.111c-0.048,0.027-0.103,0.041-0.162,0.041
h1.108c0.059,0,0.114-0.014,0.161-0.041c0.05-0.024,0.094-0.062,0.125-0.111l0.668-0.985c-0.46-0.252-0.649-0.694-0.649-1.299
c0-0.377,0.212-0.807,0.244-1.084L20.7,32.48c0.007-0.057-0.001-0.114-0.021-0.166c-0.016-0.042-0.048-0.101-0.083-0.142
l0.57,0.584c0.045,0.038,0.077,0.086,0.096,0.137c0.021,0.05,0.029,0.108,0.022,0.166l-0.017,0.133
c-0.027,0.233-0.319,0.733,0.223,1.191c0.027,0.022,0.094,0.071,0.158,0.111l0.385,0.241v-1.421h0.539v1.582
c0.001,0.059,0.018,0.114,0.045,0.162c0.027,0.047,0.065,0.089,0.115,0.121l0.526,0.335c0.051,0.032,0.106,0.049,0.16,0.052
c0.055,0.004,0.112-0.003,0.165-0.026l0.971-0.422c-0.054,0.024-0.111,0.031-0.165,0.027c-0.055-0.004-0.11-0.021-0.159-0.052
l-1.115-0.71c0.542-0.458,0.249-0.958,0.222-1.191l-0.016-0.133c-0.007-0.058,0.001-0.116,0.02-0.166
c0.021-0.051,0.053-0.099,0.097-0.137l0.57-0.584c-0.035,0.041-0.066,0.1-0.083,0.142c-0.019,0.052-0.027,0.109-0.02,0.166
l0.012,0.111c0.046,0.394,0.446,1.111,0.113,1.51l1.019,0.647c0.05,0.03,0.105,0.049,0.159,0.053
c0.055,0.004,0.112-0.004,0.166-0.029l1.015-0.44c-0.054,0.023-0.11,0.03-0.164,0.026c-0.055-0.003-0.11-0.02-0.16-0.052
l-1.102-0.701c0.24-0.492,0.038-1.273-0.195-1.725l-0.035-0.067c-0.026-0.052-0.038-0.109-0.036-0.165
c0-0.053,0.014-0.109,0.043-0.161l0.378-0.681c-0.028,0.049-0.042,0.106-0.042,0.16c-0.002,0.055,0.01,0.111,0.036,0.163
l0.139,0.27c0.073,0.134,0.114,0.214,0.178,0.372c0.62-0.559,0.758-1.098,0.363-1.557l-0.118-0.139
c-0.038-0.045-0.063-0.096-0.075-0.149c-0.013-0.054-0.013-0.112,0.003-0.168l0.202-0.753c-0.015,0.056-0.015,0.113-0.004,0.166
c0.013,0.053,0.038,0.104,0.077,0.149l0.388,0.452c0.754,0.853,0.298,1.951-0.602,2.788c0.05,0.161,0.093,0.461,0.057,0.625
l1.195,0.757c0.05,0.033,0.105,0.05,0.16,0.054c0.054,0.005,0.111-0.004,0.165-0.027l0.864-0.376
c-0.049,0.02-0.104,0.033-0.16,0.033c-0.223,0-0.403-0.181-0.403-0.402c0-0.18,0.117-0.335,0.281-0.384
c3.299-1.003,6.336-3.594,8.33-3.587c0.969,0.003,1.755,0.589,1.755,1.315c0,0.118-0.021,0.232-0.059,0.341
c-0.425,1.194,0.194,2.334,1.828,2.774c0.261,0.07,0.453,0.308,0.453,0.589c0,0.056-0.008,0.11-0.021,0.16
c0.037,0.004,0.075,0.005,0.114,0.005c0.45,0,0.848-0.223,1.089-0.566c0.28-0.002,0.587-0.019,0.901-0.053
c0.038,0.077,0.068,0.163,0.086,0.258c0.067,0.344-0.052,0.654-0.263,0.722c-0.375,0.122-0.835-0.025-1.19-0.021
c-0.672,0.007-1.215,0.553-1.215,1.227c0,0.052,0.003,0.103,0.01,0.156c-0.211,0.131-0.351,0.364-0.351,0.631
c0,0.133,0.035,0.258,0.095,0.366c0.207-0.241,0.477-0.428,0.784-0.536c0.026-0.591,0.512-1.06,1.108-1.06
c0.091,0,0.181,0.01,0.265,0.032c-0.604,0.076-1.072,0.592-1.072,1.217c0,0.045,0.003,0.089,0.008,0.134
c-0.075,0.092-0.12,0.207-0.12,0.334c0,0.16,0.072,0.305,0.185,0.402c0.114-0.25,0.389-0.485,0.745-0.605
c0.239-0.08,0.474-0.096,0.67-0.056c-0.032-0.094-0.047-0.194-0.047-0.297c0-0.534,0.431-0.966,0.965-0.966
c0.049,0,0.098,0.004,0.145,0.011c-0.372,0.049-0.658,0.369-0.658,0.754c0,0.255,0.126,0.482,0.319,0.621
c0,0.012-0.001,0.027-0.001,0.041c0,0.21,0.096,0.396,0.246,0.519c0.068-0.35,0.374-0.614,0.745-0.614
c0.316,0,0.577-0.04,0.772-0.105c0.33-0.107,0.571-0.413,0.571-0.777c0-0.253-0.115-0.479-0.297-0.628
c0.09-0.41,0.074-1.083-0.065-1.643c0.028-0.004,0.057-0.006,0.087-0.006C44.969,33.929,45.172,34.048,45.29,34.227
M28.481,41.176c-0.018-0.089-0.016-0.181,0.003-0.273c0.038-0.175,0.194-0.308,0.382-0.308c0.216,0,0.39,0.175,0.39,0.39
c0,0.104-0.04,0.198-0.105,0.268c0.073,0.007,0.148,0.011,0.226,0.011c0.201,0,0.392-0.026,0.56-0.071
c0.275-0.073,0.477-0.324,0.477-0.623c0-0.355-0.289-0.643-0.645-0.643c-0.019,0-0.039,0.001-0.058,0.002
c0.089-0.038,0.189-0.059,0.293-0.059c0.413,0,0.749,0.335,0.749,0.749c0,0.021-0.001,0.043-0.003,0.064
c1.116-0.025,2.374-1.043,2.649-1.431c-0.35,0.08-0.729,0.124-1.125,0.124c-0.449,0-0.878-0.056-1.266-0.158
c-0.549-0.146-1.089-0.226-1.504-0.226c-1.37,0-2.479,0.893-2.479,1.994c0,0.91,0.752,1.705,1.794,1.918
c2.371,0.486,5.16-0.924,7.516-1.411c0.589-0.576,1.27-1.057,2.019-1.421c-0.022-0.087-0.034-0.176-0.034-0.268v-0.006
c-3.126,0.514-5.939,2.118-8.479,2.104C29.129,41.899,28.571,41.627,28.481,41.176 M28.408,35.405
c0.048,0,0.095,0.004,0.141,0.009c-0.468,0.135-0.846,0.483-1.021,0.934c-0.291,0.095-0.501,0.371-0.501,0.694
c0,0.15,0.046,0.291,0.124,0.407c0.253-0.282,0.585-0.493,0.962-0.595c0.108-0.542,0.559-0.96,1.117-1.019
c-0.487,0.204-0.829,0.686-0.829,1.247c0,0.198,0.043,0.387,0.12,0.557c0.086-0.309,0.369-0.536,0.705-0.536
c0.085,0,0.166,0.014,0.24,0.041c0.105,0.038,0.218,0.059,0.334,0.059c0.541,0,0.98-0.44,0.98-0.982
c0-0.109-0.017-0.212-0.049-0.309c0.257,0.073,0.445,0.312,0.445,0.594c0,0.129-0.039,0.248-0.106,0.348
c0.072,0.013,0.146,0.019,0.222,0.019c0.637,0,1.163-0.479,1.236-1.098c0.32-0.172,0.601-0.406,0.843-0.698l0.17,0.828
c0.012,0.059,0.008,0.116-0.007,0.169c-0.015,0.052-0.043,0.102-0.084,0.145l0.703-0.723c0.041-0.042,0.069-0.093,0.083-0.145
c0.016-0.053,0.019-0.11,0.007-0.167l-0.207-1.012c-0.012-0.058-0.009-0.115,0.007-0.167c0.015-0.053,0.043-0.104,0.084-0.146
l0.553-0.563c-0.041,0.043-0.069,0.093-0.084,0.144c-0.015,0.054-0.018,0.111-0.006,0.168l0.207,1.014
c0.012,0.057,0.009,0.113-0.006,0.167c-0.015,0.052-0.042,0.101-0.082,0.143l0.627-0.653c0.04-0.042,0.068-0.091,0.083-0.144
c0.016-0.052,0.019-0.111,0.006-0.167l-0.206-1.01c-0.012-0.058-0.009-0.115,0.007-0.167c0.015-0.054,0.043-0.103,0.084-0.145
l0.553-0.564c-0.041,0.042-0.069,0.092-0.084,0.145c-0.015,0.052-0.018,0.11-0.006,0.167l0.208,1.013
c0.012,0.057,0.008,0.114-0.007,0.167c-0.015,0.052-0.042,0.101-0.082,0.143l0.627-0.652c0.041-0.042,0.068-0.091,0.083-0.144
c0.016-0.053,0.019-0.11,0.007-0.168l-0.101-0.494c-0.106-0.559,0.471-1.202,0.929-1.267c0.055-0.106,0.085-0.221,0.085-0.341
c0-0.566-0.675-1.026-1.509-1.026c-0.407,0-0.777,0.109-1.049,0.289c0.109,0.322,0.132,0.65-0.937,0.803
c-0.848,0.121-1.594,0.285-2.161,0.765c-0.874,0.742-0.803,1.733-1.3,2.108c0.221,0.054,0.502,0.054,0.803-0.011
c0.19-0.041,0.366-0.104,0.521-0.182c-0.093,0.179-0.306,0.348-0.586,0.467c-0.092,0.351-0.403,0.685-0.823,0.841
c-0.265,0.098-0.528,0.108-0.746,0.045l-1.023-0.296c-0.126-0.036-0.257-0.056-0.394-0.056c-0.754,0-1.376,0.582-1.468,1.332
c-0.356,0.05-0.629,0.357-0.629,0.726c0,0.136,0.037,0.263,0.101,0.371c0.245-0.249,0.556-0.434,0.904-0.528
C27.372,35.784,27.846,35.405,28.408,35.405 M22.967,44.736c0.063-0.334,0.089-0.657,0.077-0.969l-0.299,0.35
c-0.059-0.139-0.098-0.225-0.138-0.295c-0.033-0.056-0.061-0.095-0.1-0.102c-0.02,0.01-0.05,0.027-0.083,0.034
c-0.038,0.009-0.09,0.006-0.123,0.006c-0.03,0-0.082,0.003-0.121-0.006c-0.032-0.007-0.062-0.024-0.082-0.034
c-0.04,0.007-0.067,0.046-0.1,0.102c-0.04,0.07-0.079,0.156-0.138,0.295l-0.3-0.35c-0.011,0.312,0.014,0.635,0.077,0.969
c0.221-0.048,0.449-0.065,0.664-0.065C22.518,44.671,22.746,44.688,22.967,44.736 M23.101,45.636
c0.033-0.379-0.397-0.514-0.8-0.514c-0.401,0-0.831,0.135-0.798,0.514c0.041,0.462,0.473,0.242,0.798,0.244
C22.628,45.878,23.06,46.098,23.101,45.636 M24.249,42.907c-0.079,0.021-0.122,0.067-0.131,0.15
c-0.047,0.446-0.228,0.626-0.517,0.727c-0.004,0.449-0.066,0.79-0.188,1.212c0.343,0.717,0.08,1.218-0.198,1.325
c-0.265,0.103-0.607-0.035-0.91-0.035s-0.65,0.138-0.915,0.035c-0.279-0.107-0.541-0.608-0.199-1.325
c-0.121-0.422-0.184-0.763-0.187-1.212c-0.289-0.101-0.471-0.281-0.518-0.727c-0.009-0.083-0.052-0.129-0.13-0.15
c-1.14-0.313-1.248-1.729-0.671-2.131c-0.052,0.635-0.106,1.53,1.19,1.649c-0.021,0.744,0.3,0.943,0.632,0.943
c0.271,0.001,0.426-0.086,0.494-0.122c0.241-0.128,0.075-0.324,0.013-0.383c-0.166-0.154-0.25-0.375-0.21-0.593
c0.007-0.04,0.022-0.06,0.059-0.06h0.438h0.44c0.037,0,0.053,0.02,0.059,0.06c0.04,0.218-0.044,0.439-0.209,0.593
c-0.062,0.059-0.228,0.255,0.013,0.383c0.067,0.036,0.223,0.123,0.494,0.122c0.331,0,0.653-0.199,0.632-0.943
c1.296-0.119,1.241-1.014,1.19-1.649C25.497,41.178,25.388,42.594,24.249,42.907 M24.6,40.436c0,0.325-0.238,0.687-0.509,0.687
h-0.249c0.063,0.074,0.101,0.171,0.101,0.276c0,0.241-0.195,0.436-0.435,0.436c-0.241,0-0.436-0.195-0.436-0.436
c0-0.105,0.038-0.202,0.1-0.276h-0.26c-0.089,0-0.158,0.037-0.213,0.141c-0.018-0.141-0.036-0.285-0.004-0.382
c0.044-0.131,0.146-0.21,0.248-0.21h1.142C24.296,40.672,24.453,40.601,24.6,40.436 M24.449,39.895H24.05
c-0.198,0-0.335-0.082-0.451-0.215l-0.455-0.594c-0.075-0.094-0.135-0.16-0.232-0.203h0.45c0.135,0,0.255,0.057,0.349,0.178
l0.474,0.603C24.291,39.792,24.324,39.878,24.449,39.895 M22.368,38.914l0.582,0.817c0.092,0.135,0.179,0.209,0.304,0.261h-0.533
c-0.205,0-0.328-0.095-0.418-0.242l-0.458-0.702c-0.175-0.263-0.244-0.328-0.445-0.401h0.495
C22.09,38.647,22.272,38.774,22.368,38.914 M21.049,39.061l0.474,0.603c0.106,0.128,0.139,0.214,0.264,0.231h-0.398
c-0.199,0-0.336-0.082-0.452-0.215l-0.455-0.594c-0.075-0.094-0.134-0.16-0.232-0.203h0.45
C20.835,38.883,20.955,38.94,21.049,39.061 M20.762,41.123h-0.249c-0.27,0-0.509-0.362-0.509-0.687
c0.148,0.165,0.304,0.236,0.516,0.236h1.142c0.102,0,0.204,0.079,0.248,0.21c0.032,0.097,0.014,0.241-0.004,0.382
c-0.055-0.104-0.124-0.141-0.213-0.141h-0.26c0.062,0.074,0.099,0.171,0.099,0.276c0,0.241-0.195,0.436-0.435,0.436
s-0.435-0.195-0.435-0.436C20.662,41.294,20.699,41.197,20.762,41.123 M19.354,46.565l0.138-0.271
c0.027-0.052,0.038-0.108,0.037-0.163c-0.001-0.054-0.015-0.11-0.043-0.16l0.379,0.682c0.028,0.051,0.042,0.106,0.043,0.161
c0.002,0.055-0.01,0.112-0.037,0.164l-0.034,0.067c-0.233,0.452-0.45,1.299-0.209,1.79c-0.562-0.209-0.747-0.701-0.687-1.109
c-1.058-1.003-1.324-2.02-0.569-2.872l0.387-0.454c0.04-0.044,0.065-0.095,0.076-0.148c0.013-0.053,0.013-0.11-0.002-0.166
l0.202,0.753c0.014,0.057,0.015,0.114,0.003,0.168c-0.012,0.053-0.037,0.104-0.075,0.148l-0.118,0.139
c-0.395,0.46-0.289,1.083,0.329,1.642C19.239,46.779,19.281,46.698,19.354,46.565 M45.29,49.392
c0.041-0.101,0.064-0.212,0.064-0.328c0-0.473-0.383-0.858-0.856-0.858h-0.866c-0.059,0.001-0.114-0.014-0.163-0.04
c-0.048-0.025-0.092-0.063-0.125-0.111l-0.434-0.641c0.033,0.048,0.076,0.086,0.125,0.111c0.048,0.026,0.104,0.041,0.163,0.04
l1.141,0.001c0.059,0,0.115,0.014,0.163,0.04c0.048,0.025,0.092,0.063,0.125,0.111l-0.524-0.767
c-0.033-0.049-0.077-0.086-0.126-0.111c-0.048-0.026-0.104-0.041-0.162-0.041l-1.132,0.001c-0.058,0-0.114-0.014-0.162-0.04
c-0.049-0.025-0.093-0.063-0.126-0.111l-0.492-0.725c0.033,0.049,0.077,0.086,0.125,0.111c0.049,0.026,0.104,0.041,0.163,0.041
l1.136-0.001c0.059,0,0.115,0.014,0.163,0.04c0.049,0.025,0.092,0.062,0.125,0.111l-0.524-0.767
c-0.033-0.049-0.077-0.086-0.126-0.112c-0.048-0.027-0.104-0.04-0.162-0.04H41.9c-0.059,0-0.114-0.015-0.163-0.04
c-0.048-0.027-0.092-0.063-0.125-0.113l-0.607-0.89c1.227-0.146,2.217-0.811,2.414-1.727c0.255-1.188-0.926-2.342-2.636-2.593
c-0.288-0.042-0.508-0.289-0.508-0.588c0-0.253,0.16-0.471,0.385-0.555c-0.182-0.079-0.386-0.123-0.602-0.123
c-0.757,0-1.37,0.542-1.37,1.211c0,0.12,0.021,0.237,0.058,0.346c-0.848,0.367-1.62,1.016-2.211,1.717
c0.632-0.168,1.296-0.259,1.981-0.259c-0.003-0.031-0.005-0.063-0.005-0.096c0-0.513,0.414-0.928,0.928-0.928h0.013
c-0.35,0.153-0.52,0.49-0.52,0.712c0,0.265,0.215,0.479,0.479,0.479c0.103,0,0.199-0.032,0.277-0.088
c-0.018-0.059-0.028-0.124-0.028-0.19c0-0.367,0.297-0.664,0.665-0.664c0.032,0,0.065,0.002,0.096,0.007
c-0.253,0.118-0.429,0.376-0.429,0.674c0,0.411,0.333,0.744,0.744,0.744c0.044,0,0.086-0.003,0.128-0.01
c-0.012-0.044-0.018-0.089-0.018-0.137c0-0.295,0.239-0.533,0.533-0.533c0.295,0,0.534,0.238,0.534,0.533
c0,0.642-0.712,0.701-1.231,0.552c-1.478-0.427-2.862-0.617-4.201-0.431c-1.718,0.243-4.532,1.404-7.519,1.307
c-0.668-0.021-1.397-0.132-2.131-0.333c0.09,0.099,0.148,0.167,0.186,0.225c0.291,0.453,0.391,0.927,0.134,1.522
c0.007-0.666-0.543-1.215-1.004-1.551c-0.186-0.134-0.261-0.263-0.23-0.436l0.136-0.768c-0.01,0.057-0.005,0.114,0.012,0.164
c0.017,0.054,0.046,0.103,0.088,0.144l0.287,0.281c0.109-0.778-0.067-1.502-0.53-2.174c0.205-0.535,0.233-1.127,0.096-1.681
c-0.054,0.42-0.26,0.6-0.456,0.721c-0.363,0.228-0.423,0.612-0.235,0.868c-0.307-0.155-0.73-0.725-0.485-1.057
c0.264-0.36,0.987-0.191,1.076-0.806c-0.469-0.149-0.952-0.045-1.099-0.005c-0.278-0.318-0.647-0.476-1.106-0.473
c-0.363-0.329-0.829-0.466-1.4-0.409c-0.568-0.057-1.034,0.08-1.397,0.409c-0.459-0.003-0.828,0.155-1.106,0.473
c-0.148-0.04-0.63-0.144-1.1,0.005c0.089,0.615,0.811,0.446,1.076,0.806c0.245,0.332-0.178,0.902-0.485,1.057
c0.189-0.256,0.128-0.64-0.236-0.868c-0.194-0.121-0.401-0.301-0.455-0.721c-0.137,0.554-0.108,1.146,0.096,1.681
c-0.463,0.672-0.639,1.396-0.53,2.174l0.288-0.281c0.042-0.041,0.071-0.09,0.088-0.144c0.017-0.05,0.021-0.107,0.01-0.164
l0.137,0.768c0.03,0.173-0.043,0.302-0.229,0.436c-0.462,0.336-1.012,0.885-1.005,1.551c-0.256-0.595-0.153-1.09,0.135-1.522
c-0.876-0.473-1.543-1.25-1.666-1.392c-0.265-0.309-0.23-0.701,0.01-1.045c0.463-0.662,0.573-1.368-0.008-1.851
c0.004-0.036,0.006-0.072,0.006-0.107c0-0.439-0.312-0.806-0.727-0.889c0.077,0.121,0.122,0.264,0.122,0.416
c0,0.175-0.058,0.336-0.157,0.466c0.082,0.108,0.131,0.242,0.131,0.389c0,0.195-0.088,0.371-0.227,0.487
c0.014-0.066,0.02-0.136,0.02-0.209c0-0.451-0.279-0.829-0.658-0.933c-0.061-0.328-0.349-0.577-0.695-0.577
c-0.201,0-0.381,0.083-0.51,0.216c0.268,0.021,0.484,0.232,0.513,0.497c-0.128,0.097-0.231,0.229-0.298,0.385h0.017
c0.463,0,0.838,0.375,0.838,0.838c0,0.052-0.005,0.104-0.014,0.153c-0.035-0.189-0.121-0.365-0.26-0.501
c-0.26-0.253-0.638-0.306-0.984-0.174c-0.13-0.163-0.33-0.268-0.554-0.268c-0.254,0-0.476,0.133-0.601,0.333
c0.256,0.011,0.481,0.14,0.622,0.335c-0.364,0.466-0.368,1.109,0.004,1.473c0.252,0.246,0.613,0.302,0.95,0.187
c0.022-0.008,0.046-0.012,0.071-0.012c0.124,0,0.224,0.101,0.224,0.224c0,0.123-0.1,0.223-0.224,0.223
c-0.054,0-0.104-0.019-0.142-0.051c-0.085-0.071-0.195-0.113-0.314-0.113c-0.27,0-0.49,0.218-0.49,0.49
c0,0.02,0.001,0.041,0.004,0.059c-0.046,0.016-0.095,0.024-0.146,0.024c-0.132,0-0.252-0.054-0.34-0.141
c-0.014,0.054-0.021,0.11-0.021,0.167c0,0.346,0.266,0.629,0.605,0.655c0.152,0.377,0.523,0.644,0.955,0.644
c0.222,0,0.427-0.07,0.595-0.188c0.074-0.051,0.162-0.082,0.258-0.082c0.249,0,0.451,0.202,0.451,0.451
c0,0.215-0.15,0.393-0.351,0.44l-0.351,0.076c-0.057,0.014-0.115,0.011-0.168-0.005c-0.053-0.013-0.103-0.041-0.145-0.081
l0.803,0.763c0.043,0.04,0.093,0.068,0.146,0.082c0.053,0.015,0.11,0.018,0.167,0.005l0.658-0.146
c0.057-0.013,0.115-0.01,0.167,0.004c0.052,0.015,0.104,0.042,0.146,0.082l0.551,0.525c-0.043-0.04-0.093-0.068-0.147-0.082
c-0.052-0.015-0.109-0.018-0.166-0.005l-0.657,0.145c-0.057,0.013-0.115,0.01-0.167-0.005c-0.053-0.014-0.104-0.041-0.146-0.081
l0.736,0.697c0.042,0.041,0.093,0.068,0.145,0.083c0.053,0.015,0.111,0.017,0.168,0.004l0.658-0.144
c0.058-0.013,0.115-0.01,0.168,0.005c0.053,0.014,0.103,0.042,0.146,0.082l0.551,0.524c-0.043-0.04-0.093-0.068-0.146-0.082
c-0.053-0.015-0.11-0.017-0.168-0.005L16.89,47.12c-0.058,0.013-0.115,0.01-0.168-0.005c-0.053-0.014-0.103-0.041-0.146-0.081
l0.736,0.697c0.043,0.041,0.093,0.068,0.146,0.082c0.053,0.015,0.11,0.018,0.168,0.005l0.795-0.174
c-0.772,0.436-1.594,0.93-2.465,1.481c-0.515,0.325-1.078,0.386-1.725,0.138c-0.348-0.133-0.725-0.154-0.963-0.114
c-0.31,0.053-0.573,0.241-0.726,0.502c0.12-0.048,0.251-0.075,0.389-0.075c0.289,0,0.55,0.117,0.74,0.305
c-0.301-0.126-0.675-0.139-1.038-0.006c-0.65,0.236-1.029,0.849-0.881,1.398c-0.243,0.093-0.413,0.328-0.413,0.602
c0,0.181,0.074,0.345,0.194,0.462c0.064-0.288,0.316-0.505,0.621-0.516c0.127,0.084,0.275,0.143,0.434,0.175
c0.048-0.083,0.109-0.158,0.179-0.221c-0.008-0.052-0.011-0.105-0.011-0.159c0-0.593,0.48-1.074,1.073-1.074
c0.049,0,0.097,0.003,0.145,0.01c-0.471,0.113-0.822,0.537-0.822,1.044c0,0.064,0.006,0.127,0.017,0.188
c-0.254,0.098-0.433,0.343-0.433,0.631c0,0.165,0.059,0.316,0.158,0.434c0.182-0.356,0.537-0.608,0.954-0.648
c0.157,0.046,0.323,0.071,0.494,0.071c0.108,0,0.213-0.01,0.315-0.028c-0.092-0.135-0.146-0.297-0.146-0.472
c0-0.461,0.373-0.834,0.835-0.834c0.04,0,0.078,0.003,0.118,0.008c-0.441,0.187-0.711,0.57-0.618,0.919
c0.066,0.247,0.299,0.418,0.6,0.475c-0.004,0.185-0.055,0.359-0.142,0.51c0.387-0.028,0.718-0.261,0.883-0.592
c0.456-0.183,0.737-0.574,0.643-0.929c-0.034-0.127-0.113-0.234-0.22-0.315c-0.001-0.012-0.002-0.025-0.002-0.037
c0-0.244,0.199-0.443,0.442-0.443c0.246,0,0.444,0.199,0.444,0.443c0,0.116-0.044,0.221-0.117,0.3h0.927
c0.058,0,0.114-0.015,0.162-0.041c0.049-0.025,0.092-0.063,0.125-0.112l0.595-0.882c0.022-0.033,0.052-0.058,0.085-0.076
c0.033-0.017,0.07-0.028,0.111-0.028h0.728c-0.04,0-0.078,0.011-0.111,0.028c-0.033,0.018-0.063,0.043-0.085,0.076l-0.597,0.883
c-0.033,0.048-0.076,0.086-0.125,0.111c-0.048,0.026-0.103,0.041-0.162,0.041h1.108c0.059,0,0.114-0.015,0.161-0.041
c0.05-0.025,0.094-0.063,0.125-0.112l0.668-0.985c-0.46-0.252-0.649-0.693-0.649-1.299c0-0.377,0.212-0.807,0.244-1.084
l0.013-0.11c0.007-0.059-0.001-0.115-0.021-0.166c-0.016-0.042-0.048-0.102-0.083-0.143l0.57,0.584
c0.045,0.038,0.077,0.086,0.096,0.137c0.021,0.051,0.029,0.108,0.022,0.167l-0.017,0.133c-0.027,0.232-0.319,0.732,0.223,1.19
c0.027,0.023,0.094,0.071,0.158,0.111l0.385,0.242V48.48h0.539v1.581c0.001,0.059,0.018,0.114,0.045,0.162
c0.027,0.047,0.065,0.09,0.115,0.121l0.526,0.335c0.051,0.031,0.106,0.049,0.16,0.053c0.055,0.004,0.112-0.004,0.165-0.027
l0.971-0.422c-0.054,0.024-0.111,0.032-0.165,0.027c-0.055-0.004-0.11-0.021-0.159-0.052l-1.115-0.71
c0.542-0.458,0.249-0.958,0.222-1.19l-0.016-0.133c-0.007-0.059,0.001-0.116,0.02-0.167c0.021-0.051,0.053-0.099,0.097-0.137
l0.57-0.584c-0.035,0.041-0.066,0.101-0.083,0.143c-0.019,0.051-0.027,0.107-0.02,0.166l0.012,0.11
c0.046,0.395,0.446,1.111,0.113,1.511l1.019,0.646c0.05,0.031,0.105,0.049,0.159,0.053c0.055,0.004,0.112-0.004,0.166-0.028
l1.015-0.441c-0.054,0.023-0.11,0.031-0.164,0.027c-0.055-0.004-0.11-0.021-0.16-0.053l-1.102-0.701
c0.24-0.491,0.038-1.273-0.195-1.725l-0.035-0.067c-0.026-0.052-0.038-0.109-0.036-0.164c0-0.055,0.014-0.11,0.043-0.161
l0.378-0.682c-0.028,0.05-0.042,0.106-0.042,0.16c-0.002,0.055,0.01,0.111,0.036,0.163l0.139,0.271
c0.073,0.133,0.114,0.214,0.178,0.371c0.62-0.559,0.758-1.098,0.363-1.557l-0.118-0.14c-0.038-0.044-0.063-0.095-0.075-0.148
c-0.013-0.054-0.013-0.111,0.003-0.168l0.202-0.753c-0.015,0.056-0.015,0.113-0.004,0.166c0.013,0.053,0.038,0.104,0.077,0.148
l0.388,0.454c0.754,0.852,0.298,1.95-0.602,2.788c0.05,0.16,0.093,0.461,0.057,0.624l1.195,0.758
c0.05,0.032,0.105,0.049,0.16,0.053c0.054,0.005,0.111-0.004,0.165-0.027l0.864-0.376c-0.049,0.021-0.104,0.033-0.16,0.033
c-0.223,0-0.403-0.18-0.403-0.402c0-0.18,0.117-0.335,0.281-0.384c3.299-1.004,6.336-3.594,8.33-3.588
c0.969,0.004,1.755,0.59,1.755,1.317c0,0.117-0.021,0.231-0.059,0.34c-0.425,1.194,0.194,2.334,1.828,2.774
c0.261,0.07,0.453,0.308,0.453,0.59c0,0.055-0.008,0.109-0.021,0.159c0.037,0.004,0.075,0.005,0.114,0.005
c0.45,0,0.848-0.224,1.089-0.566c0.28-0.002,0.587-0.019,0.901-0.052c0.038,0.076,0.068,0.163,0.086,0.257
c0.067,0.344-0.052,0.654-0.263,0.722c-0.375,0.122-0.835-0.024-1.19-0.021c-0.672,0.007-1.215,0.553-1.215,1.226
c0,0.053,0.003,0.105,0.01,0.157c-0.211,0.131-0.351,0.365-0.351,0.631c0,0.133,0.035,0.258,0.095,0.366
c0.207-0.241,0.477-0.428,0.784-0.536c0.026-0.59,0.512-1.06,1.108-1.06c0.091,0,0.181,0.011,0.265,0.032
c-0.604,0.076-1.072,0.592-1.072,1.217c0,0.045,0.003,0.09,0.008,0.135c-0.075,0.09-0.12,0.207-0.12,0.333
c0,0.161,0.072,0.305,0.185,0.402c0.114-0.25,0.389-0.485,0.745-0.605c0.239-0.08,0.474-0.096,0.67-0.056
c-0.032-0.094-0.047-0.194-0.047-0.297c0-0.534,0.431-0.966,0.965-0.966c0.049,0,0.098,0.004,0.145,0.011
c-0.372,0.051-0.658,0.369-0.658,0.754c0,0.256,0.126,0.482,0.319,0.621c0,0.013-0.001,0.027-0.001,0.041
c0,0.21,0.096,0.396,0.246,0.519c0.068-0.35,0.374-0.614,0.745-0.614c0.316,0,0.577-0.04,0.772-0.104
c0.33-0.108,0.571-0.413,0.571-0.778c0-0.253-0.115-0.479-0.297-0.628c0.09-0.41,0.074-1.083-0.065-1.643
c0.028-0.004,0.057-0.006,0.087-0.006C44.969,49.094,45.172,49.212,45.29,49.392 M28.481,56.341
c-0.018-0.09-0.016-0.181,0.003-0.273c0.038-0.176,0.194-0.308,0.382-0.308c0.216,0,0.39,0.175,0.39,0.391
c0,0.103-0.04,0.197-0.105,0.267c0.073,0.007,0.148,0.011,0.226,0.011c0.201,0,0.392-0.025,0.56-0.07
c0.275-0.074,0.477-0.325,0.477-0.623c0-0.356-0.289-0.644-0.645-0.644c-0.019,0-0.039,0-0.058,0.002
c0.089-0.038,0.189-0.059,0.293-0.059c0.413,0,0.749,0.335,0.749,0.749c0,0.021-0.001,0.043-0.003,0.063
c1.116-0.024,2.374-1.042,2.649-1.43c-0.35,0.08-0.729,0.124-1.125,0.124c-0.449,0-0.878-0.055-1.266-0.158
c-0.549-0.145-1.089-0.226-1.504-0.226c-1.37,0-2.479,0.893-2.479,1.995c0,0.91,0.752,1.705,1.794,1.918
c2.371,0.484,5.16-0.924,7.516-1.412c0.589-0.576,1.27-1.057,2.019-1.421c-0.022-0.086-0.034-0.176-0.034-0.268v-0.006
c-3.126,0.514-5.939,2.118-8.479,2.105C29.129,57.065,28.571,56.791,28.481,56.341 M28.408,50.571
c0.048,0,0.095,0.003,0.141,0.008c-0.468,0.135-0.846,0.484-1.021,0.934c-0.291,0.096-0.501,0.371-0.501,0.694
c0,0.151,0.046,0.291,0.124,0.407c0.253-0.282,0.585-0.493,0.962-0.595c0.108-0.542,0.559-0.96,1.117-1.019
c-0.487,0.204-0.829,0.686-0.829,1.247c0,0.199,0.043,0.387,0.12,0.557c0.086-0.309,0.369-0.536,0.705-0.536
c0.085,0,0.166,0.014,0.24,0.041c0.105,0.038,0.218,0.058,0.334,0.058c0.541,0,0.98-0.439,0.98-0.981
c0-0.108-0.017-0.212-0.049-0.31c0.257,0.075,0.445,0.313,0.445,0.595c0,0.129-0.039,0.248-0.106,0.348
c0.072,0.013,0.146,0.019,0.222,0.019c0.637,0,1.163-0.479,1.236-1.096c0.32-0.174,0.601-0.408,0.843-0.7l0.17,0.829
c0.012,0.058,0.008,0.115-0.007,0.168c-0.015,0.052-0.043,0.103-0.084,0.144l0.703-0.722c0.041-0.042,0.069-0.092,0.083-0.145
c0.016-0.053,0.019-0.11,0.007-0.167l-0.207-1.012c-0.012-0.057-0.009-0.115,0.007-0.167c0.015-0.053,0.043-0.103,0.084-0.145
l0.553-0.564c-0.041,0.042-0.069,0.092-0.084,0.145c-0.015,0.053-0.018,0.11-0.006,0.168l0.207,1.013
c0.012,0.057,0.009,0.114-0.006,0.167c-0.015,0.052-0.042,0.101-0.082,0.143l0.627-0.652c0.04-0.042,0.068-0.092,0.083-0.144
c0.016-0.053,0.019-0.111,0.006-0.168l-0.206-1.01c-0.012-0.057-0.009-0.115,0.007-0.167c0.015-0.053,0.043-0.103,0.084-0.145
l0.553-0.564c-0.041,0.042-0.069,0.092-0.084,0.145c-0.015,0.053-0.018,0.11-0.006,0.167l0.208,1.013
c0.012,0.057,0.008,0.115-0.007,0.167c-0.015,0.052-0.042,0.101-0.082,0.143l0.627-0.651c0.041-0.042,0.068-0.092,0.083-0.145
c0.016-0.053,0.019-0.11,0.007-0.168l-0.101-0.494c-0.106-0.559,0.471-1.202,0.929-1.267c0.055-0.106,0.085-0.221,0.085-0.34
c0-0.567-0.675-1.027-1.509-1.027c-0.407,0-0.777,0.109-1.049,0.289c0.109,0.322,0.132,0.651-0.937,0.803
c-0.848,0.12-1.594,0.285-2.161,0.766c-0.874,0.741-0.803,1.732-1.3,2.107c0.221,0.054,0.502,0.054,0.803-0.011
c0.19-0.041,0.366-0.104,0.521-0.181c-0.093,0.178-0.306,0.347-0.586,0.467c-0.092,0.35-0.403,0.684-0.823,0.84
c-0.265,0.098-0.528,0.108-0.746,0.045l-1.023-0.296c-0.126-0.036-0.257-0.055-0.394-0.055c-0.754,0-1.376,0.581-1.468,1.332
c-0.356,0.05-0.629,0.356-0.629,0.725c0,0.136,0.037,0.262,0.101,0.371c0.245-0.249,0.556-0.434,0.904-0.528
C27.372,50.949,27.846,50.571,28.408,50.571 M22.967,59.902c0.063-0.334,0.089-0.658,0.077-0.97l-0.299,0.35
c-0.059-0.14-0.098-0.225-0.138-0.294c-0.033-0.057-0.061-0.096-0.1-0.103c-0.02,0.01-0.05,0.026-0.083,0.034
c-0.038,0.009-0.09,0.006-0.123,0.006c-0.03,0-0.082,0.003-0.121-0.006c-0.032-0.008-0.062-0.024-0.082-0.034
c-0.04,0.007-0.067,0.046-0.1,0.103c-0.04,0.069-0.079,0.154-0.138,0.294l-0.3-0.35c-0.011,0.312,0.014,0.636,0.077,0.97
c0.221-0.049,0.449-0.066,0.664-0.066C22.518,59.836,22.746,59.853,22.967,59.902 M23.101,60.801
c0.033-0.379-0.397-0.514-0.8-0.514c-0.401,0-0.831,0.135-0.798,0.514c0.041,0.462,0.473,0.242,0.798,0.244
C22.628,61.043,23.06,61.263,23.101,60.801 M24.249,58.071c-0.079,0.022-0.122,0.068-0.131,0.151
c-0.047,0.446-0.228,0.626-0.517,0.727c-0.004,0.45-0.066,0.79-0.188,1.212c0.343,0.717,0.08,1.218-0.198,1.325
c-0.265,0.103-0.607-0.035-0.91-0.035s-0.65,0.138-0.915,0.035c-0.279-0.107-0.541-0.608-0.199-1.325
c-0.121-0.422-0.184-0.762-0.187-1.212c-0.289-0.101-0.471-0.281-0.518-0.727c-0.009-0.083-0.052-0.129-0.13-0.151
c-1.14-0.312-1.248-1.728-0.671-2.129c-0.052,0.634-0.106,1.529,1.19,1.648c-0.021,0.744,0.3,0.943,0.632,0.943
c0.271,0,0.426-0.087,0.494-0.123c0.241-0.128,0.075-0.323,0.013-0.381c-0.166-0.155-0.25-0.375-0.21-0.594
c0.007-0.04,0.022-0.06,0.059-0.06h0.438h0.44c0.037,0,0.053,0.02,0.059,0.06c0.04,0.219-0.044,0.439-0.209,0.594
c-0.062,0.058-0.228,0.253,0.013,0.381c0.067,0.036,0.223,0.123,0.494,0.123c0.331,0,0.653-0.199,0.632-0.943
c1.296-0.119,1.241-1.014,1.19-1.648C25.497,56.343,25.388,57.759,24.249,58.071 M24.6,55.6c0,0.326-0.238,0.688-0.509,0.688
h-0.249c0.063,0.075,0.101,0.171,0.101,0.277c0,0.24-0.195,0.435-0.435,0.435c-0.241,0-0.436-0.195-0.436-0.435
c0-0.106,0.038-0.202,0.1-0.277h-0.26c-0.089,0-0.158,0.036-0.213,0.14c-0.018-0.14-0.036-0.284-0.004-0.381
c0.044-0.131,0.146-0.21,0.248-0.21h1.142C24.296,55.837,24.453,55.766,24.6,55.6 M24.449,55.06H24.05
c-0.198,0-0.335-0.081-0.451-0.215l-0.455-0.594c-0.075-0.094-0.135-0.16-0.232-0.204h0.45c0.135,0,0.255,0.059,0.349,0.179
l0.474,0.603C24.291,54.957,24.324,55.042,24.449,55.06 M22.368,54.079l0.582,0.818c0.092,0.134,0.179,0.209,0.304,0.26h-0.533
c-0.205,0-0.328-0.094-0.418-0.242l-0.458-0.702c-0.175-0.263-0.244-0.329-0.445-0.4h0.495
C22.09,53.813,22.272,53.94,22.368,54.079 M21.049,54.226l0.474,0.603c0.106,0.128,0.139,0.213,0.264,0.231h-0.398
c-0.199,0-0.336-0.081-0.452-0.215l-0.455-0.594c-0.075-0.094-0.134-0.16-0.232-0.204h0.45
C20.835,54.047,20.955,54.106,21.049,54.226 M20.762,56.288h-0.249c-0.27,0-0.509-0.362-0.509-0.688
c0.148,0.166,0.304,0.237,0.516,0.237h1.142c0.102,0,0.204,0.079,0.248,0.21c0.032,0.097,0.014,0.241-0.004,0.381
c-0.055-0.104-0.124-0.14-0.213-0.14h-0.26c0.062,0.075,0.099,0.171,0.099,0.277c0,0.24-0.195,0.435-0.435,0.435
s-0.435-0.195-0.435-0.435C20.662,56.459,20.699,56.363,20.762,56.288 M19.354,61.73l0.138-0.271
c0.027-0.052,0.038-0.108,0.037-0.163c-0.001-0.054-0.015-0.11-0.043-0.161l0.379,0.682c0.028,0.052,0.042,0.107,0.043,0.162
c0.002,0.055-0.01,0.111-0.037,0.164l-0.034,0.067c-0.233,0.452-0.45,1.299-0.209,1.79c-0.562-0.209-0.747-0.701-0.687-1.11
c-1.058-1.003-1.324-2.019-0.569-2.871l0.387-0.453c0.04-0.044,0.065-0.096,0.076-0.149c0.013-0.053,0.013-0.11-0.002-0.166
l0.202,0.753c0.014,0.057,0.015,0.114,0.003,0.167c-0.012,0.054-0.037,0.106-0.075,0.15l-0.118,0.138
c-0.395,0.46-0.289,1.083,0.329,1.642C19.239,61.944,19.281,61.863,19.354,61.73 M45.29,64.557
c0.041-0.101,0.064-0.212,0.064-0.328c0-0.473-0.383-0.858-0.856-0.858h-0.866c-0.059,0-0.114-0.014-0.163-0.04
c-0.048-0.025-0.092-0.063-0.125-0.111l-0.434-0.641c0.033,0.048,0.076,0.086,0.125,0.111c0.048,0.026,0.104,0.041,0.163,0.04
l1.141,0.001c0.059,0,0.115,0.014,0.163,0.04c0.048,0.025,0.092,0.063,0.125,0.111l-0.524-0.768
c-0.033-0.048-0.077-0.085-0.126-0.111c-0.048-0.025-0.104-0.04-0.162-0.04l-1.132,0.001c-0.058,0-0.114-0.015-0.162-0.04
c-0.049-0.026-0.093-0.063-0.126-0.112l-0.492-0.724c0.033,0.049,0.077,0.086,0.125,0.111c0.049,0.026,0.104,0.041,0.163,0.04
h1.136c0.059-0.001,0.115,0.014,0.163,0.04c0.049,0.025,0.092,0.062,0.125,0.111l-0.524-0.768
c-0.033-0.048-0.077-0.086-0.126-0.111c-0.048-0.026-0.104-0.04-0.162-0.04H41.9c-0.059,0-0.114-0.015-0.163-0.041
c-0.048-0.025-0.092-0.062-0.125-0.111l-0.607-0.891c1.227-0.146,2.217-0.811,2.414-1.727c0.255-1.189-0.926-2.341-2.636-2.592
c-0.288-0.042-0.508-0.289-0.508-0.588c0-0.255,0.16-0.472,0.385-0.557c-0.182-0.078-0.386-0.122-0.602-0.122
c-0.757,0-1.37,0.542-1.37,1.211c0,0.12,0.021,0.237,0.058,0.347c-0.848,0.366-1.62,1.015-2.211,1.716
c0.632-0.168,1.296-0.258,1.981-0.258c-0.003-0.032-0.005-0.064-0.005-0.097c0-0.513,0.414-0.928,0.928-0.928h0.013
c-0.35,0.154-0.52,0.49-0.52,0.712c0,0.265,0.215,0.479,0.479,0.479c0.103,0,0.199-0.032,0.277-0.087
c-0.018-0.061-0.028-0.124-0.028-0.191c0-0.367,0.297-0.664,0.665-0.664c0.032,0,0.065,0.002,0.096,0.007
c-0.253,0.118-0.429,0.376-0.429,0.674c0,0.411,0.333,0.744,0.744,0.744c0.044,0,0.086-0.003,0.128-0.011
c-0.012-0.043-0.018-0.088-0.018-0.135c0-0.295,0.239-0.534,0.533-0.534c0.295,0,0.534,0.239,0.534,0.534
c0,0.641-0.712,0.7-1.231,0.551c-1.478-0.426-2.862-0.617-4.201-0.43c-1.718,0.241-4.532,1.403-7.519,1.306
c-0.668-0.021-1.397-0.132-2.131-0.333c0.09,0.098,0.148,0.167,0.186,0.225c0.291,0.453,0.391,0.928,0.134,1.522
c0.007-0.666-0.543-1.214-1.004-1.55c-0.186-0.135-0.261-0.264-0.23-0.437l0.136-0.768c-0.01,0.057-0.005,0.114,0.012,0.165
c0.017,0.053,0.046,0.102,0.088,0.143l0.287,0.281c0.109-0.778-0.067-1.502-0.53-2.173c0.205-0.536,0.233-1.127,0.096-1.682
c-0.054,0.42-0.26,0.6-0.456,0.722c-0.363,0.227-0.423,0.611-0.235,0.868c-0.307-0.157-0.73-0.726-0.485-1.058
c0.264-0.359,0.987-0.19,1.076-0.806c-0.469-0.149-0.952-0.044-1.099-0.004c-0.278-0.319-0.647-0.477-1.106-0.474
c-0.363-0.33-0.829-0.466-1.4-0.409c-0.568-0.057-1.034,0.079-1.397,0.409c-0.459-0.003-0.828,0.155-1.106,0.474
c-0.148-0.04-0.63-0.145-1.1,0.004c0.089,0.616,0.811,0.447,1.076,0.806c0.245,0.332-0.178,0.901-0.485,1.058
c0.189-0.257,0.128-0.641-0.236-0.868c-0.194-0.122-0.401-0.302-0.455-0.722c-0.137,0.555-0.108,1.146,0.096,1.682
c-0.463,0.671-0.639,1.395-0.53,2.173l0.288-0.281c0.042-0.041,0.071-0.09,0.088-0.143c0.017-0.051,0.021-0.108,0.01-0.165
l0.137,0.768c0.03,0.173-0.043,0.302-0.229,0.437c-0.462,0.336-1.012,0.884-1.005,1.55c-0.256-0.594-0.153-1.089,0.135-1.522
c-0.876-0.473-1.543-1.25-1.666-1.392c-0.265-0.308-0.23-0.701,0.01-1.045c0.463-0.663,0.573-1.368-0.008-1.851
c0.004-0.035,0.006-0.071,0.006-0.107c0-0.439-0.312-0.805-0.727-0.888c0.077,0.12,0.122,0.263,0.122,0.416
c0,0.175-0.058,0.336-0.157,0.465c0.082,0.108,0.131,0.243,0.131,0.389c0,0.196-0.088,0.371-0.227,0.488
c0.014-0.067,0.02-0.138,0.02-0.209c0-0.452-0.279-0.83-0.658-0.934c-0.061-0.328-0.349-0.577-0.695-0.577
c-0.201,0-0.381,0.083-0.51,0.217c0.268,0.02,0.484,0.231,0.513,0.497c-0.128,0.096-0.231,0.228-0.298,0.384h0.017
c0.463,0,0.838,0.375,0.838,0.838c0,0.052-0.005,0.104-0.014,0.154c-0.035-0.191-0.121-0.366-0.26-0.502
c-0.26-0.253-0.638-0.306-0.984-0.174c-0.13-0.163-0.33-0.268-0.554-0.268c-0.254,0-0.476,0.133-0.601,0.333
c0.256,0.011,0.481,0.14,0.622,0.335c-0.364,0.466-0.368,1.11,0.004,1.473c0.252,0.246,0.613,0.303,0.95,0.187
c0.022-0.008,0.046-0.012,0.071-0.012c0.124,0,0.224,0.1,0.224,0.224c0,0.123-0.1,0.223-0.224,0.223
c-0.054,0-0.104-0.019-0.142-0.051c-0.085-0.071-0.195-0.113-0.314-0.113c-0.27,0-0.49,0.219-0.49,0.49
c0,0.02,0.001,0.041,0.004,0.06c-0.046,0.015-0.095,0.023-0.146,0.023c-0.132,0-0.252-0.054-0.34-0.14
c-0.014,0.053-0.021,0.109-0.021,0.167c0,0.345,0.266,0.628,0.605,0.654c0.152,0.378,0.523,0.644,0.955,0.644
c0.222,0,0.427-0.07,0.595-0.188c0.074-0.052,0.162-0.082,0.258-0.082c0.249,0,0.451,0.202,0.451,0.451
c0,0.215-0.15,0.394-0.351,0.439l-0.351,0.078c-0.057,0.013-0.115,0.01-0.168-0.005c-0.053-0.014-0.103-0.041-0.145-0.082
l0.803,0.763c0.043,0.04,0.093,0.068,0.146,0.082c0.053,0.015,0.11,0.018,0.167,0.005l0.658-0.146
c0.057-0.013,0.115-0.01,0.167,0.005c0.052,0.014,0.104,0.041,0.146,0.082l0.551,0.524c-0.043-0.041-0.093-0.068-0.147-0.082
c-0.052-0.015-0.109-0.018-0.166-0.005l-0.657,0.145c-0.057,0.013-0.115,0.01-0.167-0.005c-0.053-0.014-0.104-0.041-0.146-0.081
l0.736,0.697c0.042,0.041,0.093,0.068,0.145,0.082c0.053,0.015,0.111,0.018,0.168,0.005l0.658-0.144
c0.058-0.013,0.115-0.01,0.168,0.005c0.053,0.014,0.103,0.042,0.146,0.082l0.551,0.524c-0.043-0.04-0.093-0.068-0.146-0.082
c-0.053-0.015-0.11-0.018-0.168-0.005l-0.656,0.145c-0.058,0.013-0.115,0.01-0.168-0.005c-0.053-0.014-0.103-0.041-0.146-0.082
l0.736,0.698c0.043,0.041,0.093,0.068,0.146,0.082c0.053,0.015,0.11,0.018,0.168,0.005l0.795-0.174
c-0.772,0.436-1.594,0.93-2.465,1.481c-0.515,0.325-1.078,0.386-1.725,0.138c-0.348-0.133-0.725-0.155-0.963-0.114
c-0.31,0.053-0.573,0.241-0.726,0.502c0.12-0.049,0.251-0.075,0.389-0.075c0.289,0,0.55,0.117,0.74,0.305
c-0.301-0.126-0.675-0.139-1.038-0.007c-0.65,0.237-1.029,0.85-0.881,1.398c-0.243,0.094-0.413,0.328-0.413,0.603
c0,0.181,0.074,0.344,0.194,0.462c0.064-0.288,0.316-0.505,0.621-0.516c0.127,0.084,0.275,0.143,0.434,0.175
c0.048-0.083,0.109-0.158,0.179-0.221c-0.008-0.052-0.011-0.105-0.011-0.159c0-0.593,0.48-1.074,1.073-1.074
c0.049,0,0.097,0.003,0.145,0.01c-0.471,0.113-0.822,0.537-0.822,1.044c0,0.064,0.006,0.127,0.017,0.188
c-0.254,0.097-0.433,0.343-0.433,0.631c0,0.165,0.059,0.316,0.158,0.434c0.182-0.356,0.537-0.608,0.954-0.648
c0.157,0.046,0.323,0.071,0.494,0.071c0.108,0,0.213-0.01,0.315-0.028c-0.092-0.135-0.146-0.297-0.146-0.472
c0-0.461,0.373-0.835,0.835-0.835c0.04,0,0.078,0.003,0.118,0.009c-0.441,0.187-0.711,0.57-0.618,0.918
c0.066,0.248,0.299,0.419,0.6,0.475c-0.004,0.186-0.055,0.36-0.142,0.511c0.387-0.028,0.718-0.262,0.883-0.592
c0.456-0.183,0.737-0.574,0.643-0.929c-0.034-0.127-0.113-0.234-0.22-0.316c-0.001-0.012-0.002-0.024-0.002-0.036
c0-0.244,0.199-0.443,0.442-0.443c0.246,0,0.444,0.199,0.444,0.443c0,0.116-0.044,0.221-0.117,0.3h0.927
c0.058,0,0.114-0.015,0.162-0.041c0.049-0.025,0.092-0.063,0.125-0.112l0.595-0.882c0.022-0.033,0.052-0.058,0.085-0.076
c0.033-0.018,0.07-0.028,0.111-0.028h0.728c-0.04,0-0.078,0.01-0.111,0.028c-0.033,0.018-0.063,0.043-0.085,0.076l-0.597,0.882
c-0.033,0.049-0.076,0.087-0.125,0.112c-0.048,0.026-0.103,0.041-0.162,0.041h1.108c0.059,0,0.114-0.015,0.161-0.041
c0.05-0.025,0.094-0.063,0.125-0.112l0.668-0.985c-0.46-0.252-0.649-0.693-0.649-1.299c0-0.377,0.212-0.807,0.244-1.084
l0.013-0.11c0.007-0.059-0.001-0.116-0.021-0.167c-0.016-0.041-0.048-0.101-0.083-0.142l0.57,0.584
c0.045,0.038,0.077,0.086,0.096,0.137c0.021,0.051,0.029,0.108,0.022,0.166l-0.017,0.134c-0.027,0.232-0.319,0.732,0.223,1.19
c0.027,0.023,0.094,0.07,0.158,0.111l0.385,0.242v-1.421h0.539v1.581c0.001,0.059,0.018,0.114,0.045,0.161
c0.027,0.048,0.065,0.091,0.115,0.122l0.526,0.335c0.051,0.031,0.106,0.049,0.16,0.053c0.055,0.004,0.112-0.004,0.165-0.028
l0.971-0.421c-0.054,0.023-0.111,0.032-0.165,0.027c-0.055-0.004-0.11-0.021-0.159-0.053l-1.115-0.709
c0.542-0.458,0.249-0.958,0.222-1.19l-0.016-0.134c-0.007-0.058,0.001-0.115,0.02-0.166c0.021-0.051,0.053-0.099,0.097-0.137
l0.57-0.584c-0.035,0.041-0.066,0.101-0.083,0.142c-0.019,0.051-0.027,0.108-0.02,0.167l0.012,0.11
c0.046,0.395,0.446,1.111,0.113,1.51l1.019,0.647c0.05,0.031,0.105,0.048,0.159,0.052c0.055,0.005,0.112-0.003,0.166-0.027
l1.015-0.441c-0.054,0.023-0.11,0.031-0.164,0.027c-0.055-0.004-0.11-0.022-0.16-0.053l-1.102-0.701
c0.24-0.492,0.038-1.273-0.195-1.725l-0.035-0.067c-0.026-0.053-0.038-0.109-0.036-0.164c0-0.055,0.014-0.11,0.043-0.162
l0.378-0.682c-0.028,0.051-0.042,0.107-0.042,0.161c-0.002,0.055,0.01,0.111,0.036,0.163l0.139,0.271
c0.073,0.133,0.114,0.214,0.178,0.371c0.62-0.559,0.758-1.098,0.363-1.558l-0.118-0.138c-0.038-0.044-0.063-0.096-0.075-0.15
c-0.013-0.053-0.013-0.11,0.003-0.167l0.202-0.753c-0.015,0.056-0.015,0.113-0.004,0.166c0.013,0.053,0.038,0.105,0.077,0.149
l0.388,0.453c0.754,0.852,0.298,1.95-0.602,2.787c0.05,0.161,0.093,0.462,0.057,0.625l1.195,0.758
c0.05,0.032,0.105,0.049,0.16,0.053c0.054,0.005,0.111-0.004,0.165-0.027l0.864-0.376c-0.049,0.021-0.104,0.033-0.16,0.033
c-0.223,0-0.403-0.18-0.403-0.402c0-0.18,0.117-0.335,0.281-0.384c3.299-1.004,6.336-3.594,8.33-3.588
c0.969,0.003,1.755,0.59,1.755,1.317c0,0.117-0.021,0.231-0.059,0.34c-0.425,1.194,0.194,2.334,1.828,2.773
c0.261,0.071,0.453,0.309,0.453,0.591c0,0.055-0.008,0.109-0.021,0.159c0.037,0.004,0.075,0.005,0.114,0.005
c0.45,0,0.848-0.224,1.089-0.566c0.28-0.002,0.587-0.019,0.901-0.052c0.038,0.076,0.068,0.163,0.086,0.257
c0.067,0.343-0.052,0.654-0.263,0.722c-0.375,0.122-0.835-0.024-1.19-0.021c-0.672,0.007-1.215,0.553-1.215,1.226
c0,0.053,0.003,0.105,0.01,0.156c-0.211,0.132-0.351,0.366-0.351,0.632c0,0.133,0.035,0.258,0.095,0.366
c0.207-0.242,0.477-0.428,0.784-0.536c0.026-0.59,0.512-1.06,1.108-1.06c0.091,0,0.181,0.011,0.265,0.032
c-0.604,0.076-1.072,0.592-1.072,1.217c0,0.045,0.003,0.09,0.008,0.135c-0.075,0.09-0.12,0.207-0.12,0.333
c0,0.161,0.072,0.305,0.185,0.401c0.114-0.249,0.389-0.484,0.745-0.604c0.239-0.08,0.474-0.096,0.67-0.056
c-0.032-0.094-0.047-0.194-0.047-0.298c0-0.533,0.431-0.965,0.965-0.965c0.049,0,0.098,0.004,0.145,0.011
c-0.372,0.05-0.658,0.369-0.658,0.754c0,0.256,0.126,0.482,0.319,0.62c0,0.014-0.001,0.028-0.001,0.042
c0,0.209,0.096,0.396,0.246,0.519c0.068-0.35,0.374-0.614,0.745-0.614c0.316,0,0.577-0.04,0.772-0.104
c0.33-0.108,0.571-0.413,0.571-0.778c0-0.253-0.115-0.479-0.297-0.628c0.09-0.41,0.074-1.083-0.065-1.643
c0.028-0.004,0.057-0.006,0.087-0.006C44.969,64.259,45.172,64.377,45.29,64.557 M57.259,11.339h-1.134V79.37h1.134V11.339z"}]]]])
(defn maanteeamet-logo
[login-page?]
[:div {:style {:display :flex
:justify-content :flex-start}}
[:a {:href (if login-page?
"/#/login"
"/#/")}
[logo-shield {}]]])
| null | https://raw.githubusercontent.com/solita/mnt-teet/2142692d3b91e9f2fc70bd9047cc62d6431536ed/app/frontend/src/cljs/teet/navigation/navigation_logo.cljs | clojure | (ns teet.navigation.navigation-logo
(:require [teet.navigation.navigation-style :as navigation-style]
[herb.core :as herb :refer [<class]]))
(defn logo-shield
[{:keys [width height]
:or {width "100%"
height "100%"}}]
[:svg#Layer_1 {:class (<class navigation-style/logo-shield-style)
:height height
:width width
:version "1.1" :xmlns ""
:x "0px" :y "0px"
:viewBox "0 0 170.079 90.709"}
[:g
[:path.st0 {:style {:fill "#222221"}
:d "M156.76,42.142h-4.988v0.962h1.844v6.319h1.263v-6.319h1.881V42.142z M150.029,45.154h-2.681v-2.05h3.137
v-0.962h-4.4v7.281h4.4v-0.962h-3.137v-2.344h2.681V45.154z M139.173,42.142h-1.594v7.281h1.263v-4.806l0.037-0.006l1.569,4.812
h0.856l1.563-4.781l0.037,0.006v4.775h1.269v-7.281h-1.588l-1.693,5.725h-0.038L139.173,42.142z M133.217,43.917h0.037l0.919,2.9
h-1.869L133.217,43.917z M134.998,49.423h1.325l-2.425-7.281h-1.306l-2.438,7.281h1.332l0.518-1.644h2.469L134.998,49.423z
M128.873,42.142h-1.262v7.281h1.262V42.142z M123.242,43.104c0.409,0,0.748,0.193,1.019,0.577
c0.271,0.385,0.406,0.864,0.406,1.437v1.316c0,0.586-0.135,1.07-0.406,1.453c-0.271,0.382-0.61,0.574-1.019,0.574h-1.05v-5.357
H123.242z M123.242,49.423c0.767,0,1.407-0.278,1.919-0.834c0.513-0.557,0.769-1.272,0.769-2.147v-1.313
c0-0.875-0.256-1.591-0.769-2.15c-0.512-0.558-1.152-0.837-1.919-0.837h-2.312v7.281H123.242z M115.549,43.104h1.169
c0.366,0,0.641,0.111,0.825,0.332c0.183,0.22,0.275,0.518,0.275,0.893c0,0.379-0.091,0.671-0.272,0.875
c-0.181,0.204-0.457,0.306-0.828,0.306h-1.169V43.104z M116.824,46.473c0.333,0,0.59,0.106,0.769,0.319
c0.179,0.212,0.268,0.51,0.268,0.894v0.656c0,0.216,0.006,0.429,0.016,0.637c0.01,0.209,0.037,0.357,0.078,0.444h1.306v-0.106
c-0.054-0.088-0.09-0.225-0.109-0.413c-0.019-0.187-0.028-0.373-0.028-0.556v-0.669c0-0.437-0.088-0.805-0.263-1.103
c-0.175-0.298-0.458-0.507-0.85-0.628c0.35-0.162,0.617-0.385,0.8-0.669c0.184-0.283,0.275-0.618,0.275-1.006
c0-0.671-0.209-1.194-0.628-1.569c-0.418-0.375-0.999-0.562-1.74-0.562h-2.432v7.281h1.263v-2.95H116.824z M111.362,46.534
c0,0.636-0.126,1.134-0.378,1.493c-0.253,0.36-0.599,0.54-1.041,0.54c-0.454,0-0.807-0.18-1.059-0.54
c-0.253-0.359-0.379-0.857-0.379-1.493v-1.522c0-0.623,0.125-1.114,0.375-1.471c0.25-0.358,0.6-0.537,1.05-0.537
c0.446,0,0.796,0.179,1.05,0.537c0.255,0.357,0.382,0.848,0.382,1.471V46.534z M112.624,45.023c0-0.887-0.25-1.606-0.75-2.156
s-1.148-0.825-1.944-0.825c-0.8,0-1.447,0.275-1.943,0.825s-0.744,1.269-0.744,2.156v1.519c0,0.896,0.249,1.618,0.747,2.165
c0.498,0.548,1.149,0.822,1.953,0.822c0.796,0,1.442-0.274,1.937-0.822c0.496-0.547,0.744-1.269,0.744-2.165V45.023z
M102.455,43.104h1.294c0.375,0,0.665,0.139,0.869,0.416s0.306,0.611,0.306,1.003c0,0.383-0.102,0.708-0.306,0.975
c-0.204,0.267-0.494,0.4-0.869,0.4h-1.294V43.104z M103.749,46.861c0.746,0,1.34-0.219,1.781-0.656
c0.442-0.437,0.663-1.003,0.663-1.698c0-0.69-0.221-1.257-0.663-1.7c-0.441-0.444-1.035-0.665-1.781-0.665h-2.556v7.281h1.262
v-2.562H103.749z M98.037,48.274c-0.213,0.195-0.527,0.293-0.944,0.293c-0.387,0-0.705-0.102-0.953-0.304
c-0.248-0.203-0.372-0.534-0.372-0.993h-1.212l-0.019,0.037c-0.021,0.747,0.206,1.304,0.681,1.671
c0.475,0.368,1.1,0.551,1.875,0.551c0.771,0,1.385-0.18,1.841-0.539c0.456-0.36,0.684-0.854,0.684-1.481
c0-0.611-0.181-1.078-0.544-1.4c-0.362-0.322-0.925-0.594-1.687-0.816c-0.567-0.173-0.941-0.347-1.122-0.522
c-0.181-0.176-0.272-0.418-0.272-0.727c0-0.301,0.093-0.55,0.278-0.746c0.186-0.196,0.47-0.294,0.853-0.294
c0.38,0,0.666,0.117,0.86,0.352c0.194,0.234,0.29,0.544,0.29,0.93h1.213l0.012-0.037c0.017-0.692-0.186-1.233-0.609-1.623
c-0.423-0.389-1.011-0.584-1.766-0.584c-0.733,0-1.315,0.185-1.746,0.555c-0.432,0.371-0.647,0.858-0.647,1.461
c0,0.62,0.18,1.087,0.54,1.399c0.361,0.312,0.937,0.578,1.728,0.799c0.517,0.17,0.872,0.348,1.066,0.532
c0.194,0.185,0.291,0.427,0.291,0.726C98.356,47.826,98.249,48.079,98.037,48.274 M92.912,42.142h-1.269v5.025l-0.037,0.012
l-2.794-5.037H87.55v7.281h1.262v-5.031l0.038-0.013l2.793,5.044h1.269V42.142z M83.187,43.917h0.038l0.919,2.9h-1.869
L83.187,43.917z M84.969,49.423h1.325l-2.425-7.281h-1.307l-2.437,7.281h1.331l0.519-1.644h2.469L84.969,49.423z M75.35,43.104
h1.169c0.367,0,0.642,0.111,0.825,0.332c0.183,0.22,0.275,0.518,0.275,0.893c0,0.379-0.091,0.671-0.272,0.875
c-0.181,0.204-0.457,0.306-0.828,0.306H75.35V43.104z M76.625,46.473c0.334,0,0.59,0.106,0.769,0.319
c0.179,0.212,0.269,0.51,0.269,0.894v0.656c0,0.216,0.005,0.429,0.015,0.637c0.011,0.209,0.037,0.357,0.078,0.444h1.307v-0.106
c-0.054-0.088-0.091-0.225-0.11-0.413c-0.018-0.187-0.028-0.373-0.028-0.556v-0.669c0-0.437-0.087-0.805-0.262-1.103
c-0.175-0.298-0.459-0.507-0.85-0.628c0.35-0.162,0.616-0.385,0.8-0.669c0.183-0.283,0.275-0.618,0.275-1.006
c0-0.671-0.21-1.194-0.628-1.569c-0.419-0.375-0.999-0.562-1.741-0.562h-2.431v7.281h1.262v-2.95H76.625z M73.263,40.323h-5.931
v0.963h2.325v8.137h1.268v-8.137h2.338V40.323z"}]]
[:g
[:g
[:path.st1 {:style {:fill "#006EB5"}
:d "M26.221,66.786c0,0.135,0.037,0.262,0.101,0.371c0.245-0.249,0.556-0.434,0.904-0.528
c0.146-0.516,0.62-0.893,1.182-0.893c0.048,0,0.095,0.002,0.141,0.008c-0.468,0.135-0.846,0.484-1.021,0.934
c-0.291,0.096-0.501,0.371-0.501,0.694c0,0.151,0.046,0.291,0.124,0.407c0.253-0.283,0.585-0.493,0.962-0.595
c0.108-0.542,0.559-0.96,1.117-1.019c-0.487,0.204-0.829,0.686-0.829,1.247c0,0.198,0.043,0.387,0.12,0.557
c0.086-0.309,0.369-0.536,0.705-0.536c0.085,0,0.166,0.014,0.24,0.041c0.105,0.038,0.218,0.058,0.334,0.058
c0.541,0,0.98-0.439,0.98-0.981c0-0.108-0.017-0.212-0.049-0.31c0.257,0.075,0.445,0.313,0.445,0.595
c0,0.129-0.039,0.248-0.106,0.347c0.072,0.013,0.146,0.02,0.222,0.02c0.637,0,1.163-0.479,1.236-1.097
c0.32-0.173,0.601-0.407,0.843-0.699l0.17,0.829c0.012,0.057,0.008,0.115-0.007,0.167c-0.015,0.053-0.043,0.103-0.084,0.145
l0.703-0.722c0.041-0.042,0.069-0.092,0.083-0.145c0.016-0.053,0.019-0.11,0.007-0.168l-0.207-1.011
c-0.012-0.057-0.009-0.115,0.007-0.167c0.015-0.053,0.043-0.103,0.084-0.145l0.553-0.564c-0.041,0.042-0.069,0.092-0.084,0.145
s-0.018,0.11-0.006,0.167l0.207,1.013c0.012,0.058,0.009,0.115-0.006,0.168c-0.015,0.052-0.042,0.101-0.082,0.143l0.627-0.652
c0.04-0.042,0.068-0.092,0.083-0.145c0.016-0.052,0.019-0.11,0.006-0.167l-0.206-1.01c-0.012-0.057-0.009-0.115,0.007-0.167
c0.015-0.053,0.043-0.103,0.084-0.145l0.553-0.564c-0.041,0.042-0.069,0.092-0.084,0.145c-0.015,0.052-0.018,0.11-0.006,0.167
l0.208,1.013c0.012,0.057,0.008,0.115-0.007,0.167s-0.042,0.101-0.082,0.143l0.627-0.651c0.041-0.042,0.068-0.093,0.083-0.145
c0.016-0.053,0.019-0.11,0.007-0.168l-0.101-0.494c-0.106-0.559,0.471-1.202,0.929-1.267c0.055-0.106,0.085-0.221,0.085-0.34
c0-0.567-0.675-1.027-1.509-1.027c-0.407,0-0.777,0.11-1.049,0.289c0.109,0.323,0.132,0.651-0.937,0.803
c-0.848,0.12-1.594,0.285-2.161,0.766c-0.874,0.741-0.803,1.732-1.3,2.107c0.221,0.054,0.502,0.054,0.803-0.011
c0.19-0.041,0.366-0.104,0.521-0.182c-0.093,0.179-0.306,0.348-0.586,0.468c-0.092,0.35-0.403,0.684-0.823,0.84
c-0.265,0.098-0.528,0.108-0.746,0.045l-1.023-0.296c-0.126-0.036-0.257-0.055-0.394-0.055c-0.754,0-1.376,0.581-1.468,1.332
C26.494,66.111,26.221,66.417,26.221,66.786 M36.335,26.328c0.589-0.576,1.27-1.057,2.019-1.42
c-0.022-0.088-0.034-0.178-0.034-0.269v-0.006c-3.126,0.513-5.939,2.118-8.479,2.104c-0.712-0.003-1.27-0.275-1.36-0.726
c-0.018-0.089-0.016-0.181,0.003-0.273c0.038-0.175,0.194-0.308,0.382-0.308c0.216,0,0.39,0.175,0.39,0.39
c0,0.104-0.04,0.198-0.105,0.268c0.073,0.007,0.148,0.011,0.226,0.011c0.201,0,0.392-0.025,0.56-0.071
c0.275-0.073,0.477-0.324,0.477-0.623c0-0.355-0.289-0.643-0.645-0.643c-0.019,0-0.039,0.001-0.058,0.002
c0.089-0.038,0.189-0.059,0.293-0.059c0.413,0,0.749,0.335,0.749,0.749c0,0.022-0.001,0.043-0.003,0.064
c1.116-0.025,2.374-1.043,2.649-1.431c-0.35,0.08-0.729,0.124-1.125,0.124c-0.449,0-0.878-0.056-1.266-0.158
c-0.549-0.145-1.089-0.226-1.504-0.226c-1.37,0-2.479,0.893-2.479,1.994c0,0.91,0.752,1.705,1.794,1.918
C31.19,28.225,33.979,26.815,36.335,26.328 M22.967,29.571c0.063-0.334,0.089-0.657,0.077-0.969l-0.299,0.35
c-0.059-0.139-0.098-0.225-0.138-0.294c-0.033-0.057-0.061-0.096-0.1-0.103c-0.02,0.01-0.05,0.027-0.083,0.034
c-0.038,0.009-0.09,0.006-0.123,0.006c-0.03,0-0.082,0.003-0.121-0.006c-0.032-0.007-0.062-0.024-0.082-0.034
c-0.04,0.007-0.067,0.046-0.1,0.103c-0.04,0.069-0.079,0.155-0.138,0.294l-0.3-0.35c-0.011,0.312,0.014,0.635,0.077,0.969
c0.221-0.048,0.449-0.065,0.664-0.065C22.518,29.506,22.746,29.523,22.967,29.571 M23.101,30.471
c0.033-0.379-0.397-0.514-0.8-0.514c-0.401,0-0.831,0.135-0.798,0.514c0.041,0.462,0.473,0.242,0.798,0.244
C22.628,30.713,23.06,30.933,23.101,30.471 M24.249,27.742c-0.079,0.021-0.122,0.067-0.131,0.15
c-0.047,0.446-0.228,0.626-0.517,0.727c-0.004,0.449-0.066,0.79-0.188,1.212c0.343,0.717,0.08,1.218-0.198,1.326
c-0.265,0.102-0.607-0.036-0.91-0.036s-0.65,0.138-0.915,0.036c-0.279-0.108-0.541-0.609-0.199-1.326
c-0.121-0.422-0.184-0.763-0.187-1.212c-0.289-0.101-0.471-0.281-0.518-0.727c-0.009-0.083-0.052-0.129-0.13-0.15
c-1.14-0.313-1.248-1.729-0.671-2.131c-0.052,0.635-0.106,1.53,1.19,1.649c-0.021,0.744,0.3,0.943,0.632,0.943
c0.271,0.001,0.426-0.086,0.494-0.122c0.241-0.128,0.075-0.324,0.013-0.382c-0.166-0.155-0.25-0.374-0.21-0.594
c0.007-0.04,0.022-0.06,0.059-0.06h0.438h0.44c0.037,0,0.053,0.02,0.059,0.06c0.04,0.22-0.044,0.439-0.209,0.594
c-0.062,0.058-0.228,0.254,0.013,0.382c0.067,0.036,0.223,0.123,0.494,0.122c0.331,0,0.653-0.199,0.632-0.943
c1.296-0.119,1.241-1.014,1.19-1.649C25.497,26.013,25.388,27.429,24.249,27.742 M24.6,25.271c0,0.325-0.238,0.687-0.509,0.687
h-0.249c0.063,0.075,0.101,0.172,0.101,0.276c0,0.241-0.195,0.436-0.435,0.436c-0.241,0-0.436-0.195-0.436-0.436
c0-0.104,0.038-0.201,0.1-0.276h-0.26c-0.089,0-0.158,0.037-0.213,0.141c-0.018-0.141-0.036-0.286-0.004-0.381
c0.044-0.132,0.146-0.21,0.248-0.21h1.142C24.296,25.508,24.453,25.436,24.6,25.271 M24.449,24.73H24.05
c-0.198,0-0.335-0.082-0.451-0.215l-0.455-0.594c-0.075-0.094-0.135-0.16-0.232-0.203h0.45c0.135,0,0.255,0.057,0.349,0.178
l0.474,0.603C24.291,24.627,24.324,24.713,24.449,24.73 M22.368,23.749l0.582,0.817c0.092,0.135,0.179,0.209,0.304,0.261h-0.533
c-0.205,0-0.328-0.095-0.418-0.242l-0.458-0.702c-0.175-0.263-0.244-0.328-0.445-0.401h0.495
C22.09,23.482,22.272,23.609,22.368,23.749 M21.049,23.896l0.474,0.603c0.106,0.128,0.139,0.214,0.264,0.231h-0.398
c-0.199,0-0.336-0.082-0.452-0.215l-0.455-0.594c-0.075-0.094-0.134-0.16-0.232-0.203h0.45
C20.835,23.718,20.955,23.775,21.049,23.896 M20.762,25.958h-0.249c-0.27,0-0.509-0.362-0.509-0.687
c0.148,0.165,0.304,0.237,0.516,0.237h1.142c0.102,0,0.204,0.078,0.248,0.21c0.032,0.095,0.014,0.24-0.004,0.381
c-0.055-0.104-0.124-0.141-0.213-0.141h-0.26c0.062,0.075,0.099,0.172,0.099,0.276c0,0.241-0.195,0.436-0.435,0.436
s-0.435-0.195-0.435-0.436C20.662,26.13,20.699,26.033,20.762,25.958 M19.354,31.399l0.138-0.27
c0.027-0.052,0.038-0.108,0.037-0.163c-0.001-0.054-0.015-0.111-0.043-0.16l0.379,0.681c0.028,0.052,0.042,0.108,0.043,0.161
c0.002,0.056-0.01,0.113-0.037,0.165l-0.034,0.067c-0.233,0.452-0.45,1.299-0.209,1.79c-0.562-0.209-0.747-0.701-0.687-1.11
c-1.058-1.002-1.324-2.019-0.569-2.872l0.387-0.453c0.04-0.044,0.065-0.095,0.076-0.148c0.013-0.053,0.013-0.11-0.002-0.166
l0.202,0.753c0.014,0.056,0.015,0.114,0.003,0.168c-0.012,0.053-0.037,0.104-0.075,0.149l-0.118,0.138
c-0.395,0.46-0.289,1.083,0.329,1.642C19.239,31.613,19.281,31.533,19.354,31.399 M45.29,34.227
c0.041-0.101,0.064-0.212,0.064-0.329c0-0.472-0.383-0.857-0.856-0.857h-0.866c-0.059,0.001-0.114-0.015-0.163-0.04
c-0.048-0.025-0.092-0.063-0.125-0.111l-0.434-0.641c0.033,0.049,0.076,0.086,0.125,0.11c0.048,0.027,0.104,0.041,0.163,0.04
l1.141,0.001c0.059,0,0.115,0.015,0.163,0.04c0.048,0.026,0.092,0.064,0.125,0.112l-0.524-0.767
c-0.033-0.05-0.077-0.086-0.126-0.111c-0.048-0.027-0.104-0.041-0.162-0.041l-1.132,0.001c-0.058,0-0.114-0.014-0.162-0.04
c-0.049-0.027-0.093-0.064-0.126-0.112l-0.492-0.724c0.033,0.049,0.077,0.086,0.125,0.111c0.049,0.026,0.104,0.041,0.163,0.041
l1.136-0.001c0.059,0,0.115,0.014,0.163,0.04c0.049,0.025,0.092,0.063,0.125,0.111l-0.524-0.768
c-0.033-0.048-0.077-0.085-0.126-0.111c-0.048-0.026-0.104-0.04-0.162-0.04H41.9c-0.059,0-0.114-0.015-0.163-0.04
c-0.048-0.026-0.092-0.063-0.125-0.113l-0.607-0.889c1.227-0.147,2.217-0.812,2.414-1.728c0.255-1.188-0.926-2.342-2.636-2.593
c-0.288-0.042-0.508-0.289-0.508-0.588c0-0.253,0.16-0.471,0.385-0.555c-0.182-0.079-0.386-0.123-0.602-0.123
c-0.757,0-1.37,0.542-1.37,1.211c0,0.12,0.021,0.237,0.058,0.346c-0.848,0.367-1.62,1.016-2.211,1.717
c0.632-0.168,1.296-0.259,1.981-0.259c-0.003-0.031-0.005-0.063-0.005-0.096c0-0.512,0.414-0.928,0.928-0.928h0.013
c-0.35,0.154-0.52,0.49-0.52,0.712c0,0.265,0.215,0.479,0.479,0.479c0.103,0,0.199-0.032,0.277-0.088
c-0.018-0.059-0.028-0.124-0.028-0.19c0-0.367,0.297-0.664,0.665-0.664c0.032,0,0.065,0.002,0.096,0.007
c-0.253,0.118-0.429,0.376-0.429,0.674c0,0.411,0.333,0.744,0.744,0.744c0.044,0,0.086-0.003,0.128-0.01
c-0.012-0.044-0.018-0.089-0.018-0.137c0-0.295,0.239-0.532,0.533-0.532c0.295,0,0.534,0.237,0.534,0.532
c0,0.642-0.712,0.7-1.231,0.552c-1.478-0.427-2.862-0.617-4.201-0.43c-1.718,0.242-4.532,1.403-7.519,1.306
c-0.668-0.021-1.397-0.132-2.131-0.333c0.09,0.099,0.148,0.167,0.186,0.225c0.291,0.453,0.391,0.927,0.134,1.522
c0.007-0.666-0.543-1.214-1.004-1.551c-0.186-0.134-0.261-0.263-0.23-0.436l0.136-0.768c-0.01,0.057-0.005,0.113,0.012,0.166
c0.017,0.052,0.046,0.101,0.088,0.142l0.287,0.281c0.109-0.777-0.067-1.502-0.53-2.173c0.205-0.536,0.233-1.128,0.096-1.682
c-0.054,0.42-0.26,0.6-0.456,0.721c-0.363,0.229-0.423,0.612-0.235,0.868c-0.307-0.155-0.73-0.724-0.485-1.057
c0.264-0.36,0.987-0.191,1.076-0.806c-0.469-0.149-0.952-0.044-1.099-0.005c-0.278-0.318-0.647-0.476-1.106-0.473
c-0.363-0.329-0.829-0.466-1.4-0.41c-0.568-0.056-1.034,0.081-1.397,0.41c-0.459-0.003-0.828,0.155-1.106,0.473
c-0.148-0.039-0.63-0.144-1.1,0.005c0.089,0.615,0.811,0.446,1.076,0.806c0.245,0.333-0.178,0.902-0.485,1.057
c0.189-0.256,0.128-0.639-0.236-0.868c-0.194-0.121-0.401-0.301-0.455-0.721c-0.137,0.554-0.108,1.146,0.096,1.682
c-0.463,0.671-0.639,1.396-0.53,2.173l0.288-0.281c0.042-0.041,0.071-0.09,0.088-0.142c0.017-0.053,0.021-0.109,0.01-0.166
l0.137,0.768c0.03,0.173-0.043,0.302-0.229,0.436c-0.462,0.337-1.012,0.885-1.005,1.551c-0.256-0.595-0.153-1.089,0.135-1.522
c-0.876-0.473-1.543-1.25-1.666-1.392c-0.265-0.309-0.23-0.701,0.01-1.045c0.463-0.662,0.573-1.368-0.008-1.851
c0.004-0.036,0.006-0.071,0.006-0.107c0-0.439-0.312-0.806-0.727-0.888c0.077,0.12,0.122,0.263,0.122,0.415
c0,0.176-0.058,0.336-0.157,0.467c0.082,0.107,0.131,0.241,0.131,0.388c0,0.196-0.088,0.371-0.227,0.488
c0.014-0.067,0.02-0.137,0.02-0.209c0-0.452-0.279-0.83-0.658-0.934c-0.061-0.328-0.349-0.577-0.695-0.577
c-0.201,0-0.381,0.083-0.51,0.216c0.268,0.022,0.484,0.232,0.513,0.497c-0.128,0.097-0.231,0.23-0.298,0.385h0.017
c0.463,0,0.838,0.375,0.838,0.838c0,0.052-0.005,0.104-0.014,0.153c-0.035-0.189-0.121-0.365-0.26-0.501
c-0.26-0.254-0.638-0.306-0.984-0.174c-0.13-0.164-0.33-0.268-0.554-0.268c-0.254,0-0.476,0.133-0.601,0.333
c0.256,0.011,0.481,0.14,0.622,0.335c-0.364,0.466-0.368,1.109,0.004,1.473c0.252,0.246,0.613,0.302,0.95,0.187
c0.022-0.008,0.046-0.012,0.071-0.012c0.124,0,0.224,0.101,0.224,0.224s-0.1,0.223-0.224,0.223c-0.054,0-0.104-0.019-0.142-0.051
c-0.085-0.071-0.195-0.113-0.314-0.113c-0.27,0-0.49,0.218-0.49,0.49c0,0.02,0.001,0.041,0.004,0.06
c-0.046,0.015-0.095,0.023-0.146,0.023c-0.132,0-0.252-0.054-0.34-0.14c-0.014,0.053-0.021,0.109-0.021,0.167
c0,0.345,0.266,0.628,0.605,0.654c0.152,0.377,0.523,0.644,0.955,0.644c0.222,0,0.427-0.07,0.595-0.188
c0.074-0.051,0.162-0.082,0.258-0.082c0.249,0,0.451,0.202,0.451,0.451c0,0.215-0.15,0.393-0.351,0.44l-0.351,0.076
c-0.057,0.014-0.115,0.011-0.168-0.005c-0.053-0.013-0.103-0.041-0.145-0.081l0.803,0.763c0.043,0.04,0.093,0.067,0.146,0.082
c0.053,0.015,0.11,0.018,0.167,0.005l0.658-0.146c0.057-0.013,0.115-0.01,0.167,0.004c0.052,0.015,0.104,0.042,0.146,0.082
l0.551,0.525c-0.043-0.04-0.093-0.069-0.147-0.082c-0.052-0.015-0.109-0.018-0.166-0.005l-0.657,0.144
c-0.057,0.014-0.115,0.011-0.167-0.004c-0.053-0.014-0.104-0.041-0.146-0.081l0.736,0.698c0.042,0.04,0.093,0.067,0.145,0.082
c0.053,0.014,0.111,0.016,0.168,0.004l0.658-0.144c0.058-0.013,0.115-0.011,0.168,0.005c0.053,0.014,0.103,0.042,0.146,0.082
l0.551,0.523c-0.043-0.04-0.093-0.066-0.146-0.082c-0.053-0.014-0.11-0.016-0.168-0.004l-0.656,0.145
c-0.058,0.013-0.115,0.01-0.168-0.005c-0.053-0.014-0.103-0.041-0.146-0.082l0.736,0.697c0.043,0.041,0.093,0.069,0.146,0.082
c0.053,0.016,0.11,0.019,0.168,0.005l0.795-0.173c-0.772,0.436-1.594,0.93-2.465,1.481c-0.515,0.325-1.078,0.386-1.725,0.138
c-0.348-0.133-0.725-0.156-0.963-0.115c-0.31,0.054-0.573,0.242-0.726,0.502c0.12-0.047,0.251-0.074,0.389-0.074
c0.289,0,0.55,0.116,0.74,0.305c-0.301-0.126-0.675-0.139-1.038-0.006c-0.65,0.235-1.029,0.849-0.881,1.397
c-0.243,0.094-0.413,0.329-0.413,0.603c0,0.181,0.074,0.345,0.194,0.462c0.064-0.288,0.316-0.505,0.621-0.517
c0.127,0.084,0.275,0.144,0.434,0.176c0.048-0.083,0.109-0.157,0.179-0.222c-0.008-0.051-0.011-0.104-0.011-0.158
c0-0.594,0.48-1.074,1.073-1.074c0.049,0,0.097,0.003,0.145,0.01c-0.471,0.113-0.822,0.537-0.822,1.044
c0,0.064,0.006,0.127,0.017,0.188c-0.254,0.098-0.433,0.343-0.433,0.631c0,0.165,0.059,0.315,0.158,0.434
c0.182-0.356,0.537-0.608,0.954-0.648c0.157,0.046,0.323,0.07,0.494,0.07c0.108,0,0.213-0.009,0.315-0.027
c-0.092-0.135-0.146-0.297-0.146-0.473c0-0.46,0.373-0.834,0.835-0.834c0.04,0,0.078,0.002,0.118,0.008
c-0.441,0.188-0.711,0.571-0.618,0.92c0.066,0.246,0.299,0.418,0.6,0.475c-0.004,0.184-0.055,0.359-0.142,0.51
c0.387-0.028,0.718-0.261,0.883-0.592c0.456-0.183,0.737-0.574,0.643-0.929c-0.034-0.127-0.113-0.234-0.22-0.315
c-0.001-0.012-0.002-0.025-0.002-0.037c0-0.245,0.199-0.443,0.442-0.443c0.246,0,0.444,0.198,0.444,0.443
c0,0.116-0.044,0.221-0.117,0.299h0.927c0.058,0,0.114-0.014,0.162-0.041c0.049-0.024,0.092-0.062,0.125-0.111l0.595-0.882
c0.022-0.033,0.052-0.058,0.085-0.076c0.033-0.018,0.07-0.028,0.111-0.028h0.728c-0.04,0-0.078,0.01-0.111,0.028
c-0.033,0.018-0.063,0.043-0.085,0.076l-0.597,0.882c-0.033,0.049-0.076,0.087-0.125,0.111c-0.048,0.027-0.103,0.041-0.162,0.041
h1.108c0.059,0,0.114-0.014,0.161-0.041c0.05-0.024,0.094-0.062,0.125-0.111l0.668-0.985c-0.46-0.252-0.649-0.694-0.649-1.299
c0-0.377,0.212-0.807,0.244-1.084L20.7,32.48c0.007-0.057-0.001-0.114-0.021-0.166c-0.016-0.042-0.048-0.101-0.083-0.142
l0.57,0.584c0.045,0.038,0.077,0.086,0.096,0.137c0.021,0.05,0.029,0.108,0.022,0.166l-0.017,0.133
c-0.027,0.233-0.319,0.733,0.223,1.191c0.027,0.022,0.094,0.071,0.158,0.111l0.385,0.241v-1.421h0.539v1.582
c0.001,0.059,0.018,0.114,0.045,0.162c0.027,0.047,0.065,0.089,0.115,0.121l0.526,0.335c0.051,0.032,0.106,0.049,0.16,0.052
c0.055,0.004,0.112-0.003,0.165-0.026l0.971-0.422c-0.054,0.024-0.111,0.031-0.165,0.027c-0.055-0.004-0.11-0.021-0.159-0.052
l-1.115-0.71c0.542-0.458,0.249-0.958,0.222-1.191l-0.016-0.133c-0.007-0.058,0.001-0.116,0.02-0.166
c0.021-0.051,0.053-0.099,0.097-0.137l0.57-0.584c-0.035,0.041-0.066,0.1-0.083,0.142c-0.019,0.052-0.027,0.109-0.02,0.166
l0.012,0.111c0.046,0.394,0.446,1.111,0.113,1.51l1.019,0.647c0.05,0.03,0.105,0.049,0.159,0.053
c0.055,0.004,0.112-0.004,0.166-0.029l1.015-0.44c-0.054,0.023-0.11,0.03-0.164,0.026c-0.055-0.003-0.11-0.02-0.16-0.052
l-1.102-0.701c0.24-0.492,0.038-1.273-0.195-1.725l-0.035-0.067c-0.026-0.052-0.038-0.109-0.036-0.165
c0-0.053,0.014-0.109,0.043-0.161l0.378-0.681c-0.028,0.049-0.042,0.106-0.042,0.16c-0.002,0.055,0.01,0.111,0.036,0.163
l0.139,0.27c0.073,0.134,0.114,0.214,0.178,0.372c0.62-0.559,0.758-1.098,0.363-1.557l-0.118-0.139
c-0.038-0.045-0.063-0.096-0.075-0.149c-0.013-0.054-0.013-0.112,0.003-0.168l0.202-0.753c-0.015,0.056-0.015,0.113-0.004,0.166
c0.013,0.053,0.038,0.104,0.077,0.149l0.388,0.452c0.754,0.853,0.298,1.951-0.602,2.788c0.05,0.161,0.093,0.461,0.057,0.625
l1.195,0.757c0.05,0.033,0.105,0.05,0.16,0.054c0.054,0.005,0.111-0.004,0.165-0.027l0.864-0.376
c-0.049,0.02-0.104,0.033-0.16,0.033c-0.223,0-0.403-0.181-0.403-0.402c0-0.18,0.117-0.335,0.281-0.384
c3.299-1.003,6.336-3.594,8.33-3.587c0.969,0.003,1.755,0.589,1.755,1.315c0,0.118-0.021,0.232-0.059,0.341
c-0.425,1.194,0.194,2.334,1.828,2.774c0.261,0.07,0.453,0.308,0.453,0.589c0,0.056-0.008,0.11-0.021,0.16
c0.037,0.004,0.075,0.005,0.114,0.005c0.45,0,0.848-0.223,1.089-0.566c0.28-0.002,0.587-0.019,0.901-0.053
c0.038,0.077,0.068,0.163,0.086,0.258c0.067,0.344-0.052,0.654-0.263,0.722c-0.375,0.122-0.835-0.025-1.19-0.021
c-0.672,0.007-1.215,0.553-1.215,1.227c0,0.052,0.003,0.103,0.01,0.156c-0.211,0.131-0.351,0.364-0.351,0.631
c0,0.133,0.035,0.258,0.095,0.366c0.207-0.241,0.477-0.428,0.784-0.536c0.026-0.591,0.512-1.06,1.108-1.06
c0.091,0,0.181,0.01,0.265,0.032c-0.604,0.076-1.072,0.592-1.072,1.217c0,0.045,0.003,0.089,0.008,0.134
c-0.075,0.092-0.12,0.207-0.12,0.334c0,0.16,0.072,0.305,0.185,0.402c0.114-0.25,0.389-0.485,0.745-0.605
c0.239-0.08,0.474-0.096,0.67-0.056c-0.032-0.094-0.047-0.194-0.047-0.297c0-0.534,0.431-0.966,0.965-0.966
c0.049,0,0.098,0.004,0.145,0.011c-0.372,0.049-0.658,0.369-0.658,0.754c0,0.255,0.126,0.482,0.319,0.621
c0,0.012-0.001,0.027-0.001,0.041c0,0.21,0.096,0.396,0.246,0.519c0.068-0.35,0.374-0.614,0.745-0.614
c0.316,0,0.577-0.04,0.772-0.105c0.33-0.107,0.571-0.413,0.571-0.777c0-0.253-0.115-0.479-0.297-0.628
c0.09-0.41,0.074-1.083-0.065-1.643c0.028-0.004,0.057-0.006,0.087-0.006C44.969,33.929,45.172,34.048,45.29,34.227
M28.481,41.176c-0.018-0.089-0.016-0.181,0.003-0.273c0.038-0.175,0.194-0.308,0.382-0.308c0.216,0,0.39,0.175,0.39,0.39
c0,0.104-0.04,0.198-0.105,0.268c0.073,0.007,0.148,0.011,0.226,0.011c0.201,0,0.392-0.026,0.56-0.071
c0.275-0.073,0.477-0.324,0.477-0.623c0-0.355-0.289-0.643-0.645-0.643c-0.019,0-0.039,0.001-0.058,0.002
c0.089-0.038,0.189-0.059,0.293-0.059c0.413,0,0.749,0.335,0.749,0.749c0,0.021-0.001,0.043-0.003,0.064
c1.116-0.025,2.374-1.043,2.649-1.431c-0.35,0.08-0.729,0.124-1.125,0.124c-0.449,0-0.878-0.056-1.266-0.158
c-0.549-0.146-1.089-0.226-1.504-0.226c-1.37,0-2.479,0.893-2.479,1.994c0,0.91,0.752,1.705,1.794,1.918
c2.371,0.486,5.16-0.924,7.516-1.411c0.589-0.576,1.27-1.057,2.019-1.421c-0.022-0.087-0.034-0.176-0.034-0.268v-0.006
c-3.126,0.514-5.939,2.118-8.479,2.104C29.129,41.899,28.571,41.627,28.481,41.176 M28.408,35.405
c0.048,0,0.095,0.004,0.141,0.009c-0.468,0.135-0.846,0.483-1.021,0.934c-0.291,0.095-0.501,0.371-0.501,0.694
c0,0.15,0.046,0.291,0.124,0.407c0.253-0.282,0.585-0.493,0.962-0.595c0.108-0.542,0.559-0.96,1.117-1.019
c-0.487,0.204-0.829,0.686-0.829,1.247c0,0.198,0.043,0.387,0.12,0.557c0.086-0.309,0.369-0.536,0.705-0.536
c0.085,0,0.166,0.014,0.24,0.041c0.105,0.038,0.218,0.059,0.334,0.059c0.541,0,0.98-0.44,0.98-0.982
c0-0.109-0.017-0.212-0.049-0.309c0.257,0.073,0.445,0.312,0.445,0.594c0,0.129-0.039,0.248-0.106,0.348
c0.072,0.013,0.146,0.019,0.222,0.019c0.637,0,1.163-0.479,1.236-1.098c0.32-0.172,0.601-0.406,0.843-0.698l0.17,0.828
c0.012,0.059,0.008,0.116-0.007,0.169c-0.015,0.052-0.043,0.102-0.084,0.145l0.703-0.723c0.041-0.042,0.069-0.093,0.083-0.145
c0.016-0.053,0.019-0.11,0.007-0.167l-0.207-1.012c-0.012-0.058-0.009-0.115,0.007-0.167c0.015-0.053,0.043-0.104,0.084-0.146
l0.553-0.563c-0.041,0.043-0.069,0.093-0.084,0.144c-0.015,0.054-0.018,0.111-0.006,0.168l0.207,1.014
c0.012,0.057,0.009,0.113-0.006,0.167c-0.015,0.052-0.042,0.101-0.082,0.143l0.627-0.653c0.04-0.042,0.068-0.091,0.083-0.144
c0.016-0.052,0.019-0.111,0.006-0.167l-0.206-1.01c-0.012-0.058-0.009-0.115,0.007-0.167c0.015-0.054,0.043-0.103,0.084-0.145
l0.553-0.564c-0.041,0.042-0.069,0.092-0.084,0.145c-0.015,0.052-0.018,0.11-0.006,0.167l0.208,1.013
c0.012,0.057,0.008,0.114-0.007,0.167c-0.015,0.052-0.042,0.101-0.082,0.143l0.627-0.652c0.041-0.042,0.068-0.091,0.083-0.144
c0.016-0.053,0.019-0.11,0.007-0.168l-0.101-0.494c-0.106-0.559,0.471-1.202,0.929-1.267c0.055-0.106,0.085-0.221,0.085-0.341
c0-0.566-0.675-1.026-1.509-1.026c-0.407,0-0.777,0.109-1.049,0.289c0.109,0.322,0.132,0.65-0.937,0.803
c-0.848,0.121-1.594,0.285-2.161,0.765c-0.874,0.742-0.803,1.733-1.3,2.108c0.221,0.054,0.502,0.054,0.803-0.011
c0.19-0.041,0.366-0.104,0.521-0.182c-0.093,0.179-0.306,0.348-0.586,0.467c-0.092,0.351-0.403,0.685-0.823,0.841
c-0.265,0.098-0.528,0.108-0.746,0.045l-1.023-0.296c-0.126-0.036-0.257-0.056-0.394-0.056c-0.754,0-1.376,0.582-1.468,1.332
c-0.356,0.05-0.629,0.357-0.629,0.726c0,0.136,0.037,0.263,0.101,0.371c0.245-0.249,0.556-0.434,0.904-0.528
C27.372,35.784,27.846,35.405,28.408,35.405 M22.967,44.736c0.063-0.334,0.089-0.657,0.077-0.969l-0.299,0.35
c-0.059-0.139-0.098-0.225-0.138-0.295c-0.033-0.056-0.061-0.095-0.1-0.102c-0.02,0.01-0.05,0.027-0.083,0.034
c-0.038,0.009-0.09,0.006-0.123,0.006c-0.03,0-0.082,0.003-0.121-0.006c-0.032-0.007-0.062-0.024-0.082-0.034
c-0.04,0.007-0.067,0.046-0.1,0.102c-0.04,0.07-0.079,0.156-0.138,0.295l-0.3-0.35c-0.011,0.312,0.014,0.635,0.077,0.969
c0.221-0.048,0.449-0.065,0.664-0.065C22.518,44.671,22.746,44.688,22.967,44.736 M23.101,45.636
c0.033-0.379-0.397-0.514-0.8-0.514c-0.401,0-0.831,0.135-0.798,0.514c0.041,0.462,0.473,0.242,0.798,0.244
C22.628,45.878,23.06,46.098,23.101,45.636 M24.249,42.907c-0.079,0.021-0.122,0.067-0.131,0.15
c-0.047,0.446-0.228,0.626-0.517,0.727c-0.004,0.449-0.066,0.79-0.188,1.212c0.343,0.717,0.08,1.218-0.198,1.325
c-0.265,0.103-0.607-0.035-0.91-0.035s-0.65,0.138-0.915,0.035c-0.279-0.107-0.541-0.608-0.199-1.325
c-0.121-0.422-0.184-0.763-0.187-1.212c-0.289-0.101-0.471-0.281-0.518-0.727c-0.009-0.083-0.052-0.129-0.13-0.15
c-1.14-0.313-1.248-1.729-0.671-2.131c-0.052,0.635-0.106,1.53,1.19,1.649c-0.021,0.744,0.3,0.943,0.632,0.943
c0.271,0.001,0.426-0.086,0.494-0.122c0.241-0.128,0.075-0.324,0.013-0.383c-0.166-0.154-0.25-0.375-0.21-0.593
c0.007-0.04,0.022-0.06,0.059-0.06h0.438h0.44c0.037,0,0.053,0.02,0.059,0.06c0.04,0.218-0.044,0.439-0.209,0.593
c-0.062,0.059-0.228,0.255,0.013,0.383c0.067,0.036,0.223,0.123,0.494,0.122c0.331,0,0.653-0.199,0.632-0.943
c1.296-0.119,1.241-1.014,1.19-1.649C25.497,41.178,25.388,42.594,24.249,42.907 M24.6,40.436c0,0.325-0.238,0.687-0.509,0.687
h-0.249c0.063,0.074,0.101,0.171,0.101,0.276c0,0.241-0.195,0.436-0.435,0.436c-0.241,0-0.436-0.195-0.436-0.436
c0-0.105,0.038-0.202,0.1-0.276h-0.26c-0.089,0-0.158,0.037-0.213,0.141c-0.018-0.141-0.036-0.285-0.004-0.382
c0.044-0.131,0.146-0.21,0.248-0.21h1.142C24.296,40.672,24.453,40.601,24.6,40.436 M24.449,39.895H24.05
c-0.198,0-0.335-0.082-0.451-0.215l-0.455-0.594c-0.075-0.094-0.135-0.16-0.232-0.203h0.45c0.135,0,0.255,0.057,0.349,0.178
l0.474,0.603C24.291,39.792,24.324,39.878,24.449,39.895 M22.368,38.914l0.582,0.817c0.092,0.135,0.179,0.209,0.304,0.261h-0.533
c-0.205,0-0.328-0.095-0.418-0.242l-0.458-0.702c-0.175-0.263-0.244-0.328-0.445-0.401h0.495
C22.09,38.647,22.272,38.774,22.368,38.914 M21.049,39.061l0.474,0.603c0.106,0.128,0.139,0.214,0.264,0.231h-0.398
c-0.199,0-0.336-0.082-0.452-0.215l-0.455-0.594c-0.075-0.094-0.134-0.16-0.232-0.203h0.45
C20.835,38.883,20.955,38.94,21.049,39.061 M20.762,41.123h-0.249c-0.27,0-0.509-0.362-0.509-0.687
c0.148,0.165,0.304,0.236,0.516,0.236h1.142c0.102,0,0.204,0.079,0.248,0.21c0.032,0.097,0.014,0.241-0.004,0.382
c-0.055-0.104-0.124-0.141-0.213-0.141h-0.26c0.062,0.074,0.099,0.171,0.099,0.276c0,0.241-0.195,0.436-0.435,0.436
s-0.435-0.195-0.435-0.436C20.662,41.294,20.699,41.197,20.762,41.123 M19.354,46.565l0.138-0.271
c0.027-0.052,0.038-0.108,0.037-0.163c-0.001-0.054-0.015-0.11-0.043-0.16l0.379,0.682c0.028,0.051,0.042,0.106,0.043,0.161
c0.002,0.055-0.01,0.112-0.037,0.164l-0.034,0.067c-0.233,0.452-0.45,1.299-0.209,1.79c-0.562-0.209-0.747-0.701-0.687-1.109
c-1.058-1.003-1.324-2.02-0.569-2.872l0.387-0.454c0.04-0.044,0.065-0.095,0.076-0.148c0.013-0.053,0.013-0.11-0.002-0.166
l0.202,0.753c0.014,0.057,0.015,0.114,0.003,0.168c-0.012,0.053-0.037,0.104-0.075,0.148l-0.118,0.139
c-0.395,0.46-0.289,1.083,0.329,1.642C19.239,46.779,19.281,46.698,19.354,46.565 M45.29,49.392
c0.041-0.101,0.064-0.212,0.064-0.328c0-0.473-0.383-0.858-0.856-0.858h-0.866c-0.059,0.001-0.114-0.014-0.163-0.04
c-0.048-0.025-0.092-0.063-0.125-0.111l-0.434-0.641c0.033,0.048,0.076,0.086,0.125,0.111c0.048,0.026,0.104,0.041,0.163,0.04
l1.141,0.001c0.059,0,0.115,0.014,0.163,0.04c0.048,0.025,0.092,0.063,0.125,0.111l-0.524-0.767
c-0.033-0.049-0.077-0.086-0.126-0.111c-0.048-0.026-0.104-0.041-0.162-0.041l-1.132,0.001c-0.058,0-0.114-0.014-0.162-0.04
c-0.049-0.025-0.093-0.063-0.126-0.111l-0.492-0.725c0.033,0.049,0.077,0.086,0.125,0.111c0.049,0.026,0.104,0.041,0.163,0.041
l1.136-0.001c0.059,0,0.115,0.014,0.163,0.04c0.049,0.025,0.092,0.062,0.125,0.111l-0.524-0.767
c-0.033-0.049-0.077-0.086-0.126-0.112c-0.048-0.027-0.104-0.04-0.162-0.04H41.9c-0.059,0-0.114-0.015-0.163-0.04
c-0.048-0.027-0.092-0.063-0.125-0.113l-0.607-0.89c1.227-0.146,2.217-0.811,2.414-1.727c0.255-1.188-0.926-2.342-2.636-2.593
c-0.288-0.042-0.508-0.289-0.508-0.588c0-0.253,0.16-0.471,0.385-0.555c-0.182-0.079-0.386-0.123-0.602-0.123
c-0.757,0-1.37,0.542-1.37,1.211c0,0.12,0.021,0.237,0.058,0.346c-0.848,0.367-1.62,1.016-2.211,1.717
c0.632-0.168,1.296-0.259,1.981-0.259c-0.003-0.031-0.005-0.063-0.005-0.096c0-0.513,0.414-0.928,0.928-0.928h0.013
c-0.35,0.153-0.52,0.49-0.52,0.712c0,0.265,0.215,0.479,0.479,0.479c0.103,0,0.199-0.032,0.277-0.088
c-0.018-0.059-0.028-0.124-0.028-0.19c0-0.367,0.297-0.664,0.665-0.664c0.032,0,0.065,0.002,0.096,0.007
c-0.253,0.118-0.429,0.376-0.429,0.674c0,0.411,0.333,0.744,0.744,0.744c0.044,0,0.086-0.003,0.128-0.01
c-0.012-0.044-0.018-0.089-0.018-0.137c0-0.295,0.239-0.533,0.533-0.533c0.295,0,0.534,0.238,0.534,0.533
c0,0.642-0.712,0.701-1.231,0.552c-1.478-0.427-2.862-0.617-4.201-0.431c-1.718,0.243-4.532,1.404-7.519,1.307
c-0.668-0.021-1.397-0.132-2.131-0.333c0.09,0.099,0.148,0.167,0.186,0.225c0.291,0.453,0.391,0.927,0.134,1.522
c0.007-0.666-0.543-1.215-1.004-1.551c-0.186-0.134-0.261-0.263-0.23-0.436l0.136-0.768c-0.01,0.057-0.005,0.114,0.012,0.164
c0.017,0.054,0.046,0.103,0.088,0.144l0.287,0.281c0.109-0.778-0.067-1.502-0.53-2.174c0.205-0.535,0.233-1.127,0.096-1.681
c-0.054,0.42-0.26,0.6-0.456,0.721c-0.363,0.228-0.423,0.612-0.235,0.868c-0.307-0.155-0.73-0.725-0.485-1.057
c0.264-0.36,0.987-0.191,1.076-0.806c-0.469-0.149-0.952-0.045-1.099-0.005c-0.278-0.318-0.647-0.476-1.106-0.473
c-0.363-0.329-0.829-0.466-1.4-0.409c-0.568-0.057-1.034,0.08-1.397,0.409c-0.459-0.003-0.828,0.155-1.106,0.473
c-0.148-0.04-0.63-0.144-1.1,0.005c0.089,0.615,0.811,0.446,1.076,0.806c0.245,0.332-0.178,0.902-0.485,1.057
c0.189-0.256,0.128-0.64-0.236-0.868c-0.194-0.121-0.401-0.301-0.455-0.721c-0.137,0.554-0.108,1.146,0.096,1.681
c-0.463,0.672-0.639,1.396-0.53,2.174l0.288-0.281c0.042-0.041,0.071-0.09,0.088-0.144c0.017-0.05,0.021-0.107,0.01-0.164
l0.137,0.768c0.03,0.173-0.043,0.302-0.229,0.436c-0.462,0.336-1.012,0.885-1.005,1.551c-0.256-0.595-0.153-1.09,0.135-1.522
c-0.876-0.473-1.543-1.25-1.666-1.392c-0.265-0.309-0.23-0.701,0.01-1.045c0.463-0.662,0.573-1.368-0.008-1.851
c0.004-0.036,0.006-0.072,0.006-0.107c0-0.439-0.312-0.806-0.727-0.889c0.077,0.121,0.122,0.264,0.122,0.416
c0,0.175-0.058,0.336-0.157,0.466c0.082,0.108,0.131,0.242,0.131,0.389c0,0.195-0.088,0.371-0.227,0.487
c0.014-0.066,0.02-0.136,0.02-0.209c0-0.451-0.279-0.829-0.658-0.933c-0.061-0.328-0.349-0.577-0.695-0.577
c-0.201,0-0.381,0.083-0.51,0.216c0.268,0.021,0.484,0.232,0.513,0.497c-0.128,0.097-0.231,0.229-0.298,0.385h0.017
c0.463,0,0.838,0.375,0.838,0.838c0,0.052-0.005,0.104-0.014,0.153c-0.035-0.189-0.121-0.365-0.26-0.501
c-0.26-0.253-0.638-0.306-0.984-0.174c-0.13-0.163-0.33-0.268-0.554-0.268c-0.254,0-0.476,0.133-0.601,0.333
c0.256,0.011,0.481,0.14,0.622,0.335c-0.364,0.466-0.368,1.109,0.004,1.473c0.252,0.246,0.613,0.302,0.95,0.187
c0.022-0.008,0.046-0.012,0.071-0.012c0.124,0,0.224,0.101,0.224,0.224c0,0.123-0.1,0.223-0.224,0.223
c-0.054,0-0.104-0.019-0.142-0.051c-0.085-0.071-0.195-0.113-0.314-0.113c-0.27,0-0.49,0.218-0.49,0.49
c0,0.02,0.001,0.041,0.004,0.059c-0.046,0.016-0.095,0.024-0.146,0.024c-0.132,0-0.252-0.054-0.34-0.141
c-0.014,0.054-0.021,0.11-0.021,0.167c0,0.346,0.266,0.629,0.605,0.655c0.152,0.377,0.523,0.644,0.955,0.644
c0.222,0,0.427-0.07,0.595-0.188c0.074-0.051,0.162-0.082,0.258-0.082c0.249,0,0.451,0.202,0.451,0.451
c0,0.215-0.15,0.393-0.351,0.44l-0.351,0.076c-0.057,0.014-0.115,0.011-0.168-0.005c-0.053-0.013-0.103-0.041-0.145-0.081
l0.803,0.763c0.043,0.04,0.093,0.068,0.146,0.082c0.053,0.015,0.11,0.018,0.167,0.005l0.658-0.146
c0.057-0.013,0.115-0.01,0.167,0.004c0.052,0.015,0.104,0.042,0.146,0.082l0.551,0.525c-0.043-0.04-0.093-0.068-0.147-0.082
c-0.052-0.015-0.109-0.018-0.166-0.005l-0.657,0.145c-0.057,0.013-0.115,0.01-0.167-0.005c-0.053-0.014-0.104-0.041-0.146-0.081
l0.736,0.697c0.042,0.041,0.093,0.068,0.145,0.083c0.053,0.015,0.111,0.017,0.168,0.004l0.658-0.144
c0.058-0.013,0.115-0.01,0.168,0.005c0.053,0.014,0.103,0.042,0.146,0.082l0.551,0.524c-0.043-0.04-0.093-0.068-0.146-0.082
c-0.053-0.015-0.11-0.017-0.168-0.005L16.89,47.12c-0.058,0.013-0.115,0.01-0.168-0.005c-0.053-0.014-0.103-0.041-0.146-0.081
l0.736,0.697c0.043,0.041,0.093,0.068,0.146,0.082c0.053,0.015,0.11,0.018,0.168,0.005l0.795-0.174
c-0.772,0.436-1.594,0.93-2.465,1.481c-0.515,0.325-1.078,0.386-1.725,0.138c-0.348-0.133-0.725-0.154-0.963-0.114
c-0.31,0.053-0.573,0.241-0.726,0.502c0.12-0.048,0.251-0.075,0.389-0.075c0.289,0,0.55,0.117,0.74,0.305
c-0.301-0.126-0.675-0.139-1.038-0.006c-0.65,0.236-1.029,0.849-0.881,1.398c-0.243,0.093-0.413,0.328-0.413,0.602
c0,0.181,0.074,0.345,0.194,0.462c0.064-0.288,0.316-0.505,0.621-0.516c0.127,0.084,0.275,0.143,0.434,0.175
c0.048-0.083,0.109-0.158,0.179-0.221c-0.008-0.052-0.011-0.105-0.011-0.159c0-0.593,0.48-1.074,1.073-1.074
c0.049,0,0.097,0.003,0.145,0.01c-0.471,0.113-0.822,0.537-0.822,1.044c0,0.064,0.006,0.127,0.017,0.188
c-0.254,0.098-0.433,0.343-0.433,0.631c0,0.165,0.059,0.316,0.158,0.434c0.182-0.356,0.537-0.608,0.954-0.648
c0.157,0.046,0.323,0.071,0.494,0.071c0.108,0,0.213-0.01,0.315-0.028c-0.092-0.135-0.146-0.297-0.146-0.472
c0-0.461,0.373-0.834,0.835-0.834c0.04,0,0.078,0.003,0.118,0.008c-0.441,0.187-0.711,0.57-0.618,0.919
c0.066,0.247,0.299,0.418,0.6,0.475c-0.004,0.185-0.055,0.359-0.142,0.51c0.387-0.028,0.718-0.261,0.883-0.592
c0.456-0.183,0.737-0.574,0.643-0.929c-0.034-0.127-0.113-0.234-0.22-0.315c-0.001-0.012-0.002-0.025-0.002-0.037
c0-0.244,0.199-0.443,0.442-0.443c0.246,0,0.444,0.199,0.444,0.443c0,0.116-0.044,0.221-0.117,0.3h0.927
c0.058,0,0.114-0.015,0.162-0.041c0.049-0.025,0.092-0.063,0.125-0.112l0.595-0.882c0.022-0.033,0.052-0.058,0.085-0.076
c0.033-0.017,0.07-0.028,0.111-0.028h0.728c-0.04,0-0.078,0.011-0.111,0.028c-0.033,0.018-0.063,0.043-0.085,0.076l-0.597,0.883
c-0.033,0.048-0.076,0.086-0.125,0.111c-0.048,0.026-0.103,0.041-0.162,0.041h1.108c0.059,0,0.114-0.015,0.161-0.041
c0.05-0.025,0.094-0.063,0.125-0.112l0.668-0.985c-0.46-0.252-0.649-0.693-0.649-1.299c0-0.377,0.212-0.807,0.244-1.084
l0.013-0.11c0.007-0.059-0.001-0.115-0.021-0.166c-0.016-0.042-0.048-0.102-0.083-0.143l0.57,0.584
c0.045,0.038,0.077,0.086,0.096,0.137c0.021,0.051,0.029,0.108,0.022,0.167l-0.017,0.133c-0.027,0.232-0.319,0.732,0.223,1.19
c0.027,0.023,0.094,0.071,0.158,0.111l0.385,0.242V48.48h0.539v1.581c0.001,0.059,0.018,0.114,0.045,0.162
c0.027,0.047,0.065,0.09,0.115,0.121l0.526,0.335c0.051,0.031,0.106,0.049,0.16,0.053c0.055,0.004,0.112-0.004,0.165-0.027
l0.971-0.422c-0.054,0.024-0.111,0.032-0.165,0.027c-0.055-0.004-0.11-0.021-0.159-0.052l-1.115-0.71
c0.542-0.458,0.249-0.958,0.222-1.19l-0.016-0.133c-0.007-0.059,0.001-0.116,0.02-0.167c0.021-0.051,0.053-0.099,0.097-0.137
l0.57-0.584c-0.035,0.041-0.066,0.101-0.083,0.143c-0.019,0.051-0.027,0.107-0.02,0.166l0.012,0.11
c0.046,0.395,0.446,1.111,0.113,1.511l1.019,0.646c0.05,0.031,0.105,0.049,0.159,0.053c0.055,0.004,0.112-0.004,0.166-0.028
l1.015-0.441c-0.054,0.023-0.11,0.031-0.164,0.027c-0.055-0.004-0.11-0.021-0.16-0.053l-1.102-0.701
c0.24-0.491,0.038-1.273-0.195-1.725l-0.035-0.067c-0.026-0.052-0.038-0.109-0.036-0.164c0-0.055,0.014-0.11,0.043-0.161
l0.378-0.682c-0.028,0.05-0.042,0.106-0.042,0.16c-0.002,0.055,0.01,0.111,0.036,0.163l0.139,0.271
c0.073,0.133,0.114,0.214,0.178,0.371c0.62-0.559,0.758-1.098,0.363-1.557l-0.118-0.14c-0.038-0.044-0.063-0.095-0.075-0.148
c-0.013-0.054-0.013-0.111,0.003-0.168l0.202-0.753c-0.015,0.056-0.015,0.113-0.004,0.166c0.013,0.053,0.038,0.104,0.077,0.148
l0.388,0.454c0.754,0.852,0.298,1.95-0.602,2.788c0.05,0.16,0.093,0.461,0.057,0.624l1.195,0.758
c0.05,0.032,0.105,0.049,0.16,0.053c0.054,0.005,0.111-0.004,0.165-0.027l0.864-0.376c-0.049,0.021-0.104,0.033-0.16,0.033
c-0.223,0-0.403-0.18-0.403-0.402c0-0.18,0.117-0.335,0.281-0.384c3.299-1.004,6.336-3.594,8.33-3.588
c0.969,0.004,1.755,0.59,1.755,1.317c0,0.117-0.021,0.231-0.059,0.34c-0.425,1.194,0.194,2.334,1.828,2.774
c0.261,0.07,0.453,0.308,0.453,0.59c0,0.055-0.008,0.109-0.021,0.159c0.037,0.004,0.075,0.005,0.114,0.005
c0.45,0,0.848-0.224,1.089-0.566c0.28-0.002,0.587-0.019,0.901-0.052c0.038,0.076,0.068,0.163,0.086,0.257
c0.067,0.344-0.052,0.654-0.263,0.722c-0.375,0.122-0.835-0.024-1.19-0.021c-0.672,0.007-1.215,0.553-1.215,1.226
c0,0.053,0.003,0.105,0.01,0.157c-0.211,0.131-0.351,0.365-0.351,0.631c0,0.133,0.035,0.258,0.095,0.366
c0.207-0.241,0.477-0.428,0.784-0.536c0.026-0.59,0.512-1.06,1.108-1.06c0.091,0,0.181,0.011,0.265,0.032
c-0.604,0.076-1.072,0.592-1.072,1.217c0,0.045,0.003,0.09,0.008,0.135c-0.075,0.09-0.12,0.207-0.12,0.333
c0,0.161,0.072,0.305,0.185,0.402c0.114-0.25,0.389-0.485,0.745-0.605c0.239-0.08,0.474-0.096,0.67-0.056
c-0.032-0.094-0.047-0.194-0.047-0.297c0-0.534,0.431-0.966,0.965-0.966c0.049,0,0.098,0.004,0.145,0.011
c-0.372,0.051-0.658,0.369-0.658,0.754c0,0.256,0.126,0.482,0.319,0.621c0,0.013-0.001,0.027-0.001,0.041
c0,0.21,0.096,0.396,0.246,0.519c0.068-0.35,0.374-0.614,0.745-0.614c0.316,0,0.577-0.04,0.772-0.104
c0.33-0.108,0.571-0.413,0.571-0.778c0-0.253-0.115-0.479-0.297-0.628c0.09-0.41,0.074-1.083-0.065-1.643
c0.028-0.004,0.057-0.006,0.087-0.006C44.969,49.094,45.172,49.212,45.29,49.392 M28.481,56.341
c-0.018-0.09-0.016-0.181,0.003-0.273c0.038-0.176,0.194-0.308,0.382-0.308c0.216,0,0.39,0.175,0.39,0.391
c0,0.103-0.04,0.197-0.105,0.267c0.073,0.007,0.148,0.011,0.226,0.011c0.201,0,0.392-0.025,0.56-0.07
c0.275-0.074,0.477-0.325,0.477-0.623c0-0.356-0.289-0.644-0.645-0.644c-0.019,0-0.039,0-0.058,0.002
c0.089-0.038,0.189-0.059,0.293-0.059c0.413,0,0.749,0.335,0.749,0.749c0,0.021-0.001,0.043-0.003,0.063
c1.116-0.024,2.374-1.042,2.649-1.43c-0.35,0.08-0.729,0.124-1.125,0.124c-0.449,0-0.878-0.055-1.266-0.158
c-0.549-0.145-1.089-0.226-1.504-0.226c-1.37,0-2.479,0.893-2.479,1.995c0,0.91,0.752,1.705,1.794,1.918
c2.371,0.484,5.16-0.924,7.516-1.412c0.589-0.576,1.27-1.057,2.019-1.421c-0.022-0.086-0.034-0.176-0.034-0.268v-0.006
c-3.126,0.514-5.939,2.118-8.479,2.105C29.129,57.065,28.571,56.791,28.481,56.341 M28.408,50.571
c0.048,0,0.095,0.003,0.141,0.008c-0.468,0.135-0.846,0.484-1.021,0.934c-0.291,0.096-0.501,0.371-0.501,0.694
c0,0.151,0.046,0.291,0.124,0.407c0.253-0.282,0.585-0.493,0.962-0.595c0.108-0.542,0.559-0.96,1.117-1.019
c-0.487,0.204-0.829,0.686-0.829,1.247c0,0.199,0.043,0.387,0.12,0.557c0.086-0.309,0.369-0.536,0.705-0.536
c0.085,0,0.166,0.014,0.24,0.041c0.105,0.038,0.218,0.058,0.334,0.058c0.541,0,0.98-0.439,0.98-0.981
c0-0.108-0.017-0.212-0.049-0.31c0.257,0.075,0.445,0.313,0.445,0.595c0,0.129-0.039,0.248-0.106,0.348
c0.072,0.013,0.146,0.019,0.222,0.019c0.637,0,1.163-0.479,1.236-1.096c0.32-0.174,0.601-0.408,0.843-0.7l0.17,0.829
c0.012,0.058,0.008,0.115-0.007,0.168c-0.015,0.052-0.043,0.103-0.084,0.144l0.703-0.722c0.041-0.042,0.069-0.092,0.083-0.145
c0.016-0.053,0.019-0.11,0.007-0.167l-0.207-1.012c-0.012-0.057-0.009-0.115,0.007-0.167c0.015-0.053,0.043-0.103,0.084-0.145
l0.553-0.564c-0.041,0.042-0.069,0.092-0.084,0.145c-0.015,0.053-0.018,0.11-0.006,0.168l0.207,1.013
c0.012,0.057,0.009,0.114-0.006,0.167c-0.015,0.052-0.042,0.101-0.082,0.143l0.627-0.652c0.04-0.042,0.068-0.092,0.083-0.144
c0.016-0.053,0.019-0.111,0.006-0.168l-0.206-1.01c-0.012-0.057-0.009-0.115,0.007-0.167c0.015-0.053,0.043-0.103,0.084-0.145
l0.553-0.564c-0.041,0.042-0.069,0.092-0.084,0.145c-0.015,0.053-0.018,0.11-0.006,0.167l0.208,1.013
c0.012,0.057,0.008,0.115-0.007,0.167c-0.015,0.052-0.042,0.101-0.082,0.143l0.627-0.651c0.041-0.042,0.068-0.092,0.083-0.145
c0.016-0.053,0.019-0.11,0.007-0.168l-0.101-0.494c-0.106-0.559,0.471-1.202,0.929-1.267c0.055-0.106,0.085-0.221,0.085-0.34
c0-0.567-0.675-1.027-1.509-1.027c-0.407,0-0.777,0.109-1.049,0.289c0.109,0.322,0.132,0.651-0.937,0.803
c-0.848,0.12-1.594,0.285-2.161,0.766c-0.874,0.741-0.803,1.732-1.3,2.107c0.221,0.054,0.502,0.054,0.803-0.011
c0.19-0.041,0.366-0.104,0.521-0.181c-0.093,0.178-0.306,0.347-0.586,0.467c-0.092,0.35-0.403,0.684-0.823,0.84
c-0.265,0.098-0.528,0.108-0.746,0.045l-1.023-0.296c-0.126-0.036-0.257-0.055-0.394-0.055c-0.754,0-1.376,0.581-1.468,1.332
c-0.356,0.05-0.629,0.356-0.629,0.725c0,0.136,0.037,0.262,0.101,0.371c0.245-0.249,0.556-0.434,0.904-0.528
C27.372,50.949,27.846,50.571,28.408,50.571 M22.967,59.902c0.063-0.334,0.089-0.658,0.077-0.97l-0.299,0.35
c-0.059-0.14-0.098-0.225-0.138-0.294c-0.033-0.057-0.061-0.096-0.1-0.103c-0.02,0.01-0.05,0.026-0.083,0.034
c-0.038,0.009-0.09,0.006-0.123,0.006c-0.03,0-0.082,0.003-0.121-0.006c-0.032-0.008-0.062-0.024-0.082-0.034
c-0.04,0.007-0.067,0.046-0.1,0.103c-0.04,0.069-0.079,0.154-0.138,0.294l-0.3-0.35c-0.011,0.312,0.014,0.636,0.077,0.97
c0.221-0.049,0.449-0.066,0.664-0.066C22.518,59.836,22.746,59.853,22.967,59.902 M23.101,60.801
c0.033-0.379-0.397-0.514-0.8-0.514c-0.401,0-0.831,0.135-0.798,0.514c0.041,0.462,0.473,0.242,0.798,0.244
C22.628,61.043,23.06,61.263,23.101,60.801 M24.249,58.071c-0.079,0.022-0.122,0.068-0.131,0.151
c-0.047,0.446-0.228,0.626-0.517,0.727c-0.004,0.45-0.066,0.79-0.188,1.212c0.343,0.717,0.08,1.218-0.198,1.325
c-0.265,0.103-0.607-0.035-0.91-0.035s-0.65,0.138-0.915,0.035c-0.279-0.107-0.541-0.608-0.199-1.325
c-0.121-0.422-0.184-0.762-0.187-1.212c-0.289-0.101-0.471-0.281-0.518-0.727c-0.009-0.083-0.052-0.129-0.13-0.151
c-1.14-0.312-1.248-1.728-0.671-2.129c-0.052,0.634-0.106,1.529,1.19,1.648c-0.021,0.744,0.3,0.943,0.632,0.943
c0.271,0,0.426-0.087,0.494-0.123c0.241-0.128,0.075-0.323,0.013-0.381c-0.166-0.155-0.25-0.375-0.21-0.594
c0.007-0.04,0.022-0.06,0.059-0.06h0.438h0.44c0.037,0,0.053,0.02,0.059,0.06c0.04,0.219-0.044,0.439-0.209,0.594
c-0.062,0.058-0.228,0.253,0.013,0.381c0.067,0.036,0.223,0.123,0.494,0.123c0.331,0,0.653-0.199,0.632-0.943
c1.296-0.119,1.241-1.014,1.19-1.648C25.497,56.343,25.388,57.759,24.249,58.071 M24.6,55.6c0,0.326-0.238,0.688-0.509,0.688
h-0.249c0.063,0.075,0.101,0.171,0.101,0.277c0,0.24-0.195,0.435-0.435,0.435c-0.241,0-0.436-0.195-0.436-0.435
c0-0.106,0.038-0.202,0.1-0.277h-0.26c-0.089,0-0.158,0.036-0.213,0.14c-0.018-0.14-0.036-0.284-0.004-0.381
c0.044-0.131,0.146-0.21,0.248-0.21h1.142C24.296,55.837,24.453,55.766,24.6,55.6 M24.449,55.06H24.05
c-0.198,0-0.335-0.081-0.451-0.215l-0.455-0.594c-0.075-0.094-0.135-0.16-0.232-0.204h0.45c0.135,0,0.255,0.059,0.349,0.179
l0.474,0.603C24.291,54.957,24.324,55.042,24.449,55.06 M22.368,54.079l0.582,0.818c0.092,0.134,0.179,0.209,0.304,0.26h-0.533
c-0.205,0-0.328-0.094-0.418-0.242l-0.458-0.702c-0.175-0.263-0.244-0.329-0.445-0.4h0.495
C22.09,53.813,22.272,53.94,22.368,54.079 M21.049,54.226l0.474,0.603c0.106,0.128,0.139,0.213,0.264,0.231h-0.398
c-0.199,0-0.336-0.081-0.452-0.215l-0.455-0.594c-0.075-0.094-0.134-0.16-0.232-0.204h0.45
C20.835,54.047,20.955,54.106,21.049,54.226 M20.762,56.288h-0.249c-0.27,0-0.509-0.362-0.509-0.688
c0.148,0.166,0.304,0.237,0.516,0.237h1.142c0.102,0,0.204,0.079,0.248,0.21c0.032,0.097,0.014,0.241-0.004,0.381
c-0.055-0.104-0.124-0.14-0.213-0.14h-0.26c0.062,0.075,0.099,0.171,0.099,0.277c0,0.24-0.195,0.435-0.435,0.435
s-0.435-0.195-0.435-0.435C20.662,56.459,20.699,56.363,20.762,56.288 M19.354,61.73l0.138-0.271
c0.027-0.052,0.038-0.108,0.037-0.163c-0.001-0.054-0.015-0.11-0.043-0.161l0.379,0.682c0.028,0.052,0.042,0.107,0.043,0.162
c0.002,0.055-0.01,0.111-0.037,0.164l-0.034,0.067c-0.233,0.452-0.45,1.299-0.209,1.79c-0.562-0.209-0.747-0.701-0.687-1.11
c-1.058-1.003-1.324-2.019-0.569-2.871l0.387-0.453c0.04-0.044,0.065-0.096,0.076-0.149c0.013-0.053,0.013-0.11-0.002-0.166
l0.202,0.753c0.014,0.057,0.015,0.114,0.003,0.167c-0.012,0.054-0.037,0.106-0.075,0.15l-0.118,0.138
c-0.395,0.46-0.289,1.083,0.329,1.642C19.239,61.944,19.281,61.863,19.354,61.73 M45.29,64.557
c0.041-0.101,0.064-0.212,0.064-0.328c0-0.473-0.383-0.858-0.856-0.858h-0.866c-0.059,0-0.114-0.014-0.163-0.04
c-0.048-0.025-0.092-0.063-0.125-0.111l-0.434-0.641c0.033,0.048,0.076,0.086,0.125,0.111c0.048,0.026,0.104,0.041,0.163,0.04
l1.141,0.001c0.059,0,0.115,0.014,0.163,0.04c0.048,0.025,0.092,0.063,0.125,0.111l-0.524-0.768
c-0.033-0.048-0.077-0.085-0.126-0.111c-0.048-0.025-0.104-0.04-0.162-0.04l-1.132,0.001c-0.058,0-0.114-0.015-0.162-0.04
c-0.049-0.026-0.093-0.063-0.126-0.112l-0.492-0.724c0.033,0.049,0.077,0.086,0.125,0.111c0.049,0.026,0.104,0.041,0.163,0.04
h1.136c0.059-0.001,0.115,0.014,0.163,0.04c0.049,0.025,0.092,0.062,0.125,0.111l-0.524-0.768
c-0.033-0.048-0.077-0.086-0.126-0.111c-0.048-0.026-0.104-0.04-0.162-0.04H41.9c-0.059,0-0.114-0.015-0.163-0.041
c-0.048-0.025-0.092-0.062-0.125-0.111l-0.607-0.891c1.227-0.146,2.217-0.811,2.414-1.727c0.255-1.189-0.926-2.341-2.636-2.592
c-0.288-0.042-0.508-0.289-0.508-0.588c0-0.255,0.16-0.472,0.385-0.557c-0.182-0.078-0.386-0.122-0.602-0.122
c-0.757,0-1.37,0.542-1.37,1.211c0,0.12,0.021,0.237,0.058,0.347c-0.848,0.366-1.62,1.015-2.211,1.716
c0.632-0.168,1.296-0.258,1.981-0.258c-0.003-0.032-0.005-0.064-0.005-0.097c0-0.513,0.414-0.928,0.928-0.928h0.013
c-0.35,0.154-0.52,0.49-0.52,0.712c0,0.265,0.215,0.479,0.479,0.479c0.103,0,0.199-0.032,0.277-0.087
c-0.018-0.061-0.028-0.124-0.028-0.191c0-0.367,0.297-0.664,0.665-0.664c0.032,0,0.065,0.002,0.096,0.007
c-0.253,0.118-0.429,0.376-0.429,0.674c0,0.411,0.333,0.744,0.744,0.744c0.044,0,0.086-0.003,0.128-0.011
c-0.012-0.043-0.018-0.088-0.018-0.135c0-0.295,0.239-0.534,0.533-0.534c0.295,0,0.534,0.239,0.534,0.534
c0,0.641-0.712,0.7-1.231,0.551c-1.478-0.426-2.862-0.617-4.201-0.43c-1.718,0.241-4.532,1.403-7.519,1.306
c-0.668-0.021-1.397-0.132-2.131-0.333c0.09,0.098,0.148,0.167,0.186,0.225c0.291,0.453,0.391,0.928,0.134,1.522
c0.007-0.666-0.543-1.214-1.004-1.55c-0.186-0.135-0.261-0.264-0.23-0.437l0.136-0.768c-0.01,0.057-0.005,0.114,0.012,0.165
c0.017,0.053,0.046,0.102,0.088,0.143l0.287,0.281c0.109-0.778-0.067-1.502-0.53-2.173c0.205-0.536,0.233-1.127,0.096-1.682
c-0.054,0.42-0.26,0.6-0.456,0.722c-0.363,0.227-0.423,0.611-0.235,0.868c-0.307-0.157-0.73-0.726-0.485-1.058
c0.264-0.359,0.987-0.19,1.076-0.806c-0.469-0.149-0.952-0.044-1.099-0.004c-0.278-0.319-0.647-0.477-1.106-0.474
c-0.363-0.33-0.829-0.466-1.4-0.409c-0.568-0.057-1.034,0.079-1.397,0.409c-0.459-0.003-0.828,0.155-1.106,0.474
c-0.148-0.04-0.63-0.145-1.1,0.004c0.089,0.616,0.811,0.447,1.076,0.806c0.245,0.332-0.178,0.901-0.485,1.058
c0.189-0.257,0.128-0.641-0.236-0.868c-0.194-0.122-0.401-0.302-0.455-0.722c-0.137,0.555-0.108,1.146,0.096,1.682
c-0.463,0.671-0.639,1.395-0.53,2.173l0.288-0.281c0.042-0.041,0.071-0.09,0.088-0.143c0.017-0.051,0.021-0.108,0.01-0.165
l0.137,0.768c0.03,0.173-0.043,0.302-0.229,0.437c-0.462,0.336-1.012,0.884-1.005,1.55c-0.256-0.594-0.153-1.089,0.135-1.522
c-0.876-0.473-1.543-1.25-1.666-1.392c-0.265-0.308-0.23-0.701,0.01-1.045c0.463-0.663,0.573-1.368-0.008-1.851
c0.004-0.035,0.006-0.071,0.006-0.107c0-0.439-0.312-0.805-0.727-0.888c0.077,0.12,0.122,0.263,0.122,0.416
c0,0.175-0.058,0.336-0.157,0.465c0.082,0.108,0.131,0.243,0.131,0.389c0,0.196-0.088,0.371-0.227,0.488
c0.014-0.067,0.02-0.138,0.02-0.209c0-0.452-0.279-0.83-0.658-0.934c-0.061-0.328-0.349-0.577-0.695-0.577
c-0.201,0-0.381,0.083-0.51,0.217c0.268,0.02,0.484,0.231,0.513,0.497c-0.128,0.096-0.231,0.228-0.298,0.384h0.017
c0.463,0,0.838,0.375,0.838,0.838c0,0.052-0.005,0.104-0.014,0.154c-0.035-0.191-0.121-0.366-0.26-0.502
c-0.26-0.253-0.638-0.306-0.984-0.174c-0.13-0.163-0.33-0.268-0.554-0.268c-0.254,0-0.476,0.133-0.601,0.333
c0.256,0.011,0.481,0.14,0.622,0.335c-0.364,0.466-0.368,1.11,0.004,1.473c0.252,0.246,0.613,0.303,0.95,0.187
c0.022-0.008,0.046-0.012,0.071-0.012c0.124,0,0.224,0.1,0.224,0.224c0,0.123-0.1,0.223-0.224,0.223
c-0.054,0-0.104-0.019-0.142-0.051c-0.085-0.071-0.195-0.113-0.314-0.113c-0.27,0-0.49,0.219-0.49,0.49
c0,0.02,0.001,0.041,0.004,0.06c-0.046,0.015-0.095,0.023-0.146,0.023c-0.132,0-0.252-0.054-0.34-0.14
c-0.014,0.053-0.021,0.109-0.021,0.167c0,0.345,0.266,0.628,0.605,0.654c0.152,0.378,0.523,0.644,0.955,0.644
c0.222,0,0.427-0.07,0.595-0.188c0.074-0.052,0.162-0.082,0.258-0.082c0.249,0,0.451,0.202,0.451,0.451
c0,0.215-0.15,0.394-0.351,0.439l-0.351,0.078c-0.057,0.013-0.115,0.01-0.168-0.005c-0.053-0.014-0.103-0.041-0.145-0.082
l0.803,0.763c0.043,0.04,0.093,0.068,0.146,0.082c0.053,0.015,0.11,0.018,0.167,0.005l0.658-0.146
c0.057-0.013,0.115-0.01,0.167,0.005c0.052,0.014,0.104,0.041,0.146,0.082l0.551,0.524c-0.043-0.041-0.093-0.068-0.147-0.082
c-0.052-0.015-0.109-0.018-0.166-0.005l-0.657,0.145c-0.057,0.013-0.115,0.01-0.167-0.005c-0.053-0.014-0.104-0.041-0.146-0.081
l0.736,0.697c0.042,0.041,0.093,0.068,0.145,0.082c0.053,0.015,0.111,0.018,0.168,0.005l0.658-0.144
c0.058-0.013,0.115-0.01,0.168,0.005c0.053,0.014,0.103,0.042,0.146,0.082l0.551,0.524c-0.043-0.04-0.093-0.068-0.146-0.082
c-0.053-0.015-0.11-0.018-0.168-0.005l-0.656,0.145c-0.058,0.013-0.115,0.01-0.168-0.005c-0.053-0.014-0.103-0.041-0.146-0.082
l0.736,0.698c0.043,0.041,0.093,0.068,0.146,0.082c0.053,0.015,0.11,0.018,0.168,0.005l0.795-0.174
c-0.772,0.436-1.594,0.93-2.465,1.481c-0.515,0.325-1.078,0.386-1.725,0.138c-0.348-0.133-0.725-0.155-0.963-0.114
c-0.31,0.053-0.573,0.241-0.726,0.502c0.12-0.049,0.251-0.075,0.389-0.075c0.289,0,0.55,0.117,0.74,0.305
c-0.301-0.126-0.675-0.139-1.038-0.007c-0.65,0.237-1.029,0.85-0.881,1.398c-0.243,0.094-0.413,0.328-0.413,0.603
c0,0.181,0.074,0.344,0.194,0.462c0.064-0.288,0.316-0.505,0.621-0.516c0.127,0.084,0.275,0.143,0.434,0.175
c0.048-0.083,0.109-0.158,0.179-0.221c-0.008-0.052-0.011-0.105-0.011-0.159c0-0.593,0.48-1.074,1.073-1.074
c0.049,0,0.097,0.003,0.145,0.01c-0.471,0.113-0.822,0.537-0.822,1.044c0,0.064,0.006,0.127,0.017,0.188
c-0.254,0.097-0.433,0.343-0.433,0.631c0,0.165,0.059,0.316,0.158,0.434c0.182-0.356,0.537-0.608,0.954-0.648
c0.157,0.046,0.323,0.071,0.494,0.071c0.108,0,0.213-0.01,0.315-0.028c-0.092-0.135-0.146-0.297-0.146-0.472
c0-0.461,0.373-0.835,0.835-0.835c0.04,0,0.078,0.003,0.118,0.009c-0.441,0.187-0.711,0.57-0.618,0.918
c0.066,0.248,0.299,0.419,0.6,0.475c-0.004,0.186-0.055,0.36-0.142,0.511c0.387-0.028,0.718-0.262,0.883-0.592
c0.456-0.183,0.737-0.574,0.643-0.929c-0.034-0.127-0.113-0.234-0.22-0.316c-0.001-0.012-0.002-0.024-0.002-0.036
c0-0.244,0.199-0.443,0.442-0.443c0.246,0,0.444,0.199,0.444,0.443c0,0.116-0.044,0.221-0.117,0.3h0.927
c0.058,0,0.114-0.015,0.162-0.041c0.049-0.025,0.092-0.063,0.125-0.112l0.595-0.882c0.022-0.033,0.052-0.058,0.085-0.076
c0.033-0.018,0.07-0.028,0.111-0.028h0.728c-0.04,0-0.078,0.01-0.111,0.028c-0.033,0.018-0.063,0.043-0.085,0.076l-0.597,0.882
c-0.033,0.049-0.076,0.087-0.125,0.112c-0.048,0.026-0.103,0.041-0.162,0.041h1.108c0.059,0,0.114-0.015,0.161-0.041
c0.05-0.025,0.094-0.063,0.125-0.112l0.668-0.985c-0.46-0.252-0.649-0.693-0.649-1.299c0-0.377,0.212-0.807,0.244-1.084
l0.013-0.11c0.007-0.059-0.001-0.116-0.021-0.167c-0.016-0.041-0.048-0.101-0.083-0.142l0.57,0.584
c0.045,0.038,0.077,0.086,0.096,0.137c0.021,0.051,0.029,0.108,0.022,0.166l-0.017,0.134c-0.027,0.232-0.319,0.732,0.223,1.19
c0.027,0.023,0.094,0.07,0.158,0.111l0.385,0.242v-1.421h0.539v1.581c0.001,0.059,0.018,0.114,0.045,0.161
c0.027,0.048,0.065,0.091,0.115,0.122l0.526,0.335c0.051,0.031,0.106,0.049,0.16,0.053c0.055,0.004,0.112-0.004,0.165-0.028
l0.971-0.421c-0.054,0.023-0.111,0.032-0.165,0.027c-0.055-0.004-0.11-0.021-0.159-0.053l-1.115-0.709
c0.542-0.458,0.249-0.958,0.222-1.19l-0.016-0.134c-0.007-0.058,0.001-0.115,0.02-0.166c0.021-0.051,0.053-0.099,0.097-0.137
l0.57-0.584c-0.035,0.041-0.066,0.101-0.083,0.142c-0.019,0.051-0.027,0.108-0.02,0.167l0.012,0.11
c0.046,0.395,0.446,1.111,0.113,1.51l1.019,0.647c0.05,0.031,0.105,0.048,0.159,0.052c0.055,0.005,0.112-0.003,0.166-0.027
l1.015-0.441c-0.054,0.023-0.11,0.031-0.164,0.027c-0.055-0.004-0.11-0.022-0.16-0.053l-1.102-0.701
c0.24-0.492,0.038-1.273-0.195-1.725l-0.035-0.067c-0.026-0.053-0.038-0.109-0.036-0.164c0-0.055,0.014-0.11,0.043-0.162
l0.378-0.682c-0.028,0.051-0.042,0.107-0.042,0.161c-0.002,0.055,0.01,0.111,0.036,0.163l0.139,0.271
c0.073,0.133,0.114,0.214,0.178,0.371c0.62-0.559,0.758-1.098,0.363-1.558l-0.118-0.138c-0.038-0.044-0.063-0.096-0.075-0.15
c-0.013-0.053-0.013-0.11,0.003-0.167l0.202-0.753c-0.015,0.056-0.015,0.113-0.004,0.166c0.013,0.053,0.038,0.105,0.077,0.149
l0.388,0.453c0.754,0.852,0.298,1.95-0.602,2.787c0.05,0.161,0.093,0.462,0.057,0.625l1.195,0.758
c0.05,0.032,0.105,0.049,0.16,0.053c0.054,0.005,0.111-0.004,0.165-0.027l0.864-0.376c-0.049,0.021-0.104,0.033-0.16,0.033
c-0.223,0-0.403-0.18-0.403-0.402c0-0.18,0.117-0.335,0.281-0.384c3.299-1.004,6.336-3.594,8.33-3.588
c0.969,0.003,1.755,0.59,1.755,1.317c0,0.117-0.021,0.231-0.059,0.34c-0.425,1.194,0.194,2.334,1.828,2.773
c0.261,0.071,0.453,0.309,0.453,0.591c0,0.055-0.008,0.109-0.021,0.159c0.037,0.004,0.075,0.005,0.114,0.005
c0.45,0,0.848-0.224,1.089-0.566c0.28-0.002,0.587-0.019,0.901-0.052c0.038,0.076,0.068,0.163,0.086,0.257
c0.067,0.343-0.052,0.654-0.263,0.722c-0.375,0.122-0.835-0.024-1.19-0.021c-0.672,0.007-1.215,0.553-1.215,1.226
c0,0.053,0.003,0.105,0.01,0.156c-0.211,0.132-0.351,0.366-0.351,0.632c0,0.133,0.035,0.258,0.095,0.366
c0.207-0.242,0.477-0.428,0.784-0.536c0.026-0.59,0.512-1.06,1.108-1.06c0.091,0,0.181,0.011,0.265,0.032
c-0.604,0.076-1.072,0.592-1.072,1.217c0,0.045,0.003,0.09,0.008,0.135c-0.075,0.09-0.12,0.207-0.12,0.333
c0,0.161,0.072,0.305,0.185,0.401c0.114-0.249,0.389-0.484,0.745-0.604c0.239-0.08,0.474-0.096,0.67-0.056
c-0.032-0.094-0.047-0.194-0.047-0.298c0-0.533,0.431-0.965,0.965-0.965c0.049,0,0.098,0.004,0.145,0.011
c-0.372,0.05-0.658,0.369-0.658,0.754c0,0.256,0.126,0.482,0.319,0.62c0,0.014-0.001,0.028-0.001,0.042
c0,0.209,0.096,0.396,0.246,0.519c0.068-0.35,0.374-0.614,0.745-0.614c0.316,0,0.577-0.04,0.772-0.104
c0.33-0.108,0.571-0.413,0.571-0.778c0-0.253-0.115-0.479-0.297-0.628c0.09-0.41,0.074-1.083-0.065-1.643
c0.028-0.004,0.057-0.006,0.087-0.006C44.969,64.259,45.172,64.377,45.29,64.557 M57.259,11.339h-1.134V79.37h1.134V11.339z"}]]]])
(defn maanteeamet-logo
[login-page?]
[:div {:style {:display :flex
:justify-content :flex-start}}
[:a {:href (if login-page?
"/#/login"
"/#/")}
[logo-shield {}]]])
| |
dd13a4740f238459fee04e210a173876126ab1a8aa1efbdd779472bcb161ef4c | wedesoft/aiscm | harris_stephens.scm | (use-modules (aiscm magick) (aiscm image) (aiscm core) (aiscm filters))
(define img (from-image (convert-image (to-image (read-image "star-ferry.jpg")) 'GRAY)))
(define result (harris-stephens img 1.0 0.05))
(write-image (to-type <ubyte> (major (minor (+ (/ result 1000) 127) 255) 0)) "harris-stephens.jpg")
| null | https://raw.githubusercontent.com/wedesoft/aiscm/2c3db8d00cad6e042150714ada85da19cf4338ad/tests/integration/harris_stephens.scm | scheme | (use-modules (aiscm magick) (aiscm image) (aiscm core) (aiscm filters))
(define img (from-image (convert-image (to-image (read-image "star-ferry.jpg")) 'GRAY)))
(define result (harris-stephens img 1.0 0.05))
(write-image (to-type <ubyte> (major (minor (+ (/ result 1000) 127) 255) 0)) "harris-stephens.jpg")
| |
03c4752b6b2bb6eb854dd4bdb72a2c600be9c753613d43555fa0c8ade820cc1a | ferd/erlang-history | group.erl | %%
%% %CopyrightBegin%
%%
Copyright Ericsson AB 1996 - 2013 . All Rights Reserved .
%%
The contents of this file are subject to the Erlang Public License ,
Version 1.1 , ( the " License " ) ; you may not use this file except in
%% compliance with the License. You should have received a copy of the
%% Erlang Public License along with this software. If not, it can be
%% retrieved online at /.
%%
Software distributed under the License is distributed on an " AS IS "
%% basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See
%% the License for the specific language governing rights and limitations
%% under the License.
%%
%% %CopyrightEnd%
%%
-module(group).
%% A group leader process for user io.
-export([start/2, start/3, server/3]).
-export([interfaces/1]).
start(Drv, Shell) ->
start(Drv, Shell, []).
start(Drv, Shell, Options) ->
spawn_link(group, server, [Drv, Shell, Options]).
server(Drv, Shell, Options) ->
process_flag(trap_exit, true),
edlin:init(),
put(line_buffer, proplists:get_value(line_buffer, Options, group_history:load())),
put(read_mode, list),
put(user_drv, Drv),
put(expand_fun,
proplists:get_value(expand_fun, Options,
fun(B) -> edlin_expand:expand(B) end)),
put(echo, proplists:get_value(echo, Options, true)),
start_shell(Shell),
server_loop(Drv, get(shell), []).
Return the pid of user_drv and the shell process .
%% Note: We can't ask the group process for this info since it
%% may be busy waiting for data from the driver.
interfaces(Group) ->
case process_info(Group, dictionary) of
{dictionary,Dict} ->
get_pids(Dict, [], false);
_ ->
[]
end.
get_pids([Drv = {user_drv,_} | Rest], Found, _) ->
get_pids(Rest, [Drv | Found], true);
get_pids([Sh = {shell,_} | Rest], Found, Active) ->
get_pids(Rest, [Sh | Found], Active);
get_pids([_ | Rest], Found, Active) ->
get_pids(Rest, Found, Active);
get_pids([], Found, true) ->
Found;
get_pids([], _Found, false) ->
[].
start_shell(Shell )
%% Spawn a shell with its group_leader from the beginning set to ourselves.
If Shell a pid the set its group_leader .
start_shell({Mod,Func,Args}) ->
start_shell1(Mod, Func, Args);
start_shell({Node,Mod,Func,Args}) ->
start_shell1(net, call, [Node,Mod,Func,Args]);
start_shell(Shell) when is_atom(Shell) ->
start_shell1(Shell, start, []);
start_shell(Shell) when is_function(Shell) ->
start_shell1(Shell);
start_shell(Shell) when is_pid(Shell) ->
group_leader(self(), Shell), % we are the shells group leader
link(Shell), % we're linked to it.
put(shell, Shell);
start_shell(_Shell) ->
ok.
start_shell1(M, F, Args) ->
G = group_leader(),
group_leader(self(), self()),
case catch apply(M, F, Args) of
Shell when is_pid(Shell) ->
group_leader(G, self()),
link(Shell), % we're linked to it.
put(shell, Shell);
Error -> % start failure
exit(Error) % let the group process crash
end.
start_shell1(Fun) ->
G = group_leader(),
group_leader(self(), self()),
case catch Fun() of
Shell when is_pid(Shell) ->
group_leader(G, self()),
link(Shell), % we're linked to it.
put(shell, Shell);
Error -> % start failure
exit(Error) % let the group process crash
end.
server_loop(Drv, Shell, Buf0) ->
receive
{io_request,From,ReplyAs,Req} when is_pid(From) ->
Buf = io_request(Req, From, ReplyAs, Drv, Buf0),
server_loop(Drv, Shell, Buf);
{driver_id,ReplyTo} ->
ReplyTo ! {self(),driver_id,Drv},
server_loop(Drv, Shell, Buf0);
{Drv, echo, Bool} ->
put(echo, Bool),
server_loop(Drv, Shell, Buf0);
{'EXIT',Drv,interrupt} ->
%% Send interrupt to the shell.
exit_shell(interrupt),
server_loop(Drv, Shell, Buf0);
{'EXIT',Drv,R} ->
exit(R);
{'EXIT',Shell,R} ->
exit(R);
%% We want to throw away any term that we don't handle (standard
practice in receive loops ) , but not any { , _ } tuples which are
handled in io_request/5 .
NotDrvTuple when (not is_tuple(NotDrvTuple)) orelse
(tuple_size(NotDrvTuple) =/= 2) orelse
(element(1, NotDrvTuple) =/= Drv) ->
%% Ignore this unknown message.
server_loop(Drv, Shell, Buf0)
end.
exit_shell(Reason) ->
case get(shell) of
undefined -> true;
Pid -> exit(Pid, Reason)
end.
get_tty_geometry(Drv) ->
Drv ! {self(),tty_geometry},
receive
{Drv,tty_geometry,Geometry} ->
Geometry
after 2000 ->
timeout
end.
get_unicode_state(Drv) ->
Drv ! {self(),get_unicode_state},
receive
{Drv,get_unicode_state,UniState} ->
UniState;
{Drv,get_unicode_state,error} ->
{error, internal}
after 2000 ->
{error,timeout}
end.
set_unicode_state(Drv,Bool) ->
Drv ! {self(),set_unicode_state,Bool},
receive
{Drv,set_unicode_state,_OldUniState} ->
ok
after 2000 ->
timeout
end.
io_request(Req, From, ReplyAs, Drv, Buf0) ->
case io_request(Req, Drv, Buf0) of
{ok,Reply,Buf} ->
io_reply(From, ReplyAs, Reply),
Buf;
{error,Reply,Buf} ->
io_reply(From, ReplyAs, Reply),
Buf;
{exit,R} ->
%% 'kill' instead of R, since the shell is not always in
%% a state where it is ready to handle a termination
%% message.
exit_shell(kill),
exit(R)
end.
%% Put_chars, unicode is the normal message, characters are always in
%%standard unicode
%% format.
%% You might be tempted to send binaries unchecked, but the driver
%% expects unicode, so that is what we should send...
io_request({put_chars , unicode , Binary } , , Buf ) when is_binary(Binary ) - >
send_drv(Drv , { put_chars , Binary } ) ,
%% {ok,ok,Buf};
io_request({put_chars,unicode,Chars}, Drv, Buf) ->
case catch unicode:characters_to_binary(Chars,utf8) of
Binary when is_binary(Binary) ->
send_drv(Drv, {put_chars, unicode, Binary}),
{ok,ok,Buf};
_ ->
{error,{error,{put_chars, unicode,Chars}},Buf}
end;
io_request({put_chars,unicode,M,F,As}, Drv, Buf) ->
case catch apply(M, F, As) of
Binary when is_binary(Binary) ->
send_drv(Drv, {put_chars, unicode,Binary}),
{ok,ok,Buf};
Chars ->
case catch unicode:characters_to_binary(Chars,utf8) of
B when is_binary(B) ->
send_drv(Drv, {put_chars, unicode,B}),
{ok,ok,Buf};
_ ->
{error,{error,F},Buf}
end
end;
io_request({put_chars,latin1,Binary}, Drv, Buf) when is_binary(Binary) ->
send_drv(Drv, {put_chars, unicode,unicode:characters_to_binary(Binary,latin1)}),
{ok,ok,Buf};
io_request({put_chars,latin1,Chars}, Drv, Buf) ->
case catch unicode:characters_to_binary(Chars,latin1) of
Binary when is_binary(Binary) ->
send_drv(Drv, {put_chars, unicode,Binary}),
{ok,ok,Buf};
_ ->
{error,{error,{put_chars,latin1,Chars}},Buf}
end;
io_request({put_chars,latin1,M,F,As}, Drv, Buf) ->
case catch apply(M, F, As) of
Binary when is_binary(Binary) ->
send_drv(Drv, {put_chars, unicode,unicode:characters_to_binary(Binary,latin1)}),
{ok,ok,Buf};
Chars ->
case catch unicode:characters_to_binary(Chars,latin1) of
B when is_binary(B) ->
send_drv(Drv, {put_chars, unicode,B}),
{ok,ok,Buf};
_ ->
{error,{error,F},Buf}
end
end;
io_request({get_chars,Encoding,Prompt,N}, Drv, Buf) ->
get_chars(Prompt, io_lib, collect_chars, N, Drv, Buf, Encoding);
io_request({get_line,Encoding,Prompt}, Drv, Buf) ->
get_chars(Prompt, io_lib, collect_line, [], Drv, Buf, Encoding);
io_request({get_until,Encoding, Prompt,M,F,As}, Drv, Buf) ->
get_chars(Prompt, io_lib, get_until, {M,F,As}, Drv, Buf, Encoding);
io_request({get_password,_Encoding},Drv,Buf) ->
get_password_chars(Drv, Buf);
io_request({setopts,Opts}, Drv, Buf) when is_list(Opts) ->
setopts(Opts, Drv, Buf);
io_request(getopts, Drv, Buf) ->
getopts(Drv, Buf);
io_request({requests,Reqs}, Drv, Buf) ->
io_requests(Reqs, {ok,ok,Buf}, Drv);
%% New in R12
io_request({get_geometry,columns},Drv,Buf) ->
case get_tty_geometry(Drv) of
{W,_H} ->
{ok,W,Buf};
_ ->
{error,{error,enotsup},Buf}
end;
io_request({get_geometry,rows},Drv,Buf) ->
case get_tty_geometry(Drv) of
{_W,H} ->
{ok,H,Buf};
_ ->
{error,{error,enotsup},Buf}
end;
%% BC with pre-R13
io_request({put_chars,Chars}, Drv, Buf) ->
io_request({put_chars,latin1,Chars}, Drv, Buf);
io_request({put_chars,M,F,As}, Drv, Buf) ->
io_request({put_chars,latin1,M,F,As}, Drv, Buf);
io_request({get_chars,Prompt,N}, Drv, Buf) ->
io_request({get_chars,latin1,Prompt,N}, Drv, Buf);
io_request({get_line,Prompt}, Drv, Buf) ->
io_request({get_line,latin1,Prompt}, Drv, Buf);
io_request({get_until, Prompt,M,F,As}, Drv, Buf) ->
io_request({get_until,latin1, Prompt,M,F,As}, Drv, Buf);
io_request(get_password,Drv,Buf) ->
io_request({get_password,latin1},Drv,Buf);
io_request(_, _Drv, Buf) ->
{error,{error,request},Buf}.
Status = io_requests(RequestList , PrevStat , )
%% Process a list of output requests as long as the previous status is 'ok'.
io_requests([R|Rs], {ok,ok,Buf}, Drv) ->
io_requests(Rs, io_request(R, Drv, Buf), Drv);
io_requests([_|_], Error, _Drv) ->
Error;
io_requests([], Stat, _) ->
Stat.
io_reply(From , , Reply )
%% The function for sending i/o command acknowledgement.
%% The ACK contains the return value.
io_reply(From, ReplyAs, Reply) ->
From ! {io_reply,ReplyAs,Reply},
ok.
send_drv(Drv , Message )
send_drv_reqs(Drv , Requests )
send_drv(Drv, Msg) ->
Drv ! {self(),Msg},
ok.
send_drv_reqs(_Drv, []) -> ok;
send_drv_reqs(Drv, Rs) ->
send_drv(Drv, {requests,Rs}).
expand_encoding([]) ->
[];
expand_encoding([latin1 | T]) ->
[{encoding,latin1} | expand_encoding(T)];
expand_encoding([unicode | T]) ->
[{encoding,unicode} | expand_encoding(T)];
expand_encoding([H|T]) ->
[H|expand_encoding(T)].
%% setopts
setopts(Opts0,Drv,Buf) ->
Opts = proplists:unfold(
proplists:substitute_negations(
[{list,binary}],
expand_encoding(Opts0))),
case check_valid_opts(Opts) of
true ->
do_setopts(Opts,Drv,Buf);
false ->
{error,{error,enotsup},Buf}
end.
check_valid_opts([]) ->
true;
check_valid_opts([{binary,_}|T]) ->
check_valid_opts(T);
check_valid_opts([{encoding,Valid}|T]) when Valid =:= unicode; Valid =:= utf8; Valid =:= latin1 ->
check_valid_opts(T);
check_valid_opts([{echo,_}|T]) ->
check_valid_opts(T);
check_valid_opts([{expand_fun,_}|T]) ->
check_valid_opts(T);
check_valid_opts(_) ->
false.
do_setopts(Opts, Drv, Buf) ->
put(expand_fun, proplists:get_value(expand_fun, Opts, get(expand_fun))),
put(echo, proplists:get_value(echo, Opts, get(echo))),
case proplists:get_value(encoding,Opts) of
Valid when Valid =:= unicode; Valid =:= utf8 ->
set_unicode_state(Drv,true);
latin1 ->
set_unicode_state(Drv,false);
_ ->
ok
end,
case proplists:get_value(binary, Opts, case get(read_mode) of
binary -> true;
_ -> false
end) of
true ->
put(read_mode, binary),
{ok,ok,Buf};
false ->
put(read_mode, list),
{ok,ok,Buf};
_ ->
{ok,ok,Buf}
end.
getopts(Drv,Buf) ->
Exp = {expand_fun, case get(expand_fun) of
Func when is_function(Func) ->
Func;
_ ->
false
end},
Echo = {echo, case get(echo) of
Bool when Bool =:= true; Bool =:= false ->
Bool;
_ ->
false
end},
Bin = {binary, case get(read_mode) of
binary ->
true;
_ ->
false
end},
Uni = {encoding, case get_unicode_state(Drv) of
true -> unicode;
_ -> latin1
end},
{ok,[Exp,Echo,Bin,Uni],Buf}.
get_chars(Prompt , Module , Function , XtraArgument , , Buffer )
Gets characters from the input until as the applied function
%% returns {stop,Result,Rest}. Does not block output until input has been
%% received.
%% Returns:
%% {Result,NewSaveBuffer}
%% {error,What,NewSaveBuffer}
get_password_chars(Drv,Buf) ->
case get_password_line(Buf, Drv) of
{done, Line, Buf1} ->
{ok, Line, Buf1};
interrupted ->
{error, {error, interrupted}, []};
terminated ->
{exit, terminated}
end.
get_chars(Prompt, M, F, Xa, Drv, Buf, Encoding) ->
Pbs = prompt_bytes(Prompt, Encoding),
get_chars_loop(Pbs, M, F, Xa, Drv, Buf, start, Encoding).
get_chars_loop(Pbs, M, F, Xa, Drv, Buf0, State, Encoding) ->
Result = case get(echo) of
true ->
get_line(Buf0, Pbs, Drv, Encoding);
false ->
% get_line_echo_off only deals with lists
% and does not need encoding...
get_line_echo_off(Buf0, Pbs, Drv)
end,
case Result of
{done,Line,Buf1} ->
get_chars_apply(Pbs, M, F, Xa, Drv, Buf1, State, Line, Encoding);
interrupted ->
{error,{error,interrupted},[]};
terminated ->
{exit,terminated}
end.
get_chars_apply(Pbs, M, F, Xa, Drv, Buf, State0, Line, Encoding) ->
case catch M:F(State0, cast(Line,get(read_mode), Encoding), Encoding, Xa) of
{stop,Result,Rest} ->
{ok,Result,append(Rest, Buf, Encoding)};
{'EXIT',_} ->
{error,{error,err_func(M, F, Xa)},[]};
State1 ->
get_chars_loop(Pbs, M, F, Xa, Drv, Buf, State1, Encoding)
end.
Convert error code to make it look as before
err_func(io_lib, get_until, {_,F,_}) ->
F;
err_func(_, F, _) ->
F.
get_line(Chars , PromptBytes , )
%% Get a line with eventual line editing. Handle other io requests
%% while getting line.
%% Returns:
{ done , LineChars , RestChars }
%% interrupted
get_line(Chars, Pbs, Drv, Encoding) ->
{more_chars,Cont,Rs} = edlin:start(Pbs),
send_drv_reqs(Drv, Rs),
get_line1(edlin:edit_line(Chars, Cont), Drv, new_stack(get(line_buffer)),
Encoding).
get_line1({done,Line,Rest,Rs}, Drv, Ls, _Encoding) ->
send_drv_reqs(Drv, Rs),
save_line_buffer(Line, get_lines(Ls)),
{done,Line,Rest};
get_line1({undefined,{_A,Mode,Char},Cs,Cont,Rs}, Drv, Ls0, Encoding)
when ((Mode =:= none) and (Char =:= $\^P))
or ((Mode =:= meta_left_sq_bracket) and (Char =:= $A)) ->
send_drv_reqs(Drv, Rs),
case up_stack(save_line(Ls0, edlin:current_line(Cont))) of
{none,_Ls} ->
send_drv(Drv, beep),
get_line1(edlin:edit_line(Cs, Cont), Drv, Ls0, Encoding);
{Lcs,Ls} ->
send_drv_reqs(Drv, edlin:erase_line(Cont)),
{more_chars,Ncont,Nrs} = edlin:start(edlin:prompt(Cont)),
send_drv_reqs(Drv, Nrs),
get_line1(edlin:edit_line1(lists:sublist(Lcs, 1, length(Lcs)-1),
Ncont),
Drv,
Ls, Encoding)
end;
get_line1({undefined,{_A,Mode,Char},Cs,Cont,Rs}, Drv, Ls0, Encoding)
when ((Mode =:= none) and (Char =:= $\^N))
or ((Mode =:= meta_left_sq_bracket) and (Char =:= $B)) ->
send_drv_reqs(Drv, Rs),
case down_stack(save_line(Ls0, edlin:current_line(Cont))) of
{none,_Ls} ->
send_drv(Drv, beep),
get_line1(edlin:edit_line(Cs, Cont), Drv, Ls0, Encoding);
{Lcs,Ls} ->
send_drv_reqs(Drv, edlin:erase_line(Cont)),
{more_chars,Ncont,Nrs} = edlin:start(edlin:prompt(Cont)),
send_drv_reqs(Drv, Nrs),
get_line1(edlin:edit_line1(lists:sublist(Lcs, 1, length(Lcs)-1),
Ncont),
Drv,
Ls, Encoding)
end;
%% ^R = backward search, ^S = forward search.
%% Search is tricky to implement and does a lot of back-and-forth
work with edlin.erl ( from stdlib ) . takes care of writing
%% and handling lines and escape characters to get out of search,
%% whereas this module does the actual searching and appending to lines.
Erlang 's shell was n't exactly meant to traverse the wall between
%% line and line stack, so we at least restrict it by introducing
new modes : search , search_quit , search_found . These are added to
%% the regular ones (none, meta_left_sq_bracket) and handle special
%% cases of history search.
get_line1({undefined,{_A,Mode,Char},Cs,Cont,Rs}, Drv, Ls, Encoding)
when ((Mode =:= none) and (Char =:= $\^R)) ->
send_drv_reqs(Drv, Rs),
%% drop current line, move to search mode. We store the current
%% prompt ('N>') and substitute it with the search prompt.
send_drv_reqs(Drv, edlin:erase_line(Cont)),
put(search_quit_prompt, edlin:prompt(Cont)),
Pbs = prompt_bytes("(search)`': ", Encoding),
{more_chars,Ncont,Nrs} = edlin:start(Pbs, search),
send_drv_reqs(Drv, Nrs),
get_line1(edlin:edit_line1(Cs, Ncont), Drv, Ls, Encoding);
get_line1({expand, Before, Cs0, Cont,Rs}, Drv, Ls0, Encoding) ->
send_drv_reqs(Drv, Rs),
ExpandFun = get(expand_fun),
{Found, Add, Matches} = ExpandFun(Before),
case Found of
no -> send_drv(Drv, beep);
yes -> ok
end,
XXX : should this always be unicode ?
Cs = case Matches of
[] -> Cs1;
_ -> MatchStr = edlin_expand:format_matches(Matches),
send_drv(Drv, {put_chars, unicode, unicode:characters_to_binary(MatchStr,unicode)}),
[$\^L | Cs1]
end,
get_line1(edlin:edit_line(Cs, Cont), Drv, Ls0, Encoding);
get_line1({undefined,_Char,Cs,Cont,Rs}, Drv, Ls, Encoding) ->
send_drv_reqs(Drv, Rs),
send_drv(Drv, beep),
get_line1(edlin:edit_line(Cs, Cont), Drv, Ls, Encoding);
%% The search item was found and accepted (new line entered on the exact
%% result found)
get_line1({_What,Cont={line,_Prompt,_Chars,search_found},Rs}, Drv, Ls0, Encoding) ->
Line = edlin:current_line(Cont),
%% this may create duplicate entries.
Ls = save_line(new_stack(get_lines(Ls0)), Line),
get_line1({done, Line, "", Rs}, Drv, Ls, Encoding);
%% The search mode has been exited, but the user wants to remain in line
%% editing mode wherever that was, but editing the search result.
get_line1({What,Cont={line,_Prompt,_Chars,search_quit},Rs}, Drv, Ls, Encoding) ->
Line = edlin:current_chars(Cont),
%% Load back the old prompt with the correct line number.
case get(search_quit_prompt) of
undefined -> % should not happen. Fallback.
LsFallback = save_line(new_stack(get_lines(Ls)), Line),
get_line1({done, "\n", Line, Rs}, Drv, LsFallback, Encoding);
Prompt -> % redraw the line and keep going with the same stack position
NCont = {line,Prompt,{lists:reverse(Line),[]},none},
send_drv_reqs(Drv, Rs),
send_drv_reqs(Drv, edlin:erase_line(Cont)),
send_drv_reqs(Drv, edlin:redraw_line(NCont)),
get_line1({What, NCont ,[]}, Drv, pad_stack(Ls), Encoding)
end;
%% Search mode is entered.
get_line1({What,{line,Prompt,{RevCmd0,_Aft},search},Rs},
Drv, Ls0, Encoding) ->
send_drv_reqs(Drv, Rs),
Figure out search direction . ^S and ^R are returned through edlin
%% whenever we received a search while being already in search mode.
{Search, Ls1, RevCmd} = case RevCmd0 of
[$\^S|RevCmd1] ->
{fun search_down_stack/2, Ls0, RevCmd1};
[$\^R|RevCmd1] ->
{fun search_up_stack/2, Ls0, RevCmd1};
_ -> % new search, rewind stack for a proper search.
{fun search_up_stack/2, new_stack(get_lines(Ls0)), RevCmd0}
end,
Cmd = lists:reverse(RevCmd),
{Ls, NewStack} = case Search(Ls1, Cmd) of
{none, Ls2} ->
send_drv(Drv, beep),
{Ls2, {RevCmd, "': "}};
{Line, Ls2} -> % found. Complete the output edlin couldn't have done.
send_drv_reqs(Drv, [{put_chars, Encoding, Line}]),
{Ls2, {RevCmd, "': "++Line}}
end,
Cont = {line,Prompt,NewStack,search},
more_data(What, Cont, Drv, Ls, Encoding);
get_line1({What,Cont0,Rs}, Drv, Ls, Encoding) ->
send_drv_reqs(Drv, Rs),
more_data(What, Cont0, Drv, Ls, Encoding).
more_data(What, Cont0, Drv, Ls, Encoding) ->
receive
{Drv,{data,Cs}} ->
get_line1(edlin:edit_line(Cs, Cont0), Drv, Ls, Encoding);
{Drv,eof} ->
get_line1(edlin:edit_line(eof, Cont0), Drv, Ls, Encoding);
{io_request,From,ReplyAs,Req} when is_pid(From) ->
{more_chars,Cont,_More} = edlin:edit_line([], Cont0),
send_drv_reqs(Drv, edlin:erase_line(Cont)),
io_request(Req, From, ReplyAs, Drv, []), %WRONG!!!
send_drv_reqs(Drv, edlin:redraw_line(Cont)),
get_line1({more_chars,Cont,[]}, Drv, Ls, Encoding);
{'EXIT',Drv,interrupt} ->
interrupted;
{'EXIT',Drv,_} ->
terminated
after
get_line_timeout(What)->
get_line1(edlin:edit_line([], Cont0), Drv, Ls, Encoding)
end.
get_line_echo_off(Chars, Pbs, Drv) ->
send_drv_reqs(Drv, [{put_chars, unicode,Pbs}]),
get_line_echo_off1(edit_line(Chars,[]), Drv).
get_line_echo_off1({Chars,[]}, Drv) ->
receive
{Drv,{data,Cs}} ->
get_line_echo_off1(edit_line(Cs, Chars), Drv);
{Drv,eof} ->
get_line_echo_off1(edit_line(eof, Chars), Drv);
{io_request,From,ReplyAs,Req} when is_pid(From) ->
io_request(Req, From, ReplyAs, Drv, []),
get_line_echo_off1({Chars,[]}, Drv);
{'EXIT',Drv,interrupt} ->
interrupted;
{'EXIT',Drv,_} ->
terminated
end;
get_line_echo_off1({Chars,Rest}, _Drv) ->
{done,lists:reverse(Chars),case Rest of done -> []; _ -> Rest end}.
%% We support line editing for the ICANON mode except the following
%% line editing characters, which already has another meaning in
echo - on mode ( See Advanced Programming in the Unix Environment , 2nd ed ,
, page 638 ):
- ^u in posix / icanon mode : erase - line , prefix - arg in edlin
- ^t in posix / icanon mode : status , transpose - char in edlin
- ^d in posix / icanon mode : eof , delete - forward in edlin
%% - ^r in posix/icanon mode: reprint (silly in echo-off mode :-))
- ^w in posix / icanon mode : word - erase ( produces a beep in )
edit_line(eof, Chars) ->
{Chars,done};
edit_line([],Chars) ->
{Chars,[]};
edit_line([$\r,$\n|Cs],Chars) ->
{[$\n | Chars], remainder_after_nl(Cs)};
edit_line([NL|Cs],Chars) when NL =:= $\r; NL =:= $\n ->
{[$\n | Chars], remainder_after_nl(Cs)};
edit_line([Erase|Cs],[]) when Erase =:= $\177; Erase =:= $\^H ->
edit_line(Cs,[]);
edit_line([Erase|Cs],[_|Chars]) when Erase =:= $\177; Erase =:= $\^H ->
edit_line(Cs,Chars);
edit_line([Char|Cs],Chars) ->
edit_line(Cs,[Char|Chars]).
remainder_after_nl("") -> done;
remainder_after_nl(Cs) -> Cs.
get_line_timeout(blink) -> 1000;
get_line_timeout(more_chars) -> infinity.
new_stack(Ls) -> {stack,Ls,{},[]}.
up_stack({stack,[L|U],{},D}) ->
{L,{stack,U,L,D}};
up_stack({stack,[],{},D}) ->
{none,{stack,[],{},D}};
up_stack({stack,U,C,D}) ->
up_stack({stack,U,{},[C|D]}).
down_stack({stack,U,{},[L|D]}) ->
{L,{stack,U,L,D}};
down_stack({stack,U,{},[]}) ->
{none,{stack,U,{},[]}};
down_stack({stack,U,C,D}) ->
down_stack({stack,[C|U],{},D}).
save_line({stack, U, {}, []}, Line) ->
{stack, U, {}, [Line]};
save_line({stack, U, _L, D}, Line) ->
{stack, U, Line, D}.
get_lines(Ls) -> get_all_lines(Ls).
get_lines({stack , U , { } , [ ] } ) - >
U ;
get_lines({stack , U , { } , D } ) - >
: reverse(D , U ) ) ;
get_lines({stack , U , L , D } ) - >
get_lines({stack , U , { } , [ L|D ] } ) .
%% There's a funny behaviour whenever the line stack doesn't have a "\n"
%% at its end -- get_lines() seemed to work on the assumption it *will* be
%% there, but the manipulations done with search history do not require it.
%%
%% It is an assumption because the function was built with either the full
%% stack being on the 'Up' side (we're on the new line) where it isn't
%% stripped. The only other case when it isn't on the 'Up' side is when
%% someone has used the up/down arrows (or ^P and ^N) to navigate lines,
%% in which case, a line with only a \n is stored at the end of the stack
( the is returned by : current_line/1 ) .
%%
get_all_lines works the same as get_lines , but only strips the trailing
character if it 's a linebreak . Otherwise it 's kept the same . This is
%% because traversing the stack due to search history will *not* insert
%% said empty line in the stack at the same time as other commands do,
%% and thus it should not always be stripped unless we know a new line
%% is the last entry.
get_all_lines({stack, U, {}, []}) ->
U;
get_all_lines({stack, U, {}, D}) ->
case lists:reverse(D, U) of
["\n"|Lines] -> Lines;
Lines -> Lines
end;
get_all_lines({stack, U, L, D}) ->
get_all_lines({stack, U, {}, [L|D]}).
%% For the same reason as above, though, we need to expand the stack
%% in some cases to make sure we play nice with up/down arrows. We need
%% to insert newlines, but not always.
pad_stack({stack, U, L, D}) ->
{stack, U, L, D++["\n"]}.
save_line_buffer("\n", Lines) ->
save_line_buffer(Lines);
save_line_buffer(Line, [Line|_Lines]=Lines) ->
save_line_buffer(Lines);
save_line_buffer(Line, Lines) ->
group_history:add(Line),
save_line_buffer([Line|Lines]).
save_line_buffer(Lines) ->
put(line_buffer, Lines).
search_up_stack(Stack, Substr) ->
case up_stack(Stack) of
{none,NewStack} -> {none,NewStack};
{L, NewStack} ->
case string:str(L, Substr) of
0 -> search_up_stack(NewStack, Substr);
_ -> {string:strip(L,right,$\n), NewStack}
end
end.
search_down_stack(Stack, Substr) ->
case down_stack(Stack) of
{none,NewStack} -> {none,NewStack};
{L, NewStack} ->
case string:str(L, Substr) of
0 -> search_down_stack(NewStack, Substr);
_ -> {string:strip(L,right,$\n), NewStack}
end
end.
%% This is get_line without line editing (except for backspace) and
%% without echo.
get_password_line(Chars, Drv) ->
get_password1(edit_password(Chars,[]),Drv).
get_password1({Chars,[]}, Drv) ->
receive
{Drv,{data,Cs}} ->
get_password1(edit_password(Cs,Chars),Drv);
{io_request,From,ReplyAs,Req} when is_pid(From) ->
send_drv_reqs(Drv , [ { delete_chars , -length(Pbs ) } ] ) ,
io_request(Req, From, ReplyAs, Drv, []), %WRONG!!!
I guess the reason the above line is wrong is that Buf is
%% set to []. But do we expect anything but plain output?
get_password1({Chars, []}, Drv);
{'EXIT',Drv,interrupt} ->
interrupted;
{'EXIT',Drv,_} ->
terminated
end;
get_password1({Chars,Rest},Drv) ->
send_drv_reqs(Drv,[{put_chars, unicode, "\n"}]),
{done,lists:reverse(Chars),case Rest of done -> []; _ -> Rest end}.
edit_password([],Chars) ->
{Chars,[]};
edit_password([$\r],Chars) ->
{Chars,done};
edit_password([$\r|Cs],Chars) ->
{Chars,Cs};
edit_password([$\177|Cs],[]) -> %% Being able to erase characters is
edit_password(Cs,[]); %% the least we should offer, but
edit_password([$\177|Cs],[_|Chars]) ->%% is backspace enough?
edit_password(Cs,Chars);
edit_password([Char|Cs],Chars) ->
edit_password(Cs,[Char|Chars]).
%% prompt_bytes(Prompt, Encoding)
%% Return a flat list of characters for the Prompt.
prompt_bytes(Prompt, Encoding) ->
lists:flatten(io_lib:format_prompt(Prompt, Encoding)).
cast(L, binary,latin1) when is_list(L) ->
list_to_binary(L);
cast(L, list, latin1) when is_list(L) ->
binary_to_list(list_to_binary(L)); %% Exception if not bytes
cast(L, binary,unicode) when is_list(L) ->
unicode:characters_to_binary(L,utf8);
cast(Other, _, _) ->
Other.
append(B, L, latin1) when is_binary(B) ->
binary_to_list(B)++L;
append(B, L, unicode) when is_binary(B) ->
unicode:characters_to_list(B,utf8)++L;
append(L1, L2, _) when is_list(L1) ->
L1++L2;
append(_Eof, L, _) ->
L.
| null | https://raw.githubusercontent.com/ferd/erlang-history/3d74dbc36f942dec3981e44a39454257ada71d37/src/3.1/group.erl | erlang |
%CopyrightBegin%
compliance with the License. You should have received a copy of the
Erlang Public License along with this software. If not, it can be
retrieved online at /.
basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See
the License for the specific language governing rights and limitations
under the License.
%CopyrightEnd%
A group leader process for user io.
Note: We can't ask the group process for this info since it
may be busy waiting for data from the driver.
Spawn a shell with its group_leader from the beginning set to ourselves.
we are the shells group leader
we're linked to it.
we're linked to it.
start failure
let the group process crash
we're linked to it.
start failure
let the group process crash
Send interrupt to the shell.
We want to throw away any term that we don't handle (standard
Ignore this unknown message.
'kill' instead of R, since the shell is not always in
a state where it is ready to handle a termination
message.
Put_chars, unicode is the normal message, characters are always in
standard unicode
format.
You might be tempted to send binaries unchecked, but the driver
expects unicode, so that is what we should send...
{ok,ok,Buf};
New in R12
BC with pre-R13
Process a list of output requests as long as the previous status is 'ok'.
The function for sending i/o command acknowledgement.
The ACK contains the return value.
setopts
returns {stop,Result,Rest}. Does not block output until input has been
received.
Returns:
{Result,NewSaveBuffer}
{error,What,NewSaveBuffer}
get_line_echo_off only deals with lists
and does not need encoding...
Get a line with eventual line editing. Handle other io requests
while getting line.
Returns:
interrupted
^R = backward search, ^S = forward search.
Search is tricky to implement and does a lot of back-and-forth
and handling lines and escape characters to get out of search,
whereas this module does the actual searching and appending to lines.
line and line stack, so we at least restrict it by introducing
the regular ones (none, meta_left_sq_bracket) and handle special
cases of history search.
drop current line, move to search mode. We store the current
prompt ('N>') and substitute it with the search prompt.
The search item was found and accepted (new line entered on the exact
result found)
this may create duplicate entries.
The search mode has been exited, but the user wants to remain in line
editing mode wherever that was, but editing the search result.
Load back the old prompt with the correct line number.
should not happen. Fallback.
redraw the line and keep going with the same stack position
Search mode is entered.
whenever we received a search while being already in search mode.
new search, rewind stack for a proper search.
found. Complete the output edlin couldn't have done.
WRONG!!!
We support line editing for the ICANON mode except the following
line editing characters, which already has another meaning in
- ^r in posix/icanon mode: reprint (silly in echo-off mode :-))
There's a funny behaviour whenever the line stack doesn't have a "\n"
at its end -- get_lines() seemed to work on the assumption it *will* be
there, but the manipulations done with search history do not require it.
It is an assumption because the function was built with either the full
stack being on the 'Up' side (we're on the new line) where it isn't
stripped. The only other case when it isn't on the 'Up' side is when
someone has used the up/down arrows (or ^P and ^N) to navigate lines,
in which case, a line with only a \n is stored at the end of the stack
because traversing the stack due to search history will *not* insert
said empty line in the stack at the same time as other commands do,
and thus it should not always be stripped unless we know a new line
is the last entry.
For the same reason as above, though, we need to expand the stack
in some cases to make sure we play nice with up/down arrows. We need
to insert newlines, but not always.
This is get_line without line editing (except for backspace) and
without echo.
WRONG!!!
set to []. But do we expect anything but plain output?
Being able to erase characters is
the least we should offer, but
is backspace enough?
prompt_bytes(Prompt, Encoding)
Return a flat list of characters for the Prompt.
Exception if not bytes | Copyright Ericsson AB 1996 - 2013 . All Rights Reserved .
The contents of this file are subject to the Erlang Public License ,
Version 1.1 , ( the " License " ) ; you may not use this file except in
Software distributed under the License is distributed on an " AS IS "
-module(group).
-export([start/2, start/3, server/3]).
-export([interfaces/1]).
start(Drv, Shell) ->
start(Drv, Shell, []).
start(Drv, Shell, Options) ->
spawn_link(group, server, [Drv, Shell, Options]).
server(Drv, Shell, Options) ->
process_flag(trap_exit, true),
edlin:init(),
put(line_buffer, proplists:get_value(line_buffer, Options, group_history:load())),
put(read_mode, list),
put(user_drv, Drv),
put(expand_fun,
proplists:get_value(expand_fun, Options,
fun(B) -> edlin_expand:expand(B) end)),
put(echo, proplists:get_value(echo, Options, true)),
start_shell(Shell),
server_loop(Drv, get(shell), []).
Return the pid of user_drv and the shell process .
interfaces(Group) ->
case process_info(Group, dictionary) of
{dictionary,Dict} ->
get_pids(Dict, [], false);
_ ->
[]
end.
get_pids([Drv = {user_drv,_} | Rest], Found, _) ->
get_pids(Rest, [Drv | Found], true);
get_pids([Sh = {shell,_} | Rest], Found, Active) ->
get_pids(Rest, [Sh | Found], Active);
get_pids([_ | Rest], Found, Active) ->
get_pids(Rest, Found, Active);
get_pids([], Found, true) ->
Found;
get_pids([], _Found, false) ->
[].
start_shell(Shell )
If Shell a pid the set its group_leader .
start_shell({Mod,Func,Args}) ->
start_shell1(Mod, Func, Args);
start_shell({Node,Mod,Func,Args}) ->
start_shell1(net, call, [Node,Mod,Func,Args]);
start_shell(Shell) when is_atom(Shell) ->
start_shell1(Shell, start, []);
start_shell(Shell) when is_function(Shell) ->
start_shell1(Shell);
start_shell(Shell) when is_pid(Shell) ->
put(shell, Shell);
start_shell(_Shell) ->
ok.
start_shell1(M, F, Args) ->
G = group_leader(),
group_leader(self(), self()),
case catch apply(M, F, Args) of
Shell when is_pid(Shell) ->
group_leader(G, self()),
put(shell, Shell);
end.
start_shell1(Fun) ->
G = group_leader(),
group_leader(self(), self()),
case catch Fun() of
Shell when is_pid(Shell) ->
group_leader(G, self()),
put(shell, Shell);
end.
server_loop(Drv, Shell, Buf0) ->
receive
{io_request,From,ReplyAs,Req} when is_pid(From) ->
Buf = io_request(Req, From, ReplyAs, Drv, Buf0),
server_loop(Drv, Shell, Buf);
{driver_id,ReplyTo} ->
ReplyTo ! {self(),driver_id,Drv},
server_loop(Drv, Shell, Buf0);
{Drv, echo, Bool} ->
put(echo, Bool),
server_loop(Drv, Shell, Buf0);
{'EXIT',Drv,interrupt} ->
exit_shell(interrupt),
server_loop(Drv, Shell, Buf0);
{'EXIT',Drv,R} ->
exit(R);
{'EXIT',Shell,R} ->
exit(R);
practice in receive loops ) , but not any { , _ } tuples which are
handled in io_request/5 .
NotDrvTuple when (not is_tuple(NotDrvTuple)) orelse
(tuple_size(NotDrvTuple) =/= 2) orelse
(element(1, NotDrvTuple) =/= Drv) ->
server_loop(Drv, Shell, Buf0)
end.
exit_shell(Reason) ->
case get(shell) of
undefined -> true;
Pid -> exit(Pid, Reason)
end.
get_tty_geometry(Drv) ->
Drv ! {self(),tty_geometry},
receive
{Drv,tty_geometry,Geometry} ->
Geometry
after 2000 ->
timeout
end.
get_unicode_state(Drv) ->
Drv ! {self(),get_unicode_state},
receive
{Drv,get_unicode_state,UniState} ->
UniState;
{Drv,get_unicode_state,error} ->
{error, internal}
after 2000 ->
{error,timeout}
end.
set_unicode_state(Drv,Bool) ->
Drv ! {self(),set_unicode_state,Bool},
receive
{Drv,set_unicode_state,_OldUniState} ->
ok
after 2000 ->
timeout
end.
io_request(Req, From, ReplyAs, Drv, Buf0) ->
case io_request(Req, Drv, Buf0) of
{ok,Reply,Buf} ->
io_reply(From, ReplyAs, Reply),
Buf;
{error,Reply,Buf} ->
io_reply(From, ReplyAs, Reply),
Buf;
{exit,R} ->
exit_shell(kill),
exit(R)
end.
io_request({put_chars , unicode , Binary } , , Buf ) when is_binary(Binary ) - >
send_drv(Drv , { put_chars , Binary } ) ,
io_request({put_chars,unicode,Chars}, Drv, Buf) ->
case catch unicode:characters_to_binary(Chars,utf8) of
Binary when is_binary(Binary) ->
send_drv(Drv, {put_chars, unicode, Binary}),
{ok,ok,Buf};
_ ->
{error,{error,{put_chars, unicode,Chars}},Buf}
end;
io_request({put_chars,unicode,M,F,As}, Drv, Buf) ->
case catch apply(M, F, As) of
Binary when is_binary(Binary) ->
send_drv(Drv, {put_chars, unicode,Binary}),
{ok,ok,Buf};
Chars ->
case catch unicode:characters_to_binary(Chars,utf8) of
B when is_binary(B) ->
send_drv(Drv, {put_chars, unicode,B}),
{ok,ok,Buf};
_ ->
{error,{error,F},Buf}
end
end;
io_request({put_chars,latin1,Binary}, Drv, Buf) when is_binary(Binary) ->
send_drv(Drv, {put_chars, unicode,unicode:characters_to_binary(Binary,latin1)}),
{ok,ok,Buf};
io_request({put_chars,latin1,Chars}, Drv, Buf) ->
case catch unicode:characters_to_binary(Chars,latin1) of
Binary when is_binary(Binary) ->
send_drv(Drv, {put_chars, unicode,Binary}),
{ok,ok,Buf};
_ ->
{error,{error,{put_chars,latin1,Chars}},Buf}
end;
io_request({put_chars,latin1,M,F,As}, Drv, Buf) ->
case catch apply(M, F, As) of
Binary when is_binary(Binary) ->
send_drv(Drv, {put_chars, unicode,unicode:characters_to_binary(Binary,latin1)}),
{ok,ok,Buf};
Chars ->
case catch unicode:characters_to_binary(Chars,latin1) of
B when is_binary(B) ->
send_drv(Drv, {put_chars, unicode,B}),
{ok,ok,Buf};
_ ->
{error,{error,F},Buf}
end
end;
io_request({get_chars,Encoding,Prompt,N}, Drv, Buf) ->
get_chars(Prompt, io_lib, collect_chars, N, Drv, Buf, Encoding);
io_request({get_line,Encoding,Prompt}, Drv, Buf) ->
get_chars(Prompt, io_lib, collect_line, [], Drv, Buf, Encoding);
io_request({get_until,Encoding, Prompt,M,F,As}, Drv, Buf) ->
get_chars(Prompt, io_lib, get_until, {M,F,As}, Drv, Buf, Encoding);
io_request({get_password,_Encoding},Drv,Buf) ->
get_password_chars(Drv, Buf);
io_request({setopts,Opts}, Drv, Buf) when is_list(Opts) ->
setopts(Opts, Drv, Buf);
io_request(getopts, Drv, Buf) ->
getopts(Drv, Buf);
io_request({requests,Reqs}, Drv, Buf) ->
io_requests(Reqs, {ok,ok,Buf}, Drv);
io_request({get_geometry,columns},Drv,Buf) ->
case get_tty_geometry(Drv) of
{W,_H} ->
{ok,W,Buf};
_ ->
{error,{error,enotsup},Buf}
end;
io_request({get_geometry,rows},Drv,Buf) ->
case get_tty_geometry(Drv) of
{_W,H} ->
{ok,H,Buf};
_ ->
{error,{error,enotsup},Buf}
end;
io_request({put_chars,Chars}, Drv, Buf) ->
io_request({put_chars,latin1,Chars}, Drv, Buf);
io_request({put_chars,M,F,As}, Drv, Buf) ->
io_request({put_chars,latin1,M,F,As}, Drv, Buf);
io_request({get_chars,Prompt,N}, Drv, Buf) ->
io_request({get_chars,latin1,Prompt,N}, Drv, Buf);
io_request({get_line,Prompt}, Drv, Buf) ->
io_request({get_line,latin1,Prompt}, Drv, Buf);
io_request({get_until, Prompt,M,F,As}, Drv, Buf) ->
io_request({get_until,latin1, Prompt,M,F,As}, Drv, Buf);
io_request(get_password,Drv,Buf) ->
io_request({get_password,latin1},Drv,Buf);
io_request(_, _Drv, Buf) ->
{error,{error,request},Buf}.
Status = io_requests(RequestList , PrevStat , )
io_requests([R|Rs], {ok,ok,Buf}, Drv) ->
io_requests(Rs, io_request(R, Drv, Buf), Drv);
io_requests([_|_], Error, _Drv) ->
Error;
io_requests([], Stat, _) ->
Stat.
io_reply(From , , Reply )
io_reply(From, ReplyAs, Reply) ->
From ! {io_reply,ReplyAs,Reply},
ok.
send_drv(Drv , Message )
send_drv_reqs(Drv , Requests )
send_drv(Drv, Msg) ->
Drv ! {self(),Msg},
ok.
send_drv_reqs(_Drv, []) -> ok;
send_drv_reqs(Drv, Rs) ->
send_drv(Drv, {requests,Rs}).
expand_encoding([]) ->
[];
expand_encoding([latin1 | T]) ->
[{encoding,latin1} | expand_encoding(T)];
expand_encoding([unicode | T]) ->
[{encoding,unicode} | expand_encoding(T)];
expand_encoding([H|T]) ->
[H|expand_encoding(T)].
setopts(Opts0,Drv,Buf) ->
Opts = proplists:unfold(
proplists:substitute_negations(
[{list,binary}],
expand_encoding(Opts0))),
case check_valid_opts(Opts) of
true ->
do_setopts(Opts,Drv,Buf);
false ->
{error,{error,enotsup},Buf}
end.
check_valid_opts([]) ->
true;
check_valid_opts([{binary,_}|T]) ->
check_valid_opts(T);
check_valid_opts([{encoding,Valid}|T]) when Valid =:= unicode; Valid =:= utf8; Valid =:= latin1 ->
check_valid_opts(T);
check_valid_opts([{echo,_}|T]) ->
check_valid_opts(T);
check_valid_opts([{expand_fun,_}|T]) ->
check_valid_opts(T);
check_valid_opts(_) ->
false.
do_setopts(Opts, Drv, Buf) ->
put(expand_fun, proplists:get_value(expand_fun, Opts, get(expand_fun))),
put(echo, proplists:get_value(echo, Opts, get(echo))),
case proplists:get_value(encoding,Opts) of
Valid when Valid =:= unicode; Valid =:= utf8 ->
set_unicode_state(Drv,true);
latin1 ->
set_unicode_state(Drv,false);
_ ->
ok
end,
case proplists:get_value(binary, Opts, case get(read_mode) of
binary -> true;
_ -> false
end) of
true ->
put(read_mode, binary),
{ok,ok,Buf};
false ->
put(read_mode, list),
{ok,ok,Buf};
_ ->
{ok,ok,Buf}
end.
getopts(Drv,Buf) ->
Exp = {expand_fun, case get(expand_fun) of
Func when is_function(Func) ->
Func;
_ ->
false
end},
Echo = {echo, case get(echo) of
Bool when Bool =:= true; Bool =:= false ->
Bool;
_ ->
false
end},
Bin = {binary, case get(read_mode) of
binary ->
true;
_ ->
false
end},
Uni = {encoding, case get_unicode_state(Drv) of
true -> unicode;
_ -> latin1
end},
{ok,[Exp,Echo,Bin,Uni],Buf}.
get_chars(Prompt , Module , Function , XtraArgument , , Buffer )
Gets characters from the input until as the applied function
get_password_chars(Drv,Buf) ->
case get_password_line(Buf, Drv) of
{done, Line, Buf1} ->
{ok, Line, Buf1};
interrupted ->
{error, {error, interrupted}, []};
terminated ->
{exit, terminated}
end.
get_chars(Prompt, M, F, Xa, Drv, Buf, Encoding) ->
Pbs = prompt_bytes(Prompt, Encoding),
get_chars_loop(Pbs, M, F, Xa, Drv, Buf, start, Encoding).
get_chars_loop(Pbs, M, F, Xa, Drv, Buf0, State, Encoding) ->
Result = case get(echo) of
true ->
get_line(Buf0, Pbs, Drv, Encoding);
false ->
get_line_echo_off(Buf0, Pbs, Drv)
end,
case Result of
{done,Line,Buf1} ->
get_chars_apply(Pbs, M, F, Xa, Drv, Buf1, State, Line, Encoding);
interrupted ->
{error,{error,interrupted},[]};
terminated ->
{exit,terminated}
end.
get_chars_apply(Pbs, M, F, Xa, Drv, Buf, State0, Line, Encoding) ->
case catch M:F(State0, cast(Line,get(read_mode), Encoding), Encoding, Xa) of
{stop,Result,Rest} ->
{ok,Result,append(Rest, Buf, Encoding)};
{'EXIT',_} ->
{error,{error,err_func(M, F, Xa)},[]};
State1 ->
get_chars_loop(Pbs, M, F, Xa, Drv, Buf, State1, Encoding)
end.
Convert error code to make it look as before
err_func(io_lib, get_until, {_,F,_}) ->
F;
err_func(_, F, _) ->
F.
get_line(Chars , PromptBytes , )
{ done , LineChars , RestChars }
get_line(Chars, Pbs, Drv, Encoding) ->
{more_chars,Cont,Rs} = edlin:start(Pbs),
send_drv_reqs(Drv, Rs),
get_line1(edlin:edit_line(Chars, Cont), Drv, new_stack(get(line_buffer)),
Encoding).
get_line1({done,Line,Rest,Rs}, Drv, Ls, _Encoding) ->
send_drv_reqs(Drv, Rs),
save_line_buffer(Line, get_lines(Ls)),
{done,Line,Rest};
get_line1({undefined,{_A,Mode,Char},Cs,Cont,Rs}, Drv, Ls0, Encoding)
when ((Mode =:= none) and (Char =:= $\^P))
or ((Mode =:= meta_left_sq_bracket) and (Char =:= $A)) ->
send_drv_reqs(Drv, Rs),
case up_stack(save_line(Ls0, edlin:current_line(Cont))) of
{none,_Ls} ->
send_drv(Drv, beep),
get_line1(edlin:edit_line(Cs, Cont), Drv, Ls0, Encoding);
{Lcs,Ls} ->
send_drv_reqs(Drv, edlin:erase_line(Cont)),
{more_chars,Ncont,Nrs} = edlin:start(edlin:prompt(Cont)),
send_drv_reqs(Drv, Nrs),
get_line1(edlin:edit_line1(lists:sublist(Lcs, 1, length(Lcs)-1),
Ncont),
Drv,
Ls, Encoding)
end;
get_line1({undefined,{_A,Mode,Char},Cs,Cont,Rs}, Drv, Ls0, Encoding)
when ((Mode =:= none) and (Char =:= $\^N))
or ((Mode =:= meta_left_sq_bracket) and (Char =:= $B)) ->
send_drv_reqs(Drv, Rs),
case down_stack(save_line(Ls0, edlin:current_line(Cont))) of
{none,_Ls} ->
send_drv(Drv, beep),
get_line1(edlin:edit_line(Cs, Cont), Drv, Ls0, Encoding);
{Lcs,Ls} ->
send_drv_reqs(Drv, edlin:erase_line(Cont)),
{more_chars,Ncont,Nrs} = edlin:start(edlin:prompt(Cont)),
send_drv_reqs(Drv, Nrs),
get_line1(edlin:edit_line1(lists:sublist(Lcs, 1, length(Lcs)-1),
Ncont),
Drv,
Ls, Encoding)
end;
work with edlin.erl ( from stdlib ) . takes care of writing
Erlang 's shell was n't exactly meant to traverse the wall between
new modes : search , search_quit , search_found . These are added to
get_line1({undefined,{_A,Mode,Char},Cs,Cont,Rs}, Drv, Ls, Encoding)
when ((Mode =:= none) and (Char =:= $\^R)) ->
send_drv_reqs(Drv, Rs),
send_drv_reqs(Drv, edlin:erase_line(Cont)),
put(search_quit_prompt, edlin:prompt(Cont)),
Pbs = prompt_bytes("(search)`': ", Encoding),
{more_chars,Ncont,Nrs} = edlin:start(Pbs, search),
send_drv_reqs(Drv, Nrs),
get_line1(edlin:edit_line1(Cs, Ncont), Drv, Ls, Encoding);
get_line1({expand, Before, Cs0, Cont,Rs}, Drv, Ls0, Encoding) ->
send_drv_reqs(Drv, Rs),
ExpandFun = get(expand_fun),
{Found, Add, Matches} = ExpandFun(Before),
case Found of
no -> send_drv(Drv, beep);
yes -> ok
end,
XXX : should this always be unicode ?
Cs = case Matches of
[] -> Cs1;
_ -> MatchStr = edlin_expand:format_matches(Matches),
send_drv(Drv, {put_chars, unicode, unicode:characters_to_binary(MatchStr,unicode)}),
[$\^L | Cs1]
end,
get_line1(edlin:edit_line(Cs, Cont), Drv, Ls0, Encoding);
get_line1({undefined,_Char,Cs,Cont,Rs}, Drv, Ls, Encoding) ->
send_drv_reqs(Drv, Rs),
send_drv(Drv, beep),
get_line1(edlin:edit_line(Cs, Cont), Drv, Ls, Encoding);
get_line1({_What,Cont={line,_Prompt,_Chars,search_found},Rs}, Drv, Ls0, Encoding) ->
Line = edlin:current_line(Cont),
Ls = save_line(new_stack(get_lines(Ls0)), Line),
get_line1({done, Line, "", Rs}, Drv, Ls, Encoding);
get_line1({What,Cont={line,_Prompt,_Chars,search_quit},Rs}, Drv, Ls, Encoding) ->
Line = edlin:current_chars(Cont),
case get(search_quit_prompt) of
LsFallback = save_line(new_stack(get_lines(Ls)), Line),
get_line1({done, "\n", Line, Rs}, Drv, LsFallback, Encoding);
NCont = {line,Prompt,{lists:reverse(Line),[]},none},
send_drv_reqs(Drv, Rs),
send_drv_reqs(Drv, edlin:erase_line(Cont)),
send_drv_reqs(Drv, edlin:redraw_line(NCont)),
get_line1({What, NCont ,[]}, Drv, pad_stack(Ls), Encoding)
end;
get_line1({What,{line,Prompt,{RevCmd0,_Aft},search},Rs},
Drv, Ls0, Encoding) ->
send_drv_reqs(Drv, Rs),
Figure out search direction . ^S and ^R are returned through edlin
{Search, Ls1, RevCmd} = case RevCmd0 of
[$\^S|RevCmd1] ->
{fun search_down_stack/2, Ls0, RevCmd1};
[$\^R|RevCmd1] ->
{fun search_up_stack/2, Ls0, RevCmd1};
{fun search_up_stack/2, new_stack(get_lines(Ls0)), RevCmd0}
end,
Cmd = lists:reverse(RevCmd),
{Ls, NewStack} = case Search(Ls1, Cmd) of
{none, Ls2} ->
send_drv(Drv, beep),
{Ls2, {RevCmd, "': "}};
send_drv_reqs(Drv, [{put_chars, Encoding, Line}]),
{Ls2, {RevCmd, "': "++Line}}
end,
Cont = {line,Prompt,NewStack,search},
more_data(What, Cont, Drv, Ls, Encoding);
get_line1({What,Cont0,Rs}, Drv, Ls, Encoding) ->
send_drv_reqs(Drv, Rs),
more_data(What, Cont0, Drv, Ls, Encoding).
more_data(What, Cont0, Drv, Ls, Encoding) ->
receive
{Drv,{data,Cs}} ->
get_line1(edlin:edit_line(Cs, Cont0), Drv, Ls, Encoding);
{Drv,eof} ->
get_line1(edlin:edit_line(eof, Cont0), Drv, Ls, Encoding);
{io_request,From,ReplyAs,Req} when is_pid(From) ->
{more_chars,Cont,_More} = edlin:edit_line([], Cont0),
send_drv_reqs(Drv, edlin:erase_line(Cont)),
send_drv_reqs(Drv, edlin:redraw_line(Cont)),
get_line1({more_chars,Cont,[]}, Drv, Ls, Encoding);
{'EXIT',Drv,interrupt} ->
interrupted;
{'EXIT',Drv,_} ->
terminated
after
get_line_timeout(What)->
get_line1(edlin:edit_line([], Cont0), Drv, Ls, Encoding)
end.
get_line_echo_off(Chars, Pbs, Drv) ->
send_drv_reqs(Drv, [{put_chars, unicode,Pbs}]),
get_line_echo_off1(edit_line(Chars,[]), Drv).
get_line_echo_off1({Chars,[]}, Drv) ->
receive
{Drv,{data,Cs}} ->
get_line_echo_off1(edit_line(Cs, Chars), Drv);
{Drv,eof} ->
get_line_echo_off1(edit_line(eof, Chars), Drv);
{io_request,From,ReplyAs,Req} when is_pid(From) ->
io_request(Req, From, ReplyAs, Drv, []),
get_line_echo_off1({Chars,[]}, Drv);
{'EXIT',Drv,interrupt} ->
interrupted;
{'EXIT',Drv,_} ->
terminated
end;
get_line_echo_off1({Chars,Rest}, _Drv) ->
{done,lists:reverse(Chars),case Rest of done -> []; _ -> Rest end}.
echo - on mode ( See Advanced Programming in the Unix Environment , 2nd ed ,
, page 638 ):
- ^u in posix / icanon mode : erase - line , prefix - arg in edlin
- ^t in posix / icanon mode : status , transpose - char in edlin
- ^d in posix / icanon mode : eof , delete - forward in edlin
- ^w in posix / icanon mode : word - erase ( produces a beep in )
edit_line(eof, Chars) ->
{Chars,done};
edit_line([],Chars) ->
{Chars,[]};
edit_line([$\r,$\n|Cs],Chars) ->
{[$\n | Chars], remainder_after_nl(Cs)};
edit_line([NL|Cs],Chars) when NL =:= $\r; NL =:= $\n ->
{[$\n | Chars], remainder_after_nl(Cs)};
edit_line([Erase|Cs],[]) when Erase =:= $\177; Erase =:= $\^H ->
edit_line(Cs,[]);
edit_line([Erase|Cs],[_|Chars]) when Erase =:= $\177; Erase =:= $\^H ->
edit_line(Cs,Chars);
edit_line([Char|Cs],Chars) ->
edit_line(Cs,[Char|Chars]).
remainder_after_nl("") -> done;
remainder_after_nl(Cs) -> Cs.
get_line_timeout(blink) -> 1000;
get_line_timeout(more_chars) -> infinity.
new_stack(Ls) -> {stack,Ls,{},[]}.
up_stack({stack,[L|U],{},D}) ->
{L,{stack,U,L,D}};
up_stack({stack,[],{},D}) ->
{none,{stack,[],{},D}};
up_stack({stack,U,C,D}) ->
up_stack({stack,U,{},[C|D]}).
down_stack({stack,U,{},[L|D]}) ->
{L,{stack,U,L,D}};
down_stack({stack,U,{},[]}) ->
{none,{stack,U,{},[]}};
down_stack({stack,U,C,D}) ->
down_stack({stack,[C|U],{},D}).
save_line({stack, U, {}, []}, Line) ->
{stack, U, {}, [Line]};
save_line({stack, U, _L, D}, Line) ->
{stack, U, Line, D}.
get_lines(Ls) -> get_all_lines(Ls).
get_lines({stack , U , { } , [ ] } ) - >
U ;
get_lines({stack , U , { } , D } ) - >
: reverse(D , U ) ) ;
get_lines({stack , U , L , D } ) - >
get_lines({stack , U , { } , [ L|D ] } ) .
( the is returned by : current_line/1 ) .
get_all_lines works the same as get_lines , but only strips the trailing
character if it 's a linebreak . Otherwise it 's kept the same . This is
get_all_lines({stack, U, {}, []}) ->
U;
get_all_lines({stack, U, {}, D}) ->
case lists:reverse(D, U) of
["\n"|Lines] -> Lines;
Lines -> Lines
end;
get_all_lines({stack, U, L, D}) ->
get_all_lines({stack, U, {}, [L|D]}).
pad_stack({stack, U, L, D}) ->
{stack, U, L, D++["\n"]}.
save_line_buffer("\n", Lines) ->
save_line_buffer(Lines);
save_line_buffer(Line, [Line|_Lines]=Lines) ->
save_line_buffer(Lines);
save_line_buffer(Line, Lines) ->
group_history:add(Line),
save_line_buffer([Line|Lines]).
save_line_buffer(Lines) ->
put(line_buffer, Lines).
search_up_stack(Stack, Substr) ->
case up_stack(Stack) of
{none,NewStack} -> {none,NewStack};
{L, NewStack} ->
case string:str(L, Substr) of
0 -> search_up_stack(NewStack, Substr);
_ -> {string:strip(L,right,$\n), NewStack}
end
end.
search_down_stack(Stack, Substr) ->
case down_stack(Stack) of
{none,NewStack} -> {none,NewStack};
{L, NewStack} ->
case string:str(L, Substr) of
0 -> search_down_stack(NewStack, Substr);
_ -> {string:strip(L,right,$\n), NewStack}
end
end.
get_password_line(Chars, Drv) ->
get_password1(edit_password(Chars,[]),Drv).
get_password1({Chars,[]}, Drv) ->
receive
{Drv,{data,Cs}} ->
get_password1(edit_password(Cs,Chars),Drv);
{io_request,From,ReplyAs,Req} when is_pid(From) ->
send_drv_reqs(Drv , [ { delete_chars , -length(Pbs ) } ] ) ,
I guess the reason the above line is wrong is that Buf is
get_password1({Chars, []}, Drv);
{'EXIT',Drv,interrupt} ->
interrupted;
{'EXIT',Drv,_} ->
terminated
end;
get_password1({Chars,Rest},Drv) ->
send_drv_reqs(Drv,[{put_chars, unicode, "\n"}]),
{done,lists:reverse(Chars),case Rest of done -> []; _ -> Rest end}.
edit_password([],Chars) ->
{Chars,[]};
edit_password([$\r],Chars) ->
{Chars,done};
edit_password([$\r|Cs],Chars) ->
{Chars,Cs};
edit_password(Cs,Chars);
edit_password([Char|Cs],Chars) ->
edit_password(Cs,[Char|Chars]).
prompt_bytes(Prompt, Encoding) ->
lists:flatten(io_lib:format_prompt(Prompt, Encoding)).
cast(L, binary,latin1) when is_list(L) ->
list_to_binary(L);
cast(L, list, latin1) when is_list(L) ->
cast(L, binary,unicode) when is_list(L) ->
unicode:characters_to_binary(L,utf8);
cast(Other, _, _) ->
Other.
append(B, L, latin1) when is_binary(B) ->
binary_to_list(B)++L;
append(B, L, unicode) when is_binary(B) ->
unicode:characters_to_list(B,utf8)++L;
append(L1, L2, _) when is_list(L1) ->
L1++L2;
append(_Eof, L, _) ->
L.
|
b37fea595a7f21e24017b2250e3438270570735a4b494e5542cba198f4f450a9 | myuon/claire | FOLTest.hs | module ClaireTest.FOLTest where
import Test.Tasty.HUnit
import Claire
test_pFormula =
[ testCase "Var a" $ pFormula "a" @?= Const "a"
, testCase "a /\\ b" $ pFormula "a /\\ b" @?= Const "a" :/\: Const "b"
, testCase "Top" $ pFormula "Top" @?= Top
, testCase "Bottom" $ pFormula "Bottom" @?= Bottom
, testCase "p ==> q" $ pFormula "p ==> q" @?= Const "p" :==>: Const "q"
, testCase "p ==> q /\\ q' ==> r" $ pFormula "p ==> (q /\\ q' ==> r)" @?= Const "p" :==>: ((Const "q" :/\: Const "q'") :==>: Const "r")
, testCase "p /\\ q /\\ r" $ pFormula "p /\\ q /\\ r" @?= (Const "p" :/\: Const "q") :/\: Const "r"
, testCase "~p /\\ ~q" $ pFormula "~p /\\ ~ q" @?= Neg (Const "p") :/\: Neg (Const "q")
]
| null | https://raw.githubusercontent.com/myuon/claire/e14268ced1bbab2f099a93feb0f2a129cf8b6a8b/test/ClaireTest/FOLTest.hs | haskell | module ClaireTest.FOLTest where
import Test.Tasty.HUnit
import Claire
test_pFormula =
[ testCase "Var a" $ pFormula "a" @?= Const "a"
, testCase "a /\\ b" $ pFormula "a /\\ b" @?= Const "a" :/\: Const "b"
, testCase "Top" $ pFormula "Top" @?= Top
, testCase "Bottom" $ pFormula "Bottom" @?= Bottom
, testCase "p ==> q" $ pFormula "p ==> q" @?= Const "p" :==>: Const "q"
, testCase "p ==> q /\\ q' ==> r" $ pFormula "p ==> (q /\\ q' ==> r)" @?= Const "p" :==>: ((Const "q" :/\: Const "q'") :==>: Const "r")
, testCase "p /\\ q /\\ r" $ pFormula "p /\\ q /\\ r" @?= (Const "p" :/\: Const "q") :/\: Const "r"
, testCase "~p /\\ ~q" $ pFormula "~p /\\ ~ q" @?= Neg (Const "p") :/\: Neg (Const "q")
]
| |
fca521d3c6a195ac6e2862da5fc9a95f5c39024f724c06f0fda7d3e57fbd109f | DHSProgram/DHS-Indicators-SPSS | HK_BHV_YNG_MR.sps | * Encoding: windows-1252.
*****************************************************************************************************
Program: HK_BHV_YNG_MR.sps
Purpose: Code for sexual behaviors among young people
Data inputs: MR dataset
Data outputs: coded variables
Author: Shireen Assaf and translated to SPSS by Ivana Bjelic
Date last modified: Nov 29, 2019 by Ivana Bjelic
Note: The indicators below can be computed for men and women. No age selection is made here.
*****************************************************************************************************/
*----------------------------------------------------------------------------
Variables created in this file:
hk_sex_15 "Had sexual intercourse before age 15 among those age 15-24"
hk_sex_18 "Had sexual intercourse before age 18 among those age 18-24"
hk_nosex_youth "Never had sexual intercourse among never-married age 15-24"
hk_sex_youth_test "Had sexual intercourse in the past 12 months and received HIV test and results among those age 15-24"
----------------------------------------------------------------------------.
* indicators from MR file.
**************************.
*Sex before 15.
do if (mv012<=24).
+compute hk_sex_15=0.
+if range(mv531,1,14) hk_sex_15=1.
end if.
variable labels hk_sex_15 "Had sexual intercourse before age 15 among those age 15-24".
value labels hk_sex_15 0"No" 1"Yes".
*Sex before 18.
do if (mv012>=18 and mv012<=24).
+compute hk_sex_18=0.
+if range(mv531,1,17) hk_sex_18=1.
end if.
variable labels hk_sex_18 "Had sexual intercourse before age 18 among those age 18-24".
value labels hk_sex_18 0"No" 1"Yes".
*Never had sexual.
do if (mv012<=24 and mv501=0).
+compute hk_nosex_youth=0.
+if (mv525=0 | mv525=99) hk_nosex_youth=1.
end if.
variable labels hk_nosex_youth "Never had sexual intercourse among never-married age 15-24".
value labels hk_nosex_youth 0"No" 1"Yes".
*Tested and received HIV test results.
do if ((mv012<=24) and (mv527<252 or mv527>299) and mv527<=311 and mv527>=100 and not sysmis(mv527)).
+compute hk_sex_youth_test=0.
+if (range(mv527,100,251) | range(mv527,300,311)) & mv828=1 & range(mv826a,0,11) hk_sex_youth_test=1.
end if.
variable labels hk_sex_youth_test "Had sexual intercourse in the past 12 months and received HIV test and results among those age 15-24".
value labels hk_sex_youth_test 0"No" 1"Yes".
| null | https://raw.githubusercontent.com/DHSProgram/DHS-Indicators-SPSS/578e6d40eff9edebda7cf0db0d9a0a52a537d98c/Chap13_HK/HK_BHV_YNG_MR.sps | scheme | * Encoding: windows-1252.
*****************************************************************************************************
Program: HK_BHV_YNG_MR.sps
Purpose: Code for sexual behaviors among young people
Data inputs: MR dataset
Data outputs: coded variables
Author: Shireen Assaf and translated to SPSS by Ivana Bjelic
Date last modified: Nov 29, 2019 by Ivana Bjelic
Note: The indicators below can be computed for men and women. No age selection is made here.
*****************************************************************************************************/
*----------------------------------------------------------------------------
Variables created in this file:
hk_sex_15 "Had sexual intercourse before age 15 among those age 15-24"
hk_sex_18 "Had sexual intercourse before age 18 among those age 18-24"
hk_nosex_youth "Never had sexual intercourse among never-married age 15-24"
hk_sex_youth_test "Had sexual intercourse in the past 12 months and received HIV test and results among those age 15-24"
----------------------------------------------------------------------------.
* indicators from MR file.
**************************.
*Sex before 15.
do if (mv012<=24).
+compute hk_sex_15=0.
+if range(mv531,1,14) hk_sex_15=1.
end if.
variable labels hk_sex_15 "Had sexual intercourse before age 15 among those age 15-24".
value labels hk_sex_15 0"No" 1"Yes".
*Sex before 18.
do if (mv012>=18 and mv012<=24).
+compute hk_sex_18=0.
+if range(mv531,1,17) hk_sex_18=1.
end if.
variable labels hk_sex_18 "Had sexual intercourse before age 18 among those age 18-24".
value labels hk_sex_18 0"No" 1"Yes".
*Never had sexual.
do if (mv012<=24 and mv501=0).
+compute hk_nosex_youth=0.
+if (mv525=0 | mv525=99) hk_nosex_youth=1.
end if.
variable labels hk_nosex_youth "Never had sexual intercourse among never-married age 15-24".
value labels hk_nosex_youth 0"No" 1"Yes".
*Tested and received HIV test results.
do if ((mv012<=24) and (mv527<252 or mv527>299) and mv527<=311 and mv527>=100 and not sysmis(mv527)).
+compute hk_sex_youth_test=0.
+if (range(mv527,100,251) | range(mv527,300,311)) & mv828=1 & range(mv826a,0,11) hk_sex_youth_test=1.
end if.
variable labels hk_sex_youth_test "Had sexual intercourse in the past 12 months and received HIV test and results among those age 15-24".
value labels hk_sex_youth_test 0"No" 1"Yes".
| |
b11d984d3304881c2076a59af77a211834a5abdf71dca795338e559a205f0aec | haroldcarr/learn-haskell-coq-ml-etc | FuelLevel.hs | # LANGUAGE FlexibleInstances #
{-# LANGUAGE DataKinds #-}
# LANGUAGE GeneralizedNewtypeDeriving #
# LANGUAGE MultiParamTypeClasses #
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE TypeSynonymInstances #-}
module FuelLevel where
import Protolude
import Refined
import Test.Hspec
------------------------------------------------------------------------------
newtype FuelLevel0 = FuelLevel0
{ getFuelLevel0 :: Int
} deriving (Eq, Ord, Num, Show)
validateFuelLevel0 :: Int -> Maybe FuelLevel0
validateFuelLevel0 i =
if 0 <= i && i <= 10
then Just (FuelLevel0 i)
else Nothing
fl0 :: Maybe FuelLevel0
fl0 = do
x <- validateFuelLevel0 3
y <- validateFuelLevel0 9
pure (x + y)
if full = = 10 , then the result of addition should be checked to producing Nothing .
fl0t :: Spec
fl0t = it "FuelLevel0" $ fl0 `shouldBe` Just (FuelLevel0 12)
------------------------------------------------------------------------------
newtype FuelLevel1 p = FuelLevel1
{ getFuelLevel1 :: Int
} deriving (Eq, Ord, Num, Show)
data InRange1
validateFuelLevel1 :: Int -> Maybe (FuelLevel1 InRange1)
validateFuelLevel1 i =
if 0 <= i && i <= 10
then Just (FuelLevel1 i)
else Nothing
fl1 :: Maybe (FuelLevel1 InRange1)
fl1 = do
x <- validateFuelLevel1 3
y <- validateFuelLevel1 9
pure (x + y)
if full = = 10 , then the result of addition should be checked to producing Nothing .
fl1t :: Spec
fl1t = it "FuelLevel1" $ fl1 `shouldBe` Just (FuelLevel1 12)
------------------------------------------------------------------------------
type FuelLevel2 = Refined (FromTo 0 10) Int
type FuelLevelException2 = RefineException
validateFuelLevel2 :: Int -> Either FuelLevelException2 FuelLevel2
validateFuelLevel2 = refine
fl2 :: Either FuelLevelException2 FuelLevel2
fl2 = do
x <- validateFuelLevel2 3
y <- validateFuelLevel2 9
• No instance for ( FuelLevel2 ) arising from a use of ‘ + ’
-- pure (x + y)
-- • Couldn't match type ‘Int’ with ‘Refined (FromTo 0 10) Int’
-- pure (unrefine x + unrefine y)
refine (unrefine x + unrefine y)
-- this time the result of addition is check, thus raising an exception
fl2t :: Spec
fl2t =
let r = fl2 in
it "FuelLevel2" $ (show r :: Text) `shouldBe`
"Left The predicate (FromTo 0 10) does not hold: \n Value is out of range (minimum: 0, maximum: 10)"
| null | https://raw.githubusercontent.com/haroldcarr/learn-haskell-coq-ml-etc/b4e83ec7c7af730de688b7376497b9f49dc24a0e/haskell/playpen/2020-07-07-harold-carr-phantom-existential-scratchpad/src/FuelLevel.hs | haskell | # LANGUAGE DataKinds #
# LANGUAGE NoImplicitPrelude #
# LANGUAGE OverloadedStrings #
# LANGUAGE TypeSynonymInstances #
----------------------------------------------------------------------------
----------------------------------------------------------------------------
----------------------------------------------------------------------------
pure (x + y)
• Couldn't match type ‘Int’ with ‘Refined (FromTo 0 10) Int’
pure (unrefine x + unrefine y)
this time the result of addition is check, thus raising an exception | # LANGUAGE FlexibleInstances #
# LANGUAGE GeneralizedNewtypeDeriving #
# LANGUAGE MultiParamTypeClasses #
module FuelLevel where
import Protolude
import Refined
import Test.Hspec
newtype FuelLevel0 = FuelLevel0
{ getFuelLevel0 :: Int
} deriving (Eq, Ord, Num, Show)
validateFuelLevel0 :: Int -> Maybe FuelLevel0
validateFuelLevel0 i =
if 0 <= i && i <= 10
then Just (FuelLevel0 i)
else Nothing
fl0 :: Maybe FuelLevel0
fl0 = do
x <- validateFuelLevel0 3
y <- validateFuelLevel0 9
pure (x + y)
if full = = 10 , then the result of addition should be checked to producing Nothing .
fl0t :: Spec
fl0t = it "FuelLevel0" $ fl0 `shouldBe` Just (FuelLevel0 12)
newtype FuelLevel1 p = FuelLevel1
{ getFuelLevel1 :: Int
} deriving (Eq, Ord, Num, Show)
data InRange1
validateFuelLevel1 :: Int -> Maybe (FuelLevel1 InRange1)
validateFuelLevel1 i =
if 0 <= i && i <= 10
then Just (FuelLevel1 i)
else Nothing
fl1 :: Maybe (FuelLevel1 InRange1)
fl1 = do
x <- validateFuelLevel1 3
y <- validateFuelLevel1 9
pure (x + y)
if full = = 10 , then the result of addition should be checked to producing Nothing .
fl1t :: Spec
fl1t = it "FuelLevel1" $ fl1 `shouldBe` Just (FuelLevel1 12)
type FuelLevel2 = Refined (FromTo 0 10) Int
type FuelLevelException2 = RefineException
validateFuelLevel2 :: Int -> Either FuelLevelException2 FuelLevel2
validateFuelLevel2 = refine
fl2 :: Either FuelLevelException2 FuelLevel2
fl2 = do
x <- validateFuelLevel2 3
y <- validateFuelLevel2 9
• No instance for ( FuelLevel2 ) arising from a use of ‘ + ’
refine (unrefine x + unrefine y)
fl2t :: Spec
fl2t =
let r = fl2 in
it "FuelLevel2" $ (show r :: Text) `shouldBe`
"Left The predicate (FromTo 0 10) does not hold: \n Value is out of range (minimum: 0, maximum: 10)"
|
759e4e34193f572aef7e855ca752d26bdab21d94fbd5cb9ec4b9b31fea09d8aa | juspay/atlas | Search.hs | # LANGUAGE DerivingStrategies #
# LANGUAGE GeneralizedNewtypeDeriving #
# LANGUAGE QuasiQuotes #
# LANGUAGE StandaloneDeriving #
# LANGUAGE TemplateHaskell #
# OPTIONS_GHC -Wno - orphans #
|
Copyright 2022 Juspay Technologies Pvt Ltd
Licensed under the Apache License , Version 2.0 ( the " License " ) ;
you may not use this file except in compliance with the License .
You may obtain a copy of the License at
-2.0
Unless required by applicable law or agreed to in writing , software
distributed under the License is distributed on an " AS IS " BASIS ,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND , either express or implied .
See the License for the specific language governing permissions and
limitations under the License .
Module : Storage . Tabular . Search
Copyright : ( C ) Juspay Technologies Pvt Ltd 2019 - 2022
License : Apache 2.0 ( see the file LICENSE )
Maintainer :
Stability : experimental
Portability : non - portable
Copyright 2022 Juspay Technologies Pvt Ltd
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
Module : Storage.Tabular.Search
Copyright : (C) Juspay Technologies Pvt Ltd 2019-2022
License : Apache 2.0 (see the file LICENSE)
Maintainer :
Stability : experimental
Portability : non-portable
-}
module Storage.Tabular.Search where
import Beckn.Prelude
import Beckn.Storage.Esqueleto
import Beckn.Types.Id
import qualified Domain.Types.Search as Domain
mkPersist
defaultSqlSettings
[defaultQQ|
SearchT sql=search
id Text
lat Double
lon Double
requestorId Text
createdAt UTCTime
Primary id
deriving Generic
|]
instance TEntityKey SearchT where
type DomainKey SearchT = Id Domain.Search
fromKey (SearchTKey _id) = Id _id
toKey id = SearchTKey id.getId
instance TEntity SearchT Domain.Search where
fromTEntity entity = do
let SearchT {..} = entityVal entity
return $
Domain.Search
{ id = Id id,
requestorId = Id requestorId,
..
}
toTType Domain.Search {..} =
SearchT
{ id = id.getId,
requestorId = requestorId.getId,
..
}
toTEntity a =
Entity (toKey a.id) $ toTType a
| null | https://raw.githubusercontent.com/juspay/atlas/e64b227dc17887fb01c2554db21c08284d18a806/app/public-transport-bap/src/Storage/Tabular/Search.hs | haskell | # LANGUAGE DerivingStrategies #
# LANGUAGE GeneralizedNewtypeDeriving #
# LANGUAGE QuasiQuotes #
# LANGUAGE StandaloneDeriving #
# LANGUAGE TemplateHaskell #
# OPTIONS_GHC -Wno - orphans #
|
Copyright 2022 Juspay Technologies Pvt Ltd
Licensed under the Apache License , Version 2.0 ( the " License " ) ;
you may not use this file except in compliance with the License .
You may obtain a copy of the License at
-2.0
Unless required by applicable law or agreed to in writing , software
distributed under the License is distributed on an " AS IS " BASIS ,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND , either express or implied .
See the License for the specific language governing permissions and
limitations under the License .
Module : Storage . Tabular . Search
Copyright : ( C ) Juspay Technologies Pvt Ltd 2019 - 2022
License : Apache 2.0 ( see the file LICENSE )
Maintainer :
Stability : experimental
Portability : non - portable
Copyright 2022 Juspay Technologies Pvt Ltd
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
Module : Storage.Tabular.Search
Copyright : (C) Juspay Technologies Pvt Ltd 2019-2022
License : Apache 2.0 (see the file LICENSE)
Maintainer :
Stability : experimental
Portability : non-portable
-}
module Storage.Tabular.Search where
import Beckn.Prelude
import Beckn.Storage.Esqueleto
import Beckn.Types.Id
import qualified Domain.Types.Search as Domain
mkPersist
defaultSqlSettings
[defaultQQ|
SearchT sql=search
id Text
lat Double
lon Double
requestorId Text
createdAt UTCTime
Primary id
deriving Generic
|]
instance TEntityKey SearchT where
type DomainKey SearchT = Id Domain.Search
fromKey (SearchTKey _id) = Id _id
toKey id = SearchTKey id.getId
instance TEntity SearchT Domain.Search where
fromTEntity entity = do
let SearchT {..} = entityVal entity
return $
Domain.Search
{ id = Id id,
requestorId = Id requestorId,
..
}
toTType Domain.Search {..} =
SearchT
{ id = id.getId,
requestorId = requestorId.getId,
..
}
toTEntity a =
Entity (toKey a.id) $ toTType a
| |
cb04eb618acf0b9a8e9947e270f0b8744bc651d65366de6f161dce83e7914721 | pirapira/coq2rust | reduction.ml | (************************************************************************)
v * The Coq Proof Assistant / The Coq Development Team
< O _ _ _ , , * INRIA - CNRS - LIX - LRI - PPS - Copyright 1999 - 2012
\VV/ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
(* // * This file is distributed under the terms of the *)
(* * GNU Lesser General Public License Version 2.1 *)
(************************************************************************)
open Errors
open Util
open Cic
open Term
open Closure
open Esubst
open Environ
let rec is_empty_stack = function
[] -> true
| Zupdate _::s -> is_empty_stack s
| Zshift _::s -> is_empty_stack s
| _ -> false
(* Compute the lift to be performed on a term placed in a given stack *)
let el_stack el stk =
let n =
List.fold_left
(fun i z ->
match z with
Zshift n -> i+n
| _ -> i)
0
stk in
el_shft n el
let compare_stack_shape stk1 stk2 =
let rec compare_rec bal stk1 stk2 =
match (stk1,stk2) with
([],[]) -> bal=0
| ((Zupdate _|Zshift _)::s1, _) -> compare_rec bal s1 stk2
| (_, (Zupdate _|Zshift _)::s2) -> compare_rec bal stk1 s2
| (Zapp l1::s1, _) -> compare_rec (bal+Array.length l1) s1 stk2
| (_, Zapp l2::s2) -> compare_rec (bal-Array.length l2) stk1 s2
| (Zproj (n1,m1,p1)::s1, Zproj (n2,m2,p2)::s2) ->
Int.equal bal 0 && compare_rec 0 s1 s2
| (Zcase(c1,_,_)::s1, Zcase(c2,_,_)::s2) ->
bal=0 (* && c1.ci_ind = c2.ci_ind *) && compare_rec 0 s1 s2
| (Zfix(_,a1)::s1, Zfix(_,a2)::s2) ->
bal=0 && compare_rec 0 a1 a2 && compare_rec 0 s1 s2
| (_,_) -> false in
compare_rec 0 stk1 stk2
type lft_constr_stack_elt =
Zlapp of (lift * fconstr) array
| Zlproj of Names.constant * lift
| Zlfix of (lift * fconstr) * lft_constr_stack
| Zlcase of case_info * lift * fconstr * fconstr array
and lft_constr_stack = lft_constr_stack_elt list
let rec zlapp v = function
Zlapp v2 :: s -> zlapp (Array.append v v2) s
| s -> Zlapp v :: s
let pure_stack lfts stk =
let rec pure_rec lfts stk =
match stk with
[] -> (lfts,[])
| zi::s ->
(match (zi,pure_rec lfts s) with
(Zupdate _,lpstk) -> lpstk
| (Zshift n,(l,pstk)) -> (el_shft n l, pstk)
| (Zapp a, (l,pstk)) ->
(l,zlapp (Array.map (fun t -> (l,t)) a) pstk)
| (Zproj (n,m,c), (l,pstk)) ->
(l, Zlproj (c,l)::pstk)
| (Zfix(fx,a),(l,pstk)) ->
let (lfx,pa) = pure_rec l a in
(l, Zlfix((lfx,fx),pa)::pstk)
| (Zcase(ci,p,br),(l,pstk)) ->
(l,Zlcase(ci,l,p,br)::pstk)) in
snd (pure_rec lfts stk)
(****************************************************************************)
(* Reduction Functions *)
(****************************************************************************)
let whd_betaiotazeta x =
match x with
| (Sort _|Var _|Meta _|Evar _|Const _|Ind _|Construct _|
Prod _|Lambda _|Fix _|CoFix _) -> x
| _ -> whd_val (create_clos_infos betaiotazeta empty_env) (inject x)
let whd_betadeltaiota env t =
match t with
| (Sort _|Meta _|Evar _|Ind _|Construct _|
Prod _|Lambda _|Fix _|CoFix _) -> t
| _ -> whd_val (create_clos_infos betadeltaiota env) (inject t)
let whd_betadeltaiota_nolet env t =
match t with
| (Sort _|Meta _|Evar _|Ind _|Construct _|
Prod _|Lambda _|Fix _|CoFix _|LetIn _) -> t
| _ -> whd_val (create_clos_infos betadeltaiotanolet env) (inject t)
(* Beta *)
let beta_appvect c v =
let rec stacklam env t stack =
match t, stack with
Lambda(_,_,c), arg::stacktl -> stacklam (arg::env) c stacktl
| _ -> applist (substl env t, stack) in
stacklam [] c (Array.to_list v)
(********************************************************************)
(* Conversion *)
(********************************************************************)
(* Conversion utility functions *)
type 'a conversion_function = env -> 'a -> 'a -> unit
exception NotConvertible
exception NotConvertibleVect of int
let convert_universes univ u u' =
if Univ.Instance.check_eq univ u u' then ()
else raise NotConvertible
let compare_stacks f fmind lft1 stk1 lft2 stk2 =
let rec cmp_rec pstk1 pstk2 =
match (pstk1,pstk2) with
| (z1::s1, z2::s2) ->
cmp_rec s1 s2;
(match (z1,z2) with
| (Zlapp a1,Zlapp a2) -> Array.iter2 f a1 a2
| (Zlfix(fx1,a1),Zlfix(fx2,a2)) ->
f fx1 fx2; cmp_rec a1 a2
| (Zlproj (c1,l1),Zlproj (c2,l2)) ->
if not (Names.eq_con_chk c1 c2) then
raise NotConvertible
| (Zlcase(ci1,l1,p1,br1),Zlcase(ci2,l2,p2,br2)) ->
if not (fmind ci1.ci_ind ci2.ci_ind) then
raise NotConvertible;
f (l1,p1) (l2,p2);
Array.iter2 (fun c1 c2 -> f (l1,c1) (l2,c2)) br1 br2
| _ -> assert false)
| _ -> () in
if compare_stack_shape stk1 stk2 then
cmp_rec (pure_stack lft1 stk1) (pure_stack lft2 stk2)
else raise NotConvertible
(* Convertibility of sorts *)
type conv_pb =
| CONV
| CUMUL
let sort_cmp univ pb s0 s1 =
match (s0,s1) with
| (Prop c1, Prop c2) when pb = CUMUL -> if c1 = Pos && c2 = Null then raise NotConvertible
| (Prop c1, Prop c2) -> if c1 <> c2 then raise NotConvertible
| (Prop c1, Type u) ->
(match pb with
CUMUL -> ()
| _ -> raise NotConvertible)
| (Type u1, Type u2) ->
if not
(match pb with
| CONV -> Univ.check_eq univ u1 u2
| CUMUL -> Univ.check_leq univ u1 u2)
then raise NotConvertible
| (_, _) -> raise NotConvertible
let rec no_arg_available = function
| [] -> true
| Zupdate _ :: stk -> no_arg_available stk
| Zshift _ :: stk -> no_arg_available stk
| Zapp v :: stk -> Array.length v = 0 && no_arg_available stk
| Zproj _ :: _ -> true
| Zcase _ :: _ -> true
| Zfix _ :: _ -> true
let rec no_nth_arg_available n = function
| [] -> true
| Zupdate _ :: stk -> no_nth_arg_available n stk
| Zshift _ :: stk -> no_nth_arg_available n stk
| Zapp v :: stk ->
let k = Array.length v in
if n >= k then no_nth_arg_available (n-k) stk
else false
| Zproj _ :: _ -> true
| Zcase _ :: _ -> true
| Zfix _ :: _ -> true
let rec no_case_available = function
| [] -> true
| Zupdate _ :: stk -> no_case_available stk
| Zshift _ :: stk -> no_case_available stk
| Zapp _ :: stk -> no_case_available stk
| Zproj (_,_,_) :: _ -> false
| Zcase _ :: _ -> false
| Zfix _ :: _ -> true
let in_whnf (t,stk) =
match fterm_of t with
| (FLetIn _ | FCases _ | FApp _ | FCLOS _ | FLIFT _ | FCast _) -> false
| FLambda _ -> no_arg_available stk
| FConstruct _ -> no_case_available stk
| FCoFix _ -> no_case_available stk
| FFix(((ri,n),(_,_,_)),_) -> no_nth_arg_available ri.(n) stk
| (FFlex _ | FProd _ | FEvar _ | FInd _ | FAtom _ | FRel _ | FProj _) -> true
| FLOCKED -> assert false
let oracle_order fl1 fl2 =
match fl1,fl2 with
ConstKey c1, ConstKey c2 -> (*height c1 > height c2*)false
| _, ConstKey _ -> true
| _ -> false
let unfold_projection infos p c =
let pb = lookup_projection p (infos_env infos) in
let s = Zproj (pb.proj_npars, pb.proj_arg, p) in
(c, s)
(* Conversion between [lft1]term1 and [lft2]term2 *)
let rec ccnv univ cv_pb infos lft1 lft2 term1 term2 =
eqappr univ cv_pb infos (lft1, (term1,[])) (lft2, (term2,[]))
(* Conversion between [lft1](hd1 v1) and [lft2](hd2 v2) *)
and eqappr univ cv_pb infos (lft1,st1) (lft2,st2) =
Control.check_for_interrupt ();
First head reduce both terms
let rec whd_both (t1,stk1) (t2,stk2) =
let st1' = whd_stack infos t1 stk1 in
let st2' = whd_stack infos t2 stk2 in
Now , whd_stack on might have modified ( due to sharing ) ,
and st1 might not be in whnf anymore . If so , we iterate ccnv .
and st1 might not be in whnf anymore. If so, we iterate ccnv. *)
if in_whnf st1' then (st1',st2') else whd_both st1' st2' in
let ((hd1,v1),(hd2,v2)) = whd_both st1 st2 in
let appr1 = (lft1,(hd1,v1)) and appr2 = (lft2,(hd2,v2)) in
compute the lifts that apply to the head of the term ( hd1 and )
let el1 = el_stack lft1 v1 in
let el2 = el_stack lft2 v2 in
match (fterm_of hd1, fterm_of hd2) with
(* case of leaves *)
| (FAtom a1, FAtom a2) ->
(match a1, a2 with
| (Sort s1, Sort s2) ->
assert (is_empty_stack v1 && is_empty_stack v2);
sort_cmp univ cv_pb s1 s2
| (Meta n, Meta m) ->
if n=m
then convert_stacks univ infos lft1 lft2 v1 v2
else raise NotConvertible
| _ -> raise NotConvertible)
| (FEvar (ev1,args1), FEvar (ev2,args2)) ->
if ev1=ev2 then
(convert_stacks univ infos lft1 lft2 v1 v2;
convert_vect univ infos el1 el2 args1 args2)
else raise NotConvertible
2 index known to be bound to no constant
| (FRel n, FRel m) ->
if reloc_rel n el1 = reloc_rel m el2
then convert_stacks univ infos lft1 lft2 v1 v2
else raise NotConvertible
2 constants , 2 local defined vars or 2 defined rels
| (FFlex fl1, FFlex fl2) ->
try first intensional equality
if eq_table_key fl1 fl2
then convert_stacks univ infos lft1 lft2 v1 v2
else raise NotConvertible
with NotConvertible ->
(* else the oracle tells which constant is to be expanded *)
let (app1,app2) =
if oracle_order fl1 fl2 then
match unfold_reference infos fl1 with
| Some def1 -> ((lft1, whd_stack infos def1 v1), appr2)
| None ->
(match unfold_reference infos fl2 with
| Some def2 -> (appr1, (lft2, whd_stack infos def2 v2))
| None -> raise NotConvertible)
else
match unfold_reference infos fl2 with
| Some def2 -> (appr1, (lft2, whd_stack infos def2 v2))
| None ->
(match unfold_reference infos fl1 with
| Some def1 -> ((lft1, whd_stack infos def1 v1), appr2)
| None -> raise NotConvertible) in
eqappr univ cv_pb infos app1 app2)
| (FProj (p1,c1), _) ->
let (def1, s1) = unfold_projection infos p1 c1 in
eqappr univ cv_pb infos (lft1, whd_stack infos def1 (s1 :: v1)) appr2
| (_, FProj (p2,c2)) ->
let (def2, s2) = unfold_projection infos p2 c2 in
eqappr univ cv_pb infos appr1 (lft2, whd_stack infos def2 (s2 :: v2))
(* other constructors *)
| (FLambda _, FLambda _) ->
(* Inconsistency: we tolerate that v1, v2 contain shift and update but
we throw them away *)
assert (is_empty_stack v1 && is_empty_stack v2);
let (_,ty1,bd1) = destFLambda mk_clos hd1 in
let (_,ty2,bd2) = destFLambda mk_clos hd2 in
ccnv univ CONV infos el1 el2 ty1 ty2;
ccnv univ CONV infos (el_lift el1) (el_lift el2) bd1 bd2
| (FProd (_,c1,c2), FProd (_,c'1,c'2)) ->
assert (is_empty_stack v1 && is_empty_stack v2);
(* Luo's system *)
ccnv univ CONV infos el1 el2 c1 c'1;
ccnv univ cv_pb infos (el_lift el1) (el_lift el2) c2 c'2
Eta - expansion on the fly
| (FLambda _, _) ->
if v1 <> [] then
anomaly (Pp.str "conversion was given unreduced term (FLambda)");
let (_,_ty1,bd1) = destFLambda mk_clos hd1 in
eqappr univ CONV infos
(el_lift lft1,(bd1,[])) (el_lift lft2,(hd2,eta_expand_stack v2))
| (_, FLambda _) ->
if v2 <> [] then
anomaly (Pp.str "conversion was given unreduced term (FLambda)");
let (_,_ty2,bd2) = destFLambda mk_clos hd2 in
eqappr univ CONV infos
(el_lift lft1,(hd1,eta_expand_stack v1)) (el_lift lft2,(bd2,[]))
only one constant , defined var or defined rel
| (FFlex fl1, c2) ->
(match unfold_reference infos fl1 with
| Some def1 ->
eqappr univ cv_pb infos (lft1, whd_stack infos def1 v1) appr2
| None ->
match c2 with
| FConstruct ((ind2,j2),u2) ->
(try
let v2, v1 =
eta_expand_ind_stack (infos_env infos) ind2 hd2 v2 (snd appr1)
in convert_stacks univ infos lft1 lft2 v1 v2
with Not_found -> raise NotConvertible)
| _ -> raise NotConvertible)
| (c1, FFlex fl2) ->
(match unfold_reference infos fl2 with
| Some def2 ->
eqappr univ cv_pb infos appr1 (lft2, whd_stack infos def2 v2)
| None ->
match c1 with
| FConstruct ((ind1,j1),u1) ->
(try let v1, v2 =
eta_expand_ind_stack (infos_env infos) ind1 hd1 v1 (snd appr2)
in convert_stacks univ infos lft1 lft2 v1 v2
with Not_found -> raise NotConvertible)
| _ -> raise NotConvertible)
Inductive types : MutInd MutConstruct Fix Cofix
| (FInd (ind1,u1), FInd (ind2,u2)) ->
if mind_equiv_infos infos ind1 ind2
then
(let () = convert_universes univ u1 u2 in
convert_stacks univ infos lft1 lft2 v1 v2)
else raise NotConvertible
| (FConstruct ((ind1,j1),u1), FConstruct ((ind2,j2),u2)) ->
if Int.equal j1 j2 && mind_equiv_infos infos ind1 ind2
then
(let () = convert_universes univ u1 u2 in
convert_stacks univ infos lft1 lft2 v1 v2)
else raise NotConvertible
Eta expansion of records
| (FConstruct ((ind1,j1),u1), _) ->
(try
let v1, v2 =
eta_expand_ind_stack (infos_env infos) ind1 hd1 v1 (snd appr2)
in convert_stacks univ infos lft1 lft2 v1 v2
with Not_found -> raise NotConvertible)
| (_, FConstruct ((ind2,j2),u2)) ->
(try
let v2, v1 =
eta_expand_ind_stack (infos_env infos) ind2 hd2 v2 (snd appr1)
in convert_stacks univ infos lft1 lft2 v1 v2
with Not_found -> raise NotConvertible)
| (FFix ((op1,(_,tys1,cl1)),e1), FFix((op2,(_,tys2,cl2)),e2)) ->
if op1 = op2
then
let n = Array.length cl1 in
let fty1 = Array.map (mk_clos e1) tys1 in
let fty2 = Array.map (mk_clos e2) tys2 in
let fcl1 = Array.map (mk_clos (subs_liftn n e1)) cl1 in
let fcl2 = Array.map (mk_clos (subs_liftn n e2)) cl2 in
convert_vect univ infos el1 el2 fty1 fty2;
convert_vect univ infos
(el_liftn n el1) (el_liftn n el2) fcl1 fcl2;
convert_stacks univ infos lft1 lft2 v1 v2
else raise NotConvertible
| (FCoFix ((op1,(_,tys1,cl1)),e1), FCoFix((op2,(_,tys2,cl2)),e2)) ->
if op1 = op2
then
let n = Array.length cl1 in
let fty1 = Array.map (mk_clos e1) tys1 in
let fty2 = Array.map (mk_clos e2) tys2 in
let fcl1 = Array.map (mk_clos (subs_liftn n e1)) cl1 in
let fcl2 = Array.map (mk_clos (subs_liftn n e2)) cl2 in
convert_vect univ infos el1 el2 fty1 fty2;
convert_vect univ infos
(el_liftn n el1) (el_liftn n el2) fcl1 fcl2;
convert_stacks univ infos lft1 lft2 v1 v2
else raise NotConvertible
Should not happen because both ( hd1,v1 ) and ( hd2,v2 ) are in whnf
| ( (FLetIn _, _) | (FCases _,_) | (FApp _,_) | (FCLOS _,_) | (FLIFT _,_)
| (_, FLetIn _) | (_,FCases _) | (_,FApp _) | (_,FCLOS _) | (_,FLIFT _)
| (FLOCKED,_) | (_,FLOCKED) ) -> assert false
(* In all other cases, terms are not convertible *)
| _ -> raise NotConvertible
and convert_stacks univ infos lft1 lft2 stk1 stk2 =
compare_stacks
(fun (l1,t1) (l2,t2) -> ccnv univ CONV infos l1 l2 t1 t2)
(mind_equiv_infos infos)
lft1 stk1 lft2 stk2
and convert_vect univ infos lft1 lft2 v1 v2 =
Array.iter2 (fun t1 t2 -> ccnv univ CONV infos lft1 lft2 t1 t2) v1 v2
let clos_fconv cv_pb env t1 t2 =
let infos = create_clos_infos betaiotazeta env in
let univ = universes env in
ccnv univ cv_pb infos el_id el_id (inject t1) (inject t2)
let fconv cv_pb env t1 t2 =
if eq_constr t1 t2 then ()
else clos_fconv cv_pb env t1 t2
let conv = fconv CONV
let conv_leq = fconv CUMUL
(* option for conversion : no compilation for the checker *)
let vm_conv = fconv
(********************************************************************)
(* Special-Purpose Reduction *)
(********************************************************************)
pseudo - reduction rule :
* [ hnf_prod_app env s ( Prod(_,B ) ) N -- > B[N ]
* with an HNF on the first argument to produce a product .
* if this does not work , then we use the string S as part of our
* error message .
* [hnf_prod_app env s (Prod(_,B)) N --> B[N]
* with an HNF on the first argument to produce a product.
* if this does not work, then we use the string S as part of our
* error message. *)
let hnf_prod_app env t n =
match whd_betadeltaiota env t with
| Prod (_,_,b) -> subst1 n b
| _ -> anomaly ~label:"hnf_prod_app" (Pp.str "Need a product")
let hnf_prod_applist env t nl =
List.fold_left (hnf_prod_app env) t nl
(* Dealing with arities *)
let dest_prod env =
let rec decrec env m c =
let t = whd_betadeltaiota env c in
match t with
| Prod (n,a,c0) ->
let d = (n,None,a) in
decrec (push_rel d env) (d::m) c0
| _ -> m,t
in
decrec env empty_rel_context
(* The same but preserving lets in the context, not internal ones. *)
let dest_prod_assum env =
let rec prodec_rec env l ty =
let rty = whd_betadeltaiota_nolet env ty in
match rty with
| Prod (x,t,c) ->
let d = (x,None,t) in
prodec_rec (push_rel d env) (d::l) c
| LetIn (x,b,t,c) ->
let d = (x,Some b,t) in
prodec_rec (push_rel d env) (d::l) c
| Cast (c,_,_) -> prodec_rec env l c
| _ ->
let rty' = whd_betadeltaiota env rty in
if Term.eq_constr rty' rty then l, rty
else prodec_rec env l rty'
in
prodec_rec env empty_rel_context
let dest_lam_assum env =
let rec lamec_rec env l ty =
let rty = whd_betadeltaiota_nolet env ty in
match rty with
| Lambda (x,t,c) ->
let d = (x,None,t) in
lamec_rec (push_rel d env) (d::l) c
| LetIn (x,b,t,c) ->
let d = (x,Some b,t) in
lamec_rec (push_rel d env) (d::l) c
| Cast (c,_,_) -> lamec_rec env l c
| _ -> l,rty
in
lamec_rec env empty_rel_context
let dest_arity env c =
let l, c = dest_prod_assum env c in
match c with
| Sort s -> l,s
| _ -> error "not an arity"
| null | https://raw.githubusercontent.com/pirapira/coq2rust/22e8aaefc723bfb324ca2001b2b8e51fcc923543/checker/reduction.ml | ocaml | **********************************************************************
// * This file is distributed under the terms of the
* GNU Lesser General Public License Version 2.1
**********************************************************************
Compute the lift to be performed on a term placed in a given stack
&& c1.ci_ind = c2.ci_ind
**************************************************************************
Reduction Functions
**************************************************************************
Beta
******************************************************************
Conversion
******************************************************************
Conversion utility functions
Convertibility of sorts
height c1 > height c2
Conversion between [lft1]term1 and [lft2]term2
Conversion between [lft1](hd1 v1) and [lft2](hd2 v2)
case of leaves
else the oracle tells which constant is to be expanded
other constructors
Inconsistency: we tolerate that v1, v2 contain shift and update but
we throw them away
Luo's system
In all other cases, terms are not convertible
option for conversion : no compilation for the checker
******************************************************************
Special-Purpose Reduction
******************************************************************
Dealing with arities
The same but preserving lets in the context, not internal ones. | v * The Coq Proof Assistant / The Coq Development Team
< O _ _ _ , , * INRIA - CNRS - LIX - LRI - PPS - Copyright 1999 - 2012
\VV/ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
open Errors
open Util
open Cic
open Term
open Closure
open Esubst
open Environ
let rec is_empty_stack = function
[] -> true
| Zupdate _::s -> is_empty_stack s
| Zshift _::s -> is_empty_stack s
| _ -> false
let el_stack el stk =
let n =
List.fold_left
(fun i z ->
match z with
Zshift n -> i+n
| _ -> i)
0
stk in
el_shft n el
let compare_stack_shape stk1 stk2 =
let rec compare_rec bal stk1 stk2 =
match (stk1,stk2) with
([],[]) -> bal=0
| ((Zupdate _|Zshift _)::s1, _) -> compare_rec bal s1 stk2
| (_, (Zupdate _|Zshift _)::s2) -> compare_rec bal stk1 s2
| (Zapp l1::s1, _) -> compare_rec (bal+Array.length l1) s1 stk2
| (_, Zapp l2::s2) -> compare_rec (bal-Array.length l2) stk1 s2
| (Zproj (n1,m1,p1)::s1, Zproj (n2,m2,p2)::s2) ->
Int.equal bal 0 && compare_rec 0 s1 s2
| (Zcase(c1,_,_)::s1, Zcase(c2,_,_)::s2) ->
| (Zfix(_,a1)::s1, Zfix(_,a2)::s2) ->
bal=0 && compare_rec 0 a1 a2 && compare_rec 0 s1 s2
| (_,_) -> false in
compare_rec 0 stk1 stk2
type lft_constr_stack_elt =
Zlapp of (lift * fconstr) array
| Zlproj of Names.constant * lift
| Zlfix of (lift * fconstr) * lft_constr_stack
| Zlcase of case_info * lift * fconstr * fconstr array
and lft_constr_stack = lft_constr_stack_elt list
let rec zlapp v = function
Zlapp v2 :: s -> zlapp (Array.append v v2) s
| s -> Zlapp v :: s
let pure_stack lfts stk =
let rec pure_rec lfts stk =
match stk with
[] -> (lfts,[])
| zi::s ->
(match (zi,pure_rec lfts s) with
(Zupdate _,lpstk) -> lpstk
| (Zshift n,(l,pstk)) -> (el_shft n l, pstk)
| (Zapp a, (l,pstk)) ->
(l,zlapp (Array.map (fun t -> (l,t)) a) pstk)
| (Zproj (n,m,c), (l,pstk)) ->
(l, Zlproj (c,l)::pstk)
| (Zfix(fx,a),(l,pstk)) ->
let (lfx,pa) = pure_rec l a in
(l, Zlfix((lfx,fx),pa)::pstk)
| (Zcase(ci,p,br),(l,pstk)) ->
(l,Zlcase(ci,l,p,br)::pstk)) in
snd (pure_rec lfts stk)
let whd_betaiotazeta x =
match x with
| (Sort _|Var _|Meta _|Evar _|Const _|Ind _|Construct _|
Prod _|Lambda _|Fix _|CoFix _) -> x
| _ -> whd_val (create_clos_infos betaiotazeta empty_env) (inject x)
let whd_betadeltaiota env t =
match t with
| (Sort _|Meta _|Evar _|Ind _|Construct _|
Prod _|Lambda _|Fix _|CoFix _) -> t
| _ -> whd_val (create_clos_infos betadeltaiota env) (inject t)
let whd_betadeltaiota_nolet env t =
match t with
| (Sort _|Meta _|Evar _|Ind _|Construct _|
Prod _|Lambda _|Fix _|CoFix _|LetIn _) -> t
| _ -> whd_val (create_clos_infos betadeltaiotanolet env) (inject t)
let beta_appvect c v =
let rec stacklam env t stack =
match t, stack with
Lambda(_,_,c), arg::stacktl -> stacklam (arg::env) c stacktl
| _ -> applist (substl env t, stack) in
stacklam [] c (Array.to_list v)
type 'a conversion_function = env -> 'a -> 'a -> unit
exception NotConvertible
exception NotConvertibleVect of int
let convert_universes univ u u' =
if Univ.Instance.check_eq univ u u' then ()
else raise NotConvertible
let compare_stacks f fmind lft1 stk1 lft2 stk2 =
let rec cmp_rec pstk1 pstk2 =
match (pstk1,pstk2) with
| (z1::s1, z2::s2) ->
cmp_rec s1 s2;
(match (z1,z2) with
| (Zlapp a1,Zlapp a2) -> Array.iter2 f a1 a2
| (Zlfix(fx1,a1),Zlfix(fx2,a2)) ->
f fx1 fx2; cmp_rec a1 a2
| (Zlproj (c1,l1),Zlproj (c2,l2)) ->
if not (Names.eq_con_chk c1 c2) then
raise NotConvertible
| (Zlcase(ci1,l1,p1,br1),Zlcase(ci2,l2,p2,br2)) ->
if not (fmind ci1.ci_ind ci2.ci_ind) then
raise NotConvertible;
f (l1,p1) (l2,p2);
Array.iter2 (fun c1 c2 -> f (l1,c1) (l2,c2)) br1 br2
| _ -> assert false)
| _ -> () in
if compare_stack_shape stk1 stk2 then
cmp_rec (pure_stack lft1 stk1) (pure_stack lft2 stk2)
else raise NotConvertible
type conv_pb =
| CONV
| CUMUL
let sort_cmp univ pb s0 s1 =
match (s0,s1) with
| (Prop c1, Prop c2) when pb = CUMUL -> if c1 = Pos && c2 = Null then raise NotConvertible
| (Prop c1, Prop c2) -> if c1 <> c2 then raise NotConvertible
| (Prop c1, Type u) ->
(match pb with
CUMUL -> ()
| _ -> raise NotConvertible)
| (Type u1, Type u2) ->
if not
(match pb with
| CONV -> Univ.check_eq univ u1 u2
| CUMUL -> Univ.check_leq univ u1 u2)
then raise NotConvertible
| (_, _) -> raise NotConvertible
let rec no_arg_available = function
| [] -> true
| Zupdate _ :: stk -> no_arg_available stk
| Zshift _ :: stk -> no_arg_available stk
| Zapp v :: stk -> Array.length v = 0 && no_arg_available stk
| Zproj _ :: _ -> true
| Zcase _ :: _ -> true
| Zfix _ :: _ -> true
let rec no_nth_arg_available n = function
| [] -> true
| Zupdate _ :: stk -> no_nth_arg_available n stk
| Zshift _ :: stk -> no_nth_arg_available n stk
| Zapp v :: stk ->
let k = Array.length v in
if n >= k then no_nth_arg_available (n-k) stk
else false
| Zproj _ :: _ -> true
| Zcase _ :: _ -> true
| Zfix _ :: _ -> true
let rec no_case_available = function
| [] -> true
| Zupdate _ :: stk -> no_case_available stk
| Zshift _ :: stk -> no_case_available stk
| Zapp _ :: stk -> no_case_available stk
| Zproj (_,_,_) :: _ -> false
| Zcase _ :: _ -> false
| Zfix _ :: _ -> true
let in_whnf (t,stk) =
match fterm_of t with
| (FLetIn _ | FCases _ | FApp _ | FCLOS _ | FLIFT _ | FCast _) -> false
| FLambda _ -> no_arg_available stk
| FConstruct _ -> no_case_available stk
| FCoFix _ -> no_case_available stk
| FFix(((ri,n),(_,_,_)),_) -> no_nth_arg_available ri.(n) stk
| (FFlex _ | FProd _ | FEvar _ | FInd _ | FAtom _ | FRel _ | FProj _) -> true
| FLOCKED -> assert false
let oracle_order fl1 fl2 =
match fl1,fl2 with
| _, ConstKey _ -> true
| _ -> false
let unfold_projection infos p c =
let pb = lookup_projection p (infos_env infos) in
let s = Zproj (pb.proj_npars, pb.proj_arg, p) in
(c, s)
let rec ccnv univ cv_pb infos lft1 lft2 term1 term2 =
eqappr univ cv_pb infos (lft1, (term1,[])) (lft2, (term2,[]))
and eqappr univ cv_pb infos (lft1,st1) (lft2,st2) =
Control.check_for_interrupt ();
First head reduce both terms
let rec whd_both (t1,stk1) (t2,stk2) =
let st1' = whd_stack infos t1 stk1 in
let st2' = whd_stack infos t2 stk2 in
Now , whd_stack on might have modified ( due to sharing ) ,
and st1 might not be in whnf anymore . If so , we iterate ccnv .
and st1 might not be in whnf anymore. If so, we iterate ccnv. *)
if in_whnf st1' then (st1',st2') else whd_both st1' st2' in
let ((hd1,v1),(hd2,v2)) = whd_both st1 st2 in
let appr1 = (lft1,(hd1,v1)) and appr2 = (lft2,(hd2,v2)) in
compute the lifts that apply to the head of the term ( hd1 and )
let el1 = el_stack lft1 v1 in
let el2 = el_stack lft2 v2 in
match (fterm_of hd1, fterm_of hd2) with
| (FAtom a1, FAtom a2) ->
(match a1, a2 with
| (Sort s1, Sort s2) ->
assert (is_empty_stack v1 && is_empty_stack v2);
sort_cmp univ cv_pb s1 s2
| (Meta n, Meta m) ->
if n=m
then convert_stacks univ infos lft1 lft2 v1 v2
else raise NotConvertible
| _ -> raise NotConvertible)
| (FEvar (ev1,args1), FEvar (ev2,args2)) ->
if ev1=ev2 then
(convert_stacks univ infos lft1 lft2 v1 v2;
convert_vect univ infos el1 el2 args1 args2)
else raise NotConvertible
2 index known to be bound to no constant
| (FRel n, FRel m) ->
if reloc_rel n el1 = reloc_rel m el2
then convert_stacks univ infos lft1 lft2 v1 v2
else raise NotConvertible
2 constants , 2 local defined vars or 2 defined rels
| (FFlex fl1, FFlex fl2) ->
try first intensional equality
if eq_table_key fl1 fl2
then convert_stacks univ infos lft1 lft2 v1 v2
else raise NotConvertible
with NotConvertible ->
let (app1,app2) =
if oracle_order fl1 fl2 then
match unfold_reference infos fl1 with
| Some def1 -> ((lft1, whd_stack infos def1 v1), appr2)
| None ->
(match unfold_reference infos fl2 with
| Some def2 -> (appr1, (lft2, whd_stack infos def2 v2))
| None -> raise NotConvertible)
else
match unfold_reference infos fl2 with
| Some def2 -> (appr1, (lft2, whd_stack infos def2 v2))
| None ->
(match unfold_reference infos fl1 with
| Some def1 -> ((lft1, whd_stack infos def1 v1), appr2)
| None -> raise NotConvertible) in
eqappr univ cv_pb infos app1 app2)
| (FProj (p1,c1), _) ->
let (def1, s1) = unfold_projection infos p1 c1 in
eqappr univ cv_pb infos (lft1, whd_stack infos def1 (s1 :: v1)) appr2
| (_, FProj (p2,c2)) ->
let (def2, s2) = unfold_projection infos p2 c2 in
eqappr univ cv_pb infos appr1 (lft2, whd_stack infos def2 (s2 :: v2))
| (FLambda _, FLambda _) ->
assert (is_empty_stack v1 && is_empty_stack v2);
let (_,ty1,bd1) = destFLambda mk_clos hd1 in
let (_,ty2,bd2) = destFLambda mk_clos hd2 in
ccnv univ CONV infos el1 el2 ty1 ty2;
ccnv univ CONV infos (el_lift el1) (el_lift el2) bd1 bd2
| (FProd (_,c1,c2), FProd (_,c'1,c'2)) ->
assert (is_empty_stack v1 && is_empty_stack v2);
ccnv univ CONV infos el1 el2 c1 c'1;
ccnv univ cv_pb infos (el_lift el1) (el_lift el2) c2 c'2
Eta - expansion on the fly
| (FLambda _, _) ->
if v1 <> [] then
anomaly (Pp.str "conversion was given unreduced term (FLambda)");
let (_,_ty1,bd1) = destFLambda mk_clos hd1 in
eqappr univ CONV infos
(el_lift lft1,(bd1,[])) (el_lift lft2,(hd2,eta_expand_stack v2))
| (_, FLambda _) ->
if v2 <> [] then
anomaly (Pp.str "conversion was given unreduced term (FLambda)");
let (_,_ty2,bd2) = destFLambda mk_clos hd2 in
eqappr univ CONV infos
(el_lift lft1,(hd1,eta_expand_stack v1)) (el_lift lft2,(bd2,[]))
only one constant , defined var or defined rel
| (FFlex fl1, c2) ->
(match unfold_reference infos fl1 with
| Some def1 ->
eqappr univ cv_pb infos (lft1, whd_stack infos def1 v1) appr2
| None ->
match c2 with
| FConstruct ((ind2,j2),u2) ->
(try
let v2, v1 =
eta_expand_ind_stack (infos_env infos) ind2 hd2 v2 (snd appr1)
in convert_stacks univ infos lft1 lft2 v1 v2
with Not_found -> raise NotConvertible)
| _ -> raise NotConvertible)
| (c1, FFlex fl2) ->
(match unfold_reference infos fl2 with
| Some def2 ->
eqappr univ cv_pb infos appr1 (lft2, whd_stack infos def2 v2)
| None ->
match c1 with
| FConstruct ((ind1,j1),u1) ->
(try let v1, v2 =
eta_expand_ind_stack (infos_env infos) ind1 hd1 v1 (snd appr2)
in convert_stacks univ infos lft1 lft2 v1 v2
with Not_found -> raise NotConvertible)
| _ -> raise NotConvertible)
Inductive types : MutInd MutConstruct Fix Cofix
| (FInd (ind1,u1), FInd (ind2,u2)) ->
if mind_equiv_infos infos ind1 ind2
then
(let () = convert_universes univ u1 u2 in
convert_stacks univ infos lft1 lft2 v1 v2)
else raise NotConvertible
| (FConstruct ((ind1,j1),u1), FConstruct ((ind2,j2),u2)) ->
if Int.equal j1 j2 && mind_equiv_infos infos ind1 ind2
then
(let () = convert_universes univ u1 u2 in
convert_stacks univ infos lft1 lft2 v1 v2)
else raise NotConvertible
Eta expansion of records
| (FConstruct ((ind1,j1),u1), _) ->
(try
let v1, v2 =
eta_expand_ind_stack (infos_env infos) ind1 hd1 v1 (snd appr2)
in convert_stacks univ infos lft1 lft2 v1 v2
with Not_found -> raise NotConvertible)
| (_, FConstruct ((ind2,j2),u2)) ->
(try
let v2, v1 =
eta_expand_ind_stack (infos_env infos) ind2 hd2 v2 (snd appr1)
in convert_stacks univ infos lft1 lft2 v1 v2
with Not_found -> raise NotConvertible)
| (FFix ((op1,(_,tys1,cl1)),e1), FFix((op2,(_,tys2,cl2)),e2)) ->
if op1 = op2
then
let n = Array.length cl1 in
let fty1 = Array.map (mk_clos e1) tys1 in
let fty2 = Array.map (mk_clos e2) tys2 in
let fcl1 = Array.map (mk_clos (subs_liftn n e1)) cl1 in
let fcl2 = Array.map (mk_clos (subs_liftn n e2)) cl2 in
convert_vect univ infos el1 el2 fty1 fty2;
convert_vect univ infos
(el_liftn n el1) (el_liftn n el2) fcl1 fcl2;
convert_stacks univ infos lft1 lft2 v1 v2
else raise NotConvertible
| (FCoFix ((op1,(_,tys1,cl1)),e1), FCoFix((op2,(_,tys2,cl2)),e2)) ->
if op1 = op2
then
let n = Array.length cl1 in
let fty1 = Array.map (mk_clos e1) tys1 in
let fty2 = Array.map (mk_clos e2) tys2 in
let fcl1 = Array.map (mk_clos (subs_liftn n e1)) cl1 in
let fcl2 = Array.map (mk_clos (subs_liftn n e2)) cl2 in
convert_vect univ infos el1 el2 fty1 fty2;
convert_vect univ infos
(el_liftn n el1) (el_liftn n el2) fcl1 fcl2;
convert_stacks univ infos lft1 lft2 v1 v2
else raise NotConvertible
Should not happen because both ( hd1,v1 ) and ( hd2,v2 ) are in whnf
| ( (FLetIn _, _) | (FCases _,_) | (FApp _,_) | (FCLOS _,_) | (FLIFT _,_)
| (_, FLetIn _) | (_,FCases _) | (_,FApp _) | (_,FCLOS _) | (_,FLIFT _)
| (FLOCKED,_) | (_,FLOCKED) ) -> assert false
| _ -> raise NotConvertible
and convert_stacks univ infos lft1 lft2 stk1 stk2 =
compare_stacks
(fun (l1,t1) (l2,t2) -> ccnv univ CONV infos l1 l2 t1 t2)
(mind_equiv_infos infos)
lft1 stk1 lft2 stk2
and convert_vect univ infos lft1 lft2 v1 v2 =
Array.iter2 (fun t1 t2 -> ccnv univ CONV infos lft1 lft2 t1 t2) v1 v2
let clos_fconv cv_pb env t1 t2 =
let infos = create_clos_infos betaiotazeta env in
let univ = universes env in
ccnv univ cv_pb infos el_id el_id (inject t1) (inject t2)
let fconv cv_pb env t1 t2 =
if eq_constr t1 t2 then ()
else clos_fconv cv_pb env t1 t2
let conv = fconv CONV
let conv_leq = fconv CUMUL
let vm_conv = fconv
pseudo - reduction rule :
* [ hnf_prod_app env s ( Prod(_,B ) ) N -- > B[N ]
* with an HNF on the first argument to produce a product .
* if this does not work , then we use the string S as part of our
* error message .
* [hnf_prod_app env s (Prod(_,B)) N --> B[N]
* with an HNF on the first argument to produce a product.
* if this does not work, then we use the string S as part of our
* error message. *)
let hnf_prod_app env t n =
match whd_betadeltaiota env t with
| Prod (_,_,b) -> subst1 n b
| _ -> anomaly ~label:"hnf_prod_app" (Pp.str "Need a product")
let hnf_prod_applist env t nl =
List.fold_left (hnf_prod_app env) t nl
let dest_prod env =
let rec decrec env m c =
let t = whd_betadeltaiota env c in
match t with
| Prod (n,a,c0) ->
let d = (n,None,a) in
decrec (push_rel d env) (d::m) c0
| _ -> m,t
in
decrec env empty_rel_context
let dest_prod_assum env =
let rec prodec_rec env l ty =
let rty = whd_betadeltaiota_nolet env ty in
match rty with
| Prod (x,t,c) ->
let d = (x,None,t) in
prodec_rec (push_rel d env) (d::l) c
| LetIn (x,b,t,c) ->
let d = (x,Some b,t) in
prodec_rec (push_rel d env) (d::l) c
| Cast (c,_,_) -> prodec_rec env l c
| _ ->
let rty' = whd_betadeltaiota env rty in
if Term.eq_constr rty' rty then l, rty
else prodec_rec env l rty'
in
prodec_rec env empty_rel_context
let dest_lam_assum env =
let rec lamec_rec env l ty =
let rty = whd_betadeltaiota_nolet env ty in
match rty with
| Lambda (x,t,c) ->
let d = (x,None,t) in
lamec_rec (push_rel d env) (d::l) c
| LetIn (x,b,t,c) ->
let d = (x,Some b,t) in
lamec_rec (push_rel d env) (d::l) c
| Cast (c,_,_) -> lamec_rec env l c
| _ -> l,rty
in
lamec_rec env empty_rel_context
let dest_arity env c =
let l, c = dest_prod_assum env c in
match c with
| Sort s -> l,s
| _ -> error "not an arity"
|
5fc8fe1b55117188c32610cd935243d9e5d6b1c3c6debdace3da7ad1e1393201 | inria-parkas/sundialsml | idasAkzoNob_dns.ml |
* -----------------------------------------------------------------
* $ Revision : 1.2 $
* $ Date : 2009/09/30 23:33:29 $
* -----------------------------------------------------------------
* Programmer(s ): and @ LLNL
* -----------------------------------------------------------------
* OCaml port : , , Jul 2014 .
* -----------------------------------------------------------------
* Copyright ( c ) 2007 , The Regents of the University of California .
* Produced at the Lawrence Livermore National Laboratory .
* All rights reserved .
* For details , see the LICENSE file .
* -----------------------------------------------------------------
* Adjoint sensitivity example problem
*
* This IVP is a stiff system of 6 non - linear DAEs of index 1 . The
* problem originates from Akzo Nobel Central research in ,
* The Netherlands , and describes a chemical process in which 2
* species are mixed , while carbon dioxide is continuously added .
* See /~testset/report/chemakzo.pdf
*
* -----------------------------------------------------------------
* -----------------------------------------------------------------
* $Revision: 1.2 $
* $Date: 2009/09/30 23:33:29 $
* -----------------------------------------------------------------
* Programmer(s): Radu Serban and Cosmin Petra @ LLNL
* -----------------------------------------------------------------
* OCaml port: Jun Inoue, Inria, Jul 2014.
* -----------------------------------------------------------------
* Copyright (c) 2007, The Regents of the University of California.
* Produced at the Lawrence Livermore National Laboratory.
* All rights reserved.
* For details, see the LICENSE file.
* -----------------------------------------------------------------
* Adjoint sensitivity example problem
*
* This IVP is a stiff system of 6 non-linear DAEs of index 1. The
* problem originates from Akzo Nobel Central research in Arnhern,
* The Netherlands, and describes a chemical process in which 2
* species are mixed, while carbon dioxide is continuously added.
* See /~testset/report/chemakzo.pdf
*
* -----------------------------------------------------------------
*)
open Sundials
module Quad = Idas.Quadrature
module Sens = Idas.Sensitivity
module QuadSens = Idas.Sensitivity.Quadrature
let printf = Printf.printf
let nvconst = Nvector_serial.DataOps.const
let nvscale = Nvector_serial.DataOps.scale
let r_power_i base exponent =
let go expt =
let r = ref 1.0 in
for _ = 0 to expt - 1 do
r := !r *. base
done;
!r
in
if exponent < 0 then 1. /. go (- exponent)
else go exponent
(* Problem Constants *)
let neq = 6
let t0 = 0.0
first time for output
let tf = 180.0 (* Final time. *)
let nf = 25 (* Total number of outputs. *)
let rtol = 1.0e-08
let atol = 1.0e-10
let rtolq = 1.0e-10
let atolq = 1.0e-12
type user_data = { k1 : float;
k2 : float;
k3 : float;
k4 : float;
k : float;
klA : float;
ks : float;
pCO2 : float;
h : float;
}
let res data _ (y : RealArray.t) (yd : RealArray.t) (res : RealArray.t) =
let k1 = data.k1
and k2 = data.k2
and k3 = data.k3
and k4 = data.k4
and k = data.k
and klA = data.klA
and ks = data.ks
and pCO2 = data.pCO2
and h = data.h
in
let r1 = k1 *. (r_power_i y.{0} 4) *. sqrt y.{1}
and r2 = k2 *. y.{2} *. y.{3}
and r3 = k2/.k *. y.{0} *. y.{4}
and r4 = k3 *. y.{0} *. y.{3} *. y.{3}
and r5 = k4 *. y.{5} *. y.{5} *. sqrt y.{1}
and fin = klA *. ( pCO2/.h -. y.{1} )
in
res.{0} <- yd.{0} +. 2.0*.r1 -. r2 +. r3 +. r4;
res.{1} <- yd.{1} +. 0.5*.r1 +. r4 +. 0.5*.r5 -. fin;
res.{2} <- yd.{2} -. r1 +. r2 -. r3;
res.{3} <- yd.{3} +. r2 -. r3 +. 2.0*.r4;
res.{4} <- yd.{4} -. r2 +. r3 -. r5;
res.{5} <- ks*.y.{0}*.y.{3} -. y.{5}
* rhsQ routine . Computes quadrature(t , y ) .
* rhsQ routine. Computes quadrature(t,y).
*)
let rhsQ _ _ (yy : RealArray.t) _ (qdot : RealArray.t) = qdot.{0} <- yy.{0}
let idadense =
match Config.sundials_version with 2,_,_ -> "IDADENSE" | _ -> "DENSE"
let print_header rtol avtol _ =
print_string "\nidasAkzoNob_dns: Akzo Nobel chemical kinetics DAE serial example problem for IDAS\n";
printf "Linear solver: %s, Jacobian is computed by IDAS.\n" idadense;
printf "Tolerance parameters: rtol = %g atol = %g\n"
rtol avtol;
print_string "---------------------------------------------------------------------------------\n";
print_string " t y1 y2 y3 y4 y5";
print_string " y6 | nst k h\n";
print_string "---------------------------------------------------------------------------------\n"
let print_output mem t y =
let kused = Ida.get_last_order mem
and nst = Ida.get_num_steps mem
and hused = Ida.get_last_step mem
in
printf "%8.2e %8.2e %8.2e %8.2e %8.2e %8.2e %8.2e | %3d %1d %8.2e\n"
t y.{0} y.{1} y.{2} y.{3} y.{4} y.{5} nst kused hused
let print_final_stats mem =
let open Ida in
let nst = get_num_steps mem
and nre = get_num_res_evals mem
and nje = Dls.get_num_jac_evals mem
and nni = get_num_nonlin_solv_iters mem
and netf = get_num_err_test_fails mem
and ncfn = get_num_nonlin_solv_conv_fails mem
and nreLS = Dls.get_num_lin_res_evals mem
in
print_string "\nFinal Run Statistics: \n\n";
print_string "Number of steps = "; print_int nst;
print_string "\nNumber of residual evaluations = "; print_int (nre+nreLS);
print_string "\nNumber of Jacobian evaluations = "; print_int nje;
print_string "\nNumber of nonlinear iterations = "; print_int nni;
print_string "\nNumber of error test failures = "; print_int netf;
print_string "\nNumber of nonlinear conv. failures = "; print_int ncfn;
print_newline ()
Main program
let main () =
(* Fill user's data with the appropriate values for coefficients. *)
let data = { k1 = 18.7;
k2 = 0.58;
k3 = 0.09;
k4 = 0.42;
k = 34.4;
klA = 3.3;
ks = 115.83;
pCO2 = 0.9;
h = 737.0; }
in
(* Allocate N-vectors. *)
let yy = RealArray.create neq
and yp = RealArray.create neq
in
(* Consistent IC for y, y'. *)
let y01 =0.444
and y02 =0.00123
and y03 =0.00
and y04 =0.007
and y05 =0.0
in
yy.{0} <- y01;
yy.{1} <- y02;
yy.{2} <- y03;
yy.{3} <- y04;
yy.{4} <- y05;
yy.{5} <- data.ks *. y01 *. y04;
(* Get y' = - res(t0, y, 0) *)
nvconst 0.0 yp;
let rr = RealArray.create neq in
res data t0 yy yp rr;
nvscale (-1.0) rr yp;
Create and initialize q0 for quadratures .
let q = RealArray.create 1 in
q.{0} <- 0.0;
Wrap arrays in .
let wyy = Nvector_serial.wrap yy
and wyp = Nvector_serial.wrap yp
and wq = Nvector_serial.wrap q
in
Call IDACreate and IDAInit to initialize IDA memory
let m = Matrix.dense neq in
let mem = Ida.(init (SStolerances (rtol,atol))
~lsolver:Dls.(solver (dense wyy m))
(res data) t0 wyy wyp)
in
Initialize QUADRATURE(S ) .
Quad.init mem (rhsQ data) wq;
(* Set tolerances and error control for quadratures. *)
Quad.(set_tolerances mem (SStolerances (rtolq,atolq)));
print_header rtol atol yy;
(* Print initial states *)
print_output mem 0.0 yy;
let tout = ref t1
and incr = (tf/.t1) ** (1.0 /. float_of_int nf)
in
(* FORWARD run. *)
for _ = 0 to nf do
let (time, _) = Ida.solve_normal mem !tout wyy wyp in
print_output mem time yy;
tout := !tout *. incr;
done;
let _ = Quad.get mem wq in
print_string "\n--------------------------------------------------------\n";
printf "G: %24.16f \n" q.{0};
print_string "--------------------------------------------------------\n\n";
print_final_stats mem
(* Check environment variables for extra arguments. *)
let reps =
try int_of_string (Unix.getenv "NUM_REPS")
with Not_found | Failure _ -> 1
let gc_at_end =
try int_of_string (Unix.getenv "GC_AT_END") <> 0
with Not_found | Failure _ -> false
let gc_each_rep =
try int_of_string (Unix.getenv "GC_EACH_REP") <> 0
with Not_found | Failure _ -> false
(* Entry point *)
let _ =
for _ = 1 to reps do
main ();
if gc_each_rep then Gc.compact ()
done;
if gc_at_end then Gc.compact ()
| null | https://raw.githubusercontent.com/inria-parkas/sundialsml/a1848318cac2e340c32ddfd42671bef07b1390db/examples/idas/serial/idasAkzoNob_dns.ml | ocaml | Problem Constants
Final time.
Total number of outputs.
Fill user's data with the appropriate values for coefficients.
Allocate N-vectors.
Consistent IC for y, y'.
Get y' = - res(t0, y, 0)
Set tolerances and error control for quadratures.
Print initial states
FORWARD run.
Check environment variables for extra arguments.
Entry point |
* -----------------------------------------------------------------
* $ Revision : 1.2 $
* $ Date : 2009/09/30 23:33:29 $
* -----------------------------------------------------------------
* Programmer(s ): and @ LLNL
* -----------------------------------------------------------------
* OCaml port : , , Jul 2014 .
* -----------------------------------------------------------------
* Copyright ( c ) 2007 , The Regents of the University of California .
* Produced at the Lawrence Livermore National Laboratory .
* All rights reserved .
* For details , see the LICENSE file .
* -----------------------------------------------------------------
* Adjoint sensitivity example problem
*
* This IVP is a stiff system of 6 non - linear DAEs of index 1 . The
* problem originates from Akzo Nobel Central research in ,
* The Netherlands , and describes a chemical process in which 2
* species are mixed , while carbon dioxide is continuously added .
* See /~testset/report/chemakzo.pdf
*
* -----------------------------------------------------------------
* -----------------------------------------------------------------
* $Revision: 1.2 $
* $Date: 2009/09/30 23:33:29 $
* -----------------------------------------------------------------
* Programmer(s): Radu Serban and Cosmin Petra @ LLNL
* -----------------------------------------------------------------
* OCaml port: Jun Inoue, Inria, Jul 2014.
* -----------------------------------------------------------------
* Copyright (c) 2007, The Regents of the University of California.
* Produced at the Lawrence Livermore National Laboratory.
* All rights reserved.
* For details, see the LICENSE file.
* -----------------------------------------------------------------
* Adjoint sensitivity example problem
*
* This IVP is a stiff system of 6 non-linear DAEs of index 1. The
* problem originates from Akzo Nobel Central research in Arnhern,
* The Netherlands, and describes a chemical process in which 2
* species are mixed, while carbon dioxide is continuously added.
* See /~testset/report/chemakzo.pdf
*
* -----------------------------------------------------------------
*)
open Sundials
module Quad = Idas.Quadrature
module Sens = Idas.Sensitivity
module QuadSens = Idas.Sensitivity.Quadrature
let printf = Printf.printf
let nvconst = Nvector_serial.DataOps.const
let nvscale = Nvector_serial.DataOps.scale
let r_power_i base exponent =
let go expt =
let r = ref 1.0 in
for _ = 0 to expt - 1 do
r := !r *. base
done;
!r
in
if exponent < 0 then 1. /. go (- exponent)
else go exponent
let neq = 6
let t0 = 0.0
first time for output
let rtol = 1.0e-08
let atol = 1.0e-10
let rtolq = 1.0e-10
let atolq = 1.0e-12
type user_data = { k1 : float;
k2 : float;
k3 : float;
k4 : float;
k : float;
klA : float;
ks : float;
pCO2 : float;
h : float;
}
let res data _ (y : RealArray.t) (yd : RealArray.t) (res : RealArray.t) =
let k1 = data.k1
and k2 = data.k2
and k3 = data.k3
and k4 = data.k4
and k = data.k
and klA = data.klA
and ks = data.ks
and pCO2 = data.pCO2
and h = data.h
in
let r1 = k1 *. (r_power_i y.{0} 4) *. sqrt y.{1}
and r2 = k2 *. y.{2} *. y.{3}
and r3 = k2/.k *. y.{0} *. y.{4}
and r4 = k3 *. y.{0} *. y.{3} *. y.{3}
and r5 = k4 *. y.{5} *. y.{5} *. sqrt y.{1}
and fin = klA *. ( pCO2/.h -. y.{1} )
in
res.{0} <- yd.{0} +. 2.0*.r1 -. r2 +. r3 +. r4;
res.{1} <- yd.{1} +. 0.5*.r1 +. r4 +. 0.5*.r5 -. fin;
res.{2} <- yd.{2} -. r1 +. r2 -. r3;
res.{3} <- yd.{3} +. r2 -. r3 +. 2.0*.r4;
res.{4} <- yd.{4} -. r2 +. r3 -. r5;
res.{5} <- ks*.y.{0}*.y.{3} -. y.{5}
* rhsQ routine . Computes quadrature(t , y ) .
* rhsQ routine. Computes quadrature(t,y).
*)
let rhsQ _ _ (yy : RealArray.t) _ (qdot : RealArray.t) = qdot.{0} <- yy.{0}
let idadense =
match Config.sundials_version with 2,_,_ -> "IDADENSE" | _ -> "DENSE"
let print_header rtol avtol _ =
print_string "\nidasAkzoNob_dns: Akzo Nobel chemical kinetics DAE serial example problem for IDAS\n";
printf "Linear solver: %s, Jacobian is computed by IDAS.\n" idadense;
printf "Tolerance parameters: rtol = %g atol = %g\n"
rtol avtol;
print_string "---------------------------------------------------------------------------------\n";
print_string " t y1 y2 y3 y4 y5";
print_string " y6 | nst k h\n";
print_string "---------------------------------------------------------------------------------\n"
let print_output mem t y =
let kused = Ida.get_last_order mem
and nst = Ida.get_num_steps mem
and hused = Ida.get_last_step mem
in
printf "%8.2e %8.2e %8.2e %8.2e %8.2e %8.2e %8.2e | %3d %1d %8.2e\n"
t y.{0} y.{1} y.{2} y.{3} y.{4} y.{5} nst kused hused
let print_final_stats mem =
let open Ida in
let nst = get_num_steps mem
and nre = get_num_res_evals mem
and nje = Dls.get_num_jac_evals mem
and nni = get_num_nonlin_solv_iters mem
and netf = get_num_err_test_fails mem
and ncfn = get_num_nonlin_solv_conv_fails mem
and nreLS = Dls.get_num_lin_res_evals mem
in
print_string "\nFinal Run Statistics: \n\n";
print_string "Number of steps = "; print_int nst;
print_string "\nNumber of residual evaluations = "; print_int (nre+nreLS);
print_string "\nNumber of Jacobian evaluations = "; print_int nje;
print_string "\nNumber of nonlinear iterations = "; print_int nni;
print_string "\nNumber of error test failures = "; print_int netf;
print_string "\nNumber of nonlinear conv. failures = "; print_int ncfn;
print_newline ()
Main program
let main () =
let data = { k1 = 18.7;
k2 = 0.58;
k3 = 0.09;
k4 = 0.42;
k = 34.4;
klA = 3.3;
ks = 115.83;
pCO2 = 0.9;
h = 737.0; }
in
let yy = RealArray.create neq
and yp = RealArray.create neq
in
let y01 =0.444
and y02 =0.00123
and y03 =0.00
and y04 =0.007
and y05 =0.0
in
yy.{0} <- y01;
yy.{1} <- y02;
yy.{2} <- y03;
yy.{3} <- y04;
yy.{4} <- y05;
yy.{5} <- data.ks *. y01 *. y04;
nvconst 0.0 yp;
let rr = RealArray.create neq in
res data t0 yy yp rr;
nvscale (-1.0) rr yp;
Create and initialize q0 for quadratures .
let q = RealArray.create 1 in
q.{0} <- 0.0;
Wrap arrays in .
let wyy = Nvector_serial.wrap yy
and wyp = Nvector_serial.wrap yp
and wq = Nvector_serial.wrap q
in
Call IDACreate and IDAInit to initialize IDA memory
let m = Matrix.dense neq in
let mem = Ida.(init (SStolerances (rtol,atol))
~lsolver:Dls.(solver (dense wyy m))
(res data) t0 wyy wyp)
in
Initialize QUADRATURE(S ) .
Quad.init mem (rhsQ data) wq;
Quad.(set_tolerances mem (SStolerances (rtolq,atolq)));
print_header rtol atol yy;
print_output mem 0.0 yy;
let tout = ref t1
and incr = (tf/.t1) ** (1.0 /. float_of_int nf)
in
for _ = 0 to nf do
let (time, _) = Ida.solve_normal mem !tout wyy wyp in
print_output mem time yy;
tout := !tout *. incr;
done;
let _ = Quad.get mem wq in
print_string "\n--------------------------------------------------------\n";
printf "G: %24.16f \n" q.{0};
print_string "--------------------------------------------------------\n\n";
print_final_stats mem
let reps =
try int_of_string (Unix.getenv "NUM_REPS")
with Not_found | Failure _ -> 1
let gc_at_end =
try int_of_string (Unix.getenv "GC_AT_END") <> 0
with Not_found | Failure _ -> false
let gc_each_rep =
try int_of_string (Unix.getenv "GC_EACH_REP") <> 0
with Not_found | Failure _ -> false
let _ =
for _ = 1 to reps do
main ();
if gc_each_rep then Gc.compact ()
done;
if gc_at_end then Gc.compact ()
|
f50e6bbb5c6d0cb7abc80c32ce8461626e027d87631698f97be8a11ff8b9a5df | softwarelanguageslab/maf | R5RS_WeiChenRompf2019_the-little-schemer_ch2-5.scm | ; Changes:
* removed : 0
* added : 1
* swaps : 1
; * negated predicates: 0
; * swapped branches: 0
* calls to i d fun : 2
(letrec ((atom? (lambda (x)
(if (not (pair? x)) (not (null? x)) #f)))
(lat? (lambda (l)
(<change>
()
atom?)
(<change>
(if (null? l)
#t
(if (atom? (car l)) (lat? (cdr l)) #f))
((lambda (x) x) (if (null? l) #t (if (atom? (car l)) (lat? (cdr l)) #f)))))))
(<change>
(lat?
(__toplevel_cons
'Jack
(__toplevel_cons
'Sprat
(__toplevel_cons
'could
(__toplevel_cons 'eat (__toplevel_cons 'no (__toplevel_cons 'chicken (__toplevel_cons 'fat ()))))))))
(lat?
(__toplevel_cons
(__toplevel_cons 'Jack ())
(__toplevel_cons
'Sprat
(__toplevel_cons
'could
(__toplevel_cons 'eat (__toplevel_cons 'no (__toplevel_cons 'chicken (__toplevel_cons 'fat ())))))))))
(<change>
(lat?
(__toplevel_cons
(__toplevel_cons 'Jack ())
(__toplevel_cons
'Sprat
(__toplevel_cons
'could
(__toplevel_cons 'eat (__toplevel_cons 'no (__toplevel_cons 'chicken (__toplevel_cons 'fat ()))))))))
(lat?
(__toplevel_cons
'Jack
(__toplevel_cons
'Sprat
(__toplevel_cons
'could
(__toplevel_cons 'eat (__toplevel_cons 'no (__toplevel_cons 'chicken (__toplevel_cons 'fat ())))))))))
(lat?
(__toplevel_cons
'Jack
(__toplevel_cons
(__toplevel_cons 'Sprat (__toplevel_cons 'could ()))
(__toplevel_cons 'eat (__toplevel_cons 'no (__toplevel_cons 'chicken (__toplevel_cons 'fat ())))))))
(<change>
(lat? ())
((lambda (x) x) (lat? ())))) | null | https://raw.githubusercontent.com/softwarelanguageslab/maf/11acedf56b9bf0c8e55ddb6aea754b6766d8bb40/test/changes/scheme/generated/R5RS_WeiChenRompf2019_the-little-schemer_ch2-5.scm | scheme | Changes:
* negated predicates: 0
* swapped branches: 0 | * removed : 0
* added : 1
* swaps : 1
* calls to i d fun : 2
(letrec ((atom? (lambda (x)
(if (not (pair? x)) (not (null? x)) #f)))
(lat? (lambda (l)
(<change>
()
atom?)
(<change>
(if (null? l)
#t
(if (atom? (car l)) (lat? (cdr l)) #f))
((lambda (x) x) (if (null? l) #t (if (atom? (car l)) (lat? (cdr l)) #f)))))))
(<change>
(lat?
(__toplevel_cons
'Jack
(__toplevel_cons
'Sprat
(__toplevel_cons
'could
(__toplevel_cons 'eat (__toplevel_cons 'no (__toplevel_cons 'chicken (__toplevel_cons 'fat ()))))))))
(lat?
(__toplevel_cons
(__toplevel_cons 'Jack ())
(__toplevel_cons
'Sprat
(__toplevel_cons
'could
(__toplevel_cons 'eat (__toplevel_cons 'no (__toplevel_cons 'chicken (__toplevel_cons 'fat ())))))))))
(<change>
(lat?
(__toplevel_cons
(__toplevel_cons 'Jack ())
(__toplevel_cons
'Sprat
(__toplevel_cons
'could
(__toplevel_cons 'eat (__toplevel_cons 'no (__toplevel_cons 'chicken (__toplevel_cons 'fat ()))))))))
(lat?
(__toplevel_cons
'Jack
(__toplevel_cons
'Sprat
(__toplevel_cons
'could
(__toplevel_cons 'eat (__toplevel_cons 'no (__toplevel_cons 'chicken (__toplevel_cons 'fat ())))))))))
(lat?
(__toplevel_cons
'Jack
(__toplevel_cons
(__toplevel_cons 'Sprat (__toplevel_cons 'could ()))
(__toplevel_cons 'eat (__toplevel_cons 'no (__toplevel_cons 'chicken (__toplevel_cons 'fat ())))))))
(<change>
(lat? ())
((lambda (x) x) (lat? ())))) |
16de0f94731376595dad92bfe5769fc968fa335574d3ab0eb8bbb9a23c04ce44 | tlaplus/tlapm | isabelle_keywords.mli | Keywords of Isabelle .
The implementation file ( ` .ml ` ) that corresponds to
this interface file ( ` .mli ` ) is automatically generated .
Copyright ( C ) 2012 INRIA and Microsoft Corporation
The implementation file (`.ml`) that corresponds to
this interface file (`.mli`) is automatically generated.
Copyright (C) 2012 INRIA and Microsoft Corporation
*)
val v: string list
| null | https://raw.githubusercontent.com/tlaplus/tlapm/158386319f5b6cd299f95385a216ade2b85c9f72/src/isabelle_keywords.mli | ocaml | Keywords of Isabelle .
The implementation file ( ` .ml ` ) that corresponds to
this interface file ( ` .mli ` ) is automatically generated .
Copyright ( C ) 2012 INRIA and Microsoft Corporation
The implementation file (`.ml`) that corresponds to
this interface file (`.mli`) is automatically generated.
Copyright (C) 2012 INRIA and Microsoft Corporation
*)
val v: string list
| |
1d0605612897ec8c69f077b4988c2d9a2705b5d29541e75c8e75e67ac12ec781 | erlang/otp | standard_error.erl | %%
%% %CopyrightBegin%
%%
Copyright Ericsson AB 2009 - 2023 . All Rights Reserved .
%%
Licensed under the Apache License , Version 2.0 ( the " License " ) ;
%% you may not use this file except in compliance with the License.
%% You may obtain a copy of the License at
%%
%% -2.0
%%
%% Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an " AS IS " BASIS ,
%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
%% See the License for the specific language governing permissions and
%% limitations under the License.
%%
%% %CopyrightEnd%
%%
-module(standard_error).
-behaviour(supervisor_bridge).
%% Basic standard i/o server for user interface port.
-export([start_link/0, init/1, terminate/2]).
-define(NAME, standard_error).
-define(PROCNAME_SUP, standard_error_sup).
%% Defines for control ops
-define(ERTS_TTYSL_DRV_CONTROL_MAGIC_NUMBER, 16#018b0900).
-define(CTRL_OP_GET_WINSIZE, (100 + ?ERTS_TTYSL_DRV_CONTROL_MAGIC_NUMBER)).
%%
%% The basic server and start-up.
%%
-spec start_link() -> 'ignore' | {'error',term()} | {'ok',pid()}.
start_link() ->
supervisor_bridge:start_link({local, ?PROCNAME_SUP}, ?MODULE, []).
-spec terminate(term(), pid()) -> 'ok'.
terminate(_Reason,Pid) ->
(catch exit(Pid,kill)),
ok.
-spec init([]) -> {'error','no_stderror'} | {'ok',pid(),pid()}.
init([]) ->
case (catch start_port([out,binary])) of
Pid when is_pid(Pid) ->
{ok,Pid,Pid};
_ ->
{error,no_stderror}
end.
start_port(PortSettings) ->
Id = spawn(fun () -> server({fd,2,2}, PortSettings) end),
register(?NAME, Id),
Id.
server(PortName,PortSettings) ->
process_flag(trap_exit, true),
Port = open_port(PortName,PortSettings),
run(Port).
run(P) ->
put(encoding, latin1),
put(onlcr, false),
server_loop(P).
server_loop(Port) ->
receive
{io_request,From,ReplyAs,Request} when is_pid(From) ->
_ = do_io_request(Request, From, ReplyAs, Port),
server_loop(Port);
{'EXIT',Port,badsig} -> % Ignore badsig errors
server_loop(Port);
{'EXIT',Port,What} -> % Port has exited
exit(What);
_Other -> % Ignore other messages
server_loop(Port)
end.
get_fd_geometry(Port) ->
case (catch port_control(Port,?CTRL_OP_GET_WINSIZE,[])) of
List when length(List) =:= 8 ->
<<W:32/native,H:32/native>> = list_to_binary(List),
{W,H};
_ ->
error
end.
NewSaveBuffer , FromPid , ReplyAs , Port , SaveBuffer )
do_io_request(Req, From, ReplyAs, Port) ->
{_Status,Reply} = io_request(Req, Port),
io_reply(From, ReplyAs, Reply).
New in R13B
%% Encoding option (unicode/latin1)
io_request({put_chars,unicode,Chars}, Port) ->
case wrap_characters_to_binary(Chars, unicode, get(encoding)) of
error ->
{error,{error,put_chars}};
Bin ->
put_chars(Bin, Port)
end;
io_request({put_chars,unicode,Mod,Func,Args}, Port) ->
case catch apply(Mod, Func, Args) of
Data when is_list(Data); is_binary(Data) ->
case wrap_characters_to_binary(Data, unicode, get(encoding)) of
Bin when is_binary(Bin) ->
put_chars(Bin, Port);
error ->
{error,{error,put_chars}}
end;
_ ->
{error,{error,put_chars}}
end;
io_request({put_chars,latin1,Chars}, Port) ->
case catch unicode:characters_to_binary(Chars, latin1, get(encoding)) of
Data when is_binary(Data) ->
put_chars(Data, Port);
_ ->
{error,{error,put_chars}}
end;
io_request({put_chars,latin1,Mod,Func,Args}, Port) ->
case catch apply(Mod, Func, Args) of
Data when is_list(Data); is_binary(Data) ->
case
catch unicode:characters_to_binary(Data, latin1, get(encoding))
of
Bin when is_binary(Bin) ->
put_chars(Bin, Port);
_ ->
{error,{error,put_chars}}
end;
_ ->
{error,{error,put_chars}}
end;
%% BC if called from pre-R13 node
io_request({put_chars,Chars}, Port) ->
io_request({put_chars,latin1,Chars}, Port);
io_request({put_chars,Mod,Func,Args}, Port) ->
io_request({put_chars,latin1,Mod,Func,Args}, Port);
%% New in R12
io_request({get_geometry,columns},Port) ->
case get_fd_geometry(Port) of
{W,_H} ->
{ok,W};
_ ->
{error,{error,enotsup}}
end;
io_request({get_geometry,rows},Port) ->
case get_fd_geometry(Port) of
{_W,H} ->
{ok,H};
_ ->
{error,{error,enotsup}}
end;
io_request(getopts, _Port) ->
getopts();
io_request({setopts,Opts}, _Port) when is_list(Opts) ->
do_setopts(Opts);
io_request({requests,Reqs}, Port) ->
io_requests(Reqs, {ok,ok}, Port);
io_request(R, _Port) -> %Unknown request
{error,{error,{request,R}}}. %Ignore but give error (?)
Status = io_requests(RequestList , PrevStat , Port )
%% Process a list of output requests as long as the previous status is 'ok'.
io_requests([R|Rs], {ok,_Res}, Port) ->
io_requests(Rs, io_request(R, Port), Port);
io_requests([_|_], Error, _) ->
Error;
io_requests([], Stat, _) ->
Stat.
put_port(DeepList , Port )
%% Take a deep list of characters, flatten and output them to the
%% port.
put_port(List, Port) ->
send_port(Port, {command, List}).
%% send_port(Port, Command)
send_port(Port, Command) ->
Port ! {self(),Command}.
io_reply(From , , Reply )
%% The function for sending i/o command acknowledgement.
%% The ACK contains the return value.
io_reply(From, ReplyAs, Reply) ->
From ! {io_reply,ReplyAs,Reply}.
%% put_chars
put_chars(Chars, Port) when is_binary(Chars) ->
_ = put_port(Chars, Port),
{ok,ok}.
%% setopts
do_setopts(Opts0) ->
Opts = expand_encoding(Opts0),
case check_valid_opts(Opts) of
true ->
lists:foreach(
fun({encoding, Enc}) ->
put(encoding, Enc);
({onlcr, Bool}) ->
put(onlcr, Bool)
end, Opts),
{ok, ok};
false ->
{error,{error,enotsup}}
end.
check_valid_opts([]) ->
true;
check_valid_opts([{encoding,Valid}|T]) when Valid =:= unicode; Valid =:= utf8;
Valid =:= latin1 ->
check_valid_opts(T);
check_valid_opts([{onlcr,Bool}|T]) when is_boolean(Bool) ->
check_valid_opts(T);
check_valid_opts(_) ->
false.
expand_encoding([]) ->
[];
expand_encoding([latin1 | T]) ->
[{encoding,latin1} | expand_encoding(T)];
expand_encoding([unicode | T]) ->
[{encoding,unicode} | expand_encoding(T)];
expand_encoding([utf8 | T]) ->
[{encoding,unicode} | expand_encoding(T)];
expand_encoding([{encoding,utf8} | T]) ->
[{encoding,unicode} | expand_encoding(T)];
expand_encoding([H|T]) ->
[H|expand_encoding(T)].
getopts() ->
Uni = {encoding,get(encoding)},
Onlcr = {onlcr, get(onlcr)},
{ok,[Uni, Onlcr]}.
wrap_characters_to_binary(Chars,From,To) ->
TrNl = get(onlcr),
Limit = case To of
latin1 ->
255;
_Else ->
16#10ffff
end,
case catch unicode:characters_to_list(Chars, From) of
L when is_list(L) ->
unicode:characters_to_binary(
[ case X of
$\n when TrNl ->
"\r\n";
High when High > Limit ->
["\\x{",erlang:integer_to_list(X, 16),$}];
Low ->
Low
end || X <- L ], unicode, To);
_ ->
error
end.
| null | https://raw.githubusercontent.com/erlang/otp/2b397d7e5580480dc32fa9751db95f4b89ff029e/lib/kernel/src/standard_error.erl | erlang |
%CopyrightBegin%
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
-2.0
Unless required by applicable law or agreed to in writing, software
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
%CopyrightEnd%
Basic standard i/o server for user interface port.
Defines for control ops
The basic server and start-up.
Ignore badsig errors
Port has exited
Ignore other messages
Encoding option (unicode/latin1)
BC if called from pre-R13 node
New in R12
Unknown request
Ignore but give error (?)
Process a list of output requests as long as the previous status is 'ok'.
Take a deep list of characters, flatten and output them to the
port.
send_port(Port, Command)
The function for sending i/o command acknowledgement.
The ACK contains the return value.
put_chars
setopts | Copyright Ericsson AB 2009 - 2023 . All Rights Reserved .
Licensed under the Apache License , Version 2.0 ( the " License " ) ;
distributed under the License is distributed on an " AS IS " BASIS ,
-module(standard_error).
-behaviour(supervisor_bridge).
-export([start_link/0, init/1, terminate/2]).
-define(NAME, standard_error).
-define(PROCNAME_SUP, standard_error_sup).
-define(ERTS_TTYSL_DRV_CONTROL_MAGIC_NUMBER, 16#018b0900).
-define(CTRL_OP_GET_WINSIZE, (100 + ?ERTS_TTYSL_DRV_CONTROL_MAGIC_NUMBER)).
-spec start_link() -> 'ignore' | {'error',term()} | {'ok',pid()}.
start_link() ->
supervisor_bridge:start_link({local, ?PROCNAME_SUP}, ?MODULE, []).
-spec terminate(term(), pid()) -> 'ok'.
terminate(_Reason,Pid) ->
(catch exit(Pid,kill)),
ok.
-spec init([]) -> {'error','no_stderror'} | {'ok',pid(),pid()}.
init([]) ->
case (catch start_port([out,binary])) of
Pid when is_pid(Pid) ->
{ok,Pid,Pid};
_ ->
{error,no_stderror}
end.
start_port(PortSettings) ->
Id = spawn(fun () -> server({fd,2,2}, PortSettings) end),
register(?NAME, Id),
Id.
server(PortName,PortSettings) ->
process_flag(trap_exit, true),
Port = open_port(PortName,PortSettings),
run(Port).
run(P) ->
put(encoding, latin1),
put(onlcr, false),
server_loop(P).
server_loop(Port) ->
receive
{io_request,From,ReplyAs,Request} when is_pid(From) ->
_ = do_io_request(Request, From, ReplyAs, Port),
server_loop(Port);
server_loop(Port);
exit(What);
server_loop(Port)
end.
get_fd_geometry(Port) ->
case (catch port_control(Port,?CTRL_OP_GET_WINSIZE,[])) of
List when length(List) =:= 8 ->
<<W:32/native,H:32/native>> = list_to_binary(List),
{W,H};
_ ->
error
end.
NewSaveBuffer , FromPid , ReplyAs , Port , SaveBuffer )
do_io_request(Req, From, ReplyAs, Port) ->
{_Status,Reply} = io_request(Req, Port),
io_reply(From, ReplyAs, Reply).
New in R13B
io_request({put_chars,unicode,Chars}, Port) ->
case wrap_characters_to_binary(Chars, unicode, get(encoding)) of
error ->
{error,{error,put_chars}};
Bin ->
put_chars(Bin, Port)
end;
io_request({put_chars,unicode,Mod,Func,Args}, Port) ->
case catch apply(Mod, Func, Args) of
Data when is_list(Data); is_binary(Data) ->
case wrap_characters_to_binary(Data, unicode, get(encoding)) of
Bin when is_binary(Bin) ->
put_chars(Bin, Port);
error ->
{error,{error,put_chars}}
end;
_ ->
{error,{error,put_chars}}
end;
io_request({put_chars,latin1,Chars}, Port) ->
case catch unicode:characters_to_binary(Chars, latin1, get(encoding)) of
Data when is_binary(Data) ->
put_chars(Data, Port);
_ ->
{error,{error,put_chars}}
end;
io_request({put_chars,latin1,Mod,Func,Args}, Port) ->
case catch apply(Mod, Func, Args) of
Data when is_list(Data); is_binary(Data) ->
case
catch unicode:characters_to_binary(Data, latin1, get(encoding))
of
Bin when is_binary(Bin) ->
put_chars(Bin, Port);
_ ->
{error,{error,put_chars}}
end;
_ ->
{error,{error,put_chars}}
end;
io_request({put_chars,Chars}, Port) ->
io_request({put_chars,latin1,Chars}, Port);
io_request({put_chars,Mod,Func,Args}, Port) ->
io_request({put_chars,latin1,Mod,Func,Args}, Port);
io_request({get_geometry,columns},Port) ->
case get_fd_geometry(Port) of
{W,_H} ->
{ok,W};
_ ->
{error,{error,enotsup}}
end;
io_request({get_geometry,rows},Port) ->
case get_fd_geometry(Port) of
{_W,H} ->
{ok,H};
_ ->
{error,{error,enotsup}}
end;
io_request(getopts, _Port) ->
getopts();
io_request({setopts,Opts}, _Port) when is_list(Opts) ->
do_setopts(Opts);
io_request({requests,Reqs}, Port) ->
io_requests(Reqs, {ok,ok}, Port);
Status = io_requests(RequestList , PrevStat , Port )
io_requests([R|Rs], {ok,_Res}, Port) ->
io_requests(Rs, io_request(R, Port), Port);
io_requests([_|_], Error, _) ->
Error;
io_requests([], Stat, _) ->
Stat.
put_port(DeepList , Port )
put_port(List, Port) ->
send_port(Port, {command, List}).
send_port(Port, Command) ->
Port ! {self(),Command}.
io_reply(From , , Reply )
io_reply(From, ReplyAs, Reply) ->
From ! {io_reply,ReplyAs,Reply}.
put_chars(Chars, Port) when is_binary(Chars) ->
_ = put_port(Chars, Port),
{ok,ok}.
do_setopts(Opts0) ->
Opts = expand_encoding(Opts0),
case check_valid_opts(Opts) of
true ->
lists:foreach(
fun({encoding, Enc}) ->
put(encoding, Enc);
({onlcr, Bool}) ->
put(onlcr, Bool)
end, Opts),
{ok, ok};
false ->
{error,{error,enotsup}}
end.
check_valid_opts([]) ->
true;
check_valid_opts([{encoding,Valid}|T]) when Valid =:= unicode; Valid =:= utf8;
Valid =:= latin1 ->
check_valid_opts(T);
check_valid_opts([{onlcr,Bool}|T]) when is_boolean(Bool) ->
check_valid_opts(T);
check_valid_opts(_) ->
false.
expand_encoding([]) ->
[];
expand_encoding([latin1 | T]) ->
[{encoding,latin1} | expand_encoding(T)];
expand_encoding([unicode | T]) ->
[{encoding,unicode} | expand_encoding(T)];
expand_encoding([utf8 | T]) ->
[{encoding,unicode} | expand_encoding(T)];
expand_encoding([{encoding,utf8} | T]) ->
[{encoding,unicode} | expand_encoding(T)];
expand_encoding([H|T]) ->
[H|expand_encoding(T)].
getopts() ->
Uni = {encoding,get(encoding)},
Onlcr = {onlcr, get(onlcr)},
{ok,[Uni, Onlcr]}.
wrap_characters_to_binary(Chars,From,To) ->
TrNl = get(onlcr),
Limit = case To of
latin1 ->
255;
_Else ->
16#10ffff
end,
case catch unicode:characters_to_list(Chars, From) of
L when is_list(L) ->
unicode:characters_to_binary(
[ case X of
$\n when TrNl ->
"\r\n";
High when High > Limit ->
["\\x{",erlang:integer_to_list(X, 16),$}];
Low ->
Low
end || X <- L ], unicode, To);
_ ->
error
end.
|
3aad17cd5ead10b56cf6263ce108acb6727e5e6c311a48af95fcd93744383dc4 | cbaggers/trivial-macroexpand-all | package.lisp | package.lisp
(defpackage #:trivial-macroexpand-all
(:use #:cl)
(:export :macroexpand-all))
| null | https://raw.githubusercontent.com/cbaggers/trivial-macroexpand-all/933270ac7107477de1bc92c1fd641fe646a7a8a9/package.lisp | lisp | package.lisp
(defpackage #:trivial-macroexpand-all
(:use #:cl)
(:export :macroexpand-all))
| |
61c345c948e166f7f5632d2f5054bf3d0bf4da7adfbaf06bcaa1f855b85b2906 | nasa/Common-Metadata-Repository | index_set_generics.clj | (ns cmr.indexer.data.index-set-generics
(:refer-clojure :exclude [update])
(:require
[cheshire.core :as json]
[clojure.java.io :as io]
[clojure.string :as string]
[cmr.common.config :as cfg :refer [defconfig]]
[cmr.common.log :as log :refer (error)]
[cmr.elastic-utils.index-util :as m]
[cmr.indexer.data.concepts.generic-util :as gen-util]
[cmr.schema-validation.json-schema :as js-validater]))
(defn- validate-index-against-schema
"Validate a document, returns an array of errors if there are problems
Parameters:
* raw-json, json as a string to validate"
[raw-json]
(let [schema-file (slurp (io/resource "schemas/index/v0.0.1/schema.json"))
schema-obj (js-validater/json-string->json-schema schema-file)]
(js-validater/validate-json schema-obj raw-json)))
(def default-generic-index-num-shards
"This is the default generic index number of shards."
5)
(defconfig elastic-generic-index-num-shards
"Number of shards to use for the generic document index. This value can be overriden
by an environment variable. This value can also be overriden in the schema specific
configuration files. These files are found in the schemas project.
Here is an example:
\"IndexSetup\" : {
\"index\" : {\"number_of_shards\" : 5,
\"number_of_replicas\" : 1,
\"refresh_interval\" : \"1s\"}
},"
{:default default-generic-index-num-shards :type Long})
(def generic-setting
"This def is here as a default just in case these values are not specified in the
schema specific configuration file found in the schemas project.
These values can be overriden in the schema specific configuration file.
Here is an example:
\"IndexSetup\" : {
\"index\" : {\"number_of_shards\" : 5,
\"number_of_replicas\" : 1,
\"refresh_interval\" : \"1s\"}
},"
{:index
{:number_of_shards (elastic-generic-index-num-shards)
:number_of_replicas 1
:refresh_interval "1s"}})
;; By default, these are the indexes that all generics will have, these are mostly
;; from the database table
(def base-indexes
{:concept-id m/string-field-mapping
:revision-id m/int-field-mapping
:deleted m/bool-field-mapping
:gen-name m/string-field-mapping
:gen-name-lowercase m/string-field-mapping
:gen-version m/string-field-mapping
:generic-type m/string-field-mapping
:provider-id m/string-field-mapping
:provider-id-lowercase m/string-field-mapping
:keyword m/string-field-mapping
:user-id m/string-field-mapping
:revision-date m/date-field-mapping
:native-id m/string-field-mapping
:native-id-lowercase m/string-field-mapping
:associations-gzip-b64 m/binary-field-mapping})
;; These are the types which are allowed to be expressed in the Index config file
(def config->index-mappings
{"string" m/string-field-mapping
"int" m/int-field-mapping
"date" m/date-field-mapping})
(defn mapping->index-key
"takes an index definition map and adds index names to the configuration
* destination is the document to assoc to
* index-definition contains one index config, :Names will be added using :Mapping values
Example:
{:Name 'add-me' :Mapping 'string'}
Will create:
{:add-me {:type 'keyword'}, :add-me-lowercase {:type 'keyword'}}
"
[destination index-definition]
(let [index-name (string/lower-case (:Name index-definition))
index-name-lower (str index-name "-lowercase")
converted-mapping (get config->index-mappings (:Mapping index-definition))]
(-> destination
(assoc (keyword index-name) converted-mapping)
(assoc (keyword index-name-lower) converted-mapping))))
(defn get-settings
"Get the elastic settings from the configuration files. If the default number of shards has
changed, then use that instead of what was configured."
[index-definition]
(if-let [settings (:IndexSetup index-definition)]
(let [config-shards (get-in settings [:index :number_of_shards])
;; A changed environment variable takes precedence, then the config file, then the default.
;; If the the environment variable = default value then the environment variable is not set.
;; If the environment variable is set, then use it.
num-shards (cond
(not= (elastic-generic-index-num-shards) default-generic-index-num-shards)
(elastic-generic-index-num-shards)
config-shards
(get-in settings [:index :number_of_shards])
:else
default-generic-index-num-shards)]
(if (= config-shards num-shards)
settings
(assoc-in settings [:index :number_of_shards] num-shards)))
generic-setting))
(defn read-schema-definition
"Read in the specific schema given the schema name and version number. Throw an error
if the file can't be read."
[gen-name gen-version]
(try
(-> "schemas/%s/v%s/index.json"
(format (name gen-name) gen-version)
(io/resource)
(slurp))
(catch Exception e
(error
(format (str "The index.json file for schema [%s] version [%s] cannot be found. Please make sure that it exists."
(.getMessage e))
gen-name
gen-version)))))
(defn- validate-index-against-schema-safe
"Wrap the validate-index-against-schema function in a try catch block to prevent
basic JSON parse errors from throwing errors. If problems are encountered, log
the event and return nil allowing other code to proceide with working schemas.
"
[raw-json schema]
(try
(validate-index-against-schema raw-json)
(catch java.lang.NullPointerException npe
(let [msg (format "%s : Null Pointer Exception while trying to validate index.json for %s."
(.getMessage npe)
schema)]
(error msg)
[msg]))
(catch com.fasterxml.jackson.core.JacksonException je
(do (error (.getMessage je))
[(.getMessage je)]))))
(defn- json-parse-string-safe
"Wrap the json parse-string function in a try/catch block and write an error log
and return nil if there is a problem, otherwise return the parsed JSON. All
parameteres are passed to json/parse-string."
[& options]
(try
(apply json/parse-string options)
(catch com.fasterxml.jackson.core.JacksonException je
(do
(error (.getMessage je))
[(.getMessage je)]))
))
(defn generic-mappings-generator
"create a map with an index for each of the known generic types. This is used
to inform Elastic on CMR boot on what an index should look like
Return looks like this:
{:generic-grid
{:indexes []
:mapping {:properties {:index-key-name {:type 'type'}}}}}
If the matching index.json file is not valid, then that schema will be logged and skipped.
"
[]
(reduce (fn [data gen-keyword]
(let [gen-name (name gen-keyword)
gen-ver (last (gen-keyword (cfg/approved-pipeline-documents)))
index-definition-str (read-schema-definition gen-keyword gen-ver)
index-definition (when-not (validate-index-against-schema-safe
index-definition-str
gen-name)
(json-parse-string-safe index-definition-str true))
index-list (gen-util/only-elastic-preferences (:Indexes index-definition))
generic-settings (get-settings index-definition)]
(if index-definition
(assoc data
(keyword (str "generic-" gen-name))
{:indexes [{:name (format "generic-%s" gen-name)
:settings generic-settings}
{:name (format "all-generic-%s-revisions" gen-name)
:settings generic-settings}]
:mapping {:properties (reduce mapping->index-key base-indexes index-list)}})
(do
(error (format "Could not parse the index.json file for %s version %s."
gen-name
gen-ver))
data))))
{}
(keys (cfg/approved-pipeline-documents))))
(comment
Since the change to distribute schemas files as a JAR makes it hard to test
;; a bad index.json, add the following line after the index-definition-str
;; declare in the let and run the function below
;index-definition-str (if (= :grid gen-keyword) "{bad-json}" index-definition-str)
(when (nil? (:generic-grid (generic-mappings-generator)))
(println "Missing Generic Grid definition"))
)
| null | https://raw.githubusercontent.com/nasa/Common-Metadata-Repository/e740c38151ed3c045192eb55545212ce883c5855/indexer-app/src/cmr/indexer/data/index_set_generics.clj | clojure | By default, these are the indexes that all generics will have, these are mostly
from the database table
These are the types which are allowed to be expressed in the Index config file
A changed environment variable takes precedence, then the config file, then the default.
If the the environment variable = default value then the environment variable is not set.
If the environment variable is set, then use it.
a bad index.json, add the following line after the index-definition-str
declare in the let and run the function below
index-definition-str (if (= :grid gen-keyword) "{bad-json}" index-definition-str) | (ns cmr.indexer.data.index-set-generics
(:refer-clojure :exclude [update])
(:require
[cheshire.core :as json]
[clojure.java.io :as io]
[clojure.string :as string]
[cmr.common.config :as cfg :refer [defconfig]]
[cmr.common.log :as log :refer (error)]
[cmr.elastic-utils.index-util :as m]
[cmr.indexer.data.concepts.generic-util :as gen-util]
[cmr.schema-validation.json-schema :as js-validater]))
(defn- validate-index-against-schema
"Validate a document, returns an array of errors if there are problems
Parameters:
* raw-json, json as a string to validate"
[raw-json]
(let [schema-file (slurp (io/resource "schemas/index/v0.0.1/schema.json"))
schema-obj (js-validater/json-string->json-schema schema-file)]
(js-validater/validate-json schema-obj raw-json)))
(def default-generic-index-num-shards
"This is the default generic index number of shards."
5)
(defconfig elastic-generic-index-num-shards
"Number of shards to use for the generic document index. This value can be overriden
by an environment variable. This value can also be overriden in the schema specific
configuration files. These files are found in the schemas project.
Here is an example:
\"IndexSetup\" : {
\"index\" : {\"number_of_shards\" : 5,
\"number_of_replicas\" : 1,
\"refresh_interval\" : \"1s\"}
},"
{:default default-generic-index-num-shards :type Long})
(def generic-setting
"This def is here as a default just in case these values are not specified in the
schema specific configuration file found in the schemas project.
These values can be overriden in the schema specific configuration file.
Here is an example:
\"IndexSetup\" : {
\"index\" : {\"number_of_shards\" : 5,
\"number_of_replicas\" : 1,
\"refresh_interval\" : \"1s\"}
},"
{:index
{:number_of_shards (elastic-generic-index-num-shards)
:number_of_replicas 1
:refresh_interval "1s"}})
(def base-indexes
{:concept-id m/string-field-mapping
:revision-id m/int-field-mapping
:deleted m/bool-field-mapping
:gen-name m/string-field-mapping
:gen-name-lowercase m/string-field-mapping
:gen-version m/string-field-mapping
:generic-type m/string-field-mapping
:provider-id m/string-field-mapping
:provider-id-lowercase m/string-field-mapping
:keyword m/string-field-mapping
:user-id m/string-field-mapping
:revision-date m/date-field-mapping
:native-id m/string-field-mapping
:native-id-lowercase m/string-field-mapping
:associations-gzip-b64 m/binary-field-mapping})
(def config->index-mappings
{"string" m/string-field-mapping
"int" m/int-field-mapping
"date" m/date-field-mapping})
(defn mapping->index-key
"takes an index definition map and adds index names to the configuration
* destination is the document to assoc to
* index-definition contains one index config, :Names will be added using :Mapping values
Example:
{:Name 'add-me' :Mapping 'string'}
Will create:
{:add-me {:type 'keyword'}, :add-me-lowercase {:type 'keyword'}}
"
[destination index-definition]
(let [index-name (string/lower-case (:Name index-definition))
index-name-lower (str index-name "-lowercase")
converted-mapping (get config->index-mappings (:Mapping index-definition))]
(-> destination
(assoc (keyword index-name) converted-mapping)
(assoc (keyword index-name-lower) converted-mapping))))
(defn get-settings
"Get the elastic settings from the configuration files. If the default number of shards has
changed, then use that instead of what was configured."
[index-definition]
(if-let [settings (:IndexSetup index-definition)]
(let [config-shards (get-in settings [:index :number_of_shards])
num-shards (cond
(not= (elastic-generic-index-num-shards) default-generic-index-num-shards)
(elastic-generic-index-num-shards)
config-shards
(get-in settings [:index :number_of_shards])
:else
default-generic-index-num-shards)]
(if (= config-shards num-shards)
settings
(assoc-in settings [:index :number_of_shards] num-shards)))
generic-setting))
(defn read-schema-definition
"Read in the specific schema given the schema name and version number. Throw an error
if the file can't be read."
[gen-name gen-version]
(try
(-> "schemas/%s/v%s/index.json"
(format (name gen-name) gen-version)
(io/resource)
(slurp))
(catch Exception e
(error
(format (str "The index.json file for schema [%s] version [%s] cannot be found. Please make sure that it exists."
(.getMessage e))
gen-name
gen-version)))))
(defn- validate-index-against-schema-safe
"Wrap the validate-index-against-schema function in a try catch block to prevent
basic JSON parse errors from throwing errors. If problems are encountered, log
the event and return nil allowing other code to proceide with working schemas.
"
[raw-json schema]
(try
(validate-index-against-schema raw-json)
(catch java.lang.NullPointerException npe
(let [msg (format "%s : Null Pointer Exception while trying to validate index.json for %s."
(.getMessage npe)
schema)]
(error msg)
[msg]))
(catch com.fasterxml.jackson.core.JacksonException je
(do (error (.getMessage je))
[(.getMessage je)]))))
(defn- json-parse-string-safe
"Wrap the json parse-string function in a try/catch block and write an error log
and return nil if there is a problem, otherwise return the parsed JSON. All
parameteres are passed to json/parse-string."
[& options]
(try
(apply json/parse-string options)
(catch com.fasterxml.jackson.core.JacksonException je
(do
(error (.getMessage je))
[(.getMessage je)]))
))
(defn generic-mappings-generator
"create a map with an index for each of the known generic types. This is used
to inform Elastic on CMR boot on what an index should look like
Return looks like this:
{:generic-grid
{:indexes []
:mapping {:properties {:index-key-name {:type 'type'}}}}}
If the matching index.json file is not valid, then that schema will be logged and skipped.
"
[]
(reduce (fn [data gen-keyword]
(let [gen-name (name gen-keyword)
gen-ver (last (gen-keyword (cfg/approved-pipeline-documents)))
index-definition-str (read-schema-definition gen-keyword gen-ver)
index-definition (when-not (validate-index-against-schema-safe
index-definition-str
gen-name)
(json-parse-string-safe index-definition-str true))
index-list (gen-util/only-elastic-preferences (:Indexes index-definition))
generic-settings (get-settings index-definition)]
(if index-definition
(assoc data
(keyword (str "generic-" gen-name))
{:indexes [{:name (format "generic-%s" gen-name)
:settings generic-settings}
{:name (format "all-generic-%s-revisions" gen-name)
:settings generic-settings}]
:mapping {:properties (reduce mapping->index-key base-indexes index-list)}})
(do
(error (format "Could not parse the index.json file for %s version %s."
gen-name
gen-ver))
data))))
{}
(keys (cfg/approved-pipeline-documents))))
(comment
Since the change to distribute schemas files as a JAR makes it hard to test
(when (nil? (:generic-grid (generic-mappings-generator)))
(println "Missing Generic Grid definition"))
)
|
832994079b6436e49784c3736c7f968d46d9b3d1e298b78f03d36e67d7c6852e | balint99/sfpl | Pretty.hs | # LANGUAGE LambdaCase #
-- | Pretty-printing elements of the core syntax.
module SFPL.Syntax.Core.Pretty where
import Prelude hiding ((<>))
import Control.Arrow (first, second)
import Control.Monad.State
import Data.Array.IArray hiding (Ix)
import Data.Char (showLitChar)
import Data.List (foldl')
import SFPL.Base
import SFPL.Syntax.Core.Types
import qualified SFPL.Syntax.Raw.Pretty as Raw (prettyCtrPat)
import SFPL.Utils
import Text.PrettyPrint
----------------------------------------
-- Printing types
-- | Information context for printing types: The names of bound type variables,
-- metavariables and defined types.
--
-- @since 1.0.0
type TyPCxt = ([TyName], Array Metavar TyName, Array Lvl TyName)
-- | Create an information context for types from the given list of
-- type variable names, metavariable-name associations and list of type names.
--
-- @since 1.0.0
tyPCxt :: [TyName] -> [(Metavar, TyName)] -> [TyName] -> TyPCxt
tyPCxt xs ms ts = (xs, assocArr ms, arr ts)
tyBind :: TyName -> TyPCxt -> TyPCxt
tyBind x (xs, ms, ts) = (xs :> x, ms, ts)
prettyData :: Bool -> Prec -> TyPCxt -> TyName -> TSpine -> Doc
prettyData o p cxt x sp
| x == dsList = case sp of
[a] -> brackets $ prettyTy o LowP cxt a
_ -> devError "list type doesn't have 1 type parameter"
| otherwise = case sp of
[] -> text x
sp :> a -> par p AppP $ prettyData o AppP cxt x sp <+> prettyTy o AtomP cxt a
prettyMetavar :: Metavar -> Doc
prettyMetavar (Metavar m) = char '?' <> int m
prettyMeta :: Prec -> TyPCxt -> Metavar -> TSpine -> Doc
prettyMeta p cxt m = \case
[] -> prettyMetavar m
sp :> a -> par p AppP $ prettyMeta AppP cxt m sp <+> prettyTy False AtomP cxt a
prettyFreshMeta :: Prec -> [TyName] -> Metavar -> Doc
prettyFreshMeta p xs m = case xs of
[] -> prettyMetavar m
xs :> x -> par p AppP $ prettyFreshMeta AppP xs m <+> text x
prettyForAll :: Bool -> TyPCxt -> Ty -> Doc
prettyForAll o cxt = \case
ForAll x a -> space <> text x <> prettyForAll o (tyBind x cxt) a
a -> char '.' <+> prettyTy o LowP cxt a
-- | Pretty-print a type in the given precedence context, using the given
information context . The first parameter tells whether metavariables should be
-- printed by name or as a top-level function applied to its spine.
--
-- @since 1.0.0
prettyTy :: Bool -> Prec -> TyPCxt -> Ty -> Doc
prettyTy o p cxt@(xs, ms, ts) = \case
TyVar i -> text $ xs !! unIx i
Data l sp -> prettyData o p cxt (ts ! l) sp
Meta m sp -> if o then text $ ms ! m else prettyMeta p cxt m sp
FreshMeta m -> if o then text $ ms ! m else prettyFreshMeta p xs m
Int -> text kwInt
Float -> text kwFloat
Char -> text kwChar
Tuple as -> parens . hjoin ", " $ map (prettyTy o LowP cxt) as
World a -> par p P9 $ char '%' <+> prettyTy o AppP cxt a
Fun a b -> par p P0 $ prettyTy o P1 cxt a <+> text "->" <+> prettyTy o LowP cxt b
ForAll x a -> par p LowP $ char '@' <+> text x <> prettyForAll o (tyBind x cxt) a
THole -> char '_'
-- | Convert a type to a pretty string, using the given information context.
--
-- @since 1.0.0
showTyPrec :: Bool -> Prec -> TyPCxt -> Ty -> String
showTyPrec o p cxt a = render $ prettyTy o p cxt a
-- | Same as 'showTyPrec', with the lowest precedence.
--
-- @since 1.0.0
showTy :: Bool -> TyPCxt -> Ty -> String
showTy o = showTyPrec o LowP
----------------------------------------
-- Printing patterns
-- | Information context for printing patterns: the names of the constructors of
-- defined data types.
--
-- @since 1.0.0
type PatPCxt = Array Lvl Name
-- | Create an information context for patterns from the given list of constructor names.
An inner list corresponds to the constructors of one data type .
--
-- @since 1.0.0
patPCxt :: [Name] -> PatPCxt
patPCxt = arr
prettyCtr :: Prec -> Name -> CtrArgs -> Doc
prettyCtr p x args
| x == dsNil = case args of
[] -> brackets empty
_ -> devError "nil constructor doesn't have 0 arguments"
| x == dsCons = case args of
[Left x, Left y] -> text x <+> text "::" <+> text y
_ -> devError "cons constructor doesn't have 2 explicit arguments"
| otherwise = Raw.prettyCtrPat p x args
-- | Pretty-print a pattern in the given precedence context, using the given
-- information context.
--
-- @since 1.0.0
prettyPat :: Prec -> PatPCxt -> Pattern -> Doc
prettyPat p cxt = \case
PInt n -> prettyIntLit n
PFloat n -> prettyFloatLit n
PChar c -> prettyCharLit c
PTuple xs -> parens . hjoin ", " $ map text xs
PCtr l bs -> prettyCtr p (cxt ! l) bs
PWildcard -> text "_"
----------------------------------------
-- Printing terms
-- | Information context for printing terms: the names of bound variables,
-- top-level definitions, bound type variables, metavariables,
-- defined types and data constructors.
--
-- @since 1.0.0
type TmPCxt = ([Name], Array Lvl Name, TyPCxt, PatPCxt)
-- | Create an information context for terms from the given information:
-- names of bound variables, top-level definitions, bound type variables,
-- metavariables, defined types and data constructors.
--
-- @since 1.0.0
tmPCxt :: [Name] -> [Name] ->
[TyName] -> [(Metavar, TyName)] -> [TyName] -> [Name] -> TmPCxt
tmPCxt xs tls ys ms ts cs = (xs, arr tls, tyPCxt ys ms ts, patPCxt cs)
tmBind :: Name -> TmPCxt -> TmPCxt
tmBind x (xs, tls, tcxt, pcxt) = (xs :> x, tls, tcxt, pcxt)
tmBindTy :: TyName -> TmPCxt -> TmPCxt
tmBindTy y (xs, tls, tcxt, pcxt) = (xs, tls, tyBind y tcxt, pcxt)
prettyTySig :: Bool -> TyPCxt -> Name -> Ty -> Doc
prettyTySig o tcxt x a = text x <+> char ':' <+> prettyTy o LowP tcxt a
prettyExplBind :: Bool -> TyPCxt -> Name -> Ty -> Doc
prettyExplBind o tcxt x a = parens $ prettyTySig o tcxt x a
prettyLam :: Bool -> TmPCxt -> Tm -> Doc
prettyLam o cxt@(_, _, tcxt, _) = \case
Lam x a t -> prettyExplBind o tcxt x a <> prettyLam o (tmBind x cxt) t
LamI x t -> text " {" <> text x <> prettyLamI o (tmBindTy x cxt) t
t -> char '.' <+> prettyTm o LowP cxt t
prettyLamI :: Bool -> TmPCxt -> Tm -> Doc
prettyLamI o cxt@(_, _, tcxt, _) = \case
Lam x a t -> text "} " <> prettyExplBind o tcxt x a <> prettyLam o (tmBind x cxt) t
LamI x t -> space <> text x <> prettyLamI o (tmBindTy x cxt) t
t -> text "}." <+> prettyTm o LowP cxt t
-- Get the reversed spine of an implicit application, as well as the principal term.
appISpine :: Tm -> (Tm, [Ty])
appISpine = \case
AppI t a -> second (a :) $ appISpine t
t -> (t, [])
prettyAppI :: Bool -> TmPCxt -> Tm -> Ty -> Doc
prettyAppI o cxt@(_, _, tcxt, _) t a =
let (t', as) = appISpine t
spine = map (prettyTy o LowP tcxt) $ reverse (a : as)
in prettyTm o AppP cxt t' <+> braces (hjoin ", " spine)
-- | Local binding in a let or bind expression.
type LocalBind = (Name, Ty, Tm)
-- Get the local bindings after a let expression.
letBinds :: Tm -> ([LocalBind], Tm)
letBinds = \case
Let x a t u -> first ((x, a, t) : ) $ letBinds u
t -> ([], t)
prettyLetBind :: Bool -> LocalBind -> State TmPCxt Doc
prettyLetBind o (x, a, t) = do
cxt@(_, _, tcxt, _) <- get
put $ tmBind x cxt
pure $ prettyTySig o tcxt x a
$$ nest 2 (char '=' <+> prettyTm o LowP cxt t)
prettyLet :: Bool -> TmPCxt -> Name -> Ty -> Tm -> Tm -> Doc
prettyLet o cxt x a t u = let (bs, u') = letBinds u
mbs = mapM (prettyLetBind o) $ (x, a, t) : bs
(defs, cxt') = runState mbs cxt
in text "let"
$$ nest 4 (vjoin ";" defs)
$$ text "in" <+> prettyTm o LowP cxt' u'
prettyIntLit :: Integer -> Doc
prettyIntLit = integer
prettyFloatLit :: Double -> Doc
prettyFloatLit = double
prettyCharLit :: Char -> Doc
prettyCharLit c = quotes . text $ showLitChar c ""
prettyKwApp :: Bool -> Prec -> TmPCxt -> Keyword -> [Tm] -> Doc
prettyKwApp o p cxt kw ts = par p AppP $ text kw <+> hsep (map (prettyTm o AtomP cxt) ts)
prettyUnOp :: Bool -> Prec -> TmPCxt -> UnaryOp -> Tm -> Doc
prettyUnOp o p cxt op t =
let (opP, opSymbol) = unOpDetails op
in par p opP $ text opSymbol <+> prettyTm o (succ opP) cxt t
prettyBinOp :: Bool -> Prec -> TmPCxt -> BinaryOp -> Tm -> Tm -> Doc
prettyBinOp o p cxt op t u =
let (opP, assoc, opSymbol) = binOpDetails op
(leftP, rightP) = case assoc of
None -> (opP , opP )
LeftAssoc -> (opP , succ opP)
RightAssoc -> (succ opP, opP )
in par p opP $ prettyTm o leftP cxt t <+> text opSymbol <+> prettyTm o rightP cxt u
prettyCaseBranch :: Bool -> TmPCxt -> CaseBranch -> Doc
prettyCaseBranch o cxt@(xs, tls, tcxt, pcxt) (pat, t) =
let cxt' = case pat of
PTuple xs -> foldl (flip tmBind) cxt xs
PCtr _ args -> foldl bindArg cxt args
_ -> cxt
in prettyPat LowP pcxt pat <> char '.' <+> prettyTm o LowP cxt' t
where
bindArg cxt = either (flip tmBind cxt) (flip tmBindTy cxt)
prettyCase :: Bool -> TmPCxt -> Tm -> [CaseBranch] -> Doc
prettyCase o cxt t = \case
[] -> text "case" <+> prettyTm o LowP cxt t <+> text "of {}"
bs -> text "case" <+> prettyTm o LowP cxt t <+> text "of {"
$$ nest 2 (vjoin ";" $ map (prettyCaseBranch o cxt) bs)
$$ char '}'
-- Get the local bindings after a bind expression.
bindBinds :: Tm -> ([LocalBind], Tm)
bindBinds = \case
Bind x a t u -> first ((x, a, t) : ) $ bindBinds u
t -> ([], t)
prettyBindBind :: Bool -> LocalBind -> State TmPCxt Doc
prettyBindBind o (x, a, t) = do
cxt@(_, _, tcxt, _) <- get
put $ tmBind x cxt
pure $ prettyTySig o tcxt x a
$$ nest 2 (text "<-" <+> prettyTm o LowP cxt t)
prettyBind :: Bool -> TmPCxt -> Name -> Ty -> Tm -> Tm -> Doc
prettyBind o cxt x a t u = let (bs, u') = bindBinds u
mbs = mapM (prettyBindBind o) $ (x, a, t) : bs
(binds, cxt') = runState mbs cxt
in text "do"
$$ nest 3 (vjoin ";" binds)
$$ text "then" <+> prettyTm o LowP cxt' u'
-- | Pretty-print a term in the given precedence context, using the given
information context . The first parameter tells whether metavariables should be
-- printed by name or as a top-level function applied to its spine.
--
-- @since 1.0.0
prettyTm :: Bool -> Prec -> TmPCxt -> Tm -> Doc
prettyTm o p cxt@(xs, tls, tcxt, pcxt) = \case
Var i -> text $ xs !! unIx i
TopLevel l -> text $ tls ! l
Lam x a t -> par p LowP $ char '\\' <> prettyExplBind o tcxt x a <> prettyLam o (tmBind x cxt) t
LamI x t -> par p LowP $ text "\\{" <> text x <> prettyLamI o (tmBindTy x cxt) t
App t u -> par p AppP $ prettyTm o AppP cxt t <+> prettyTm o AtomP cxt u
AppI t a -> par p AppP $ prettyAppI o cxt t a
Let x a t u -> par p LowP $ prettyLet o cxt x a t u
IntLit n -> prettyIntLit n
FloatLit n -> prettyFloatLit n
CharLit c -> prettyCharLit c
Tup ts -> parens . hjoin ", " $ map (prettyTm o LowP cxt) ts
Ctr l -> text $ pcxt ! l
UnOp op t -> prettyUnOp o p cxt op t
BinOp op t u -> prettyBinOp o p cxt op t u
NullFunc f -> text (nullFuncName f)
UnFunc f t -> prettyKwApp o p cxt (unFuncName f) [t]
BinFunc f t u -> prettyKwApp o p cxt (binFuncName f) [t, u]
Case t bs -> par p BlockP $ prettyCase o cxt t bs
Bind x a t u -> par p LowP $ prettyBind o cxt x a t u
Hole -> char '_'
-- | Convert a term to a pretty string, using the given information context.
--
-- @since 1.0.0
showTmPrec :: Bool -> Prec -> TmPCxt -> Tm -> String
showTmPrec o p cxt t = render $ prettyTm o p cxt t
-- | Same as 'showTmPrec', with the lowest precedence.
--
-- @since 1.0.0
showTm :: Bool -> TmPCxt -> Tm -> String
showTm o = showTmPrec o LowP
-- | Information context for printing top-level definitions:
-- the names of all top-level definitions, metavariables, defined types and
-- data constructors.
--
-- @since 1.0.0
type TLPCxt = (Array Lvl Name, Array Metavar TyName, Array Lvl TyName, Array Lvl Name)
-- | Create an information context for top-level definitions from the given information:
-- names of top-level definitions, metavariables, defined types and data constructors.
--
-- @since 1.0.0
tlPCxt :: [Name] -> [(Metavar, TyName)] -> [TyName] -> [Name] -> TLPCxt
tlPCxt tls ms ts cs = (arr tls, assocArr ms, arr ts, arr cs)
| Pretty - print a top - level definition . The first parameter tells
-- whether metavariables should be printed by name or as a
-- top-level function applied to its spine.
--
-- @since 1.0.0
prettyTopLevelDef :: Bool -> Prec -> TLPCxt -> TopLevelDef -> Doc
prettyTopLevelDef o p cxt@(tls, ms, ts, cs) (TL l a t) =
par p LowP $ prettyTySig o tyCxt (tls ! l) a
$$ nest 2 (char '=' <+> prettyTm o LowP tmCxt t) <> char ';'
where
tyCxt = ([], ms, ts)
tmCxt = ([], tls, tyCxt, cs)
-- | Convert a top-level definition to a pretty string,
-- using the given information context.
--
-- @since 1.0.0
showTopLevelDefPrec :: Bool -> Prec -> TLPCxt -> TopLevelDef -> String
showTopLevelDefPrec o p cxt tl = render $ prettyTopLevelDef o p cxt tl
| Same as ' showTopLevelDefPrec ' , with the lowest precedence .
--
-- @since 1.0.0
showTopLevelDef :: Bool -> TLPCxt -> TopLevelDef -> String
showTopLevelDef o = showTopLevelDefPrec o LowP
----------------------------------------
-- Printing type declarations
-- | Information context for printing data constructor declarations:
-- the names of bound type variables, defined types and data constructors.
--
-- @since 1.0.0
type CtrPCxt = ([TyName], Array Lvl TyName, Array Lvl Name)
-- | Create an information context for data constructor declarations
-- from the given information: the type variables bound by the owning
-- data type, the names of defined types and data constructors.
--
-- @since 1.0.0
ctrPCxt :: [TyName] -> [TyName] -> [Name] -> CtrPCxt
ctrPCxt xs ts cs = (reverse xs, arr ts, arr cs)
-- | Pretty-print a data constructor declaration.
--
-- @since 1.0.0
prettyConstructor :: Prec -> CtrPCxt -> Constructor -> Doc
prettyConstructor p cxt@(xs, ts, cs) (Constructor l a) =
par p LowP $ prettyTySig False tcxt (cs ! l) a
where
tcxt = (xs, assocArr [], ts)
-- | Information context for printing data type declarations:
-- the names of defined types and data constructors.
--
-- @since 1.0.0
type DDPCxt = (Array Lvl TyName, Array Lvl Name)
-- | Create an information context for data type declarations
-- from the given information: the names of defined types and data constructors.
--
-- @since 1.0.0
ddPCxt :: [TyName] -> [Name] -> DDPCxt
ddPCxt ts cs = (arr ts, arr cs)
prettyConstructors :: CtrPCxt -> Constructor -> [Constructor] -> Doc
prettyConstructors ccxt c cs =
char '=' <+> prettyConstructor LowP ccxt c
$$ vcat (map (\c -> char '|' <+> prettyConstructor LowP ccxt c) cs)
-- | Pretty-print a data type declaration.
--
-- @since 1.0.0
prettyDataDecl :: Prec -> DDPCxt -> DataDecl -> Doc
prettyDataDecl p cxt@(ts, ctrs) (DD l xs cs) = par p LowP $ case cs of
[] -> text "data" <+> text (ts ! l) <+> hsep (map text xs) <> char ';'
c : cs -> text "data" <+> text (ts ! l) <+> hsep (map text xs)
$$ nest 2 (prettyConstructors ccxt c cs <> char ';')
where
ccxt = (reverse xs, ts, ctrs)
-- | Information context for printing type declarations:
-- the names of defined types and data constructors.
--
-- @since 1.0.0
type TDPCxt = DDPCxt
-- | Create an information context for type declarations
-- from the given information: names of defined types and data constructors.
--
-- @since 1.0.0
tdPCxt :: [TyName] -> [Name] -> TDPCxt
tdPCxt = ddPCxt
-- | Pretty-print a type declaration.
--
-- @since 1.0.0
prettyTypeDecl :: Prec -> TDPCxt -> TypeDecl -> Doc
prettyTypeDecl p cxt = \case
DataDecl dd -> prettyDataDecl p cxt dd
------------------------------------------------------------
-- Printing programs
-- | Information context for printing programs:
-- the names of all top-level definitions, metavariables, defined types and
-- data constructors.
--
-- @since 1.0.0
type ProgPCxt = TLPCxt
-- | Create an information context for programs from the given information:
-- names of top-level definitions, metavariables, defined types and data constructors.
--
-- @since 1.0.0
progPCxt :: [Name] -> [(Metavar, TyName)] -> [TyName] -> [Name] -> ProgPCxt
progPCxt = tlPCxt
| Pretty - print a program . The first parameter tells
-- whether metavariables should be printed by name or as a
-- top-level function applied to its spine.
--
-- @since 1.0.0
prettyProgram :: Bool -> Prec -> ProgPCxt -> Program -> Doc
prettyProgram o p cxt@(tls, ms, ts, cs) =
par p LowP . vcat
. map (endDef . either (prettyTypeDecl p tdcxt) (prettyTopLevelDef o p tlcxt))
where
endDef doc = doc $$ text ""
tdcxt = (ts, cs)
tlcxt = cxt
-- | Convert a program to a pretty string,
-- using the given information context.
--
-- @since 1.0.0
showProgramPrec :: Bool -> Prec -> ProgPCxt -> Program -> String
showProgramPrec o p cxt pr = render $ prettyProgram o p cxt pr
-- | Same as 'showProgramPrec', with the lowest precedence.
--
-- @since 1.0.0
showProgram :: Bool -> ProgPCxt -> Program -> String
showProgram o = showProgramPrec o LowP
| null | https://raw.githubusercontent.com/balint99/sfpl/7cf8924e6f436704f578927ce2904e45caa76725/app/SFPL/Syntax/Core/Pretty.hs | haskell | | Pretty-printing elements of the core syntax.
--------------------------------------
Printing types
| Information context for printing types: The names of bound type variables,
metavariables and defined types.
@since 1.0.0
| Create an information context for types from the given list of
type variable names, metavariable-name associations and list of type names.
@since 1.0.0
| Pretty-print a type in the given precedence context, using the given
printed by name or as a top-level function applied to its spine.
@since 1.0.0
| Convert a type to a pretty string, using the given information context.
@since 1.0.0
| Same as 'showTyPrec', with the lowest precedence.
@since 1.0.0
--------------------------------------
Printing patterns
| Information context for printing patterns: the names of the constructors of
defined data types.
@since 1.0.0
| Create an information context for patterns from the given list of constructor names.
@since 1.0.0
| Pretty-print a pattern in the given precedence context, using the given
information context.
@since 1.0.0
--------------------------------------
Printing terms
| Information context for printing terms: the names of bound variables,
top-level definitions, bound type variables, metavariables,
defined types and data constructors.
@since 1.0.0
| Create an information context for terms from the given information:
names of bound variables, top-level definitions, bound type variables,
metavariables, defined types and data constructors.
@since 1.0.0
Get the reversed spine of an implicit application, as well as the principal term.
| Local binding in a let or bind expression.
Get the local bindings after a let expression.
Get the local bindings after a bind expression.
| Pretty-print a term in the given precedence context, using the given
printed by name or as a top-level function applied to its spine.
@since 1.0.0
| Convert a term to a pretty string, using the given information context.
@since 1.0.0
| Same as 'showTmPrec', with the lowest precedence.
@since 1.0.0
| Information context for printing top-level definitions:
the names of all top-level definitions, metavariables, defined types and
data constructors.
@since 1.0.0
| Create an information context for top-level definitions from the given information:
names of top-level definitions, metavariables, defined types and data constructors.
@since 1.0.0
whether metavariables should be printed by name or as a
top-level function applied to its spine.
@since 1.0.0
| Convert a top-level definition to a pretty string,
using the given information context.
@since 1.0.0
@since 1.0.0
--------------------------------------
Printing type declarations
| Information context for printing data constructor declarations:
the names of bound type variables, defined types and data constructors.
@since 1.0.0
| Create an information context for data constructor declarations
from the given information: the type variables bound by the owning
data type, the names of defined types and data constructors.
@since 1.0.0
| Pretty-print a data constructor declaration.
@since 1.0.0
| Information context for printing data type declarations:
the names of defined types and data constructors.
@since 1.0.0
| Create an information context for data type declarations
from the given information: the names of defined types and data constructors.
@since 1.0.0
| Pretty-print a data type declaration.
@since 1.0.0
| Information context for printing type declarations:
the names of defined types and data constructors.
@since 1.0.0
| Create an information context for type declarations
from the given information: names of defined types and data constructors.
@since 1.0.0
| Pretty-print a type declaration.
@since 1.0.0
----------------------------------------------------------
Printing programs
| Information context for printing programs:
the names of all top-level definitions, metavariables, defined types and
data constructors.
@since 1.0.0
| Create an information context for programs from the given information:
names of top-level definitions, metavariables, defined types and data constructors.
@since 1.0.0
whether metavariables should be printed by name or as a
top-level function applied to its spine.
@since 1.0.0
| Convert a program to a pretty string,
using the given information context.
@since 1.0.0
| Same as 'showProgramPrec', with the lowest precedence.
@since 1.0.0 | # LANGUAGE LambdaCase #
module SFPL.Syntax.Core.Pretty where
import Prelude hiding ((<>))
import Control.Arrow (first, second)
import Control.Monad.State
import Data.Array.IArray hiding (Ix)
import Data.Char (showLitChar)
import Data.List (foldl')
import SFPL.Base
import SFPL.Syntax.Core.Types
import qualified SFPL.Syntax.Raw.Pretty as Raw (prettyCtrPat)
import SFPL.Utils
import Text.PrettyPrint
type TyPCxt = ([TyName], Array Metavar TyName, Array Lvl TyName)
tyPCxt :: [TyName] -> [(Metavar, TyName)] -> [TyName] -> TyPCxt
tyPCxt xs ms ts = (xs, assocArr ms, arr ts)
tyBind :: TyName -> TyPCxt -> TyPCxt
tyBind x (xs, ms, ts) = (xs :> x, ms, ts)
prettyData :: Bool -> Prec -> TyPCxt -> TyName -> TSpine -> Doc
prettyData o p cxt x sp
| x == dsList = case sp of
[a] -> brackets $ prettyTy o LowP cxt a
_ -> devError "list type doesn't have 1 type parameter"
| otherwise = case sp of
[] -> text x
sp :> a -> par p AppP $ prettyData o AppP cxt x sp <+> prettyTy o AtomP cxt a
prettyMetavar :: Metavar -> Doc
prettyMetavar (Metavar m) = char '?' <> int m
prettyMeta :: Prec -> TyPCxt -> Metavar -> TSpine -> Doc
prettyMeta p cxt m = \case
[] -> prettyMetavar m
sp :> a -> par p AppP $ prettyMeta AppP cxt m sp <+> prettyTy False AtomP cxt a
prettyFreshMeta :: Prec -> [TyName] -> Metavar -> Doc
prettyFreshMeta p xs m = case xs of
[] -> prettyMetavar m
xs :> x -> par p AppP $ prettyFreshMeta AppP xs m <+> text x
prettyForAll :: Bool -> TyPCxt -> Ty -> Doc
prettyForAll o cxt = \case
ForAll x a -> space <> text x <> prettyForAll o (tyBind x cxt) a
a -> char '.' <+> prettyTy o LowP cxt a
information context . The first parameter tells whether metavariables should be
prettyTy :: Bool -> Prec -> TyPCxt -> Ty -> Doc
prettyTy o p cxt@(xs, ms, ts) = \case
TyVar i -> text $ xs !! unIx i
Data l sp -> prettyData o p cxt (ts ! l) sp
Meta m sp -> if o then text $ ms ! m else prettyMeta p cxt m sp
FreshMeta m -> if o then text $ ms ! m else prettyFreshMeta p xs m
Int -> text kwInt
Float -> text kwFloat
Char -> text kwChar
Tuple as -> parens . hjoin ", " $ map (prettyTy o LowP cxt) as
World a -> par p P9 $ char '%' <+> prettyTy o AppP cxt a
Fun a b -> par p P0 $ prettyTy o P1 cxt a <+> text "->" <+> prettyTy o LowP cxt b
ForAll x a -> par p LowP $ char '@' <+> text x <> prettyForAll o (tyBind x cxt) a
THole -> char '_'
showTyPrec :: Bool -> Prec -> TyPCxt -> Ty -> String
showTyPrec o p cxt a = render $ prettyTy o p cxt a
showTy :: Bool -> TyPCxt -> Ty -> String
showTy o = showTyPrec o LowP
type PatPCxt = Array Lvl Name
An inner list corresponds to the constructors of one data type .
patPCxt :: [Name] -> PatPCxt
patPCxt = arr
prettyCtr :: Prec -> Name -> CtrArgs -> Doc
prettyCtr p x args
| x == dsNil = case args of
[] -> brackets empty
_ -> devError "nil constructor doesn't have 0 arguments"
| x == dsCons = case args of
[Left x, Left y] -> text x <+> text "::" <+> text y
_ -> devError "cons constructor doesn't have 2 explicit arguments"
| otherwise = Raw.prettyCtrPat p x args
prettyPat :: Prec -> PatPCxt -> Pattern -> Doc
prettyPat p cxt = \case
PInt n -> prettyIntLit n
PFloat n -> prettyFloatLit n
PChar c -> prettyCharLit c
PTuple xs -> parens . hjoin ", " $ map text xs
PCtr l bs -> prettyCtr p (cxt ! l) bs
PWildcard -> text "_"
type TmPCxt = ([Name], Array Lvl Name, TyPCxt, PatPCxt)
tmPCxt :: [Name] -> [Name] ->
[TyName] -> [(Metavar, TyName)] -> [TyName] -> [Name] -> TmPCxt
tmPCxt xs tls ys ms ts cs = (xs, arr tls, tyPCxt ys ms ts, patPCxt cs)
tmBind :: Name -> TmPCxt -> TmPCxt
tmBind x (xs, tls, tcxt, pcxt) = (xs :> x, tls, tcxt, pcxt)
tmBindTy :: TyName -> TmPCxt -> TmPCxt
tmBindTy y (xs, tls, tcxt, pcxt) = (xs, tls, tyBind y tcxt, pcxt)
prettyTySig :: Bool -> TyPCxt -> Name -> Ty -> Doc
prettyTySig o tcxt x a = text x <+> char ':' <+> prettyTy o LowP tcxt a
prettyExplBind :: Bool -> TyPCxt -> Name -> Ty -> Doc
prettyExplBind o tcxt x a = parens $ prettyTySig o tcxt x a
prettyLam :: Bool -> TmPCxt -> Tm -> Doc
prettyLam o cxt@(_, _, tcxt, _) = \case
Lam x a t -> prettyExplBind o tcxt x a <> prettyLam o (tmBind x cxt) t
LamI x t -> text " {" <> text x <> prettyLamI o (tmBindTy x cxt) t
t -> char '.' <+> prettyTm o LowP cxt t
prettyLamI :: Bool -> TmPCxt -> Tm -> Doc
prettyLamI o cxt@(_, _, tcxt, _) = \case
Lam x a t -> text "} " <> prettyExplBind o tcxt x a <> prettyLam o (tmBind x cxt) t
LamI x t -> space <> text x <> prettyLamI o (tmBindTy x cxt) t
t -> text "}." <+> prettyTm o LowP cxt t
appISpine :: Tm -> (Tm, [Ty])
appISpine = \case
AppI t a -> second (a :) $ appISpine t
t -> (t, [])
prettyAppI :: Bool -> TmPCxt -> Tm -> Ty -> Doc
prettyAppI o cxt@(_, _, tcxt, _) t a =
let (t', as) = appISpine t
spine = map (prettyTy o LowP tcxt) $ reverse (a : as)
in prettyTm o AppP cxt t' <+> braces (hjoin ", " spine)
type LocalBind = (Name, Ty, Tm)
letBinds :: Tm -> ([LocalBind], Tm)
letBinds = \case
Let x a t u -> first ((x, a, t) : ) $ letBinds u
t -> ([], t)
prettyLetBind :: Bool -> LocalBind -> State TmPCxt Doc
prettyLetBind o (x, a, t) = do
cxt@(_, _, tcxt, _) <- get
put $ tmBind x cxt
pure $ prettyTySig o tcxt x a
$$ nest 2 (char '=' <+> prettyTm o LowP cxt t)
prettyLet :: Bool -> TmPCxt -> Name -> Ty -> Tm -> Tm -> Doc
prettyLet o cxt x a t u = let (bs, u') = letBinds u
mbs = mapM (prettyLetBind o) $ (x, a, t) : bs
(defs, cxt') = runState mbs cxt
in text "let"
$$ nest 4 (vjoin ";" defs)
$$ text "in" <+> prettyTm o LowP cxt' u'
prettyIntLit :: Integer -> Doc
prettyIntLit = integer
prettyFloatLit :: Double -> Doc
prettyFloatLit = double
prettyCharLit :: Char -> Doc
prettyCharLit c = quotes . text $ showLitChar c ""
prettyKwApp :: Bool -> Prec -> TmPCxt -> Keyword -> [Tm] -> Doc
prettyKwApp o p cxt kw ts = par p AppP $ text kw <+> hsep (map (prettyTm o AtomP cxt) ts)
prettyUnOp :: Bool -> Prec -> TmPCxt -> UnaryOp -> Tm -> Doc
prettyUnOp o p cxt op t =
let (opP, opSymbol) = unOpDetails op
in par p opP $ text opSymbol <+> prettyTm o (succ opP) cxt t
prettyBinOp :: Bool -> Prec -> TmPCxt -> BinaryOp -> Tm -> Tm -> Doc
prettyBinOp o p cxt op t u =
let (opP, assoc, opSymbol) = binOpDetails op
(leftP, rightP) = case assoc of
None -> (opP , opP )
LeftAssoc -> (opP , succ opP)
RightAssoc -> (succ opP, opP )
in par p opP $ prettyTm o leftP cxt t <+> text opSymbol <+> prettyTm o rightP cxt u
prettyCaseBranch :: Bool -> TmPCxt -> CaseBranch -> Doc
prettyCaseBranch o cxt@(xs, tls, tcxt, pcxt) (pat, t) =
let cxt' = case pat of
PTuple xs -> foldl (flip tmBind) cxt xs
PCtr _ args -> foldl bindArg cxt args
_ -> cxt
in prettyPat LowP pcxt pat <> char '.' <+> prettyTm o LowP cxt' t
where
bindArg cxt = either (flip tmBind cxt) (flip tmBindTy cxt)
prettyCase :: Bool -> TmPCxt -> Tm -> [CaseBranch] -> Doc
prettyCase o cxt t = \case
[] -> text "case" <+> prettyTm o LowP cxt t <+> text "of {}"
bs -> text "case" <+> prettyTm o LowP cxt t <+> text "of {"
$$ nest 2 (vjoin ";" $ map (prettyCaseBranch o cxt) bs)
$$ char '}'
bindBinds :: Tm -> ([LocalBind], Tm)
bindBinds = \case
Bind x a t u -> first ((x, a, t) : ) $ bindBinds u
t -> ([], t)
prettyBindBind :: Bool -> LocalBind -> State TmPCxt Doc
prettyBindBind o (x, a, t) = do
cxt@(_, _, tcxt, _) <- get
put $ tmBind x cxt
pure $ prettyTySig o tcxt x a
$$ nest 2 (text "<-" <+> prettyTm o LowP cxt t)
prettyBind :: Bool -> TmPCxt -> Name -> Ty -> Tm -> Tm -> Doc
prettyBind o cxt x a t u = let (bs, u') = bindBinds u
mbs = mapM (prettyBindBind o) $ (x, a, t) : bs
(binds, cxt') = runState mbs cxt
in text "do"
$$ nest 3 (vjoin ";" binds)
$$ text "then" <+> prettyTm o LowP cxt' u'
information context . The first parameter tells whether metavariables should be
prettyTm :: Bool -> Prec -> TmPCxt -> Tm -> Doc
prettyTm o p cxt@(xs, tls, tcxt, pcxt) = \case
Var i -> text $ xs !! unIx i
TopLevel l -> text $ tls ! l
Lam x a t -> par p LowP $ char '\\' <> prettyExplBind o tcxt x a <> prettyLam o (tmBind x cxt) t
LamI x t -> par p LowP $ text "\\{" <> text x <> prettyLamI o (tmBindTy x cxt) t
App t u -> par p AppP $ prettyTm o AppP cxt t <+> prettyTm o AtomP cxt u
AppI t a -> par p AppP $ prettyAppI o cxt t a
Let x a t u -> par p LowP $ prettyLet o cxt x a t u
IntLit n -> prettyIntLit n
FloatLit n -> prettyFloatLit n
CharLit c -> prettyCharLit c
Tup ts -> parens . hjoin ", " $ map (prettyTm o LowP cxt) ts
Ctr l -> text $ pcxt ! l
UnOp op t -> prettyUnOp o p cxt op t
BinOp op t u -> prettyBinOp o p cxt op t u
NullFunc f -> text (nullFuncName f)
UnFunc f t -> prettyKwApp o p cxt (unFuncName f) [t]
BinFunc f t u -> prettyKwApp o p cxt (binFuncName f) [t, u]
Case t bs -> par p BlockP $ prettyCase o cxt t bs
Bind x a t u -> par p LowP $ prettyBind o cxt x a t u
Hole -> char '_'
showTmPrec :: Bool -> Prec -> TmPCxt -> Tm -> String
showTmPrec o p cxt t = render $ prettyTm o p cxt t
showTm :: Bool -> TmPCxt -> Tm -> String
showTm o = showTmPrec o LowP
type TLPCxt = (Array Lvl Name, Array Metavar TyName, Array Lvl TyName, Array Lvl Name)
tlPCxt :: [Name] -> [(Metavar, TyName)] -> [TyName] -> [Name] -> TLPCxt
tlPCxt tls ms ts cs = (arr tls, assocArr ms, arr ts, arr cs)
| Pretty - print a top - level definition . The first parameter tells
prettyTopLevelDef :: Bool -> Prec -> TLPCxt -> TopLevelDef -> Doc
prettyTopLevelDef o p cxt@(tls, ms, ts, cs) (TL l a t) =
par p LowP $ prettyTySig o tyCxt (tls ! l) a
$$ nest 2 (char '=' <+> prettyTm o LowP tmCxt t) <> char ';'
where
tyCxt = ([], ms, ts)
tmCxt = ([], tls, tyCxt, cs)
showTopLevelDefPrec :: Bool -> Prec -> TLPCxt -> TopLevelDef -> String
showTopLevelDefPrec o p cxt tl = render $ prettyTopLevelDef o p cxt tl
| Same as ' showTopLevelDefPrec ' , with the lowest precedence .
showTopLevelDef :: Bool -> TLPCxt -> TopLevelDef -> String
showTopLevelDef o = showTopLevelDefPrec o LowP
type CtrPCxt = ([TyName], Array Lvl TyName, Array Lvl Name)
ctrPCxt :: [TyName] -> [TyName] -> [Name] -> CtrPCxt
ctrPCxt xs ts cs = (reverse xs, arr ts, arr cs)
prettyConstructor :: Prec -> CtrPCxt -> Constructor -> Doc
prettyConstructor p cxt@(xs, ts, cs) (Constructor l a) =
par p LowP $ prettyTySig False tcxt (cs ! l) a
where
tcxt = (xs, assocArr [], ts)
type DDPCxt = (Array Lvl TyName, Array Lvl Name)
ddPCxt :: [TyName] -> [Name] -> DDPCxt
ddPCxt ts cs = (arr ts, arr cs)
prettyConstructors :: CtrPCxt -> Constructor -> [Constructor] -> Doc
prettyConstructors ccxt c cs =
char '=' <+> prettyConstructor LowP ccxt c
$$ vcat (map (\c -> char '|' <+> prettyConstructor LowP ccxt c) cs)
prettyDataDecl :: Prec -> DDPCxt -> DataDecl -> Doc
prettyDataDecl p cxt@(ts, ctrs) (DD l xs cs) = par p LowP $ case cs of
[] -> text "data" <+> text (ts ! l) <+> hsep (map text xs) <> char ';'
c : cs -> text "data" <+> text (ts ! l) <+> hsep (map text xs)
$$ nest 2 (prettyConstructors ccxt c cs <> char ';')
where
ccxt = (reverse xs, ts, ctrs)
type TDPCxt = DDPCxt
tdPCxt :: [TyName] -> [Name] -> TDPCxt
tdPCxt = ddPCxt
prettyTypeDecl :: Prec -> TDPCxt -> TypeDecl -> Doc
prettyTypeDecl p cxt = \case
DataDecl dd -> prettyDataDecl p cxt dd
type ProgPCxt = TLPCxt
progPCxt :: [Name] -> [(Metavar, TyName)] -> [TyName] -> [Name] -> ProgPCxt
progPCxt = tlPCxt
| Pretty - print a program . The first parameter tells
prettyProgram :: Bool -> Prec -> ProgPCxt -> Program -> Doc
prettyProgram o p cxt@(tls, ms, ts, cs) =
par p LowP . vcat
. map (endDef . either (prettyTypeDecl p tdcxt) (prettyTopLevelDef o p tlcxt))
where
endDef doc = doc $$ text ""
tdcxt = (ts, cs)
tlcxt = cxt
showProgramPrec :: Bool -> Prec -> ProgPCxt -> Program -> String
showProgramPrec o p cxt pr = render $ prettyProgram o p cxt pr
showProgram :: Bool -> ProgPCxt -> Program -> String
showProgram o = showProgramPrec o LowP
|
88e8bad9869e4e29e137b5907a862c3f94ca27e7b8531a098916f138620ed554 | dianjin/cljs-agar | constants.cljc | (ns cljsagar.constants)
; ~~~~~~~~~~~~~~~~~~~~~~~~
; Server
; ~~~~~~~~~~~~~~~~~~~~~~~~
(def tick-interval 50)
; ~~~~~~~~~~~~~~~~~~~~~~~~
; Game physics
; ~~~~~~~~~~~~~~~~~~~~~~~~
(def min-x -750)
(def min-y -750)
(def max-x 750)
(def max-y 750)
(def target-edibles 60)
(def cell-size 50)
(def radius-boost 0.5)
(def inverse-radius-speed-factor 3.88)
; ~~~~~~~~~~~~~~~~~~~~~~~~
; Colors
; ~~~~~~~~~~~~~~~~~~~~~~~~
(def player-colors [
"#4EB3DE"
"#8DE0A6"
"#FEDD30"
"#f8875f"
"#ff79b2"
])
(def num-colors (count player-colors))
(def line-color "#4EB3DE")
(def background-color "white")
; ~~~~~~~~~~~~~~~~~~~~~~~~
; Player constants
; ~~~~~~~~~~~~~~~~~~~~~~~~
(defn type->radius
[type]
(case type
:user 18
:cpu 18
:edible 12
)
)
(defn type->alive
[type]
(case type
:user false
:cpu true
:edible true
)
)
| null | https://raw.githubusercontent.com/dianjin/cljs-agar/e6d4bbb8fb76fd185e640c26fa2660c22da6a4f0/src/cljsagar/constants.cljc | clojure | ~~~~~~~~~~~~~~~~~~~~~~~~
Server
~~~~~~~~~~~~~~~~~~~~~~~~
~~~~~~~~~~~~~~~~~~~~~~~~
Game physics
~~~~~~~~~~~~~~~~~~~~~~~~
~~~~~~~~~~~~~~~~~~~~~~~~
Colors
~~~~~~~~~~~~~~~~~~~~~~~~
~~~~~~~~~~~~~~~~~~~~~~~~
Player constants
~~~~~~~~~~~~~~~~~~~~~~~~ | (ns cljsagar.constants)
(def tick-interval 50)
(def min-x -750)
(def min-y -750)
(def max-x 750)
(def max-y 750)
(def target-edibles 60)
(def cell-size 50)
(def radius-boost 0.5)
(def inverse-radius-speed-factor 3.88)
(def player-colors [
"#4EB3DE"
"#8DE0A6"
"#FEDD30"
"#f8875f"
"#ff79b2"
])
(def num-colors (count player-colors))
(def line-color "#4EB3DE")
(def background-color "white")
(defn type->radius
[type]
(case type
:user 18
:cpu 18
:edible 12
)
)
(defn type->alive
[type]
(case type
:user false
:cpu true
:edible true
)
)
|
a74f8f4d4b7d188bbb244036c64a086b811bc4d761b545458921df5d25a43755 | xhtmlboi/yocaml | log.mli | (** Describing log-level. *)
type level =
| Trace
| Debug
| Info
| Warning
| Alert
| null | https://raw.githubusercontent.com/xhtmlboi/yocaml/8b67d643da565993c2adf6530ea98149774445bd/lib/yocaml/log.mli | ocaml | * Describing log-level. |
type level =
| Trace
| Debug
| Info
| Warning
| Alert
|
2c019d9872c24a4395f5fa9ea34be05f95860a13f91c3f12eca2a966488e7527 | jonase/eastwood | red.clj | (ns testcases.refer-clojure-exclude.red
(:require
[clojure.test :refer [deftest is]]))
(defn sut [x]
(* x 2))
(deftest uses-update
(update {} :f inc)
(is (= 42 (sut 21))))
| null | https://raw.githubusercontent.com/jonase/eastwood/605ab4a1d169270701200005792fa37b4c025405/cases/testcases/refer_clojure_exclude/red.clj | clojure | (ns testcases.refer-clojure-exclude.red
(:require
[clojure.test :refer [deftest is]]))
(defn sut [x]
(* x 2))
(deftest uses-update
(update {} :f inc)
(is (= 42 (sut 21))))
| |
a006b76ceed0faf961053b218f93a0bebdbf98a171e8b56dd80b1d15302a6f53 | JeffreyBenjaminBrown/hode | Window.hs | # LANGUAGE ScopedTypeVariables #
module Hode.UI.Window (
hideReassurance -- ^ St -> St
, showError, showReassurance -- ^ String -> St -> St
, emptyLangCmdWindow -- ^ St -> St
, replaceLangCmd -- ^ St -> St
) where
import qualified Data.Set as S
import Lens.Micro
import qualified Data.Text.Zipper.Generic as TxZ
import qualified Brick.Widgets.Edit as B
import Hode.UI.Types.Names
import Hode.UI.Types.State
import Hode.UI.Types.Views
hideReassurance :: St -> St
hideReassurance = optionalWindows
%~ S.delete Reassurance
showError, showReassurance :: String -> St -> St
showError msg =
( optionalWindows %~
S.delete Reassurance
. S.insert Error )
. (uiError .~ msg)
showReassurance msg =
( optionalWindows %~
S.insert Reassurance
. S.delete Error )
. (reassurance .~ msg)
emptyLangCmdWindow :: St -> St
emptyLangCmdWindow = commands . B.editContentsL
.~ TxZ.textZipper [] Nothing
| Replace the command shown in the ` LangCmd ` window with
-- the last successful search run from this `Buffer`.
-- Cannot be called from the `Cycles` `Buffer`,
-- only from an ordinary search results `Buffer`.
replaceLangCmd :: St -> St
replaceLangCmd st = maybe st f query where
query :: Maybe String
query = st ^? ( stGet_focusedBuffer . getBuffer_viewForkType
. _VFQuery . _QueryView )
f :: String -> St
f s = st & commands . B.editContentsL
.~ TxZ.textZipper ["/f " ++ s] Nothing
| null | https://raw.githubusercontent.com/JeffreyBenjaminBrown/hode/79a54a6796fa01570cde6903b398675c42954e62/hode-ui/Hode/UI/Window.hs | haskell | ^ St -> St
^ String -> St -> St
^ St -> St
^ St -> St
the last successful search run from this `Buffer`.
Cannot be called from the `Cycles` `Buffer`,
only from an ordinary search results `Buffer`. | # LANGUAGE ScopedTypeVariables #
module Hode.UI.Window (
) where
import qualified Data.Set as S
import Lens.Micro
import qualified Data.Text.Zipper.Generic as TxZ
import qualified Brick.Widgets.Edit as B
import Hode.UI.Types.Names
import Hode.UI.Types.State
import Hode.UI.Types.Views
hideReassurance :: St -> St
hideReassurance = optionalWindows
%~ S.delete Reassurance
showError, showReassurance :: String -> St -> St
showError msg =
( optionalWindows %~
S.delete Reassurance
. S.insert Error )
. (uiError .~ msg)
showReassurance msg =
( optionalWindows %~
S.insert Reassurance
. S.delete Error )
. (reassurance .~ msg)
emptyLangCmdWindow :: St -> St
emptyLangCmdWindow = commands . B.editContentsL
.~ TxZ.textZipper [] Nothing
| Replace the command shown in the ` LangCmd ` window with
replaceLangCmd :: St -> St
replaceLangCmd st = maybe st f query where
query :: Maybe String
query = st ^? ( stGet_focusedBuffer . getBuffer_viewForkType
. _VFQuery . _QueryView )
f :: String -> St
f s = st & commands . B.editContentsL
.~ TxZ.textZipper ["/f " ++ s] Nothing
|
368811cbc1bd713d6d8ee6b5c0ce3ced3289021ab9d227fc2caa78c2ec4e543d | eeng/shevek | designer_test.clj | (ns shevek.acceptance.designer-test
(:require [clojure.test :refer [deftest use-fixtures is]]
[shevek.acceptance.test-helper :refer [wrap-acceptance-tests click click-text has-css? it has-title? has-text? login visit click-tid fill wait-exists refresh element-value has-no-text?]]
[shevek.support.druid :refer [with-fake-druid query-req-matching druid-res]]
[shevek.support.designer :refer [make-wikiticker-cube go-to-designer]]
[shevek.makers :refer [make!]]
[shevek.schemas.report :refer [Report]]
[etaoin.keys :as keys]))
(use-fixtures :once wrap-acceptance-tests)
(deftest ^:acceptance designer-tests
(it "shows dimensions, measures and basic stats on entry"
(with-fake-druid
{(query-req-matching #"queryType.*timeseries") (druid-res "acceptance/totals")}
(go-to-designer)
(is (has-css? ".statistic" :count 3))
(is (has-css? ".statistics" :text "394298"))
(is (has-css? ".dimensions" :text "Region Name"))
(is (has-css? ".measures" :text "User Unique"))))
(it "add a split"
(with-fake-druid
{(query-req-matching #"queryType.*timeseries") (druid-res "acceptance/totals")
(query-req-matching #"queryType.*topN") (druid-res "acceptance/topn")}
(go-to-designer)
(click {:css ".dimensions .item:nth-child(2)"})
(is (has-css? ".split .button" :count 0))
(click {:data-tid "add-split"})
(is (has-css? ".split .button" :count 1))
(is (has-css? ".visualization" :text "City Name"))
(is (has-css? ".visualization" :text "Buenos Aires"))))
(it "raw data modal"
(with-fake-druid
{(query-req-matching #"queryType.*timeseries") (druid-res "acceptance/totals")
(query-req-matching #"queryType.*select") (druid-res "acceptance/select")}
(go-to-designer)
(click-tid "raw-data")
(is (has-css? ".raw-data" :text "Showing the first 100 events matching: Latest Day"))
(is (has-css? ".raw-data tbody tr" :count 2))))
(it "save as, save again and refresh page"
(with-fake-druid
{(query-req-matching #"queryType.*timeseries") (druid-res "acceptance/totals")}
(go-to-designer)
(is (has-css? ".statistic" :count 3))
(click {:fn/text "Added"})
(is (has-css? ".statistic" :count 2))
(click-tid "save")
(fill {:name "name"} (keys/with-shift keys/home) keys/delete "The Amazing Report")
(click-text "Save")
(is (has-css? "#notification" :text "Report saved!"))
(is (has-text? "The Amazing Report"))
(wait-exists {:css "#notification.hidden"})
(click-tid "save") ; This saves should open the Save As dialog again
(is (has-css? "#notification" :text "Report saved!"))
(refresh)
(is (has-css? ".statistic" :count 2))
(is (has-text? "The Amazing Report"))))
(it "allows to share a report"
(with-fake-druid
{(query-req-matching #"queryType.*timeseries") (druid-res "acceptance/totals")}
(go-to-designer)
(click-tid "share")
(is (has-css? ".modal .header" :text "Share"))
(is (re-matches #":4100/reports/.+"
(element-value {:css ".modal input"})))
(click-text "Copy")
(is (has-css? "#notification" :text "Link copied!"))))
(it "authorization"
(let [u (login {:allowed-cubes []})]
(make! Report {:name "R1" :cube "wikiticker" :measures ["count"] :owner-id (:id u)})
(is (has-text? "There are no cubes defined"))
(refresh)
(click-text "R1")
(is (has-css? "#designer"))
(is (has-css? ".page-message" :text "This cube is no longer available"))
(is (has-no-text? "Count"))
(is (has-no-text? "City")))))
| null | https://raw.githubusercontent.com/eeng/shevek/7783b8037303b8dd5f320f35edee3bfbb2b41c02/test/clj/shevek/acceptance/designer_test.clj | clojure | This saves should open the Save As dialog again | (ns shevek.acceptance.designer-test
(:require [clojure.test :refer [deftest use-fixtures is]]
[shevek.acceptance.test-helper :refer [wrap-acceptance-tests click click-text has-css? it has-title? has-text? login visit click-tid fill wait-exists refresh element-value has-no-text?]]
[shevek.support.druid :refer [with-fake-druid query-req-matching druid-res]]
[shevek.support.designer :refer [make-wikiticker-cube go-to-designer]]
[shevek.makers :refer [make!]]
[shevek.schemas.report :refer [Report]]
[etaoin.keys :as keys]))
(use-fixtures :once wrap-acceptance-tests)
(deftest ^:acceptance designer-tests
(it "shows dimensions, measures and basic stats on entry"
(with-fake-druid
{(query-req-matching #"queryType.*timeseries") (druid-res "acceptance/totals")}
(go-to-designer)
(is (has-css? ".statistic" :count 3))
(is (has-css? ".statistics" :text "394298"))
(is (has-css? ".dimensions" :text "Region Name"))
(is (has-css? ".measures" :text "User Unique"))))
(it "add a split"
(with-fake-druid
{(query-req-matching #"queryType.*timeseries") (druid-res "acceptance/totals")
(query-req-matching #"queryType.*topN") (druid-res "acceptance/topn")}
(go-to-designer)
(click {:css ".dimensions .item:nth-child(2)"})
(is (has-css? ".split .button" :count 0))
(click {:data-tid "add-split"})
(is (has-css? ".split .button" :count 1))
(is (has-css? ".visualization" :text "City Name"))
(is (has-css? ".visualization" :text "Buenos Aires"))))
(it "raw data modal"
(with-fake-druid
{(query-req-matching #"queryType.*timeseries") (druid-res "acceptance/totals")
(query-req-matching #"queryType.*select") (druid-res "acceptance/select")}
(go-to-designer)
(click-tid "raw-data")
(is (has-css? ".raw-data" :text "Showing the first 100 events matching: Latest Day"))
(is (has-css? ".raw-data tbody tr" :count 2))))
(it "save as, save again and refresh page"
(with-fake-druid
{(query-req-matching #"queryType.*timeseries") (druid-res "acceptance/totals")}
(go-to-designer)
(is (has-css? ".statistic" :count 3))
(click {:fn/text "Added"})
(is (has-css? ".statistic" :count 2))
(click-tid "save")
(fill {:name "name"} (keys/with-shift keys/home) keys/delete "The Amazing Report")
(click-text "Save")
(is (has-css? "#notification" :text "Report saved!"))
(is (has-text? "The Amazing Report"))
(wait-exists {:css "#notification.hidden"})
(is (has-css? "#notification" :text "Report saved!"))
(refresh)
(is (has-css? ".statistic" :count 2))
(is (has-text? "The Amazing Report"))))
(it "allows to share a report"
(with-fake-druid
{(query-req-matching #"queryType.*timeseries") (druid-res "acceptance/totals")}
(go-to-designer)
(click-tid "share")
(is (has-css? ".modal .header" :text "Share"))
(is (re-matches #":4100/reports/.+"
(element-value {:css ".modal input"})))
(click-text "Copy")
(is (has-css? "#notification" :text "Link copied!"))))
(it "authorization"
(let [u (login {:allowed-cubes []})]
(make! Report {:name "R1" :cube "wikiticker" :measures ["count"] :owner-id (:id u)})
(is (has-text? "There are no cubes defined"))
(refresh)
(click-text "R1")
(is (has-css? "#designer"))
(is (has-css? ".page-message" :text "This cube is no longer available"))
(is (has-no-text? "Count"))
(is (has-no-text? "City")))))
|
3c986362dd6f22449f6974defb06528d32f01888f1c1386edbe94154b545de6d | softwarelanguageslab/maf | R5RS_rosetta_quadratic-5.scm | ; Changes:
* removed : 0
* added : 1
* swaps : 0
* negated predicates : 1
; * swapped branches: 0
; * calls to id fun: 0
(letrec ((quadratic (lambda (a b c)
(if (= a 0)
(if (= b 0) 'fail (- (/ c b)))
(let ((delta (- (* b b) (* 4 a c))))
(<change>
()
delta)
(if (<change> (if (real? delta) (> delta 0) #f) (not (if (real? delta) (> delta 0) #f)))
(let ((u (+ b (* (if (>= b 0) 1 -1) (sqrt delta)))))
(list (/ u -2 a) (/ (* -2 c) u)))
(list (/ (- (sqrt delta) b) 2 a) (/ (+ (sqrt delta) b) -2 a))))))))
(let ((res1 (quadratic 0 0 1))
(exp1 'fail)
(res2 (quadratic 1 2 0))
(exp2 (cons -2 (cons 0 ()))))
(if (eq? res1 exp1) (equal? res2 exp2) #f))) | null | https://raw.githubusercontent.com/softwarelanguageslab/maf/11acedf56b9bf0c8e55ddb6aea754b6766d8bb40/test/changes/scheme/generated/R5RS_rosetta_quadratic-5.scm | scheme | Changes:
* swapped branches: 0
* calls to id fun: 0 | * removed : 0
* added : 1
* swaps : 0
* negated predicates : 1
(letrec ((quadratic (lambda (a b c)
(if (= a 0)
(if (= b 0) 'fail (- (/ c b)))
(let ((delta (- (* b b) (* 4 a c))))
(<change>
()
delta)
(if (<change> (if (real? delta) (> delta 0) #f) (not (if (real? delta) (> delta 0) #f)))
(let ((u (+ b (* (if (>= b 0) 1 -1) (sqrt delta)))))
(list (/ u -2 a) (/ (* -2 c) u)))
(list (/ (- (sqrt delta) b) 2 a) (/ (+ (sqrt delta) b) -2 a))))))))
(let ((res1 (quadratic 0 0 1))
(exp1 'fail)
(res2 (quadratic 1 2 0))
(exp2 (cons -2 (cons 0 ()))))
(if (eq? res1 exp1) (equal? res2 exp2) #f))) |
701b6a4a8d12a8c03d20f13acd9c9d536850592fb884454650152cd4c7ceb963 | hidaris/thinking-dumps | lang.rkt | (module lang (lib "eopl.ss" "eopl")
;; language for EXPLICIT-REFS
(require "drscheme-init.rkt")
(provide (all-defined-out))
;;;;;;;;;;;;;;;; grammatical specification ;;;;;;;;;;;;;;;;
(define the-lexical-spec
'((whitespace (whitespace) skip)
(comment ("%" (arbno (not #\newline))) skip)
(identifier
(letter (arbno (or letter digit "_" "-" "?")))
symbol)
(number (digit (arbno digit)) number)
(number ("-" digit (arbno digit)) number)
))
(define the-grammar
'((program (expression) a-program)
(expression (number) const-exp)
(expression
("-" "(" expression "," expression ")")
diff-exp)
(expression
("zero?" "(" expression ")")
zero?-exp)
(expression
("if" expression "then" expression "else" expression)
if-exp)
(expression (identifier) var-exp)
(expression
("let" identifier "=" expression "in" expression)
let-exp)
(expression
("proc" "(" identifier ")" expression)
proc-exp)
(expression
("(" expression expression ")")
call-exp)
(expression
("letrec"
(arbno identifier "(" identifier ")" "=" expression)
"in" expression)
letrec-exp)
;; new for explicit-refs
(expression
("begin" expression (arbno ";" expression) "end")
begin-exp)
(expression
("newref" "(" expression ")")
newref-exp)
(expression
("deref" "(" expression ")")
deref-exp)
(expression
("setref" "(" expression "," expression ")")
setref-exp)
added by 4.11
(expression
("list" "(" (separated-list expression ",") ")")
list-exp)
))
;;;;;;;;;;;;;;;; sllgen boilerplate ;;;;;;;;;;;;;;;;
(sllgen:make-define-datatypes the-lexical-spec the-grammar)
(define show-the-datatypes
(lambda () (sllgen:list-define-datatypes the-lexical-spec the-grammar)))
(define scan&parse
(sllgen:make-string-parser the-lexical-spec the-grammar))
(define just-scan
(sllgen:make-string-scanner the-lexical-spec the-grammar))
)
| null | https://raw.githubusercontent.com/hidaris/thinking-dumps/3fceaf9e6195ab99c8315749814a7377ef8baf86/eopl-solutions/chap4/4-12/store-passing/lang.rkt | racket | language for EXPLICIT-REFS
grammatical specification ;;;;;;;;;;;;;;;;
new for explicit-refs
sllgen boilerplate ;;;;;;;;;;;;;;;; | (module lang (lib "eopl.ss" "eopl")
(require "drscheme-init.rkt")
(provide (all-defined-out))
(define the-lexical-spec
'((whitespace (whitespace) skip)
(comment ("%" (arbno (not #\newline))) skip)
(identifier
(letter (arbno (or letter digit "_" "-" "?")))
symbol)
(number (digit (arbno digit)) number)
(number ("-" digit (arbno digit)) number)
))
(define the-grammar
'((program (expression) a-program)
(expression (number) const-exp)
(expression
("-" "(" expression "," expression ")")
diff-exp)
(expression
("zero?" "(" expression ")")
zero?-exp)
(expression
("if" expression "then" expression "else" expression)
if-exp)
(expression (identifier) var-exp)
(expression
("let" identifier "=" expression "in" expression)
let-exp)
(expression
("proc" "(" identifier ")" expression)
proc-exp)
(expression
("(" expression expression ")")
call-exp)
(expression
("letrec"
(arbno identifier "(" identifier ")" "=" expression)
"in" expression)
letrec-exp)
(expression
("begin" expression (arbno ";" expression) "end")
begin-exp)
(expression
("newref" "(" expression ")")
newref-exp)
(expression
("deref" "(" expression ")")
deref-exp)
(expression
("setref" "(" expression "," expression ")")
setref-exp)
added by 4.11
(expression
("list" "(" (separated-list expression ",") ")")
list-exp)
))
(sllgen:make-define-datatypes the-lexical-spec the-grammar)
(define show-the-datatypes
(lambda () (sllgen:list-define-datatypes the-lexical-spec the-grammar)))
(define scan&parse
(sllgen:make-string-parser the-lexical-spec the-grammar))
(define just-scan
(sllgen:make-string-scanner the-lexical-spec the-grammar))
)
|
2a7d9ffabdd9603b726b624164f636845ba70188d0ef3e35cd8e24eb15ffaef4 | mirage/ocaml-git | traverse_bfs.mli |
* Copyright ( c ) 2013 - 2017 < >
* and < >
*
* 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) 2013-2017 Thomas Gazagnaire <>
* and Romain Calascibetta <>
*
* 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.
*)
module type STORE = sig
module Hash : S.HASH
module Value : Value.S with type hash = Hash.t
type t
val root : t -> Fpath.t
val read_exn : t -> Hash.t -> Value.t Lwt.t
val is_shallowed : t -> Hash.t -> bool Lwt.t
end
module Make (Store : STORE) : sig
val fold :
Store.t ->
('a ->
?name:Fpath.t ->
length:int64 ->
Store.Hash.t ->
Store.Value.t ->
'a Lwt.t) ->
path:Fpath.t ->
'a ->
Store.Hash.t ->
'a Lwt.t
val iter :
Store.t ->
(Store.Hash.t -> Store.Value.t -> unit Lwt.t) ->
Store.Hash.t ->
unit Lwt.t
end
| null | https://raw.githubusercontent.com/mirage/ocaml-git/37c9ef41944b5b19117c34eee83ca672bb63f482/src/git/traverse_bfs.mli | ocaml |
* Copyright ( c ) 2013 - 2017 < >
* and < >
*
* 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) 2013-2017 Thomas Gazagnaire <>
* and Romain Calascibetta <>
*
* 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.
*)
module type STORE = sig
module Hash : S.HASH
module Value : Value.S with type hash = Hash.t
type t
val root : t -> Fpath.t
val read_exn : t -> Hash.t -> Value.t Lwt.t
val is_shallowed : t -> Hash.t -> bool Lwt.t
end
module Make (Store : STORE) : sig
val fold :
Store.t ->
('a ->
?name:Fpath.t ->
length:int64 ->
Store.Hash.t ->
Store.Value.t ->
'a Lwt.t) ->
path:Fpath.t ->
'a ->
Store.Hash.t ->
'a Lwt.t
val iter :
Store.t ->
(Store.Hash.t -> Store.Value.t -> unit Lwt.t) ->
Store.Hash.t ->
unit Lwt.t
end
| |
bcf5688ce30be8c0a19ae09f3c845b09c371eb679900ac437803109d987f24ba | antalsz/choose-your-own-derivative | NFI.hs | # LANGUAGE KindSignatures , TypeOperators , PolyKinds , DataKinds , GADTs ,
TypeInType , TypeFamilies , UndecidableInstances , RankNTypes ,
ScopedTypeVariables , AllowAmbiguousTypes , TypeApplications ,
LambdaCase
#
TypeInType, TypeFamilies, UndecidableInstances, RankNTypes,
ScopedTypeVariables, AllowAmbiguousTypes, TypeApplications,
LambdaCase
#-}
# OPTIONS_GHC -Wall -fno - warn - unticked - promoted - constructors #
{-# OPTIONS_GHC -Wno-unused-matches #-}
--{-# OPTIONS_GHC -fno-warn-unused-variables #-}
-- WARNING "Turn off -fno-warn-unused-variables"
module NFI where
import Data.Type.Equality
import Data.Constraint
import Constraints
import Types
import Derivatives
data NotFreeIn (x :: Nat) (t :: FMType) where
NFIVar :: ((x == y) ~ False, (y==x) ~ False)
=> Sing y -> NotFreeIn x (Var y)
NFIZero :: NotFreeIn x Zero
NFIOne :: NotFreeIn x One
NFIPlus :: NotFreeIn x t -> NotFreeIn x s -> NotFreeIn x (t :+: s)
NFITimes :: NotFreeIn x t -> NotFreeIn x s -> NotFreeIn x (t :×: s)
NFIMuEq :: ((x == y) ~ True) => Sing y -> Sing t -> NotFreeIn x (Mu y t)
NFIMuNEq :: ((x == y) ~ False) => Sing y -> NotFreeIn x t -> NotFreeIn x (Mu y t)
NFISubstEq :: ((x == y) ~ True) => Sing t -> Sing y -> NotFreeIn x s -> NotFreeIn x (Subst t y s)
NFISubstNEq :: ((x == y) ~ False) => NotFreeIn x t -> Sing y
-> NotFreeIn x s -> NotFreeIn x (Subst t y s)
NFIFunctorial :: NotFreeIn x t -> NotFreeIn x (Functorial t)
NFIPrim :: NotFreeIn x (Prim a)
infixr 6 `NFIPlus`
infixr 7 `NFITimes`
nfiToSing :: x `NotFreeIn` t -> Sing t
nfiToSing (NFIVar y) = SVar y
nfiToSing NFIZero = SZero
nfiToSing NFIOne = SOne
nfiToSing (l `NFIPlus` r) = nfiToSing l `SPlus` nfiToSing r
nfiToSing (l `NFITimes` r) = nfiToSing l `STimes` nfiToSing r
nfiToSing (NFIMuEq y t) = SMu y t
nfiToSing (NFIMuNEq y t) = SMu y $ nfiToSing t
nfiToSing (NFISubstEq t y s) = SSubst t y (nfiToSing s)
nfiToSing (NFISubstNEq t y s) = SSubst (nfiToSing t) y (nfiToSing s)
nfiToSing (NFIFunctorial t) = SFunctorial $ nfiToSing t
nfiToSing NFIPrim = SPrim
Claim 1 : ( FreshFor t ) is not free in t
nfiFreshFor :: Sing t -> FreshFor t `NotFreeIn` t
nfiFreshFor t = case geRefl t_fresh of Dict -> geFreshForNFI t_fresh t
where
t_fresh = sFreshFor t
geFreshForNFI :: (x >= FreshFor t) ~ True => Sing x -> Sing t -> x `NotFreeIn` t
geFreshForNFI x = \case
SVar y -> case succGeTrue x y of Dict -> NFIVar y
SZero -> NFIZero
SOne -> NFIOne
SPlus t1 t2 -> case maxGeTrans x (sFreshFor t1) (sFreshFor t2) of
Dict -> NFIPlus (geFreshForNFI x t1) (geFreshForNFI x t2)
STimes t1 t2 -> case maxGeTrans x (sFreshFor t1) (sFreshFor t2) of
Dict -> NFITimes (geFreshForNFI x t1) (geFreshForNFI x t2)
SMu y t -> nfiMu x y t
SSubst t y s -> nfiSubst x t y s
SFunctorial t -> NFIFunctorial $ geFreshForNFI x t
SPrim -> NFIPrim
nfiMu :: x >= Max (S y) (FreshFor t) ~ True
=> Sing x -> Sing y -> Sing t -> x `NotFreeIn` 'Mu y t
nfiMu x y t = case maxGeTrans x (SS y) (sFreshFor t) of {Dict ->
case succGeTrue x y of {Dict ->
NFIMuNEq y $ geFreshForNFI x t
}}
nfiSubst :: (x >= (S y `Max` FreshFor t `Max` FreshFor s)) ~ True
=> Sing x -> Sing t -> Sing y -> Sing s
-> x `NotFreeIn` 'Subst t y s
nfiSubst x t y s = case maxGeTrans x (sMax (SS y) fresh_t) fresh_s of {Dict ->
case maxGeTrans x (SS y) fresh_t of {Dict ->
case succGeTrue x y of {Dict ->
NFISubstNEq (geFreshForNFI x t) y (geFreshForNFI x s)
}}}
where
fresh_t = sFreshFor t
fresh_s = sFreshFor s
Claim 2 : derivatives
type DMu ( w : : Wrt ) ( z : : ) ( y : : ) ( t : : FMType ) =
-- 'Mu z (DSubst w t y ('Mu y t) ('Var z))
nfiD :: forall (w :: Wrt) (x :: Nat) (t :: FMType).
Sing w -> Sing x -> x `NotFreeIn` t -> x `NotFreeIn` D' w t
nfiD (SWrtVar y) _ (NFIVar z) = ifEqNat y z NFIOne NFIZero
nfiD SWrtFunctor _ (NFIVar _) = NFIZero
nfiD _ _ NFIZero = NFIZero
nfiD _ _ NFIOne = NFIZero
nfiD w x (nfiL `NFIPlus` nfiR) = nfiD w x nfiL `NFIPlus` nfiD w x nfiR
nfiD w x (nfiL `NFITimes` nfiR) = (nfiD w x nfiL `NFITimes` nfiR) `NFIPlus`
(nfiL `NFITimes` nfiD w x nfiR)
nfiD (SWrtVar y) x (NFIMuEq z t) =
ifEqNat y z
NFIZero
(ifEqNat x fresh
(NFIMuEq fresh (sDSubst (SWrtVar y) t z (SMu z t) (SVar x)))
(NFIMuNEq fresh (NFISubstEq (sD (SWrtVar y) t) z (NFIMuEq z t) `NFIPlus`
NFISubstEq (sD (SWrtVar z) t) z (NFIMuEq z t) `NFITimes`
NFIVar fresh)))
where fresh = sMax (SS z) (sFreshFor t)
nfiD (SWrtVar y) x (NFIMuNEq z t) =
ifEqNat y z
NFIZero
(ifEqNat x fresh
(NFIMuEq fresh (sDSubst (SWrtVar y) st z (SMu z st) (SVar x)))
(NFIMuNEq fresh ((NFISubstNEq (nfiD (SWrtVar y) x t) z (NFIMuNEq z t)) `NFIPlus`
(NFISubstNEq (nfiD (SWrtVar z) x t) z (NFIMuNEq z t) `NFITimes`
NFIVar fresh))))
where st = nfiToSing t
fresh = sMax (SS z) (sFreshFor st)
nfiD SWrtFunctor x (NFIMuEq y t) =
ifEqNat x fresh
(NFIMuEq fresh (sDSubst SWrtFunctor t y (SMu y t) (SVar x)))
(NFIMuNEq fresh (NFISubstEq (sD SWrtFunctor t) y (NFIMuEq y t) `NFIPlus`
NFISubstEq (sD (SWrtVar y) t) y (NFIMuEq y t) `NFITimes`
NFIVar fresh))
where fresh = sMax (SS y) (sFreshFor t)
nfiD SWrtFunctor x (NFIMuNEq y t) =
ifEqNat x fresh
(NFIMuEq fresh (sDSubst SWrtFunctor st y (SMu y st) (SVar x)))
(NFIMuNEq fresh ((NFISubstNEq (nfiD SWrtFunctor x t) y (NFIMuNEq y t)) `NFIPlus`
(NFISubstNEq (nfiD (SWrtVar y) x t) y (NFIMuNEq y t) `NFITimes`
NFIVar fresh)))
where st = nfiToSing t
fresh = sMax (SS y) (sFreshFor st)
nfiD (SWrtVar y) x (NFISubstEq t z nfiResult) =
ifEqNat y z
(NFISubstEq (sD (SWrtVar y) t) z nfiResult `NFITimes`
nfiD (SWrtVar y) x nfiResult)
((NFISubstEq (sD (SWrtVar y) t) z nfiResult) `NFIPlus`
(NFISubstEq (sD (SWrtVar z) t) z nfiResult `NFITimes`
nfiD (SWrtVar y) x nfiResult))
nfiD (SWrtVar y) x (NFISubstNEq nfiBody z nfiResult) =
ifEqNat y z
(NFISubstNEq (nfiD (SWrtVar y) x nfiBody) z nfiResult `NFITimes`
nfiD (SWrtVar y) x nfiResult)
((NFISubstNEq (nfiD (SWrtVar y) x nfiBody) z nfiResult) `NFIPlus`
(NFISubstNEq (nfiD (SWrtVar z) x nfiBody) z nfiResult `NFITimes`
nfiD (SWrtVar y) x nfiResult))
nfiD SWrtFunctor x (NFISubstEq t y nfiResult) =
(NFISubstEq (sD SWrtFunctor t) y nfiResult) `NFIPlus`
(NFISubstEq (sD (SWrtVar y) t) y nfiResult `NFITimes` nfiD SWrtFunctor x nfiResult)
nfiD SWrtFunctor x (NFISubstNEq nfiBody y nfiResult) =
(NFISubstNEq (nfiD SWrtFunctor x nfiBody) y nfiResult) `NFIPlus`
(NFISubstNEq (nfiD (SWrtVar y) x nfiBody) y nfiResult `NFITimes`
nfiD SWrtFunctor x nfiResult)
nfiD (SWrtVar _) _ (NFIFunctorial _) = NFIZero
nfiD SWrtFunctor _ (NFIFunctorial nfi) = nfi
nfiD _ _ NFIPrim = NFIZero
| null | https://raw.githubusercontent.com/antalsz/choose-your-own-derivative/29897118314da416023977b317971ba4f840a5eb/src/NFI.hs | haskell | # OPTIONS_GHC -Wno-unused-matches #
{-# OPTIONS_GHC -fno-warn-unused-variables #-}
WARNING "Turn off -fno-warn-unused-variables"
'Mu z (DSubst w t y ('Mu y t) ('Var z)) | # LANGUAGE KindSignatures , TypeOperators , PolyKinds , DataKinds , GADTs ,
TypeInType , TypeFamilies , UndecidableInstances , RankNTypes ,
ScopedTypeVariables , AllowAmbiguousTypes , TypeApplications ,
LambdaCase
#
TypeInType, TypeFamilies, UndecidableInstances, RankNTypes,
ScopedTypeVariables, AllowAmbiguousTypes, TypeApplications,
LambdaCase
#-}
# OPTIONS_GHC -Wall -fno - warn - unticked - promoted - constructors #
module NFI where
import Data.Type.Equality
import Data.Constraint
import Constraints
import Types
import Derivatives
data NotFreeIn (x :: Nat) (t :: FMType) where
NFIVar :: ((x == y) ~ False, (y==x) ~ False)
=> Sing y -> NotFreeIn x (Var y)
NFIZero :: NotFreeIn x Zero
NFIOne :: NotFreeIn x One
NFIPlus :: NotFreeIn x t -> NotFreeIn x s -> NotFreeIn x (t :+: s)
NFITimes :: NotFreeIn x t -> NotFreeIn x s -> NotFreeIn x (t :×: s)
NFIMuEq :: ((x == y) ~ True) => Sing y -> Sing t -> NotFreeIn x (Mu y t)
NFIMuNEq :: ((x == y) ~ False) => Sing y -> NotFreeIn x t -> NotFreeIn x (Mu y t)
NFISubstEq :: ((x == y) ~ True) => Sing t -> Sing y -> NotFreeIn x s -> NotFreeIn x (Subst t y s)
NFISubstNEq :: ((x == y) ~ False) => NotFreeIn x t -> Sing y
-> NotFreeIn x s -> NotFreeIn x (Subst t y s)
NFIFunctorial :: NotFreeIn x t -> NotFreeIn x (Functorial t)
NFIPrim :: NotFreeIn x (Prim a)
infixr 6 `NFIPlus`
infixr 7 `NFITimes`
nfiToSing :: x `NotFreeIn` t -> Sing t
nfiToSing (NFIVar y) = SVar y
nfiToSing NFIZero = SZero
nfiToSing NFIOne = SOne
nfiToSing (l `NFIPlus` r) = nfiToSing l `SPlus` nfiToSing r
nfiToSing (l `NFITimes` r) = nfiToSing l `STimes` nfiToSing r
nfiToSing (NFIMuEq y t) = SMu y t
nfiToSing (NFIMuNEq y t) = SMu y $ nfiToSing t
nfiToSing (NFISubstEq t y s) = SSubst t y (nfiToSing s)
nfiToSing (NFISubstNEq t y s) = SSubst (nfiToSing t) y (nfiToSing s)
nfiToSing (NFIFunctorial t) = SFunctorial $ nfiToSing t
nfiToSing NFIPrim = SPrim
Claim 1 : ( FreshFor t ) is not free in t
nfiFreshFor :: Sing t -> FreshFor t `NotFreeIn` t
nfiFreshFor t = case geRefl t_fresh of Dict -> geFreshForNFI t_fresh t
where
t_fresh = sFreshFor t
geFreshForNFI :: (x >= FreshFor t) ~ True => Sing x -> Sing t -> x `NotFreeIn` t
geFreshForNFI x = \case
SVar y -> case succGeTrue x y of Dict -> NFIVar y
SZero -> NFIZero
SOne -> NFIOne
SPlus t1 t2 -> case maxGeTrans x (sFreshFor t1) (sFreshFor t2) of
Dict -> NFIPlus (geFreshForNFI x t1) (geFreshForNFI x t2)
STimes t1 t2 -> case maxGeTrans x (sFreshFor t1) (sFreshFor t2) of
Dict -> NFITimes (geFreshForNFI x t1) (geFreshForNFI x t2)
SMu y t -> nfiMu x y t
SSubst t y s -> nfiSubst x t y s
SFunctorial t -> NFIFunctorial $ geFreshForNFI x t
SPrim -> NFIPrim
nfiMu :: x >= Max (S y) (FreshFor t) ~ True
=> Sing x -> Sing y -> Sing t -> x `NotFreeIn` 'Mu y t
nfiMu x y t = case maxGeTrans x (SS y) (sFreshFor t) of {Dict ->
case succGeTrue x y of {Dict ->
NFIMuNEq y $ geFreshForNFI x t
}}
nfiSubst :: (x >= (S y `Max` FreshFor t `Max` FreshFor s)) ~ True
=> Sing x -> Sing t -> Sing y -> Sing s
-> x `NotFreeIn` 'Subst t y s
nfiSubst x t y s = case maxGeTrans x (sMax (SS y) fresh_t) fresh_s of {Dict ->
case maxGeTrans x (SS y) fresh_t of {Dict ->
case succGeTrue x y of {Dict ->
NFISubstNEq (geFreshForNFI x t) y (geFreshForNFI x s)
}}}
where
fresh_t = sFreshFor t
fresh_s = sFreshFor s
Claim 2 : derivatives
type DMu ( w : : Wrt ) ( z : : ) ( y : : ) ( t : : FMType ) =
nfiD :: forall (w :: Wrt) (x :: Nat) (t :: FMType).
Sing w -> Sing x -> x `NotFreeIn` t -> x `NotFreeIn` D' w t
nfiD (SWrtVar y) _ (NFIVar z) = ifEqNat y z NFIOne NFIZero
nfiD SWrtFunctor _ (NFIVar _) = NFIZero
nfiD _ _ NFIZero = NFIZero
nfiD _ _ NFIOne = NFIZero
nfiD w x (nfiL `NFIPlus` nfiR) = nfiD w x nfiL `NFIPlus` nfiD w x nfiR
nfiD w x (nfiL `NFITimes` nfiR) = (nfiD w x nfiL `NFITimes` nfiR) `NFIPlus`
(nfiL `NFITimes` nfiD w x nfiR)
nfiD (SWrtVar y) x (NFIMuEq z t) =
ifEqNat y z
NFIZero
(ifEqNat x fresh
(NFIMuEq fresh (sDSubst (SWrtVar y) t z (SMu z t) (SVar x)))
(NFIMuNEq fresh (NFISubstEq (sD (SWrtVar y) t) z (NFIMuEq z t) `NFIPlus`
NFISubstEq (sD (SWrtVar z) t) z (NFIMuEq z t) `NFITimes`
NFIVar fresh)))
where fresh = sMax (SS z) (sFreshFor t)
nfiD (SWrtVar y) x (NFIMuNEq z t) =
ifEqNat y z
NFIZero
(ifEqNat x fresh
(NFIMuEq fresh (sDSubst (SWrtVar y) st z (SMu z st) (SVar x)))
(NFIMuNEq fresh ((NFISubstNEq (nfiD (SWrtVar y) x t) z (NFIMuNEq z t)) `NFIPlus`
(NFISubstNEq (nfiD (SWrtVar z) x t) z (NFIMuNEq z t) `NFITimes`
NFIVar fresh))))
where st = nfiToSing t
fresh = sMax (SS z) (sFreshFor st)
nfiD SWrtFunctor x (NFIMuEq y t) =
ifEqNat x fresh
(NFIMuEq fresh (sDSubst SWrtFunctor t y (SMu y t) (SVar x)))
(NFIMuNEq fresh (NFISubstEq (sD SWrtFunctor t) y (NFIMuEq y t) `NFIPlus`
NFISubstEq (sD (SWrtVar y) t) y (NFIMuEq y t) `NFITimes`
NFIVar fresh))
where fresh = sMax (SS y) (sFreshFor t)
nfiD SWrtFunctor x (NFIMuNEq y t) =
ifEqNat x fresh
(NFIMuEq fresh (sDSubst SWrtFunctor st y (SMu y st) (SVar x)))
(NFIMuNEq fresh ((NFISubstNEq (nfiD SWrtFunctor x t) y (NFIMuNEq y t)) `NFIPlus`
(NFISubstNEq (nfiD (SWrtVar y) x t) y (NFIMuNEq y t) `NFITimes`
NFIVar fresh)))
where st = nfiToSing t
fresh = sMax (SS y) (sFreshFor st)
nfiD (SWrtVar y) x (NFISubstEq t z nfiResult) =
ifEqNat y z
(NFISubstEq (sD (SWrtVar y) t) z nfiResult `NFITimes`
nfiD (SWrtVar y) x nfiResult)
((NFISubstEq (sD (SWrtVar y) t) z nfiResult) `NFIPlus`
(NFISubstEq (sD (SWrtVar z) t) z nfiResult `NFITimes`
nfiD (SWrtVar y) x nfiResult))
nfiD (SWrtVar y) x (NFISubstNEq nfiBody z nfiResult) =
ifEqNat y z
(NFISubstNEq (nfiD (SWrtVar y) x nfiBody) z nfiResult `NFITimes`
nfiD (SWrtVar y) x nfiResult)
((NFISubstNEq (nfiD (SWrtVar y) x nfiBody) z nfiResult) `NFIPlus`
(NFISubstNEq (nfiD (SWrtVar z) x nfiBody) z nfiResult `NFITimes`
nfiD (SWrtVar y) x nfiResult))
nfiD SWrtFunctor x (NFISubstEq t y nfiResult) =
(NFISubstEq (sD SWrtFunctor t) y nfiResult) `NFIPlus`
(NFISubstEq (sD (SWrtVar y) t) y nfiResult `NFITimes` nfiD SWrtFunctor x nfiResult)
nfiD SWrtFunctor x (NFISubstNEq nfiBody y nfiResult) =
(NFISubstNEq (nfiD SWrtFunctor x nfiBody) y nfiResult) `NFIPlus`
(NFISubstNEq (nfiD (SWrtVar y) x nfiBody) y nfiResult `NFITimes`
nfiD SWrtFunctor x nfiResult)
nfiD (SWrtVar _) _ (NFIFunctorial _) = NFIZero
nfiD SWrtFunctor _ (NFIFunctorial nfi) = nfi
nfiD _ _ NFIPrim = NFIZero
|
fdfe3f3a3b37d4d85459aff48b84b43e7c12e41bbaac9467348df00efac94e6f | mmontone/erudite | factorial.lisp | ;; @code-indexing nil
;; This is the factorial function:
(defun factorial (n)
(if (<= n 1)
;; @chunk base-case
1
;; @end chunk
;; @chunk recursive-case
(* n (factorial (1- n)))
;; @end chunk
))
;; The base case is simple, just check for @verb{n=1} less:
;; @insert-chunk base-case
The recursive step is @verb{n x n - 1 } :
;; @insert-chunk recursive-case
| null | https://raw.githubusercontent.com/mmontone/erudite/d421f4ed27faa636d5d4d768c4b64274023d63b2/test/factorial.lisp | lisp | @code-indexing nil
This is the factorial function:
@chunk base-case
@end chunk
@chunk recursive-case
@end chunk
The base case is simple, just check for @verb{n=1} less:
@insert-chunk base-case
@insert-chunk recursive-case | (defun factorial (n)
(if (<= n 1)
1
(* n (factorial (1- n)))
))
The recursive step is @verb{n x n - 1 } :
|
0305756f3c721e06358dbf9f9a3525a6509c5c05b8d07d908baf5d1fbd718c41 | LexiFi/gen_js_api | main.ml |
(* To run as a standalone binary, run the registered drivers *)
let () = Ppxlib.Driver.standalone ()
| null | https://raw.githubusercontent.com/LexiFi/gen_js_api/bee3b595898fdaf7db0366a9b1a009db9a6c6026/ppx-test/ppx/main.ml | ocaml | To run as a standalone binary, run the registered drivers |
let () = Ppxlib.Driver.standalone ()
|
217d8a88880152ab410149f75eb711298c95e2197ca3e747b3ecb2fc982e7467 | shayan-najd/NativeMetaprogramming | T8832.hs | # LANGUAGE CPP #
I 'm concerned that the -ddump - simpl output may differ on 32 and 64 - bit
platforms . So far I 've only put in output for 64 - bit platforms .
module T8832 where
import Data.Bits
import Data.Int
import Data.Word
#define T(s,T) \
s :: T ; \
s = clearBit (bit 0) 0 ; \
T(i,Int)
T(i8,Int8)
T(i16,Int16)
T(i32,Int32)
#ifdef T8832_WORDSIZE_64
T(i64,Int64)
#endif
T(w,Word)
T(w8,Word8)
T(w16,Word16)
T(w32,Word32)
#ifdef T8832_WORDSIZE_64
T(w64,Word64)
#endif
T(z,Integer)
| null | https://raw.githubusercontent.com/shayan-najd/NativeMetaprogramming/24e5f85990642d3f0b0044be4327b8f52fce2ba3/testsuite/tests/simplCore/should_compile/T8832.hs | haskell | # LANGUAGE CPP #
I 'm concerned that the -ddump - simpl output may differ on 32 and 64 - bit
platforms . So far I 've only put in output for 64 - bit platforms .
module T8832 where
import Data.Bits
import Data.Int
import Data.Word
#define T(s,T) \
s :: T ; \
s = clearBit (bit 0) 0 ; \
T(i,Int)
T(i8,Int8)
T(i16,Int16)
T(i32,Int32)
#ifdef T8832_WORDSIZE_64
T(i64,Int64)
#endif
T(w,Word)
T(w8,Word8)
T(w16,Word16)
T(w32,Word32)
#ifdef T8832_WORDSIZE_64
T(w64,Word64)
#endif
T(z,Integer)
| |
6afe3b5d008862b6a1a4b63ba1810874bd256d26ec705c2cc5f1d40fc2394574 | fukamachi/psychiq | redis.lisp | (in-package :cl-user)
(defpackage psychiq.util.redis
(:use #:cl)
(:import-from #:psychiq.specials
#:*psychiq-namespace*)
(:import-from #:alexandria
#:with-gensyms
#:starts-with-subseq)
(:export #:with-redis-transaction
#:*psychiq-namespace*
#:redis-key
#:omit-redis-prefix))
(in-package :psychiq.util.redis)
(defmacro with-redis-transaction (&body body)
(with-gensyms (ok)
`(let (,ok)
(red:multi)
(unwind-protect (multiple-value-prog1
(progn ,@body)
(setf ,ok t))
(if ,ok
(red:exec)
(red:discard))))))
(defun redis-key (&rest keys)
(format nil "~A:~{~A~^:~}"
*psychiq-namespace*
keys))
(defun omit-redis-prefix (key &rest prefixes)
(let ((prefix (concatenate 'string (apply #'redis-key prefixes) ":")))
(unless (starts-with-subseq prefix key)
(error "~S does not start with ~S" key prefix))
(subseq key (length prefix))))
| null | https://raw.githubusercontent.com/fukamachi/psychiq/602fbb51d4c871de5909ec0c5a159652f4ae9ad3/src/util/redis.lisp | lisp | (in-package :cl-user)
(defpackage psychiq.util.redis
(:use #:cl)
(:import-from #:psychiq.specials
#:*psychiq-namespace*)
(:import-from #:alexandria
#:with-gensyms
#:starts-with-subseq)
(:export #:with-redis-transaction
#:*psychiq-namespace*
#:redis-key
#:omit-redis-prefix))
(in-package :psychiq.util.redis)
(defmacro with-redis-transaction (&body body)
(with-gensyms (ok)
`(let (,ok)
(red:multi)
(unwind-protect (multiple-value-prog1
(progn ,@body)
(setf ,ok t))
(if ,ok
(red:exec)
(red:discard))))))
(defun redis-key (&rest keys)
(format nil "~A:~{~A~^:~}"
*psychiq-namespace*
keys))
(defun omit-redis-prefix (key &rest prefixes)
(let ((prefix (concatenate 'string (apply #'redis-key prefixes) ":")))
(unless (starts-with-subseq prefix key)
(error "~S does not start with ~S" key prefix))
(subseq key (length prefix))))
| |
a5b00beec5f1eacc25654c1a2bb65cffb2ce8e2a0bdad9f644f5e89368aaf5ec | kupl/FixML | sub11.ml | type exp = V of var
| P of var * exp
| C of exp * exp
and var = string
let rec check : exp -> bool
=fun e -> checking (e, makelist (e,[]))
and makelist : exp * var list -> var list
= fun (e, l) -> match (e,l) with
| ((V v), l) -> l
| ((P (v,e)), l)-> v::(makelist (e,l))
| ((C (e1,e2)), l1) -> let l2 = makelist (e1, l1) in makelist (e2, l2)
and checking : (exp * var list) -> bool
= fun (e,l) -> match ( e, l) with
| (V v, l) -> findv (v ,l)
| (P (v,e) , l) -> checking (e,l)
| (C (e1,e2) , l) -> (checking (e1, l) && checking (e2,l))
and findv : var * var list -> bool
= fun (v, l) -> match (v, l) with
|(_,[]) -> false
|(v, hd::tl )-> if hd = v then true else findv (v, tl)
| null | https://raw.githubusercontent.com/kupl/FixML/0a032a733d68cd8ccc8b1034d2908cd43b241fce/benchmarks/wellformedness/wellformedness/submissions/sub11.ml | ocaml | type exp = V of var
| P of var * exp
| C of exp * exp
and var = string
let rec check : exp -> bool
=fun e -> checking (e, makelist (e,[]))
and makelist : exp * var list -> var list
= fun (e, l) -> match (e,l) with
| ((V v), l) -> l
| ((P (v,e)), l)-> v::(makelist (e,l))
| ((C (e1,e2)), l1) -> let l2 = makelist (e1, l1) in makelist (e2, l2)
and checking : (exp * var list) -> bool
= fun (e,l) -> match ( e, l) with
| (V v, l) -> findv (v ,l)
| (P (v,e) , l) -> checking (e,l)
| (C (e1,e2) , l) -> (checking (e1, l) && checking (e2,l))
and findv : var * var list -> bool
= fun (v, l) -> match (v, l) with
|(_,[]) -> false
|(v, hd::tl )-> if hd = v then true else findv (v, tl)
| |
2f3793e9db2967ae9b7d98f4d1889e745c199ff1013e87036a8bd0fc8110d06f | clj-kondo/clj-kondo | no_errors.clj | (ns corpus.no-errors)
(defn foo [] 1)
(foo)
| null | https://raw.githubusercontent.com/clj-kondo/clj-kondo/626978461cbf113c376634cdf034d7262deb429f/corpus/no_errors.clj | clojure | (ns corpus.no-errors)
(defn foo [] 1)
(foo)
| |
49cb6030db2e592748b7d2f655f484ecdd15687bef4d88ba7fdffc3e1314c16c | jrh13/hol-light | rqe_lib.ml | (* ---------------------------------------------------------------------- *)
(* Refs *)
(* ---------------------------------------------------------------------- *)
let (+=) a b = a := !a + b;;
let (+.=) a b = a := !a +. b;;
(* ---------------------------------------------------------------------- *)
(* Timing *)
(* ---------------------------------------------------------------------- *)
let ptime f x =
let start_time = Sys.time() in
try let result = f x in
let finish_time = Sys.time() in
let total_time = finish_time -. start_time in
(result,total_time)
with e ->
let finish_time = Sys.time() in
let total_time = finish_time -. start_time in
(print_string("Failed after (user) CPU time of "^
(string_of_float(total_time) ^": "));
raise e);;
(* ---------------------------------------------------------------------- *)
(* Lists *)
(* ---------------------------------------------------------------------- *)
let mappair f g l =
let a,b = unzip l in
let la = map f a in
let lb = map g b in
zip la lb;;
let rec insertat i x l =
if i = 0 then x::l else
match l with
[] -> failwith "insertat: list too short for position to exist"
| h::t -> h::(insertat (i-1) x t);;
let rec allcombs f l =
match l with
[] -> []
| h::t ->
map (f h) t @ allcombs f t;;
let rec assoc_list keys assl =
match keys with
[] -> []
| h::t -> assoc h assl::assoc_list t assl;;
let add_to_list l1 l2 =
l1 := !l1 @ l2;;
let list x = [x];;
let rec ith i l =
if i = 0 then hd l else ith (i-1) (tl l);;
let rev_ith i l = ith (length l - i - 1) l;;
let get_index p l =
let rec get_index p l n =
match l with
[] -> failwith "get_index"
| h::t -> if p h then n else get_index p t (n + 1) in
get_index p l 0;;
get_index ( fun x - > x > 5 ) [ 1;2;3;7;9 ]
get_index (fun x -> x > 5) [1;2;3;7;9]
*)
let bindex p l =
let rec bindex p l i =
match l with
[] -> failwith "bindex: not found"
| h::t -> if p h then i else bindex p t (i + 1) in
bindex p l 0;;
let cons x y = x :: y;;
let rec swap_lists l store =
match l with
[] -> store
| h::t ->
let store' = map2 cons h store in
swap_lists t store';;
swap_lists [ [ 1;2;3];[4;5;6];[7;8;9];[10;11;12 ] ]
-- >
[ [ 1 ; 4 ; 7 ; 10 ] ; [ 2 ; 5 ; 8 ; 11 ] ; [ 3 ; 6 ; 9 ; 12 ] ]
swap_lists [[1;2;3];[4;5;6];[7;8;9];[10;11;12]]
-->
[[1; 4; 7; 10]; [2; 5; 8; 11]; [3; 6; 9; 12]]
*)
let swap_lists l =
let n = length (hd l) in
let l' = swap_lists l (replicate [] n) in
map rev l';;
bindex ( fun x - > x = 5 ) [ 1;2;5 ] ; ;
bindex (fun x -> x = 5) [1;2;5];;
*)
let fst3 (a,_,_) = a;;
let snd3 (_,a,_) = a;;
let thd3 (_,_,a) = a;;
let odd n = (n mod 2 = 1);;
let even n = (n mod 2 = 0);;
(* ---------------------------------------------------------------------- *)
(* Terms *)
(* ---------------------------------------------------------------------- *)
let dest_var_or_const t =
match t with
Var(s,ty) -> s,ty
| Const(s,ty) -> s,ty
| _ -> failwith "not a var or const";;
let can_match t1 t2 =
try
let n1,_ = dest_var_or_const t1 in
let n2,_ = dest_var_or_const t2 in
n1 = n2 && can (term_match [] t1) t2
with Failure _ -> false;;
let dest_quant tm =
if is_forall tm then dest_forall tm
else if is_exists tm then dest_exists tm
else failwith "dest_quant: not a quantified term";;
let get_binop tm =
try let f,r = dest_comb tm in
let xop,l = dest_comb f in
xop,l,r
with Failure _ -> failwith "get_binop";;
| null | https://raw.githubusercontent.com/jrh13/hol-light/ea44a4cacd238d7fa5a397f043f3e3321eb66543/Rqe/rqe_lib.ml | ocaml | ----------------------------------------------------------------------
Refs
----------------------------------------------------------------------
----------------------------------------------------------------------
Timing
----------------------------------------------------------------------
----------------------------------------------------------------------
Lists
----------------------------------------------------------------------
----------------------------------------------------------------------
Terms
---------------------------------------------------------------------- |
let (+=) a b = a := !a + b;;
let (+.=) a b = a := !a +. b;;
let ptime f x =
let start_time = Sys.time() in
try let result = f x in
let finish_time = Sys.time() in
let total_time = finish_time -. start_time in
(result,total_time)
with e ->
let finish_time = Sys.time() in
let total_time = finish_time -. start_time in
(print_string("Failed after (user) CPU time of "^
(string_of_float(total_time) ^": "));
raise e);;
let mappair f g l =
let a,b = unzip l in
let la = map f a in
let lb = map g b in
zip la lb;;
let rec insertat i x l =
if i = 0 then x::l else
match l with
[] -> failwith "insertat: list too short for position to exist"
| h::t -> h::(insertat (i-1) x t);;
let rec allcombs f l =
match l with
[] -> []
| h::t ->
map (f h) t @ allcombs f t;;
let rec assoc_list keys assl =
match keys with
[] -> []
| h::t -> assoc h assl::assoc_list t assl;;
let add_to_list l1 l2 =
l1 := !l1 @ l2;;
let list x = [x];;
let rec ith i l =
if i = 0 then hd l else ith (i-1) (tl l);;
let rev_ith i l = ith (length l - i - 1) l;;
let get_index p l =
let rec get_index p l n =
match l with
[] -> failwith "get_index"
| h::t -> if p h then n else get_index p t (n + 1) in
get_index p l 0;;
get_index ( fun x - > x > 5 ) [ 1;2;3;7;9 ]
get_index (fun x -> x > 5) [1;2;3;7;9]
*)
let bindex p l =
let rec bindex p l i =
match l with
[] -> failwith "bindex: not found"
| h::t -> if p h then i else bindex p t (i + 1) in
bindex p l 0;;
let cons x y = x :: y;;
let rec swap_lists l store =
match l with
[] -> store
| h::t ->
let store' = map2 cons h store in
swap_lists t store';;
swap_lists [ [ 1;2;3];[4;5;6];[7;8;9];[10;11;12 ] ]
-- >
[ [ 1 ; 4 ; 7 ; 10 ] ; [ 2 ; 5 ; 8 ; 11 ] ; [ 3 ; 6 ; 9 ; 12 ] ]
swap_lists [[1;2;3];[4;5;6];[7;8;9];[10;11;12]]
-->
[[1; 4; 7; 10]; [2; 5; 8; 11]; [3; 6; 9; 12]]
*)
let swap_lists l =
let n = length (hd l) in
let l' = swap_lists l (replicate [] n) in
map rev l';;
bindex ( fun x - > x = 5 ) [ 1;2;5 ] ; ;
bindex (fun x -> x = 5) [1;2;5];;
*)
let fst3 (a,_,_) = a;;
let snd3 (_,a,_) = a;;
let thd3 (_,_,a) = a;;
let odd n = (n mod 2 = 1);;
let even n = (n mod 2 = 0);;
let dest_var_or_const t =
match t with
Var(s,ty) -> s,ty
| Const(s,ty) -> s,ty
| _ -> failwith "not a var or const";;
let can_match t1 t2 =
try
let n1,_ = dest_var_or_const t1 in
let n2,_ = dest_var_or_const t2 in
n1 = n2 && can (term_match [] t1) t2
with Failure _ -> false;;
let dest_quant tm =
if is_forall tm then dest_forall tm
else if is_exists tm then dest_exists tm
else failwith "dest_quant: not a quantified term";;
let get_binop tm =
try let f,r = dest_comb tm in
let xop,l = dest_comb f in
xop,l,r
with Failure _ -> failwith "get_binop";;
|
c7bd4e3b9963ce3075ff249985236222b4da7cf3c0b4192ba549dd08849d4411 | bgamari/ghc-dump | Reconstruct.hs | # LANGUAGE RecordWildCards #
module GhcDump.Reconstruct (reconModule) where
import Data.Foldable
import Data.Bifunctor
import Prelude hiding (readFile)
import Data.Hashable
import qualified Data.HashMap.Lazy as HM
import GhcDump.Ast
newtype BinderMap = BinderMap (HM.HashMap BinderId Binder)
instance Hashable BinderId where
hashWithSalt salt (BinderId (Unique c i)) = salt `hashWithSalt` c `hashWithSalt` i
emptyBinderMap :: BinderMap
emptyBinderMap = BinderMap mempty
insertBinder :: Binder -> BinderMap -> BinderMap
insertBinder (Bndr b) (BinderMap m) = BinderMap $ HM.insert (binderId b) (Bndr b) m
insertBinders :: [Binder] -> BinderMap -> BinderMap
insertBinders bs bm = foldl' (flip insertBinder) bm bs
getBinder :: BinderMap -> BinderId -> Binder
getBinder (BinderMap m) bid
| Just b <- HM.lookup bid m = b
| otherwise = error $ "unknown binder "++ show bid ++ ":\nin scope:\n"
++ unlines (map (\(bid',b) -> show bid' ++ "\t" ++ show b) (HM.toList m))
-- "recon" == "reconstruct"
reconModule :: SModule -> Module
reconModule m = Module (moduleName m) (modulePhase m) (modulePhaseId m) binds
where
binds = map reconTopBinding $ moduleTopBindings m
bm = insertBinders (map (\(a,_,_) -> a) $ concatMap topBindings binds) emptyBinderMap
reconTopBinding :: STopBinding -> TopBinding
reconTopBinding (NonRecTopBinding b stats rhs) = NonRecTopBinding b' stats (reconExpr bm rhs)
where b' = reconBinder bm b
reconTopBinding (RecTopBinding bs) = RecTopBinding bs'
where bs' = map (\(a,stats,rhs) -> (reconBinder bm a, stats, reconExpr bm rhs)) bs
reconExternalName :: BinderMap -> SExternalName -> ExternalName
reconExternalName bm (ExternalName {..}) = ExternalName { externalType = reconType bm externalType, ..}
reconExternalName bm ForeignCall = ForeignCall
reconExpr :: BinderMap -> SExpr -> Expr
reconExpr bm (EVar var) = EVar $ getBinder bm var
reconExpr bm (EVarGlobal n) = EVarGlobal (reconExternalName bm n)
reconExpr _ (ELit l) = ELit l
reconExpr bm (EApp x y) = EApp (reconExpr bm x) (reconExpr bm y)
reconExpr bm (ETyLam b x) = let b' = reconBinder bm b
bm' = insertBinder b' bm
in ETyLam b' (reconExpr bm' x)
reconExpr bm (ELam b x) = let b' = reconBinder bm b
bm' = insertBinder b' bm
in ELam b' (reconExpr bm' x)
reconExpr bm (ELet bs x) = let bs' = map (bimap (reconBinder bm') (reconExpr bm')) bs
bm' = insertBinders (map fst bs') bm
in ELet bs' (reconExpr bm' x)
reconExpr bm (ECase x b alts) = let b' = reconBinder bm b
bm' = insertBinder b' bm
in ECase (reconExpr bm x) b' (map (reconAlt bm') alts)
reconExpr bm (EType t) = EType (reconType bm t)
reconExpr _ ECoercion = ECoercion
reconBinder :: BinderMap -> SBinder -> Binder
reconBinder bm (SBndr b@Binder{}) =
Bndr $ b { binderType = reconType bm $ binderType b
, binderIdInfo = reconIdInfo bm $ binderIdInfo b
}
reconBinder bm (SBndr b@TyBinder{}) =
Bndr $ b { binderKind = reconType bm $ binderKind b }
reconIdInfo :: BinderMap -> IdInfo SBinder BinderId -> IdInfo Binder Binder
reconIdInfo bm i =
i { idiUnfolding = reconUnfolding bm $ idiUnfolding i }
reconUnfolding :: BinderMap -> Unfolding SBinder BinderId -> Unfolding Binder Binder
reconUnfolding _ NoUnfolding = NoUnfolding
reconUnfolding _ BootUnfolding = BootUnfolding
reconUnfolding _ (OtherCon alts) = OtherCon alts
reconUnfolding _ DFunUnfolding = DFunUnfolding
reconUnfolding bm CoreUnfolding{..} = CoreUnfolding { unfTemplate = reconExpr bm unfTemplate
, .. }
reconAlt :: BinderMap -> SAlt -> Alt
reconAlt bm0 (Alt con bs rhs) =
let (bm', bs') = doBinders bm0 [] bs
in Alt con bs' (reconExpr bm' rhs)
where
doBinders bm acc [] = (bm, reverse acc)
doBinders bm acc (b:rest) = doBinders bm' (b':acc) rest
where
b' = reconBinder bm b
bm' = insertBinder b' bm
reconType :: BinderMap -> SType -> Type
reconType bm (VarTy v) = VarTy $ getBinder bm v
reconType bm (FunTy x y) = FunTy (reconType bm x) (reconType bm y)
reconType bm (TyConApp tc tys) = TyConApp tc (map (reconType bm) tys)
reconType bm (AppTy x y) = AppTy (reconType bm x) (reconType bm y)
reconType bm (ForAllTy b x) = let b' = reconBinder bm b
bm' = insertBinder b' bm
in ForAllTy b' (reconType bm' x)
reconType _ (LitTy litty) = LitTy litty
reconType _ CoercionTy = CoercionTy
| null | https://raw.githubusercontent.com/bgamari/ghc-dump/0d69ff20c2d5dea7aa2422749bb1cfc8986787ea/ghc-dump-util/src/GhcDump/Reconstruct.hs | haskell | "recon" == "reconstruct" | # LANGUAGE RecordWildCards #
module GhcDump.Reconstruct (reconModule) where
import Data.Foldable
import Data.Bifunctor
import Prelude hiding (readFile)
import Data.Hashable
import qualified Data.HashMap.Lazy as HM
import GhcDump.Ast
newtype BinderMap = BinderMap (HM.HashMap BinderId Binder)
instance Hashable BinderId where
hashWithSalt salt (BinderId (Unique c i)) = salt `hashWithSalt` c `hashWithSalt` i
emptyBinderMap :: BinderMap
emptyBinderMap = BinderMap mempty
insertBinder :: Binder -> BinderMap -> BinderMap
insertBinder (Bndr b) (BinderMap m) = BinderMap $ HM.insert (binderId b) (Bndr b) m
insertBinders :: [Binder] -> BinderMap -> BinderMap
insertBinders bs bm = foldl' (flip insertBinder) bm bs
getBinder :: BinderMap -> BinderId -> Binder
getBinder (BinderMap m) bid
| Just b <- HM.lookup bid m = b
| otherwise = error $ "unknown binder "++ show bid ++ ":\nin scope:\n"
++ unlines (map (\(bid',b) -> show bid' ++ "\t" ++ show b) (HM.toList m))
reconModule :: SModule -> Module
reconModule m = Module (moduleName m) (modulePhase m) (modulePhaseId m) binds
where
binds = map reconTopBinding $ moduleTopBindings m
bm = insertBinders (map (\(a,_,_) -> a) $ concatMap topBindings binds) emptyBinderMap
reconTopBinding :: STopBinding -> TopBinding
reconTopBinding (NonRecTopBinding b stats rhs) = NonRecTopBinding b' stats (reconExpr bm rhs)
where b' = reconBinder bm b
reconTopBinding (RecTopBinding bs) = RecTopBinding bs'
where bs' = map (\(a,stats,rhs) -> (reconBinder bm a, stats, reconExpr bm rhs)) bs
reconExternalName :: BinderMap -> SExternalName -> ExternalName
reconExternalName bm (ExternalName {..}) = ExternalName { externalType = reconType bm externalType, ..}
reconExternalName bm ForeignCall = ForeignCall
reconExpr :: BinderMap -> SExpr -> Expr
reconExpr bm (EVar var) = EVar $ getBinder bm var
reconExpr bm (EVarGlobal n) = EVarGlobal (reconExternalName bm n)
reconExpr _ (ELit l) = ELit l
reconExpr bm (EApp x y) = EApp (reconExpr bm x) (reconExpr bm y)
reconExpr bm (ETyLam b x) = let b' = reconBinder bm b
bm' = insertBinder b' bm
in ETyLam b' (reconExpr bm' x)
reconExpr bm (ELam b x) = let b' = reconBinder bm b
bm' = insertBinder b' bm
in ELam b' (reconExpr bm' x)
reconExpr bm (ELet bs x) = let bs' = map (bimap (reconBinder bm') (reconExpr bm')) bs
bm' = insertBinders (map fst bs') bm
in ELet bs' (reconExpr bm' x)
reconExpr bm (ECase x b alts) = let b' = reconBinder bm b
bm' = insertBinder b' bm
in ECase (reconExpr bm x) b' (map (reconAlt bm') alts)
reconExpr bm (EType t) = EType (reconType bm t)
reconExpr _ ECoercion = ECoercion
reconBinder :: BinderMap -> SBinder -> Binder
reconBinder bm (SBndr b@Binder{}) =
Bndr $ b { binderType = reconType bm $ binderType b
, binderIdInfo = reconIdInfo bm $ binderIdInfo b
}
reconBinder bm (SBndr b@TyBinder{}) =
Bndr $ b { binderKind = reconType bm $ binderKind b }
reconIdInfo :: BinderMap -> IdInfo SBinder BinderId -> IdInfo Binder Binder
reconIdInfo bm i =
i { idiUnfolding = reconUnfolding bm $ idiUnfolding i }
reconUnfolding :: BinderMap -> Unfolding SBinder BinderId -> Unfolding Binder Binder
reconUnfolding _ NoUnfolding = NoUnfolding
reconUnfolding _ BootUnfolding = BootUnfolding
reconUnfolding _ (OtherCon alts) = OtherCon alts
reconUnfolding _ DFunUnfolding = DFunUnfolding
reconUnfolding bm CoreUnfolding{..} = CoreUnfolding { unfTemplate = reconExpr bm unfTemplate
, .. }
reconAlt :: BinderMap -> SAlt -> Alt
reconAlt bm0 (Alt con bs rhs) =
let (bm', bs') = doBinders bm0 [] bs
in Alt con bs' (reconExpr bm' rhs)
where
doBinders bm acc [] = (bm, reverse acc)
doBinders bm acc (b:rest) = doBinders bm' (b':acc) rest
where
b' = reconBinder bm b
bm' = insertBinder b' bm
reconType :: BinderMap -> SType -> Type
reconType bm (VarTy v) = VarTy $ getBinder bm v
reconType bm (FunTy x y) = FunTy (reconType bm x) (reconType bm y)
reconType bm (TyConApp tc tys) = TyConApp tc (map (reconType bm) tys)
reconType bm (AppTy x y) = AppTy (reconType bm x) (reconType bm y)
reconType bm (ForAllTy b x) = let b' = reconBinder bm b
bm' = insertBinder b' bm
in ForAllTy b' (reconType bm' x)
reconType _ (LitTy litty) = LitTy litty
reconType _ CoercionTy = CoercionTy
|
b6436a84563a19b73f859926ff831ba0bf128d3bfd0047efc381d57ffd044434 | haskell/cabal | Benchmark.hs | # LANGUAGE CPP #
{-# LANGUAGE DeriveDataTypeable #-}
# LANGUAGE DeriveGeneric #
# LANGUAGE FlexibleContexts #
{-# LANGUAGE RankNTypes #-}
-----------------------------------------------------------------------------
-- |
-- Module : Distribution.Simple.Benchmark
Copyright : 2003 - 2004
2007
-- License : BSD3
--
-- Maintainer :
-- Portability : portable
--
-- Definition of the benchmarking command-line options.
-- See: @Distribution.Simple.Setup@
module Distribution.Simple.Setup.Benchmark (
BenchmarkFlags(..), emptyBenchmarkFlags,
defaultBenchmarkFlags, benchmarkCommand,
benchmarkOptions'
) where
import Prelude ()
import Distribution.Compat.Prelude hiding (get)
import Distribution.Simple.Command hiding (boolOpt, boolOpt')
import Distribution.Simple.Flag
import Distribution.Simple.Utils
import Distribution.Simple.InstallDirs
import Distribution.Verbosity
import Distribution.Simple.Setup.Common
-- ------------------------------------------------------------
-- * Benchmark flags
-- ------------------------------------------------------------
data BenchmarkFlags = BenchmarkFlags {
benchmarkDistPref :: Flag FilePath,
benchmarkVerbosity :: Flag Verbosity,
benchmarkOptions :: [PathTemplate]
} deriving (Show, Generic, Typeable)
defaultBenchmarkFlags :: BenchmarkFlags
defaultBenchmarkFlags = BenchmarkFlags {
benchmarkDistPref = NoFlag,
benchmarkVerbosity = Flag normal,
benchmarkOptions = []
}
benchmarkCommand :: CommandUI BenchmarkFlags
benchmarkCommand = CommandUI
{ commandName = "bench"
, commandSynopsis =
"Run all/specific benchmarks."
, commandDescription = Just $ \ _pname -> wrapText $
testOrBenchmarkHelpText "benchmark"
, commandNotes = Nothing
, commandUsage = usageAlternatives "bench"
[ "[FLAGS]"
, "BENCHCOMPONENTS [FLAGS]"
]
, commandDefaultFlags = defaultBenchmarkFlags
, commandOptions = benchmarkOptions'
}
benchmarkOptions' :: ShowOrParseArgs -> [OptionField BenchmarkFlags]
benchmarkOptions' showOrParseArgs =
[ optionVerbosity benchmarkVerbosity
(\v flags -> flags { benchmarkVerbosity = v })
, optionDistPref
benchmarkDistPref (\d flags -> flags { benchmarkDistPref = d })
showOrParseArgs
, option [] ["benchmark-options"]
("give extra options to benchmark executables "
++ "(name templates can use $pkgid, $compiler, "
++ "$os, $arch, $benchmark)")
benchmarkOptions (\v flags -> flags { benchmarkOptions = v })
(reqArg' "TEMPLATES" (map toPathTemplate . splitArgs)
(const []))
, option [] ["benchmark-option"]
("give extra option to benchmark executables "
++ "(no need to quote options containing spaces, "
++ "name template can use $pkgid, $compiler, "
++ "$os, $arch, $benchmark)")
benchmarkOptions (\v flags -> flags { benchmarkOptions = v })
(reqArg' "TEMPLATE" (\x -> [toPathTemplate x])
(map fromPathTemplate))
]
emptyBenchmarkFlags :: BenchmarkFlags
emptyBenchmarkFlags = mempty
instance Monoid BenchmarkFlags where
mempty = gmempty
mappend = (<>)
instance Semigroup BenchmarkFlags where
(<>) = gmappend
| null | https://raw.githubusercontent.com/haskell/cabal/ab24689731e9fb45efa6277f290624622a6c214f/Cabal/src/Distribution/Simple/Setup/Benchmark.hs | haskell | # LANGUAGE DeriveDataTypeable #
# LANGUAGE RankNTypes #
---------------------------------------------------------------------------
|
Module : Distribution.Simple.Benchmark
License : BSD3
Maintainer :
Portability : portable
Definition of the benchmarking command-line options.
See: @Distribution.Simple.Setup@
------------------------------------------------------------
* Benchmark flags
------------------------------------------------------------ | # LANGUAGE CPP #
# LANGUAGE DeriveGeneric #
# LANGUAGE FlexibleContexts #
Copyright : 2003 - 2004
2007
module Distribution.Simple.Setup.Benchmark (
BenchmarkFlags(..), emptyBenchmarkFlags,
defaultBenchmarkFlags, benchmarkCommand,
benchmarkOptions'
) where
import Prelude ()
import Distribution.Compat.Prelude hiding (get)
import Distribution.Simple.Command hiding (boolOpt, boolOpt')
import Distribution.Simple.Flag
import Distribution.Simple.Utils
import Distribution.Simple.InstallDirs
import Distribution.Verbosity
import Distribution.Simple.Setup.Common
data BenchmarkFlags = BenchmarkFlags {
benchmarkDistPref :: Flag FilePath,
benchmarkVerbosity :: Flag Verbosity,
benchmarkOptions :: [PathTemplate]
} deriving (Show, Generic, Typeable)
defaultBenchmarkFlags :: BenchmarkFlags
defaultBenchmarkFlags = BenchmarkFlags {
benchmarkDistPref = NoFlag,
benchmarkVerbosity = Flag normal,
benchmarkOptions = []
}
benchmarkCommand :: CommandUI BenchmarkFlags
benchmarkCommand = CommandUI
{ commandName = "bench"
, commandSynopsis =
"Run all/specific benchmarks."
, commandDescription = Just $ \ _pname -> wrapText $
testOrBenchmarkHelpText "benchmark"
, commandNotes = Nothing
, commandUsage = usageAlternatives "bench"
[ "[FLAGS]"
, "BENCHCOMPONENTS [FLAGS]"
]
, commandDefaultFlags = defaultBenchmarkFlags
, commandOptions = benchmarkOptions'
}
benchmarkOptions' :: ShowOrParseArgs -> [OptionField BenchmarkFlags]
benchmarkOptions' showOrParseArgs =
[ optionVerbosity benchmarkVerbosity
(\v flags -> flags { benchmarkVerbosity = v })
, optionDistPref
benchmarkDistPref (\d flags -> flags { benchmarkDistPref = d })
showOrParseArgs
, option [] ["benchmark-options"]
("give extra options to benchmark executables "
++ "(name templates can use $pkgid, $compiler, "
++ "$os, $arch, $benchmark)")
benchmarkOptions (\v flags -> flags { benchmarkOptions = v })
(reqArg' "TEMPLATES" (map toPathTemplate . splitArgs)
(const []))
, option [] ["benchmark-option"]
("give extra option to benchmark executables "
++ "(no need to quote options containing spaces, "
++ "name template can use $pkgid, $compiler, "
++ "$os, $arch, $benchmark)")
benchmarkOptions (\v flags -> flags { benchmarkOptions = v })
(reqArg' "TEMPLATE" (\x -> [toPathTemplate x])
(map fromPathTemplate))
]
emptyBenchmarkFlags :: BenchmarkFlags
emptyBenchmarkFlags = mempty
instance Monoid BenchmarkFlags where
mempty = gmempty
mappend = (<>)
instance Semigroup BenchmarkFlags where
(<>) = gmappend
|
292f7faa2fe13039e31265e90ecb70c472803119b578ddec980e01e7f76c8625 | pirapira/bamboo | ethereum.mli | val word_bits : int
val signature_bits : int
type interface_typ =
| InterfaceUint of int
| InterfaceBytes of int
| InterfaceAddress
| InterfaceBool
(** size of values of the interface type in bytes *)
val interface_typ_size : interface_typ -> int
type interface_arg = string * interface_typ
* [ interpret_interface_type ] parses " uint " into InterfaceUint 256 , etc .
val interpret_interface_type : Syntax.typ -> interface_typ
val to_typ : interface_typ -> Syntax.typ
* [ string_of_interface_type t ] is a string that is used to compute the
* method signatures . Addresses are " address " , uint is " uint256 " .
* method signatures. Addresses are "address", uint is "uint256". *)
val string_of_interface_type : interface_typ -> string
type function_signature =
{ sig_return : interface_typ list
; sig_name : string
; sig_args : interface_typ list
}
val get_interface_typs :
Syntax.arg list -> (string * interface_typ) list
val arguments_with_locations :
Syntax.typ Syntax.case -> (string * Location.location) list
val constructor_arguments :
Syntax.typ Syntax.contract -> (string * interface_typ) list
val arrays_in_contract :
Syntax.typ Syntax.contract -> (string * Syntax.typ * Syntax.typ) list
val total_size_of_interface_args :
interface_typ list -> int
* [ string_keccak ] returns the Keccak-256 hash of a string in
* hex , without the prefix [ 0x ] .
* hex, without the prefix [0x]. *)
val string_keccak : string -> string
* [ hex_keccak ] expects a hex string and returns the Keccak-256 hash of the
* represented byte sequence , without the prefix [ 0x ] .
* represented byte sequence, without the prefix [0x]. *)
val hex_keccak : string -> string
* [ keccak_short " pay(address ) " ] returns the
* method signature code ( which is commonly used in the ABI .
* method signature code (which is commonly used in the ABI.
*)
val keccak_signature : string -> string
(** [case_heaer_signature_string h] returns the
* signature of a fucntion as used for creating the
* function hash. Like "pay(address)"
* TODO: cite some document here.
*)
val case_header_signature_string : Syntax.usual_case_header -> string
* [ compute_singature_hash ] takes a string like ` f(uint8,address ) ` and
returns a 4byte signature hash commonly used in Ethereum ABI .
returns a 4byte signature hash commonly used in Ethereum ABI. *)
val compute_signature_hash : string -> string
* [ case_header_signature_hash h ] returns the
* method signature used in the common ABI .
* The hex hash comes without 0x
* method signature used in the common ABI.
* The hex hash comes without 0x
*)
val case_header_signature_hash :
Syntax.usual_case_header -> string
val event_signature_hash :
Syntax.event -> string
val print_abi : Syntax.typ Syntax.toplevel Assoc.contract_id_assoc -> unit
| null | https://raw.githubusercontent.com/pirapira/bamboo/1cca98e0b6d2579fe32885e66aafd0f5e25d9eb5/src/ast/ethereum.mli | ocaml | * size of values of the interface type in bytes
* [case_heaer_signature_string h] returns the
* signature of a fucntion as used for creating the
* function hash. Like "pay(address)"
* TODO: cite some document here.
| val word_bits : int
val signature_bits : int
type interface_typ =
| InterfaceUint of int
| InterfaceBytes of int
| InterfaceAddress
| InterfaceBool
val interface_typ_size : interface_typ -> int
type interface_arg = string * interface_typ
* [ interpret_interface_type ] parses " uint " into InterfaceUint 256 , etc .
val interpret_interface_type : Syntax.typ -> interface_typ
val to_typ : interface_typ -> Syntax.typ
* [ string_of_interface_type t ] is a string that is used to compute the
* method signatures . Addresses are " address " , uint is " uint256 " .
* method signatures. Addresses are "address", uint is "uint256". *)
val string_of_interface_type : interface_typ -> string
type function_signature =
{ sig_return : interface_typ list
; sig_name : string
; sig_args : interface_typ list
}
val get_interface_typs :
Syntax.arg list -> (string * interface_typ) list
val arguments_with_locations :
Syntax.typ Syntax.case -> (string * Location.location) list
val constructor_arguments :
Syntax.typ Syntax.contract -> (string * interface_typ) list
val arrays_in_contract :
Syntax.typ Syntax.contract -> (string * Syntax.typ * Syntax.typ) list
val total_size_of_interface_args :
interface_typ list -> int
* [ string_keccak ] returns the Keccak-256 hash of a string in
* hex , without the prefix [ 0x ] .
* hex, without the prefix [0x]. *)
val string_keccak : string -> string
* [ hex_keccak ] expects a hex string and returns the Keccak-256 hash of the
* represented byte sequence , without the prefix [ 0x ] .
* represented byte sequence, without the prefix [0x]. *)
val hex_keccak : string -> string
* [ keccak_short " pay(address ) " ] returns the
* method signature code ( which is commonly used in the ABI .
* method signature code (which is commonly used in the ABI.
*)
val keccak_signature : string -> string
val case_header_signature_string : Syntax.usual_case_header -> string
* [ compute_singature_hash ] takes a string like ` f(uint8,address ) ` and
returns a 4byte signature hash commonly used in Ethereum ABI .
returns a 4byte signature hash commonly used in Ethereum ABI. *)
val compute_signature_hash : string -> string
* [ case_header_signature_hash h ] returns the
* method signature used in the common ABI .
* The hex hash comes without 0x
* method signature used in the common ABI.
* The hex hash comes without 0x
*)
val case_header_signature_hash :
Syntax.usual_case_header -> string
val event_signature_hash :
Syntax.event -> string
val print_abi : Syntax.typ Syntax.toplevel Assoc.contract_id_assoc -> unit
|
faa8c98bec99be08cfe4f303ad25e615aa22d843a82a2b63246d716a6474f5b3 | Bogdanp/koyo | user.rkt | #lang racket/base
(require component
db
deta
gregor
koyo/database
koyo/hasher
koyo/profiler
koyo/random
racket/contract
racket/string
threading)
;; user ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(provide
(schema-out user))
(define-schema user
([id id/f #:primary-key #:auto-increment]
[username string/f #:contract non-empty-string? #:wrapper string-downcase]
[(password-hash "") string/f]
[(verified? #f) boolean/f]
[(verification-code (generate-random-string)) string/f #:contract non-empty-string?]
[(created-at (now/moment)) datetime-tz/f]
[(updated-at (now/moment)) datetime-tz/f])
#:pre-persist-hook
(lambda (u)
(set-user-updated-at u (now/moment))))
(define (set-password um u p)
(set-user-password-hash u (hasher-make-hash (user-manager-hasher um) p)))
(define (password-valid? um u p)
(hasher-hash-matches? (user-manager-hasher um) (user-password-hash u) p))
;; password reset ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(define-schema password-reset
#:table "password_reset_requests"
([user-id id/f #:unique]
[ip-address string/f #:contract non-empty-string?]
[user-agent string/f #:contract non-empty-string?]
[(token (generate-random-string)) string/f #:contract non-empty-string?]
[(expires-at (+days (now/moment) 1)) datetime-tz/f]))
;; user-manager ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(provide
exn:fail:user-manager?
exn:fail:user-manager:username-taken?
make-user-manager
user-manager?
user-manager-lookup/id
user-manager-lookup/username
user-manager-create!
user-manager-create-reset-token!
user-manager-login
user-manager-verify!
user-manager-reset-password!)
(struct exn:fail:user-manager exn:fail ())
(struct exn:fail:user-manager:username-taken exn:fail:user-manager ())
(struct user-manager (db hasher)
#:transparent)
(define/contract (make-user-manager db h)
(-> database? hasher? user-manager?)
(user-manager db h))
(define/contract (user-manager-create! um username password)
(-> user-manager? string? string? user?)
(define the-user
(~> (make-user #:username username)
(set-password um _ password)))
(with-handlers ([exn:fail:sql:constraint-violation?
(lambda (_e)
(raise (exn:fail:user-manager:username-taken
(format "username '~a' is taken" username)
(current-continuation-marks))))])
(with-database-transaction [conn (user-manager-db um)]
(insert-one! conn the-user))))
(define/contract (user-manager-create-reset-token! um
#:username username
#:ip-address ip-address
#:user-agent user-agent)
(-> user-manager?
#:username non-empty-string?
#:ip-address non-empty-string?
#:user-agent non-empty-string?
(values (or/c false/c user?)
(or/c false/c string?)))
(with-timing 'user-manager "user-manager-create-reset-token!"
(with-database-transaction [conn (user-manager-db um)]
(cond
[(user-manager-lookup/username um username)
=> (lambda (user)
(query-exec conn (delete (~> (from password-reset #:as pr)
(where (= pr.user-id ,(user-id user))))))
(values user
(~> (make-password-reset #:user-id (user-id user)
#:ip-address ip-address
#:user-agent user-agent)
(insert-one! conn _)
(password-reset-token))))]
[else
(values #f #f)]))))
(define/contract (user-manager-lookup/id um id)
(-> user-manager? exact-positive-integer? (or/c false/c user?))
(with-timing 'user-manager (format "(user-manager-lookup/id ~v)" id)
(with-database-connection [conn (user-manager-db um)]
(lookup conn (~> (from user #:as u)
(where (= u.id ,id)))))))
(define/contract (user-manager-lookup/username um username)
(-> user-manager? string? (or/c false/c user?))
(with-timing 'user-manager (format "(user-manager-lookup/username ~v)" username)
(with-database-connection [conn (user-manager-db um)]
(lookup conn (~> (from user #:as u)
(where (= u.username ,(string-downcase username))))))))
(define/contract (user-manager-login um username password)
(-> user-manager? string? string? (or/c false/c user?))
(with-timing 'user-manager "user-manager-login"
(define user (user-manager-lookup/username um username))
(and user (password-valid? um user password) user)))
(define/contract (user-manager-verify! um id verification-code)
(-> user-manager? exact-positive-integer? string? void?)
(with-timing 'user-manager "user-manager-verify!"
(void
(with-database-transaction [conn (user-manager-db um)]
(query-exec conn (~> (from user #:as u)
(update [verified? #t])
(where (and (= u.id ,id)
(= u.verification-code ,verification-code)))))))))
(define/contract (user-manager-reset-password! um
#:user-id user-id
#:token token
#:password password)
(-> user-manager?
#:user-id id/c
#:token non-empty-string?
#:password non-empty-string?
boolean?)
(with-timing 'user-manager "user-manager-reset-password!"
(with-database-transaction [conn (user-manager-db um)]
(cond
[(lookup-password-reset conn user-id token)
=> (lambda (_pr)
(begin0 #t
(clear-password-reset! conn user-id)
(and~> (lookup conn
(~> (from user #:as u)
(where (= u.id ,user-id))))
(set-password um _ password)
(update! conn _))))]
[else #f]))))
(define (lookup-password-reset conn user-id token)
(lookup conn (~> (from password-reset #:as pr)
(where (and (= pr.user-id ,user-id)
(= pr.token ,token)
(> pr.expires-at (now)))))))
(define (clear-password-reset! conn user-id)
(query-exec conn (~> (from password-reset #:as pr)
(where (= pr.user-id ,user-id))
(delete))))
| null | https://raw.githubusercontent.com/Bogdanp/koyo/9fac1c0430e34030b430b82b2e6228819642b448/koyo-lib/blueprints/standard/app-name-here/components/user.rkt | racket | user ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
password reset ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
user-manager ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; | #lang racket/base
(require component
db
deta
gregor
koyo/database
koyo/hasher
koyo/profiler
koyo/random
racket/contract
racket/string
threading)
(provide
(schema-out user))
(define-schema user
([id id/f #:primary-key #:auto-increment]
[username string/f #:contract non-empty-string? #:wrapper string-downcase]
[(password-hash "") string/f]
[(verified? #f) boolean/f]
[(verification-code (generate-random-string)) string/f #:contract non-empty-string?]
[(created-at (now/moment)) datetime-tz/f]
[(updated-at (now/moment)) datetime-tz/f])
#:pre-persist-hook
(lambda (u)
(set-user-updated-at u (now/moment))))
(define (set-password um u p)
(set-user-password-hash u (hasher-make-hash (user-manager-hasher um) p)))
(define (password-valid? um u p)
(hasher-hash-matches? (user-manager-hasher um) (user-password-hash u) p))
(define-schema password-reset
#:table "password_reset_requests"
([user-id id/f #:unique]
[ip-address string/f #:contract non-empty-string?]
[user-agent string/f #:contract non-empty-string?]
[(token (generate-random-string)) string/f #:contract non-empty-string?]
[(expires-at (+days (now/moment) 1)) datetime-tz/f]))
(provide
exn:fail:user-manager?
exn:fail:user-manager:username-taken?
make-user-manager
user-manager?
user-manager-lookup/id
user-manager-lookup/username
user-manager-create!
user-manager-create-reset-token!
user-manager-login
user-manager-verify!
user-manager-reset-password!)
(struct exn:fail:user-manager exn:fail ())
(struct exn:fail:user-manager:username-taken exn:fail:user-manager ())
(struct user-manager (db hasher)
#:transparent)
(define/contract (make-user-manager db h)
(-> database? hasher? user-manager?)
(user-manager db h))
(define/contract (user-manager-create! um username password)
(-> user-manager? string? string? user?)
(define the-user
(~> (make-user #:username username)
(set-password um _ password)))
(with-handlers ([exn:fail:sql:constraint-violation?
(lambda (_e)
(raise (exn:fail:user-manager:username-taken
(format "username '~a' is taken" username)
(current-continuation-marks))))])
(with-database-transaction [conn (user-manager-db um)]
(insert-one! conn the-user))))
(define/contract (user-manager-create-reset-token! um
#:username username
#:ip-address ip-address
#:user-agent user-agent)
(-> user-manager?
#:username non-empty-string?
#:ip-address non-empty-string?
#:user-agent non-empty-string?
(values (or/c false/c user?)
(or/c false/c string?)))
(with-timing 'user-manager "user-manager-create-reset-token!"
(with-database-transaction [conn (user-manager-db um)]
(cond
[(user-manager-lookup/username um username)
=> (lambda (user)
(query-exec conn (delete (~> (from password-reset #:as pr)
(where (= pr.user-id ,(user-id user))))))
(values user
(~> (make-password-reset #:user-id (user-id user)
#:ip-address ip-address
#:user-agent user-agent)
(insert-one! conn _)
(password-reset-token))))]
[else
(values #f #f)]))))
(define/contract (user-manager-lookup/id um id)
(-> user-manager? exact-positive-integer? (or/c false/c user?))
(with-timing 'user-manager (format "(user-manager-lookup/id ~v)" id)
(with-database-connection [conn (user-manager-db um)]
(lookup conn (~> (from user #:as u)
(where (= u.id ,id)))))))
(define/contract (user-manager-lookup/username um username)
(-> user-manager? string? (or/c false/c user?))
(with-timing 'user-manager (format "(user-manager-lookup/username ~v)" username)
(with-database-connection [conn (user-manager-db um)]
(lookup conn (~> (from user #:as u)
(where (= u.username ,(string-downcase username))))))))
(define/contract (user-manager-login um username password)
(-> user-manager? string? string? (or/c false/c user?))
(with-timing 'user-manager "user-manager-login"
(define user (user-manager-lookup/username um username))
(and user (password-valid? um user password) user)))
(define/contract (user-manager-verify! um id verification-code)
(-> user-manager? exact-positive-integer? string? void?)
(with-timing 'user-manager "user-manager-verify!"
(void
(with-database-transaction [conn (user-manager-db um)]
(query-exec conn (~> (from user #:as u)
(update [verified? #t])
(where (and (= u.id ,id)
(= u.verification-code ,verification-code)))))))))
(define/contract (user-manager-reset-password! um
#:user-id user-id
#:token token
#:password password)
(-> user-manager?
#:user-id id/c
#:token non-empty-string?
#:password non-empty-string?
boolean?)
(with-timing 'user-manager "user-manager-reset-password!"
(with-database-transaction [conn (user-manager-db um)]
(cond
[(lookup-password-reset conn user-id token)
=> (lambda (_pr)
(begin0 #t
(clear-password-reset! conn user-id)
(and~> (lookup conn
(~> (from user #:as u)
(where (= u.id ,user-id))))
(set-password um _ password)
(update! conn _))))]
[else #f]))))
(define (lookup-password-reset conn user-id token)
(lookup conn (~> (from password-reset #:as pr)
(where (and (= pr.user-id ,user-id)
(= pr.token ,token)
(> pr.expires-at (now)))))))
(define (clear-password-reset! conn user-id)
(query-exec conn (~> (from password-reset #:as pr)
(where (= pr.user-id ,user-id))
(delete))))
|
d140ff7242c4f6618b35efb47cf3a7b64c343ee0bfa59c25a4c45dd50452e979 | pouriya/cfg | cfg_filter.erl | %%% ----------------------------------------------------------------------------
@author < >
%%% @hidden
%% -----------------------------------------------------------------------------
-module(cfg_filter).
-author('').
%% -----------------------------------------------------------------------------
%% Exports:
%% API
-export(
[
do/2,
get_module_filters/1,
get_application_filters/1
]
).
%% -----------------------------------------------------------------------------
%% Behaviour callback:
-callback
config_filters() -> Filters when
Filters :: [] | [Filter],
Filter :: {Key :: atom(), KeyFilter, DefaultValue :: term()}
| {Key :: atom(), infer, DefaultValue :: term()}
| {Key :: atom(), safe_infer, DefaultValue :: term()}
| {Key :: atom(), KeyFilter},
KeyFilter :: any | '_'
| atom
| binary
| number
| integer
| float
| list
| boolean
| proplist
| try_atom
| try_existing_atom
| try_binary
| try_number
| try_integer
| try_float
| try_boolean
| try_map
| atom_to_list
| list_to_atom
| list_to_binary
| list_to_integer
| list_to_float
| binary_to_list
| binary_to_integer
| binary_to_float
| atom_to_binary
| binary_to_atom
| proplist_to_map
| {'&' | 'and', KeyFilters}
| {'|' | 'or', KeyFilters}
| {proplist, Filters}
| {list, KeyFilter}
| {f, function()}
| {mf, {module(), FunctionName :: atom()}}
| {allowed_values, [any()]}
| {size, Size},
Size :: number()
| {min, number()}
| {max, number()}
| {Min :: number(), Max :: number()}.
%% -----------------------------------------------------------------------------
Records & Macros & Includes :
-include("cfg_stacktrace.hrl").
%% -----------------------------------------------------------------------------
%% API:
do(AppName, Cfg) when erlang:is_atom(AppName) ->
case get_application_filters(AppName) of
{ok, Filters} ->
filter_application(Filters, Cfg, [], AppName);
{_, {Reason, ErrParams}} ->
{error, {Reason, ErrParams#{application => AppName}}}
end;
do(Filters, Cfg) ->
filter(Filters, Cfg).
filter(Filters, Cfg) ->
case filter(Filters, Cfg, [], 1) of
{_, {Reason, ErrParams}} ->
{error, {Reason, ErrParams#{filters => Filters}}};
Ok ->
Ok
end.
get_application_filters(AppName) ->
case application:get_key(AppName, modules) of
{ok, Mods} ->
case get_modules_filters(Mods, []) of
{ok, _}=Ok ->
Ok;
{_, {Reason, ErrParams}} ->
{error, {Reason, ErrParams#{application => AppName}}}
end;
_ -> % undefined
{
error,
{
application_filters,
#{application => AppName, reason => not_found}
}
}
end.
get_module_filters(Mod) when erlang:is_atom(Mod) ->
try erlang:function_exported(Mod, config_filters, 0) andalso
Mod:config_filters()
of
false ->
{ok, []};
Filters ->
{ok, Filters}
catch
?define_stacktrace(_, Reason, Stacktrace) ->
{
error,
{
module_filters,
#{
module => Mod,
exception => Reason,
stacktrace => ?get_stacktrace(Stacktrace)
}
}
}
end.
%% -----------------------------------------------------------------------------
%% Internals:
filter_application([{Mod, ModFilters} | Filters], Cfg, Ret, AppName) ->
case filter(ModFilters, Cfg, Ret, 1) of
{ok, Ret2} ->
filter_application(Filters, Cfg, Ret2, AppName);
{_, {Reason, ErrParams}} ->
{
error,
{
Reason,
ErrParams#{filter_module => Mod, application => AppName}
}
}
end;
filter_application(_, _, Ret, _) ->
{ok, Ret}.
filter([Filter | Filters], Cfg, Ret, Index) ->
case do_filter(Filter, Cfg) of
{ok, {Key, Value}} ->
filter(Filters, Cfg, [{Key, remove_readers(Value)}|Ret], Index + 1);
{_, {Reason, ErrParams}} ->
{error, {Reason, make_error(ErrParams#{index => Index})}}
end;
filter([], _, Ret, _) ->
{ok, lists:reverse(Ret)}.
do_filter({Key, KeyFilter, Default}=Filter, Cfg) ->
case lookup_and_filter(Key, KeyFilter, {Default}, Cfg) of
{ok, _}=Ok ->
Ok;
{_, {Reason, ErrParams}} ->
{
error,
{
Reason,
ErrParams#{
filter => Filter,
key => Key,
key_filter => KeyFilter,
default_value => Default
}
}
}
end;
do_filter({Key, KeyFilter}=Filter, Cfg) ->
case lookup_and_filter(Key, KeyFilter, undefined, Cfg) of
{ok, _}=Ok ->
Ok;
{_, {Reason, ErrParams}} ->
{
error,
{
Reason,
ErrParams#{
filter => Filter,
key => Key,
key_filter => KeyFilter
}
}
}
end;
do_filter(Unknown, _) ->
{error, {filter_config, #{reason => bad_filter, filter => Unknown}}}.
lookup_and_filter(
Key,
Infer,
{DefaultValue}=Default,
Cfg
) when erlang:is_atom(Key) andalso
(Infer == infer orelse Infer == safe_infer orelse Infer == infer_safe) ->
SafeMode =
if
Infer == infer ->
false;
true ->
true
end,
case infer_key_filter(DefaultValue, SafeMode) of
{ok, KeyFilter} ->
case lookup_and_filter(Key, KeyFilter, Default, Cfg) of
{ok, _}=Ok ->
Ok;
{_, {Reason, ErrParams}} ->
{
error,
{
Reason,
ErrParams#{infered_key_filter => KeyFilter}
}
}
end;
_ -> % error
{error, {filter_config, #{reason => could_not_infer_filter}}}
end;
lookup_and_filter(Key, KeyFilter, Default, Cfg) when erlang:is_atom(Key) ->
case lookup(Key, Cfg, Default) of
{ok, Value, Readers} ->
case filter_value(KeyFilter, Key, Value) of
{ok, Value2} ->
{ok, {Key, Value2}};
{_, ErrParams} ->
{
error,
{
filter_config,
ErrParams#{readers => Readers, value => Value}
}
}
end;
not_found ->
{error, {filter_config, #{reason => value_not_found}}}
end;
lookup_and_filter(_, _, _, _) ->
{error, {filter_config, #{reason => bad_key}}}.
lookup(Key, Cfg, Default) ->
case lists:keyfind(Key, 1, Cfg) of
{_, Value} ->
{ok, Value, undefined};
{_, Value, Readers} ->
{ok, Value, Readers};
_ when erlang:is_tuple(Default) ->
{ok, erlang:element(1, Default), undefined};
_ ->
not_found
end.
filter_value(Any, _, Value) when Any == any orelse Any == '_' ->
{ok, Value};
filter_value(Type, _, Value) when Type == atom orelse
Type == binary orelse
Type == number orelse
Type == integer orelse
Type == float orelse
Type == list orelse
Type == boolean ->
case erlang:(
erlang:list_to_atom("is_" ++ erlang:atom_to_list(Type))
)(Value) of
true ->
{ok, Value};
_ ->
{error, #{allowed_type => Type}}
end;
filter_value(proplist, _, Value) ->
case is_proplist(Value) of
true ->
{ok, Value};
_ ->
{error, #{allowed_type => proplist}}
end;
filter_value(Type, _, Value) when Type == try_atom orelse
Type == try_existing_atom orelse
Type == try_binary orelse
Type == try_number orelse
Type == try_integer orelse
Type == try_float orelse
Type == try_boolean orelse
Type == try_map ->
case try_convert(Type, Value) of
{ok, _}=Ok ->
Ok;
not_found ->
{error, #{reason => atom_not_found}};
_ -> % error
{error, #{reason => could_not_convert}}
end;
filter_value(BIF, _, Value) when BIF == atom_to_list orelse
BIF == list_to_atom orelse
BIF == list_to_binary orelse
BIF == list_to_integer orelse
BIF == list_to_float orelse
BIF == binary_to_list orelse
BIF == binary_to_integer orelse
BIF == binary_to_float ->
try
{ok, erlang:BIF(Value)}
catch
_:_ ->
{error, #{reason => could_not_convert}}
end;
filter_value(BIF, _, Value) when BIF == atom_to_binary orelse
BIF == binary_to_atom ->
try
{ok, erlang:BIF(Value, utf8)}
catch
_:_ ->
{error, #{reason => could_not_convert}}
end;
filter_value(proplist_to_map, _, Value) ->
case is_proplist(Value) of
true ->
{ok, maps:from_list(remove_readers(Value))};
_ ->
{error, #{reason => could_not_convert}}
end;
filter_value({proplist, Filters}, _, Value) ->
case filter(Filters, Value, [], 1) of
{ok, _}=Ok ->
Ok;
{_, {_, ErrParams}} ->
{error, #{previous_error => ErrParams, proplist_filters => Filters}}
end;
filter_value({list, Filter}, Key, Value) ->
case filter_list(Value, Filter, Key, 1, []) of
{ok, _}=Ok ->
Ok;
{_, ErrParams} ->
{error, ErrParams#{list_filter => Filter}}
end;
filter_value({And, List}, Key, Value) when And == '&' orelse And == 'and' ->
case filter_and(List, Key, Value, 1, Value) of
{ok, _}=Ok ->
Ok;
{_, ErrParams} ->
{error, ErrParams#{and_filters => List}}
end;
filter_value({Or, List}, Key, Value) when Or == '|' orelse Or == 'or' ->
case filter_or(List, Key, Value, 0, undefined, undefined) of
{ok, _}=Ok ->
Ok;
{_, ErrParams} ->
{error, ErrParams#{or_filters => List}}
end;
filter_value({allowed_values, List}, _, Value) ->
filter_allowed_values(List, Value);
filter_value({size, Size}, _, Value) ->
filter_size(Size, Value);
filter_value({mf, MF}, Keys, Value) ->
filter_mf(MF, Keys, Value);
filter_value({f, F}, Keys, Value) ->
filter_f(F, Keys, Value);
filter_value(_, _, _) ->
{error, #{reason => bad_key_filter}}.
filter_mf({Mod, Func}, Keys, Value) when erlang:is_atom(Mod) andalso
erlang:is_atom(Func) ->
Arity =
case erlang:function_exported(Mod, Func, 2) of
true ->
2;
_ ->
1
end,
case run_filter(Arity, {Mod, Func}, Keys, Value) of
{error, ErrParams} ->
{
error,
ErrParams#{
mf_module => Mod,
mf_function => Func,
mf_arity => Arity
}
};
Ok ->
Ok
end.
filter_f(Func, Keys, Value) when erlang:is_function(Func) ->
{_, Arity} = erlang:fun_info(Func, arity),
case run_filter(Arity, Func, Keys, Value) of
{error, ErrParams} ->
{error, ErrParams#{f_function => Func, f_arity => Arity}};
Ok ->
Ok
end.
run_filter(Arity, Filter, Key, Value) when Arity == 1 orelse Arity == 2 ->
try
case Filter of
{Mod, Func} when Arity == 1 ->
Mod:Func(Value);
{Mod, Func} ->
Mod:Func(Key, Value);
_ when Arity == 1 ->
Filter(Value);
_ ->
Filter(Key, Value)
end
of
Ok when Ok == ok orelse Ok == true ->
{ok, Value};
{ok, _}=Ok ->
Ok;
false ->
{error, #{reason => bad_value}};
{error, ErrParams} when erlang:is_map(ErrParams) ->
{error, #{previous_error => ErrParams}};
Other ->
{error, #{returned_value => Other}}
catch
?define_stacktrace(_, Reason, Stacktrace) ->
{
error,
#{
exception => Reason,
stacktrace => ?get_stacktrace(Stacktrace)
}
}
end;
run_filter(_, _, _, _) ->
{error, #{f_allowed_arity => [1,2]}}.
filter_allowed_values(List, Value) ->
try lists:member(Value, List) of
true ->
{ok, Value};
_ ->
{error, #{allowed_values => List}}
catch
_:_ ->
{error, #{reason => bad_allowed_values, allowed_values => List}}
end.
filter_size(Size, Value) when erlang:is_number(Size) ->
case get_size(Value) of
{ok, Size2} when erlang:round(Size2) == Size ->
{ok, Value};
{ok, Size2} ->
{error, #{allowed_size => Size, size => Size2}};
Err ->
Err
end;
filter_size({min, Size}, Value) when erlang:is_number(Size) ->
case get_size(Value) of
{ok, Size2} when Size2 >= Size ->
{ok, Value};
{ok, Size2} ->
{error, #{allowed_min_size => Size, size => Size2}};
Err ->
Err
end;
filter_size({max, Size}, Value) when erlang:is_number(Size) ->
case get_size(Value) of
{ok, Size2} when Size2 =< Size ->
{ok, Value};
{ok, Size2} ->
{error, #{allowed_max_size => Size, size => Size2}};
Err ->
Err
end;
filter_size(
{MinSize, MaxSize},
Value
) when erlang:is_number(MinSize) andalso erlang:is_number(MaxSize) ->
case get_size(Value) of
{ok, Size2} when Size2 =< MaxSize andalso Size2 >= MinSize ->
{ok, Value};
{ok, Size2} when Size2 =< MaxSize ->
{error, #{allowed_min_size => MinSize, size => Size2}};
{ok, Size2} ->
{error, #{allowed_max_size => MaxSize, size => Size2}};
Err ->
Err
end;
filter_size(Unknown, _) ->
{error, #{reason => size_bad_value, size_value => Unknown}}.
get_size(Value) ->
if
erlang:is_list(Value) ->
try
{ok, erlang:length(Value)}
catch
_:_ ->
{error, #{reason => unknown_size}}
end;
erlang:is_binary(Value) ->
{ok, erlang:byte_size(Value)};
erlang:is_integer(Value) andalso Value >= 0 ->
{ok, Value};
erlang:is_float(Value) andalso Value >= 0 ->
{ok, erlang:trunc(Value)};
erlang:is_atom(Value) ->
{ok, erlang:length(erlang:atom_to_list(Value))};
true ->
{error, #{reason => unknown_size}}
end.
filter_and([Filter | Filters], Key, Value, Index, OrigValue) ->
case filter_value(Filter, Key, Value) of
{ok, Value2} ->
filter_and(Filters, Key, Value2, Index + 1, OrigValue);
{_, ErrParams} ->
{
error,
#{
and_last_value => Value,
and_original_value => OrigValue,
previous_error => ErrParams,
and_filter => Filter,
and_filter_index => Index
}
}
end;
filter_and([], _, Value, _, _) ->
{ok, Value};
filter_and(Filters, _, _, 1, _) ->
{error, #{reason => and_bad_filters, and_filters => Filters}};
filter_and(Unknown, _, _, Index, _) ->
{
error,
#{
reason => and_bad_filter,
and_filter_index => Index,
and_filter => Unknown
}
}.
filter_or([Filter | Filters], Key, Value, Index, _, _) ->
case filter_value(Filter, Key, Value) of
{ok, _}=Ok ->
Ok;
{_, ErrParams} ->
filter_or(Filters, Key, Value, Index + 1, Filter, ErrParams)
end;
filter_or([], _, _, 0, _, _) ->
{error, #{reason => or_empty_filters}};
filter_or([], _, _, Index, LastFilter, LastErrParams) ->
{
error,
#{
or_filter_index => Index,
or_last_filter => LastFilter,
previous_error => LastErrParams
}
};
filter_or(Filters, _, _, 0, _, _) ->
{error, #{reason => or_bad_filters, or_filters => Filters}};
filter_or(Unknown, _, _, Index, _, _) ->
{
error,
#{
reason => or_bad_filter,
or_filter_index => Index,
or_filter => Unknown
}
}.
filter_list([Element | List], Filter, Key, Index, Ret) ->
case filter_value(Filter, Key, Element) of
{ok, Element2} ->
filter_list(List, Filter, Key, Index + 1, [Element2 | Ret]);
{_, ErrParams} ->
{
error,
#{
list_element => Element,
list_index => Index,
previous_error => ErrParams
}
}
end;
filter_list([], _, _, _, Ret) ->
{ok, lists:reverse(Ret)};
filter_list(_, _, _, 1, _) ->
{error, #{allowed_type => list}};
filter_list(Unknown, _, _, Index, _) ->
{
error,
#{
reason => bad_list_element,
index => Index,
list_element => Unknown
}
}.
get_modules_filters([Mod | Mods], Filters) ->
case get_module_filters(Mod) of
{ok, ModFilters} ->
get_modules_filters(Mods, [{Mod, ModFilters} | Filters]);
Err ->
Err
end;
get_modules_filters(_, Filters) ->
{ok, Filters}.
infer_key_filter(Value, SafeMode) when erlang:is_atom(Value) ->
if
SafeMode ->
{ok, try_existing_atom};
true ->
{ok, try_atom}
end;
infer_key_filter(Value, _) when erlang:is_binary(Value) ->
{ok, try_binary};
infer_key_filter(Value, _) when erlang:is_integer(Value) ->
{ok, try_integer};
infer_key_filter(Value, _) when erlang:is_float(Value) ->
{ok, try_float};
infer_key_filter(Value, SafeMode) when erlang:is_list(Value) ->
case is_proplist(Value) of
true ->
infer_proplist(Value, SafeMode, []);
_ ->
infer_list(Value, SafeMode, [])
end;
infer_key_filter(Value, SafeMode) when erlang:is_map(Value) ->
case infer_key_filter(maps:to_list(Value), SafeMode) of
{ok, ProplistFilter} ->
{ok, {'and', [ProplistFilter, proplist_to_map]}};
Err ->
Err
end;
infer_key_filter(_, _) ->
error.
infer_proplist([{Key, Value} | Proplist], SafeMode, Ret) ->
case infer_key_filter(Value, SafeMode) of
{ok, Filter} ->
infer_proplist(Proplist, SafeMode, [{Key, Filter, Value} | Ret]);
Err ->
Err
end;
infer_proplist([], _, [_|_]=Ret) ->
{ok, {proplist, lists:reverse(Ret)}};
infer_proplist([], _, _) ->
{ok, list};
infer_proplist(_, _, _) ->
error.
infer_list([Value | List], SafeMode, Ret) ->
case infer_key_filter(Value, SafeMode) of
{ok, Filter} ->
infer_list(List, SafeMode, [Filter | Ret]);
Err ->
Err
end;
infer_list(_, _, [_|_]=Filters) ->
{ok, {list, {'or', sets:to_list(sets:from_list(lists:reverse(Filters)))}}};
infer_list(_, _, _) ->
{ok, list}.
try_convert(try_atom, Value) ->
try_convert_to_atom(Value);
try_convert(try_binary, Value) ->
try_convert_to_binary(Value);
try_convert(try_integer, Value) ->
try_convert_to_integer(Value);
try_convert(try_number, Value) ->
try_convert_to_number(Value);
try_convert(try_float, Value) ->
try_convert_to_float(Value);
try_convert(try_existing_atom, Value) ->
try_convert_to_existing_atom(Value);
try_convert(try_boolean, Value) ->
try_convert_to_boolean(Value);
try_convert(_, Value) -> % try_map
try_convert_to_map(Value).
try_convert_to_atom(Value) when erlang:is_binary(Value) ->
{ok, erlang:binary_to_atom(Value, utf8)};
try_convert_to_atom(Value) when erlang:is_list(Value) ->
try
{ok, erlang:list_to_atom(Value)}
catch
_:_ ->
error
end;
try_convert_to_atom(Value) when erlang:is_integer(Value) ->
{ok, erlang:list_to_atom(erlang:integer_to_list(Value))};
try_convert_to_atom(Value) when erlang:is_atom(Value) ->
{ok, Value};
try_convert_to_atom(_) ->
error.
try_convert_to_existing_atom(Value) when erlang:is_binary(Value) ->
try_convert_to_existing_atom(erlang:binary_to_list(Value));
try_convert_to_existing_atom(Value) when erlang:is_list(Value) ->
try
{ok, erlang:list_to_existing_atom(Value)}
catch
_:_ ->
not_found
end;
try_convert_to_existing_atom(Value) when erlang:is_integer(Value) ->
try_convert_to_existing_atom(erlang:integer_to_list(Value));
try_convert_to_existing_atom(Value) when erlang:is_atom(Value) ->
{ok, Value};
try_convert_to_existing_atom(_) ->
error.
try_convert_to_binary(Value) when erlang:is_list(Value) ->
try
{ok, erlang:list_to_binary(Value)}
catch
_:_ ->
error
end;
try_convert_to_binary(Value) when erlang:is_integer(Value) ->
{ok, erlang:integer_to_binary(Value)};
try_convert_to_binary(Value) when erlang:is_float(Value) ->
{ok, erlang:float_to_binary(Value, [compact, {decimals, 15}])};
try_convert_to_binary(Value) when erlang:is_atom(Value) ->
{ok, erlang:atom_to_binary(Value, utf8)};
try_convert_to_binary(Value) when erlang:is_binary(Value) ->
{ok, Value};
try_convert_to_binary(_) ->
error.
try_convert_to_integer(Value) when erlang:is_binary(Value) ->
try_convert_to_integer(erlang:binary_to_list(Value));
try_convert_to_integer(Value) when erlang:is_list(Value) ->
TryFloat =
try erlang:list_to_float(Value) of
Value2 ->
try_convert_to_integer(Value2)
catch
_:_ ->
error
end,
if
TryFloat /= error ->
TryFloat;
true ->
try
{ok, erlang:list_to_integer(Value)}
catch
_:_ ->
error
end
end;
try_convert_to_integer(Value) when erlang:is_float(Value) ->
{ok, erlang:list_to_integer(erlang:float_to_list(Value, [{decimals, 0}]))};
try_convert_to_integer(Value) when erlang:is_atom(Value) ->
try_convert_to_integer(erlang:atom_to_list(Value));
try_convert_to_integer(Value) when erlang:is_integer(Value) ->
{ok, Value};
try_convert_to_integer(_) ->
error.
try_convert_to_float(Value) when erlang:is_binary(Value) ->
try_convert_to_float(erlang:binary_to_list(Value));
try_convert_to_float(Value) when erlang:is_list(Value) ->
TryFloat =
try
{ok, erlang:list_to_float(Value)}
catch
_:_ ->
error
end,
if
TryFloat /= error ->
TryFloat;
true ->
try
{ok, erlang:float(erlang:list_to_integer(Value))}
catch
_:_ ->
error
end
end;
try_convert_to_float(Value) when erlang:is_integer(Value) ->
{ok, erlang:float(Value)};
try_convert_to_float(Value) when erlang:is_atom(Value) ->
try_convert_to_float(erlang:atom_to_list(Value));
try_convert_to_float(Value) when erlang:is_float(Value) ->
{ok, Value};
try_convert_to_float(_) ->
error.
try_convert_to_number(Value) ->
case {try_convert_to_float(Value), try_convert_to_integer(Value)} of
{{_, Float}, {_, Integer}=Ok} when Float == Integer ->
Ok;
{{_, _}=Ok, _} ->
Ok;
_ ->
error
end.
try_convert_to_boolean(Value) when erlang:is_binary(Value) ->
try_convert_to_boolean(erlang:binary_to_list(Value));
try_convert_to_boolean("true") ->
{ok, true};
try_convert_to_boolean("false") ->
{ok, false};
try_convert_to_boolean(0) ->
{ok, false};
try_convert_to_boolean(1) ->
{ok, true};
try_convert_to_boolean(Value) when erlang:is_list(Value) ->
case try_convert_to_integer(Value) of
{ok, Integer} ->
try_convert_to_boolean(Integer);
_ ->
error
end;
try_convert_to_boolean(Value) when erlang:is_boolean(Value) ->
{ok, Value};
try_convert_to_boolean(_) ->
error.
try_convert_to_map(Value) ->
case is_proplist(Value) of
true ->
{ok, maps:from_list(remove_readers(Value))};
_ ->
error
end.
is_proplist([{Key, _}|Rest]) when erlang:is_atom(Key) ->
is_proplist(Rest);
is_proplist([{Key, _, _}|Rest]) when erlang:is_atom(Key) ->
is_proplist(Rest);
is_proplist([]) ->
true;
is_proplist(_) ->
false.
remove_readers([{Key, Value, _} | Rest]) ->
[{Key, remove_readers(Value)} | remove_readers(Rest)];
remove_readers([{Key, Value} | Rest]) ->
[{Key, remove_readers(Value)} | remove_readers(Rest)];
remove_readers(X) ->
X.
make_error(
#{previous_error := PrevErr}=ErrParams
) when erlang:is_map(PrevErr) ->
PrevErr2 = make_error(PrevErr),
FilterFun =
fun(Key, Value, {PrevErrX, ErrParamsX}) ->
case maps:is_key(Key, ErrParamsX) of
false ->
{maps:remove(Key, PrevErrX), ErrParamsX#{Key => Value}};
_ ->
{PrevErrX, ErrParamsX}
end
end,
case maps:fold(FilterFun, {make_error(PrevErr), ErrParams}, PrevErr2) of
{PrevErr3, ErrParams2} when erlang:map_size(PrevErr3) == 0 ->
maps:remove(previous_error, ErrParams2);
{PrevErr3, ErrParams2} ->
ErrParams2#{previous_error => PrevErr3}
end;
make_error(X) ->
X.
| null | https://raw.githubusercontent.com/pouriya/cfg/b03eb73549e2fa11b88f91db73f700d7e6ef4617/src/cfg_filter.erl | erlang | ----------------------------------------------------------------------------
@hidden
-----------------------------------------------------------------------------
-----------------------------------------------------------------------------
Exports:
API
-----------------------------------------------------------------------------
Behaviour callback:
-----------------------------------------------------------------------------
-----------------------------------------------------------------------------
API:
undefined
-----------------------------------------------------------------------------
Internals:
error
error
try_map | @author < >
-module(cfg_filter).
-author('').
-export(
[
do/2,
get_module_filters/1,
get_application_filters/1
]
).
-callback
config_filters() -> Filters when
Filters :: [] | [Filter],
Filter :: {Key :: atom(), KeyFilter, DefaultValue :: term()}
| {Key :: atom(), infer, DefaultValue :: term()}
| {Key :: atom(), safe_infer, DefaultValue :: term()}
| {Key :: atom(), KeyFilter},
KeyFilter :: any | '_'
| atom
| binary
| number
| integer
| float
| list
| boolean
| proplist
| try_atom
| try_existing_atom
| try_binary
| try_number
| try_integer
| try_float
| try_boolean
| try_map
| atom_to_list
| list_to_atom
| list_to_binary
| list_to_integer
| list_to_float
| binary_to_list
| binary_to_integer
| binary_to_float
| atom_to_binary
| binary_to_atom
| proplist_to_map
| {'&' | 'and', KeyFilters}
| {'|' | 'or', KeyFilters}
| {proplist, Filters}
| {list, KeyFilter}
| {f, function()}
| {mf, {module(), FunctionName :: atom()}}
| {allowed_values, [any()]}
| {size, Size},
Size :: number()
| {min, number()}
| {max, number()}
| {Min :: number(), Max :: number()}.
Records & Macros & Includes :
-include("cfg_stacktrace.hrl").
do(AppName, Cfg) when erlang:is_atom(AppName) ->
case get_application_filters(AppName) of
{ok, Filters} ->
filter_application(Filters, Cfg, [], AppName);
{_, {Reason, ErrParams}} ->
{error, {Reason, ErrParams#{application => AppName}}}
end;
do(Filters, Cfg) ->
filter(Filters, Cfg).
filter(Filters, Cfg) ->
case filter(Filters, Cfg, [], 1) of
{_, {Reason, ErrParams}} ->
{error, {Reason, ErrParams#{filters => Filters}}};
Ok ->
Ok
end.
get_application_filters(AppName) ->
case application:get_key(AppName, modules) of
{ok, Mods} ->
case get_modules_filters(Mods, []) of
{ok, _}=Ok ->
Ok;
{_, {Reason, ErrParams}} ->
{error, {Reason, ErrParams#{application => AppName}}}
end;
{
error,
{
application_filters,
#{application => AppName, reason => not_found}
}
}
end.
get_module_filters(Mod) when erlang:is_atom(Mod) ->
try erlang:function_exported(Mod, config_filters, 0) andalso
Mod:config_filters()
of
false ->
{ok, []};
Filters ->
{ok, Filters}
catch
?define_stacktrace(_, Reason, Stacktrace) ->
{
error,
{
module_filters,
#{
module => Mod,
exception => Reason,
stacktrace => ?get_stacktrace(Stacktrace)
}
}
}
end.
filter_application([{Mod, ModFilters} | Filters], Cfg, Ret, AppName) ->
case filter(ModFilters, Cfg, Ret, 1) of
{ok, Ret2} ->
filter_application(Filters, Cfg, Ret2, AppName);
{_, {Reason, ErrParams}} ->
{
error,
{
Reason,
ErrParams#{filter_module => Mod, application => AppName}
}
}
end;
filter_application(_, _, Ret, _) ->
{ok, Ret}.
filter([Filter | Filters], Cfg, Ret, Index) ->
case do_filter(Filter, Cfg) of
{ok, {Key, Value}} ->
filter(Filters, Cfg, [{Key, remove_readers(Value)}|Ret], Index + 1);
{_, {Reason, ErrParams}} ->
{error, {Reason, make_error(ErrParams#{index => Index})}}
end;
filter([], _, Ret, _) ->
{ok, lists:reverse(Ret)}.
do_filter({Key, KeyFilter, Default}=Filter, Cfg) ->
case lookup_and_filter(Key, KeyFilter, {Default}, Cfg) of
{ok, _}=Ok ->
Ok;
{_, {Reason, ErrParams}} ->
{
error,
{
Reason,
ErrParams#{
filter => Filter,
key => Key,
key_filter => KeyFilter,
default_value => Default
}
}
}
end;
do_filter({Key, KeyFilter}=Filter, Cfg) ->
case lookup_and_filter(Key, KeyFilter, undefined, Cfg) of
{ok, _}=Ok ->
Ok;
{_, {Reason, ErrParams}} ->
{
error,
{
Reason,
ErrParams#{
filter => Filter,
key => Key,
key_filter => KeyFilter
}
}
}
end;
do_filter(Unknown, _) ->
{error, {filter_config, #{reason => bad_filter, filter => Unknown}}}.
lookup_and_filter(
Key,
Infer,
{DefaultValue}=Default,
Cfg
) when erlang:is_atom(Key) andalso
(Infer == infer orelse Infer == safe_infer orelse Infer == infer_safe) ->
SafeMode =
if
Infer == infer ->
false;
true ->
true
end,
case infer_key_filter(DefaultValue, SafeMode) of
{ok, KeyFilter} ->
case lookup_and_filter(Key, KeyFilter, Default, Cfg) of
{ok, _}=Ok ->
Ok;
{_, {Reason, ErrParams}} ->
{
error,
{
Reason,
ErrParams#{infered_key_filter => KeyFilter}
}
}
end;
{error, {filter_config, #{reason => could_not_infer_filter}}}
end;
lookup_and_filter(Key, KeyFilter, Default, Cfg) when erlang:is_atom(Key) ->
case lookup(Key, Cfg, Default) of
{ok, Value, Readers} ->
case filter_value(KeyFilter, Key, Value) of
{ok, Value2} ->
{ok, {Key, Value2}};
{_, ErrParams} ->
{
error,
{
filter_config,
ErrParams#{readers => Readers, value => Value}
}
}
end;
not_found ->
{error, {filter_config, #{reason => value_not_found}}}
end;
lookup_and_filter(_, _, _, _) ->
{error, {filter_config, #{reason => bad_key}}}.
lookup(Key, Cfg, Default) ->
case lists:keyfind(Key, 1, Cfg) of
{_, Value} ->
{ok, Value, undefined};
{_, Value, Readers} ->
{ok, Value, Readers};
_ when erlang:is_tuple(Default) ->
{ok, erlang:element(1, Default), undefined};
_ ->
not_found
end.
filter_value(Any, _, Value) when Any == any orelse Any == '_' ->
{ok, Value};
filter_value(Type, _, Value) when Type == atom orelse
Type == binary orelse
Type == number orelse
Type == integer orelse
Type == float orelse
Type == list orelse
Type == boolean ->
case erlang:(
erlang:list_to_atom("is_" ++ erlang:atom_to_list(Type))
)(Value) of
true ->
{ok, Value};
_ ->
{error, #{allowed_type => Type}}
end;
filter_value(proplist, _, Value) ->
case is_proplist(Value) of
true ->
{ok, Value};
_ ->
{error, #{allowed_type => proplist}}
end;
filter_value(Type, _, Value) when Type == try_atom orelse
Type == try_existing_atom orelse
Type == try_binary orelse
Type == try_number orelse
Type == try_integer orelse
Type == try_float orelse
Type == try_boolean orelse
Type == try_map ->
case try_convert(Type, Value) of
{ok, _}=Ok ->
Ok;
not_found ->
{error, #{reason => atom_not_found}};
{error, #{reason => could_not_convert}}
end;
filter_value(BIF, _, Value) when BIF == atom_to_list orelse
BIF == list_to_atom orelse
BIF == list_to_binary orelse
BIF == list_to_integer orelse
BIF == list_to_float orelse
BIF == binary_to_list orelse
BIF == binary_to_integer orelse
BIF == binary_to_float ->
try
{ok, erlang:BIF(Value)}
catch
_:_ ->
{error, #{reason => could_not_convert}}
end;
filter_value(BIF, _, Value) when BIF == atom_to_binary orelse
BIF == binary_to_atom ->
try
{ok, erlang:BIF(Value, utf8)}
catch
_:_ ->
{error, #{reason => could_not_convert}}
end;
filter_value(proplist_to_map, _, Value) ->
case is_proplist(Value) of
true ->
{ok, maps:from_list(remove_readers(Value))};
_ ->
{error, #{reason => could_not_convert}}
end;
filter_value({proplist, Filters}, _, Value) ->
case filter(Filters, Value, [], 1) of
{ok, _}=Ok ->
Ok;
{_, {_, ErrParams}} ->
{error, #{previous_error => ErrParams, proplist_filters => Filters}}
end;
filter_value({list, Filter}, Key, Value) ->
case filter_list(Value, Filter, Key, 1, []) of
{ok, _}=Ok ->
Ok;
{_, ErrParams} ->
{error, ErrParams#{list_filter => Filter}}
end;
filter_value({And, List}, Key, Value) when And == '&' orelse And == 'and' ->
case filter_and(List, Key, Value, 1, Value) of
{ok, _}=Ok ->
Ok;
{_, ErrParams} ->
{error, ErrParams#{and_filters => List}}
end;
filter_value({Or, List}, Key, Value) when Or == '|' orelse Or == 'or' ->
case filter_or(List, Key, Value, 0, undefined, undefined) of
{ok, _}=Ok ->
Ok;
{_, ErrParams} ->
{error, ErrParams#{or_filters => List}}
end;
filter_value({allowed_values, List}, _, Value) ->
filter_allowed_values(List, Value);
filter_value({size, Size}, _, Value) ->
filter_size(Size, Value);
filter_value({mf, MF}, Keys, Value) ->
filter_mf(MF, Keys, Value);
filter_value({f, F}, Keys, Value) ->
filter_f(F, Keys, Value);
filter_value(_, _, _) ->
{error, #{reason => bad_key_filter}}.
filter_mf({Mod, Func}, Keys, Value) when erlang:is_atom(Mod) andalso
erlang:is_atom(Func) ->
Arity =
case erlang:function_exported(Mod, Func, 2) of
true ->
2;
_ ->
1
end,
case run_filter(Arity, {Mod, Func}, Keys, Value) of
{error, ErrParams} ->
{
error,
ErrParams#{
mf_module => Mod,
mf_function => Func,
mf_arity => Arity
}
};
Ok ->
Ok
end.
filter_f(Func, Keys, Value) when erlang:is_function(Func) ->
{_, Arity} = erlang:fun_info(Func, arity),
case run_filter(Arity, Func, Keys, Value) of
{error, ErrParams} ->
{error, ErrParams#{f_function => Func, f_arity => Arity}};
Ok ->
Ok
end.
run_filter(Arity, Filter, Key, Value) when Arity == 1 orelse Arity == 2 ->
try
case Filter of
{Mod, Func} when Arity == 1 ->
Mod:Func(Value);
{Mod, Func} ->
Mod:Func(Key, Value);
_ when Arity == 1 ->
Filter(Value);
_ ->
Filter(Key, Value)
end
of
Ok when Ok == ok orelse Ok == true ->
{ok, Value};
{ok, _}=Ok ->
Ok;
false ->
{error, #{reason => bad_value}};
{error, ErrParams} when erlang:is_map(ErrParams) ->
{error, #{previous_error => ErrParams}};
Other ->
{error, #{returned_value => Other}}
catch
?define_stacktrace(_, Reason, Stacktrace) ->
{
error,
#{
exception => Reason,
stacktrace => ?get_stacktrace(Stacktrace)
}
}
end;
run_filter(_, _, _, _) ->
{error, #{f_allowed_arity => [1,2]}}.
filter_allowed_values(List, Value) ->
try lists:member(Value, List) of
true ->
{ok, Value};
_ ->
{error, #{allowed_values => List}}
catch
_:_ ->
{error, #{reason => bad_allowed_values, allowed_values => List}}
end.
filter_size(Size, Value) when erlang:is_number(Size) ->
case get_size(Value) of
{ok, Size2} when erlang:round(Size2) == Size ->
{ok, Value};
{ok, Size2} ->
{error, #{allowed_size => Size, size => Size2}};
Err ->
Err
end;
filter_size({min, Size}, Value) when erlang:is_number(Size) ->
case get_size(Value) of
{ok, Size2} when Size2 >= Size ->
{ok, Value};
{ok, Size2} ->
{error, #{allowed_min_size => Size, size => Size2}};
Err ->
Err
end;
filter_size({max, Size}, Value) when erlang:is_number(Size) ->
case get_size(Value) of
{ok, Size2} when Size2 =< Size ->
{ok, Value};
{ok, Size2} ->
{error, #{allowed_max_size => Size, size => Size2}};
Err ->
Err
end;
filter_size(
{MinSize, MaxSize},
Value
) when erlang:is_number(MinSize) andalso erlang:is_number(MaxSize) ->
case get_size(Value) of
{ok, Size2} when Size2 =< MaxSize andalso Size2 >= MinSize ->
{ok, Value};
{ok, Size2} when Size2 =< MaxSize ->
{error, #{allowed_min_size => MinSize, size => Size2}};
{ok, Size2} ->
{error, #{allowed_max_size => MaxSize, size => Size2}};
Err ->
Err
end;
filter_size(Unknown, _) ->
{error, #{reason => size_bad_value, size_value => Unknown}}.
get_size(Value) ->
if
erlang:is_list(Value) ->
try
{ok, erlang:length(Value)}
catch
_:_ ->
{error, #{reason => unknown_size}}
end;
erlang:is_binary(Value) ->
{ok, erlang:byte_size(Value)};
erlang:is_integer(Value) andalso Value >= 0 ->
{ok, Value};
erlang:is_float(Value) andalso Value >= 0 ->
{ok, erlang:trunc(Value)};
erlang:is_atom(Value) ->
{ok, erlang:length(erlang:atom_to_list(Value))};
true ->
{error, #{reason => unknown_size}}
end.
filter_and([Filter | Filters], Key, Value, Index, OrigValue) ->
case filter_value(Filter, Key, Value) of
{ok, Value2} ->
filter_and(Filters, Key, Value2, Index + 1, OrigValue);
{_, ErrParams} ->
{
error,
#{
and_last_value => Value,
and_original_value => OrigValue,
previous_error => ErrParams,
and_filter => Filter,
and_filter_index => Index
}
}
end;
filter_and([], _, Value, _, _) ->
{ok, Value};
filter_and(Filters, _, _, 1, _) ->
{error, #{reason => and_bad_filters, and_filters => Filters}};
filter_and(Unknown, _, _, Index, _) ->
{
error,
#{
reason => and_bad_filter,
and_filter_index => Index,
and_filter => Unknown
}
}.
filter_or([Filter | Filters], Key, Value, Index, _, _) ->
case filter_value(Filter, Key, Value) of
{ok, _}=Ok ->
Ok;
{_, ErrParams} ->
filter_or(Filters, Key, Value, Index + 1, Filter, ErrParams)
end;
filter_or([], _, _, 0, _, _) ->
{error, #{reason => or_empty_filters}};
filter_or([], _, _, Index, LastFilter, LastErrParams) ->
{
error,
#{
or_filter_index => Index,
or_last_filter => LastFilter,
previous_error => LastErrParams
}
};
filter_or(Filters, _, _, 0, _, _) ->
{error, #{reason => or_bad_filters, or_filters => Filters}};
filter_or(Unknown, _, _, Index, _, _) ->
{
error,
#{
reason => or_bad_filter,
or_filter_index => Index,
or_filter => Unknown
}
}.
filter_list([Element | List], Filter, Key, Index, Ret) ->
case filter_value(Filter, Key, Element) of
{ok, Element2} ->
filter_list(List, Filter, Key, Index + 1, [Element2 | Ret]);
{_, ErrParams} ->
{
error,
#{
list_element => Element,
list_index => Index,
previous_error => ErrParams
}
}
end;
filter_list([], _, _, _, Ret) ->
{ok, lists:reverse(Ret)};
filter_list(_, _, _, 1, _) ->
{error, #{allowed_type => list}};
filter_list(Unknown, _, _, Index, _) ->
{
error,
#{
reason => bad_list_element,
index => Index,
list_element => Unknown
}
}.
get_modules_filters([Mod | Mods], Filters) ->
case get_module_filters(Mod) of
{ok, ModFilters} ->
get_modules_filters(Mods, [{Mod, ModFilters} | Filters]);
Err ->
Err
end;
get_modules_filters(_, Filters) ->
{ok, Filters}.
infer_key_filter(Value, SafeMode) when erlang:is_atom(Value) ->
if
SafeMode ->
{ok, try_existing_atom};
true ->
{ok, try_atom}
end;
infer_key_filter(Value, _) when erlang:is_binary(Value) ->
{ok, try_binary};
infer_key_filter(Value, _) when erlang:is_integer(Value) ->
{ok, try_integer};
infer_key_filter(Value, _) when erlang:is_float(Value) ->
{ok, try_float};
infer_key_filter(Value, SafeMode) when erlang:is_list(Value) ->
case is_proplist(Value) of
true ->
infer_proplist(Value, SafeMode, []);
_ ->
infer_list(Value, SafeMode, [])
end;
infer_key_filter(Value, SafeMode) when erlang:is_map(Value) ->
case infer_key_filter(maps:to_list(Value), SafeMode) of
{ok, ProplistFilter} ->
{ok, {'and', [ProplistFilter, proplist_to_map]}};
Err ->
Err
end;
infer_key_filter(_, _) ->
error.
infer_proplist([{Key, Value} | Proplist], SafeMode, Ret) ->
case infer_key_filter(Value, SafeMode) of
{ok, Filter} ->
infer_proplist(Proplist, SafeMode, [{Key, Filter, Value} | Ret]);
Err ->
Err
end;
infer_proplist([], _, [_|_]=Ret) ->
{ok, {proplist, lists:reverse(Ret)}};
infer_proplist([], _, _) ->
{ok, list};
infer_proplist(_, _, _) ->
error.
infer_list([Value | List], SafeMode, Ret) ->
case infer_key_filter(Value, SafeMode) of
{ok, Filter} ->
infer_list(List, SafeMode, [Filter | Ret]);
Err ->
Err
end;
infer_list(_, _, [_|_]=Filters) ->
{ok, {list, {'or', sets:to_list(sets:from_list(lists:reverse(Filters)))}}};
infer_list(_, _, _) ->
{ok, list}.
try_convert(try_atom, Value) ->
try_convert_to_atom(Value);
try_convert(try_binary, Value) ->
try_convert_to_binary(Value);
try_convert(try_integer, Value) ->
try_convert_to_integer(Value);
try_convert(try_number, Value) ->
try_convert_to_number(Value);
try_convert(try_float, Value) ->
try_convert_to_float(Value);
try_convert(try_existing_atom, Value) ->
try_convert_to_existing_atom(Value);
try_convert(try_boolean, Value) ->
try_convert_to_boolean(Value);
try_convert_to_map(Value).
try_convert_to_atom(Value) when erlang:is_binary(Value) ->
{ok, erlang:binary_to_atom(Value, utf8)};
try_convert_to_atom(Value) when erlang:is_list(Value) ->
try
{ok, erlang:list_to_atom(Value)}
catch
_:_ ->
error
end;
try_convert_to_atom(Value) when erlang:is_integer(Value) ->
{ok, erlang:list_to_atom(erlang:integer_to_list(Value))};
try_convert_to_atom(Value) when erlang:is_atom(Value) ->
{ok, Value};
try_convert_to_atom(_) ->
error.
try_convert_to_existing_atom(Value) when erlang:is_binary(Value) ->
try_convert_to_existing_atom(erlang:binary_to_list(Value));
try_convert_to_existing_atom(Value) when erlang:is_list(Value) ->
try
{ok, erlang:list_to_existing_atom(Value)}
catch
_:_ ->
not_found
end;
try_convert_to_existing_atom(Value) when erlang:is_integer(Value) ->
try_convert_to_existing_atom(erlang:integer_to_list(Value));
try_convert_to_existing_atom(Value) when erlang:is_atom(Value) ->
{ok, Value};
try_convert_to_existing_atom(_) ->
error.
try_convert_to_binary(Value) when erlang:is_list(Value) ->
try
{ok, erlang:list_to_binary(Value)}
catch
_:_ ->
error
end;
try_convert_to_binary(Value) when erlang:is_integer(Value) ->
{ok, erlang:integer_to_binary(Value)};
try_convert_to_binary(Value) when erlang:is_float(Value) ->
{ok, erlang:float_to_binary(Value, [compact, {decimals, 15}])};
try_convert_to_binary(Value) when erlang:is_atom(Value) ->
{ok, erlang:atom_to_binary(Value, utf8)};
try_convert_to_binary(Value) when erlang:is_binary(Value) ->
{ok, Value};
try_convert_to_binary(_) ->
error.
try_convert_to_integer(Value) when erlang:is_binary(Value) ->
try_convert_to_integer(erlang:binary_to_list(Value));
try_convert_to_integer(Value) when erlang:is_list(Value) ->
TryFloat =
try erlang:list_to_float(Value) of
Value2 ->
try_convert_to_integer(Value2)
catch
_:_ ->
error
end,
if
TryFloat /= error ->
TryFloat;
true ->
try
{ok, erlang:list_to_integer(Value)}
catch
_:_ ->
error
end
end;
try_convert_to_integer(Value) when erlang:is_float(Value) ->
{ok, erlang:list_to_integer(erlang:float_to_list(Value, [{decimals, 0}]))};
try_convert_to_integer(Value) when erlang:is_atom(Value) ->
try_convert_to_integer(erlang:atom_to_list(Value));
try_convert_to_integer(Value) when erlang:is_integer(Value) ->
{ok, Value};
try_convert_to_integer(_) ->
error.
try_convert_to_float(Value) when erlang:is_binary(Value) ->
try_convert_to_float(erlang:binary_to_list(Value));
try_convert_to_float(Value) when erlang:is_list(Value) ->
TryFloat =
try
{ok, erlang:list_to_float(Value)}
catch
_:_ ->
error
end,
if
TryFloat /= error ->
TryFloat;
true ->
try
{ok, erlang:float(erlang:list_to_integer(Value))}
catch
_:_ ->
error
end
end;
try_convert_to_float(Value) when erlang:is_integer(Value) ->
{ok, erlang:float(Value)};
try_convert_to_float(Value) when erlang:is_atom(Value) ->
try_convert_to_float(erlang:atom_to_list(Value));
try_convert_to_float(Value) when erlang:is_float(Value) ->
{ok, Value};
try_convert_to_float(_) ->
error.
try_convert_to_number(Value) ->
case {try_convert_to_float(Value), try_convert_to_integer(Value)} of
{{_, Float}, {_, Integer}=Ok} when Float == Integer ->
Ok;
{{_, _}=Ok, _} ->
Ok;
_ ->
error
end.
try_convert_to_boolean(Value) when erlang:is_binary(Value) ->
try_convert_to_boolean(erlang:binary_to_list(Value));
try_convert_to_boolean("true") ->
{ok, true};
try_convert_to_boolean("false") ->
{ok, false};
try_convert_to_boolean(0) ->
{ok, false};
try_convert_to_boolean(1) ->
{ok, true};
try_convert_to_boolean(Value) when erlang:is_list(Value) ->
case try_convert_to_integer(Value) of
{ok, Integer} ->
try_convert_to_boolean(Integer);
_ ->
error
end;
try_convert_to_boolean(Value) when erlang:is_boolean(Value) ->
{ok, Value};
try_convert_to_boolean(_) ->
error.
try_convert_to_map(Value) ->
case is_proplist(Value) of
true ->
{ok, maps:from_list(remove_readers(Value))};
_ ->
error
end.
is_proplist([{Key, _}|Rest]) when erlang:is_atom(Key) ->
is_proplist(Rest);
is_proplist([{Key, _, _}|Rest]) when erlang:is_atom(Key) ->
is_proplist(Rest);
is_proplist([]) ->
true;
is_proplist(_) ->
false.
remove_readers([{Key, Value, _} | Rest]) ->
[{Key, remove_readers(Value)} | remove_readers(Rest)];
remove_readers([{Key, Value} | Rest]) ->
[{Key, remove_readers(Value)} | remove_readers(Rest)];
remove_readers(X) ->
X.
make_error(
#{previous_error := PrevErr}=ErrParams
) when erlang:is_map(PrevErr) ->
PrevErr2 = make_error(PrevErr),
FilterFun =
fun(Key, Value, {PrevErrX, ErrParamsX}) ->
case maps:is_key(Key, ErrParamsX) of
false ->
{maps:remove(Key, PrevErrX), ErrParamsX#{Key => Value}};
_ ->
{PrevErrX, ErrParamsX}
end
end,
case maps:fold(FilterFun, {make_error(PrevErr), ErrParams}, PrevErr2) of
{PrevErr3, ErrParams2} when erlang:map_size(PrevErr3) == 0 ->
maps:remove(previous_error, ErrParams2);
{PrevErr3, ErrParams2} ->
ErrParams2#{previous_error => PrevErr3}
end;
make_error(X) ->
X.
|
26217e27bcba8d33315d57e957587d1ed6390c94fa04a79eb66352510dddba92 | tezos/tezos-mirror | proof_helpers.ml | (*****************************************************************************)
(* *)
(* Open Source License *)
Copyright ( c ) 2023 Nomadic Labs , < >
(* *)
(* Permission is hereby granted, free of charge, to any person obtaining a *)
(* copy of this software and associated documentation files (the "Software"),*)
to deal in the Software without restriction , including without limitation
(* the rights to use, copy, modify, merge, publish, distribute, sublicense, *)
and/or sell copies of the Software , and to permit persons to whom the
(* Software is furnished to do so, subject to the following conditions: *)
(* *)
(* The above copyright notice and this permission notice shall be included *)
(* in all copies or substantial portions of the Software. *)
(* *)
THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND , EXPRESS OR
(* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *)
(* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL *)
(* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER*)
LIABILITY , WHETHER IN AN ACTION OF CONTRACT , TORT OR OTHERWISE , ARISING
(* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER *)
(* DEALINGS IN THE SOFTWARE. *)
(* *)
(*****************************************************************************)
open Protocol.Alpha_context
let origination_proof ~boot_sector kind =
let aux = function
| Sc_rollup.Kind.Example_arith ->
let open Lwt_result_syntax in
let context = Context_helpers.In_memory.make_empty_context () in
let* proof =
Pvm.Arith_pvm_in_memory.produce_origination_proof context boot_sector
in
let*? proof =
Sc_rollup.Proof.serialize_pvm_step
~pvm:(module Pvm.Arith_pvm_in_memory)
proof
in
return proof
| Sc_rollup.Kind.Wasm_2_0_0 ->
let open Lwt_result_syntax in
let context = Context_helpers.In_memory.make_empty_context () in
let* proof =
Pvm.Wasm_pvm_in_memory.produce_origination_proof context boot_sector
in
let*? proof =
Sc_rollup.Proof.serialize_pvm_step
~pvm:(module Pvm.Wasm_pvm_in_memory)
proof
in
return proof
in
aux kind
| null | https://raw.githubusercontent.com/tezos/tezos-mirror/adb9ff09cb5f0a9cae8c8d8924efee6c4764399a/src/proto_alpha/lib_sc_rollup/proof_helpers.ml | ocaml | ***************************************************************************
Open Source License
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Software"),
the rights to use, copy, modify, merge, publish, distribute, sublicense,
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
*************************************************************************** | Copyright ( c ) 2023 Nomadic Labs , < >
to deal in the Software without restriction , including without limitation
and/or sell copies of the Software , and to permit persons to whom the
THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND , EXPRESS OR
LIABILITY , WHETHER IN AN ACTION OF CONTRACT , TORT OR OTHERWISE , ARISING
open Protocol.Alpha_context
let origination_proof ~boot_sector kind =
let aux = function
| Sc_rollup.Kind.Example_arith ->
let open Lwt_result_syntax in
let context = Context_helpers.In_memory.make_empty_context () in
let* proof =
Pvm.Arith_pvm_in_memory.produce_origination_proof context boot_sector
in
let*? proof =
Sc_rollup.Proof.serialize_pvm_step
~pvm:(module Pvm.Arith_pvm_in_memory)
proof
in
return proof
| Sc_rollup.Kind.Wasm_2_0_0 ->
let open Lwt_result_syntax in
let context = Context_helpers.In_memory.make_empty_context () in
let* proof =
Pvm.Wasm_pvm_in_memory.produce_origination_proof context boot_sector
in
let*? proof =
Sc_rollup.Proof.serialize_pvm_step
~pvm:(module Pvm.Wasm_pvm_in_memory)
proof
in
return proof
in
aux kind
|
327a473ed817b2792e7c229a4e8044c0dca327f6323954caeb8c2498c45e6562 | mariorz/covid19-mx-time-series | sinave.clj | (ns covid19-mx-time-series.sinave
(:require [clj-http.client :as http]
[clojure.data.json :as json]
[clj-time.core :as t]
[clj-time.format :as f]
[clj-time.local :as l]))
(defn fetch-daily-states
[]
(let [map-url ""
headers {:headers
{"Content-Type" "application/json; charset=utf-8"}}
data (http/post map-url headers)]
(filter #(not= (second %) "NACIONAL") (json/read-str (:d (json/read-json (:body data)))))))
(defn total-deaths
[states]
(apply + (map (comp #(Integer/parseInt %) #(nth % 7))
states)))
(defn total-confirmed
[states]
(apply + (map (comp #(Integer/parseInt %) #(nth % 4))
states)))
(defn current-deaths
[]
(total-deaths (fetch-daily-states)))
(defn write-daily-states
[date data]
(let [existing (slurp "data/states.edn")
current (if (= existing "") [] (clojure.tools.reader.edn/read-string existing))]
(spit "data/states.edn" (pr-str
(concat current
[{:date date :data data}])))))
(defn day-mx
[]
(f/unparse
(f/formatter "dd-MM-yyyy")
(t/minus (l/local-now) (t/hours 6))))
(defn fetch-and-write-daily
[]
(let [s (fetch-daily-states)
dmx (day-mx)]
(write-daily-states dmx s)))
(defn read-daily-states
[]
(clojure.tools.reader.edn/read-string (slurp "data/states.edn")))
(defn state-name
[day-value]
(second day-value))
(defn state-confirmed
[day-value]
(nth day-value 4))
(defn state-negatives
[day-value]
(nth day-value 5))
(defn state-suspects
[day-value]
(nth day-value 6))
(defn state-deaths
[day-value]
(nth day-value 7))
(defn count-by-state
[states catfn]
(into {}
(map (juxt second (comp #(Integer/parseInt %) catfn))
states)))
(defn death-counts
[states]
(count-by-state states state-deaths))
(defn confirmed-counts
[states]
(count-by-state states state-confirmed))
(defn suspect-counts
[states]
(count-by-state states state-suspects))
(defn negative-counts
[states]
(count-by-state states state-negatives))
(def staterows (:data (first (read-daily-states))))
(def statename->code
(into {} (map (fn [x] {(state-name x) (first x)})
staterows)))
(def statename->pcode
(into {} (map (fn [x] {(state-name x) (nth x 3)})
staterows)))
(def statename->somedec
(into {} (map (fn [x] {(state-name x) (nth x 2)})
staterows)))
(defn make-time-series
[state-vals value-fn]
(vec (concat [(state-name (first state-vals))]
(map value-fn state-vals))))
(defn state-vals
[daily-states state-pos]
(doall (map (comp (fn [x] (nth x state-pos)) :data) daily-states)))
| null | https://raw.githubusercontent.com/mariorz/covid19-mx-time-series/dde1183e8be502a85f7d1abf3aff25abdb176156/src/covid19_mx_time_series/sinave.clj | clojure | (ns covid19-mx-time-series.sinave
(:require [clj-http.client :as http]
[clojure.data.json :as json]
[clj-time.core :as t]
[clj-time.format :as f]
[clj-time.local :as l]))
(defn fetch-daily-states
[]
(let [map-url ""
headers {:headers
{"Content-Type" "application/json; charset=utf-8"}}
data (http/post map-url headers)]
(filter #(not= (second %) "NACIONAL") (json/read-str (:d (json/read-json (:body data)))))))
(defn total-deaths
[states]
(apply + (map (comp #(Integer/parseInt %) #(nth % 7))
states)))
(defn total-confirmed
[states]
(apply + (map (comp #(Integer/parseInt %) #(nth % 4))
states)))
(defn current-deaths
[]
(total-deaths (fetch-daily-states)))
(defn write-daily-states
[date data]
(let [existing (slurp "data/states.edn")
current (if (= existing "") [] (clojure.tools.reader.edn/read-string existing))]
(spit "data/states.edn" (pr-str
(concat current
[{:date date :data data}])))))
(defn day-mx
[]
(f/unparse
(f/formatter "dd-MM-yyyy")
(t/minus (l/local-now) (t/hours 6))))
(defn fetch-and-write-daily
[]
(let [s (fetch-daily-states)
dmx (day-mx)]
(write-daily-states dmx s)))
(defn read-daily-states
[]
(clojure.tools.reader.edn/read-string (slurp "data/states.edn")))
(defn state-name
[day-value]
(second day-value))
(defn state-confirmed
[day-value]
(nth day-value 4))
(defn state-negatives
[day-value]
(nth day-value 5))
(defn state-suspects
[day-value]
(nth day-value 6))
(defn state-deaths
[day-value]
(nth day-value 7))
(defn count-by-state
[states catfn]
(into {}
(map (juxt second (comp #(Integer/parseInt %) catfn))
states)))
(defn death-counts
[states]
(count-by-state states state-deaths))
(defn confirmed-counts
[states]
(count-by-state states state-confirmed))
(defn suspect-counts
[states]
(count-by-state states state-suspects))
(defn negative-counts
[states]
(count-by-state states state-negatives))
(def staterows (:data (first (read-daily-states))))
(def statename->code
(into {} (map (fn [x] {(state-name x) (first x)})
staterows)))
(def statename->pcode
(into {} (map (fn [x] {(state-name x) (nth x 3)})
staterows)))
(def statename->somedec
(into {} (map (fn [x] {(state-name x) (nth x 2)})
staterows)))
(defn make-time-series
[state-vals value-fn]
(vec (concat [(state-name (first state-vals))]
(map value-fn state-vals))))
(defn state-vals
[daily-states state-pos]
(doall (map (comp (fn [x] (nth x state-pos)) :data) daily-states)))
| |
874d1c2d29840a168b2115623af2736db43cf3e8ddd8c40bc407160cde508e40 | tezos/tezos-mirror | sampler.ml | open G
* { 2 Core type definitions }
(** ['kind cfg] is the type of the configuration of the network sampler, parametric
over node ['kind]. *)
type 'kind cfg = {
bounds : vertex -> int * int;
(** [bounds v] is the inclusive interval in which the degree of [v] should be. *)
kind : vertex -> 'kind; (** [kind v] is the kind of [v]. *)
compat : 'kind -> 'kind -> bool;
(** [compat k1 k2] is a symmetric and reflexive relation on kinds.
It does not need to be transitive. *)
edges : Edge.t array;
(** [edges] contain all edges [v1, v2] such that [compat (kind v1) (kind v2)] holds.
It represents the maximal graph satisfying [compat]. *)
}
type state =
| State : {
graph : G.t; (** [graph] represents the network. *)
degrees : int Vertex_map.t;
(** [degrees] is used to bypass the slow [G.out_degree] *)
error : float;
(** [error] is the total error over all nodes. Error is computed for each
node as the absolute value of the difference between the current degree
of the node and the closest bound of its bounding interval. Hence if
the degree lies in the interval, the error is 0 for that node. *)
cfg : 'kind cfg;
}
-> state
(** {2 Accessors} *)
let graph (State {graph; _}) = graph
let error (State {error; _}) = error
let vertex_count (State {graph; _}) = G.nb_vertex graph
let edge_count (State {cfg = {edges; _}; _}) = Array.length edges
* { 2 State initialization helpers }
let rec product_outer l1 l2 f acc =
match l1 with
| [] -> acc
| x1 :: tl1 ->
let acc = product_inner x1 l2 f acc in
product_outer tl1 l2 f acc
and product_inner x1 l2 f acc =
match l2 with
| [] -> acc
| x2 :: tl2 ->
let acc = f x1 x2 acc in
product_inner x1 tl2 f acc
let product l1 l2 f acc = product_outer l1 l2 f acc
* { 2 Helpers to compute the error induced by violated degree bound constraints }
let err delta = abs_float delta
let degree (State {degrees; _}) v =
Vertex_map.find_opt v degrees |> Option.value ~default:0
let incr_degree degrees v =
Vertex_map.update
v
(function None -> Some 1 | Some d -> Some (d + 1))
degrees
let decr_degree degrees v =
Vertex_map.update
v
(function None -> assert false | Some d -> Some (d - 1))
degrees
let node_error (lo, hi) deg =
assert (0 <= lo && lo <= hi) ;
if lo <= deg then
if deg <= hi then 0.0 else (* deg > hi *)
err (float_of_int (deg - hi))
else (* deg < low *)
err (float_of_int (lo - deg))
* { 2 State initialization }
let create_empty n ~kind ~compat ~bounds =
if n <= 0 then invalid_arg "create_empty: n <= 0" ;
let graph =
Seq.unfold (fun i -> if i >= n then None else Some (i, i + 1)) 0
|> Seq.fold_left G.add_vertex G.empty
in
let vertices = G.fold_vertex (fun x l -> x :: l) graph [] in
let edges =
product
vertices
vertices
(fun v v' acc ->
if v >= v' then (* Important: we exclude self edges *)
acc
else
let k1 = kind v in
let k2 = kind v' in
if compat k1 k2 then Edge_set.add (v, v') acc else acc)
Edge_set.empty
in
let edges = Array.of_seq (Edge_set.to_seq edges) in
assert (Array.length edges > 0) ;
Format.printf "Maximal graph has %d edges@." (Array.length edges) ;
let error =
G.fold_vertex
(fun v acc -> acc +. node_error (bounds v) (G.out_degree graph v))
graph
0.0
in
Format.printf "initial error: %f@." error ;
let cfg = {bounds; kind; compat; edges} in
let degrees = Vertex_map.empty in
State {graph; error; cfg; degrees}
* { 2 - based sampling of networks respecting the degree bound constraints }
(** [quality_delta graph_before bounds (v, v') is_added] computes the network quality increment starting
from [graph_before], under degree constraints specified by [bounds],
when the edge [v, v'] is flipped. If [add] is [true], the
edge is added, if not it is removed. *)
let quality_delta graph_before bounds (v, v') is_added =
let vbounds = bounds v in
let v'bounds = bounds v' in
let deg_v = degree graph_before v in
let deg_v' = degree graph_before v' in
let deg_incr = if is_added then 1 else -1 in
(* error before *)
let v_bef = node_error vbounds deg_v in
let v_aft = node_error vbounds (deg_v + deg_incr) in
(* error after *)
let v'_bef = node_error v'bounds deg_v' in
let v'_aft = node_error v'bounds (deg_v' + deg_incr) in
(* delta *)
v'_aft +. v_aft -. v'_bef -. v_bef
(** Parameters of the network sampler. *)
module MH_parameters = struct
type t = state
let pp fmtr (State state) = Format.fprintf fmtr "error=%f@." state.error
(** [proposal state rng_state] samples uniformly at random in the maximal graph
an edge to flip. If the edge exists, it is removed. If not, it is added. *)
let proposal (State state as s : t) rng_state =
let {edges; bounds; _} = state.cfg in
let graph = state.graph in
let error = state.error in
let i = Random.State.int rng_state (Array.length edges) in
let ((v, v') as edge) = edges.(i) in
if G.mem_edge_e graph edge then
let graph' = G.remove_edge_e graph edge in
let error = error +. quality_delta s bounds edge false in
let degrees = decr_degree state.degrees v in
let degrees = decr_degree degrees v' in
State {state with graph = graph'; error; degrees}
else
let graph' = G.add_edge_e graph edge in
let error' = error +. quality_delta s bounds edge true in
let degrees = incr_degree state.degrees v in
let degrees = incr_degree degrees v' in
State {state with graph = graph'; error = error'; degrees}
let proposal_log_density _ _ = Stats.Log_space.one
* [ ] encodes the logarithm of the objective function that the sampler will try
to maximize .
The objective function is proportional to [ exp ( - error^2 ) ] , hence the smaller the error
the bigger the objective function .
to maximize.
The objective function is proportional to [exp (- error^2)], hence the smaller the error
the bigger the objective function. *)
let log_weight (State {error; _}) =
(* If we don't square the error, the ratio of a big error and a slightly bigger error
is still close to 1 - so we stay in error land. By squaring, we make Metropolis 'feel'
that increasing a big error is more bad than increasing a small error. *)
Stats.Log_space.unsafe_cast ~-.(Float.max 1. error ** 2.)
end
* [ Network_sampler ] instantiates the network sampler .
module Network_sampler = Stats.Mh.Make (MH_parameters)
let network = Network_sampler.mcmc
* { 2 Basic statistics over networks }
module Network_stats_helpers = Stats.Graph.Make (struct
include G
module V = struct
include V
let pp = Format.pp_print_int
end
end)
(** [avg_degree state] computes the average degree of the network. *)
let avg_degree (State state) =
let g = state.graph in
let vertices = G.nb_vertex g in
let volume = G.fold_vertex (fun v acc -> acc + G.out_degree g v) g 0 in
float volume /. float vertices
* { 2 Sampling routings uniformly at random and deriving bandwidth statistics . }
let op (x, y) = (y, x) [@@ocaml.inline]
type bandwidth_stats = {
incoming : float ref Vertex_table.t;
outgoing : float ref Vertex_table.t;
}
let create_bandwidth_stats () =
{incoming = Vertex_table.create 51; outgoing = Vertex_table.create 51}
let normalize_bandwidth_stats stats count =
let nrm = 1. /. float count in
Vertex_table.iter (fun _v r -> r := !r *. nrm) stats.incoming ;
Vertex_table.iter (fun _v r -> r := !r *. nrm) stats.outgoing
let float_incr table key dx =
match Vertex_table.find_opt table key with
| None -> Vertex_table.add table key (ref 0.0)
| Some x -> x := !x +. dx
[@@ocaml.inline]
let uniform_spanning_trees ~graph ~source ~subgraph_predicate =
if not (subgraph_predicate source) then
Format.kasprintf
invalid_arg
"uniform_spanning_trees: source vertex %d is not in subraph induced by \
predicate"
source ;
let random_spanning_tree =
Network_stats_helpers.aldous_broder graph source subgraph_predicate
in
Stats.Gen.iid random_spanning_tree
let vertices_of_tree tree =
let verts = ref [] in
Network_stats_helpers.Tree.iter_vertices tree (fun x -> verts := x :: !verts) ;
let verts = Array.of_list !verts in
Array.sort Int.compare verts ;
verts
let estimate_bandwidth ~state ~subgraph_predicate ~counters ~spanning_trees
rng_state =
let (State {graph; cfg = _; _}) = state in
let {incoming; outgoing} = counters in
let nsamples = List.length spanning_trees in
assert (nsamples > 0) ;
(* [db] is the bandwidth increment, pre-normalized by [nsamples] *)
let db = 1. /. float nsamples in
(* Note we avoid reallocating this rather large table at each iteration. *)
let add_edge_to_routing routing ((src, dst) as e) =
float_incr incoming dst db ;
float_incr outgoing src db ;
Edge_table.add routing e ()
[@@ocaml.inline]
in
Invariant : all spanning trees have the same support , corresponding to the subgraph predicate .
Hence , we optimize as follows :
- compute [ verts ] , the set of vertices of the first spanning tree , corresponding
equal to the set of vertices in the subgraph .
- compute [ succs ] , the set of successors of each element of [ verts ] that are in the
subgraph .
Use [ verts ] and [ succs ] in the loop below , to iterate efficiently on those edges
that are in the subgraph but not in the spanning tree .
Without this optimization , we need to iterate over all successors in the { e full }
graph , which is potentially much larger .
Hence, we optimize as follows:
- compute [verts], the set of vertices of the first spanning tree, corresponding
equal to the set of vertices in the subgraph.
- compute [succs], the set of successors of each element of [verts] that are in the
subgraph.
Use [verts] and [succs] in the loop below, to iterate efficiently on those edges
that are in the subgraph but not in the spanning tree.
Without this optimization, we need to iterate over all successors in the {e full}
graph, which is potentially much larger. *)
let verts = vertices_of_tree (List.hd spanning_trees) in
let succs =
let tbl = Hashtbl.create 11 in
Array.iter
(fun v ->
G.iter_succ
(fun v' -> if subgraph_predicate v' then Hashtbl.add tbl v v')
graph
v)
verts ;
tbl
in
let routing = Edge_table.create (Hashtbl.length succs) in
List.iter
(fun spanning_tree ->
Edge_table.clear routing ;
Network_stats_helpers.Tree.iter_edges spanning_tree (fun e ->
add_edge_to_routing routing e) ;
Array.iter
(fun v ->
let succs = Hashtbl.find_all succs v in
List.iter
(fun v' ->
let e = (v, v') in
[ e ] or [ opp e ] is possibly in the routing table ,
in which case we have the property that it has
already been accounted for in the stats
in which case we have the property that it has
already been accounted for in the stats *)
if Edge_table.mem routing e then ()
else
let flip = Random.State.bool rng_state in
add_edge_to_routing routing (if flip then e else op e))
succs)
verts)
spanning_trees
| null | https://raw.githubusercontent.com/tezos/tezos-mirror/bbca5502eb430d3915ad697259d3bffc62c2d01d/devtools/simdal/lib/sampler.ml | ocaml | * ['kind cfg] is the type of the configuration of the network sampler, parametric
over node ['kind].
* [bounds v] is the inclusive interval in which the degree of [v] should be.
* [kind v] is the kind of [v].
* [compat k1 k2] is a symmetric and reflexive relation on kinds.
It does not need to be transitive.
* [edges] contain all edges [v1, v2] such that [compat (kind v1) (kind v2)] holds.
It represents the maximal graph satisfying [compat].
* [graph] represents the network.
* [degrees] is used to bypass the slow [G.out_degree]
* [error] is the total error over all nodes. Error is computed for each
node as the absolute value of the difference between the current degree
of the node and the closest bound of its bounding interval. Hence if
the degree lies in the interval, the error is 0 for that node.
* {2 Accessors}
deg > hi
deg < low
Important: we exclude self edges
* [quality_delta graph_before bounds (v, v') is_added] computes the network quality increment starting
from [graph_before], under degree constraints specified by [bounds],
when the edge [v, v'] is flipped. If [add] is [true], the
edge is added, if not it is removed.
error before
error after
delta
* Parameters of the network sampler.
* [proposal state rng_state] samples uniformly at random in the maximal graph
an edge to flip. If the edge exists, it is removed. If not, it is added.
If we don't square the error, the ratio of a big error and a slightly bigger error
is still close to 1 - so we stay in error land. By squaring, we make Metropolis 'feel'
that increasing a big error is more bad than increasing a small error.
* [avg_degree state] computes the average degree of the network.
[db] is the bandwidth increment, pre-normalized by [nsamples]
Note we avoid reallocating this rather large table at each iteration. | open G
* { 2 Core type definitions }
type 'kind cfg = {
bounds : vertex -> int * int;
compat : 'kind -> 'kind -> bool;
edges : Edge.t array;
}
type state =
| State : {
degrees : int Vertex_map.t;
error : float;
cfg : 'kind cfg;
}
-> state
let graph (State {graph; _}) = graph
let error (State {error; _}) = error
let vertex_count (State {graph; _}) = G.nb_vertex graph
let edge_count (State {cfg = {edges; _}; _}) = Array.length edges
* { 2 State initialization helpers }
let rec product_outer l1 l2 f acc =
match l1 with
| [] -> acc
| x1 :: tl1 ->
let acc = product_inner x1 l2 f acc in
product_outer tl1 l2 f acc
and product_inner x1 l2 f acc =
match l2 with
| [] -> acc
| x2 :: tl2 ->
let acc = f x1 x2 acc in
product_inner x1 tl2 f acc
let product l1 l2 f acc = product_outer l1 l2 f acc
* { 2 Helpers to compute the error induced by violated degree bound constraints }
let err delta = abs_float delta
let degree (State {degrees; _}) v =
Vertex_map.find_opt v degrees |> Option.value ~default:0
let incr_degree degrees v =
Vertex_map.update
v
(function None -> Some 1 | Some d -> Some (d + 1))
degrees
let decr_degree degrees v =
Vertex_map.update
v
(function None -> assert false | Some d -> Some (d - 1))
degrees
let node_error (lo, hi) deg =
assert (0 <= lo && lo <= hi) ;
if lo <= deg then
err (float_of_int (deg - hi))
err (float_of_int (lo - deg))
* { 2 State initialization }
let create_empty n ~kind ~compat ~bounds =
if n <= 0 then invalid_arg "create_empty: n <= 0" ;
let graph =
Seq.unfold (fun i -> if i >= n then None else Some (i, i + 1)) 0
|> Seq.fold_left G.add_vertex G.empty
in
let vertices = G.fold_vertex (fun x l -> x :: l) graph [] in
let edges =
product
vertices
vertices
(fun v v' acc ->
acc
else
let k1 = kind v in
let k2 = kind v' in
if compat k1 k2 then Edge_set.add (v, v') acc else acc)
Edge_set.empty
in
let edges = Array.of_seq (Edge_set.to_seq edges) in
assert (Array.length edges > 0) ;
Format.printf "Maximal graph has %d edges@." (Array.length edges) ;
let error =
G.fold_vertex
(fun v acc -> acc +. node_error (bounds v) (G.out_degree graph v))
graph
0.0
in
Format.printf "initial error: %f@." error ;
let cfg = {bounds; kind; compat; edges} in
let degrees = Vertex_map.empty in
State {graph; error; cfg; degrees}
* { 2 - based sampling of networks respecting the degree bound constraints }
let quality_delta graph_before bounds (v, v') is_added =
let vbounds = bounds v in
let v'bounds = bounds v' in
let deg_v = degree graph_before v in
let deg_v' = degree graph_before v' in
let deg_incr = if is_added then 1 else -1 in
let v_bef = node_error vbounds deg_v in
let v_aft = node_error vbounds (deg_v + deg_incr) in
let v'_bef = node_error v'bounds deg_v' in
let v'_aft = node_error v'bounds (deg_v' + deg_incr) in
v'_aft +. v_aft -. v'_bef -. v_bef
module MH_parameters = struct
type t = state
let pp fmtr (State state) = Format.fprintf fmtr "error=%f@." state.error
let proposal (State state as s : t) rng_state =
let {edges; bounds; _} = state.cfg in
let graph = state.graph in
let error = state.error in
let i = Random.State.int rng_state (Array.length edges) in
let ((v, v') as edge) = edges.(i) in
if G.mem_edge_e graph edge then
let graph' = G.remove_edge_e graph edge in
let error = error +. quality_delta s bounds edge false in
let degrees = decr_degree state.degrees v in
let degrees = decr_degree degrees v' in
State {state with graph = graph'; error; degrees}
else
let graph' = G.add_edge_e graph edge in
let error' = error +. quality_delta s bounds edge true in
let degrees = incr_degree state.degrees v in
let degrees = incr_degree degrees v' in
State {state with graph = graph'; error = error'; degrees}
let proposal_log_density _ _ = Stats.Log_space.one
* [ ] encodes the logarithm of the objective function that the sampler will try
to maximize .
The objective function is proportional to [ exp ( - error^2 ) ] , hence the smaller the error
the bigger the objective function .
to maximize.
The objective function is proportional to [exp (- error^2)], hence the smaller the error
the bigger the objective function. *)
let log_weight (State {error; _}) =
Stats.Log_space.unsafe_cast ~-.(Float.max 1. error ** 2.)
end
* [ Network_sampler ] instantiates the network sampler .
module Network_sampler = Stats.Mh.Make (MH_parameters)
let network = Network_sampler.mcmc
* { 2 Basic statistics over networks }
module Network_stats_helpers = Stats.Graph.Make (struct
include G
module V = struct
include V
let pp = Format.pp_print_int
end
end)
let avg_degree (State state) =
let g = state.graph in
let vertices = G.nb_vertex g in
let volume = G.fold_vertex (fun v acc -> acc + G.out_degree g v) g 0 in
float volume /. float vertices
* { 2 Sampling routings uniformly at random and deriving bandwidth statistics . }
let op (x, y) = (y, x) [@@ocaml.inline]
type bandwidth_stats = {
incoming : float ref Vertex_table.t;
outgoing : float ref Vertex_table.t;
}
let create_bandwidth_stats () =
{incoming = Vertex_table.create 51; outgoing = Vertex_table.create 51}
let normalize_bandwidth_stats stats count =
let nrm = 1. /. float count in
Vertex_table.iter (fun _v r -> r := !r *. nrm) stats.incoming ;
Vertex_table.iter (fun _v r -> r := !r *. nrm) stats.outgoing
let float_incr table key dx =
match Vertex_table.find_opt table key with
| None -> Vertex_table.add table key (ref 0.0)
| Some x -> x := !x +. dx
[@@ocaml.inline]
let uniform_spanning_trees ~graph ~source ~subgraph_predicate =
if not (subgraph_predicate source) then
Format.kasprintf
invalid_arg
"uniform_spanning_trees: source vertex %d is not in subraph induced by \
predicate"
source ;
let random_spanning_tree =
Network_stats_helpers.aldous_broder graph source subgraph_predicate
in
Stats.Gen.iid random_spanning_tree
let vertices_of_tree tree =
let verts = ref [] in
Network_stats_helpers.Tree.iter_vertices tree (fun x -> verts := x :: !verts) ;
let verts = Array.of_list !verts in
Array.sort Int.compare verts ;
verts
let estimate_bandwidth ~state ~subgraph_predicate ~counters ~spanning_trees
rng_state =
let (State {graph; cfg = _; _}) = state in
let {incoming; outgoing} = counters in
let nsamples = List.length spanning_trees in
assert (nsamples > 0) ;
let db = 1. /. float nsamples in
let add_edge_to_routing routing ((src, dst) as e) =
float_incr incoming dst db ;
float_incr outgoing src db ;
Edge_table.add routing e ()
[@@ocaml.inline]
in
Invariant : all spanning trees have the same support , corresponding to the subgraph predicate .
Hence , we optimize as follows :
- compute [ verts ] , the set of vertices of the first spanning tree , corresponding
equal to the set of vertices in the subgraph .
- compute [ succs ] , the set of successors of each element of [ verts ] that are in the
subgraph .
Use [ verts ] and [ succs ] in the loop below , to iterate efficiently on those edges
that are in the subgraph but not in the spanning tree .
Without this optimization , we need to iterate over all successors in the { e full }
graph , which is potentially much larger .
Hence, we optimize as follows:
- compute [verts], the set of vertices of the first spanning tree, corresponding
equal to the set of vertices in the subgraph.
- compute [succs], the set of successors of each element of [verts] that are in the
subgraph.
Use [verts] and [succs] in the loop below, to iterate efficiently on those edges
that are in the subgraph but not in the spanning tree.
Without this optimization, we need to iterate over all successors in the {e full}
graph, which is potentially much larger. *)
let verts = vertices_of_tree (List.hd spanning_trees) in
let succs =
let tbl = Hashtbl.create 11 in
Array.iter
(fun v ->
G.iter_succ
(fun v' -> if subgraph_predicate v' then Hashtbl.add tbl v v')
graph
v)
verts ;
tbl
in
let routing = Edge_table.create (Hashtbl.length succs) in
List.iter
(fun spanning_tree ->
Edge_table.clear routing ;
Network_stats_helpers.Tree.iter_edges spanning_tree (fun e ->
add_edge_to_routing routing e) ;
Array.iter
(fun v ->
let succs = Hashtbl.find_all succs v in
List.iter
(fun v' ->
let e = (v, v') in
[ e ] or [ opp e ] is possibly in the routing table ,
in which case we have the property that it has
already been accounted for in the stats
in which case we have the property that it has
already been accounted for in the stats *)
if Edge_table.mem routing e then ()
else
let flip = Random.State.bool rng_state in
add_edge_to_routing routing (if flip then e else op e))
succs)
verts)
spanning_trees
|
d3424fdf97e8df932c4a051315f5615442a88eeffb55f69f477de702a4a058ac | kiselgra/chipotle | night.lisp | (require :chipotle)
(in-package :chipotle)
(lisp
(defun atrous (filter n)
(flet ((blow-up-row (row)
(let ((x (list (first row))))
(loop for y in (rest row)
do (setf x (append x
(make-list (1- (expt 2 n)) :initial-element 0)
(list y))))
(list x)))
(empty-row () (make-list (1+ (* (expt 2 n) (1- (cl:length filter)))) :initial-element 0)))
(let ((x (blow-up-row (first filter))))
(loop for y in (rest filter)
do (setf x (append x
(make-list (1- (expt 2 n)) :initial-element (empty-row))
(blow-up-row y))))
x))))
(defmacro atrous-step (n &key (prefix "atrous") input output (arch 'cuda))
(let ((in (cl:if input input (cintern (format nil "~a~a" prefix (cl:1- n)))))
(out (cl:if output output (cintern (format nil "~a~a" prefix n)))))
`(edge ,(cintern (format nil "compute-~a~a" prefix n))
(:input ,in :output ,out :arch ,arch)
(deflocal :mask ,(atrous '((0.057118 0.124758 0.057118)
(0.124758 0.272496 0.124758)
(0.057118 0.124758 0.057118)) n)
:initially ((float r0 = (/ (,in 0 0 0) 255.0f))
(float g0 = (/ (,in 0 0 1) 255.0f))
(float b0 = (/ (,in 0 0 2) 255.0f))
(float r = 0.0f)
(float g = 0.0f)
(float b = 0.0f)
(float W = 0.0f))
:codelet (macrolet ((mask (rx ry)
`(let ((mh (lisp (floor (/ (cl:length mask) 2)))))
(lisp (nth (+ mh ,ry) (nth (+ mh ,rx) mask))))))
(decl ((float R = (/ (,in rx ry 0) 255.0f))
(float G = (/ (,in rx ry 1) 255.0f))
(float B = (/ (,in rx ry 2) 255.0f))
(float w0 = (float-type (mask rx ry)))
(float rd = (- R r0))
(float gd = (- G g0))
(float bd = (- B b0))
(float w1 = (+ (* rd rd) (* gd gd) (* bd bd))))
(set w1 (* (fminf 1.0f (expf (- (* w1 1.0f)))) w0))
(set W (+ W w1))
(set r (+ r (* R w1))
g (+ g (* G w1))
b (+ b (* B w1)))))
:finally (set (,out 0) (* (/ r W) 255.0f)
(,out 1) (* (/ g W) 255.0f)
(,out 2) (* (/ b W) 255.0f))))))
(defmacro nightvision-filter (&key (iterations 3) (architecture cpu))
(let ((arch (ensure-list architecture)))
`(filter-graph blub
(edge load-base (:output base) (load-image :file "test.jpg"))
(atrous-step 0 :input base :arch (,@arch unsigned-char))
,@(loop for i from 1 to (cl:1- iterations) collect `(atrous-step ,i :arch (,@arch unsigned-char)))
(atrous-step ,iterations :output prefiltered :arch (,@arch unsigned-char))
(edge scoto (:input prefiltered :output scotopic2 :arch (,@arch unsigned-char))
(defpoint ()
(decl ((float r = (prefiltered 0))
(float g = (prefiltered 1))
(float b = (prefiltered 2))
(float X = (+ (* 0.5149f r) (* 0.3244f g) (* 0.1607f b)))
(float Y = (/ (+ (* 0.2654f r) (* 0.6704f g) (* 0.0642f b)) 3.0f))
(float Z = (+ (* 0.0248f r) (* 0.1248f g) (* 0.8504f b)))
(float V = (* Y (- (* 1.33f (+ 1.0f (/ (+ Y Z) X))) 1.68f)))
(float W = (+ X Y Z))
(float luma = (+ (* 0.2126f r) (* 0.7152f g) (* 0.0722f b)))
( / luma 2.0f ) )
(float xl = (/ X W))
(float yl = (/ Y W))
(const float xb = 0.25f)
(const float yb = 0.25f))
(set xl (+ (* (- 1.0f s) xb) (* s xl))
yl (+ (* (- 1.0f s) yb) (* s yl))
Y (+ (* V 0.4468f (- 1.0f s)) (* s Y))
X (/ (* xl Y) yl)
Z (- (/ X yl) X Y))
(decl ((float rgb_r = (+ (* 2.562263f X) (* -1.166107f Y) (* -0.396157f Z)))
(float rgb_g = (+ (* -1.021558f X) (* 1.977828f Y) (* 0.043730f Z)))
(float rgb_b = (+ (* 0.075196f X) (* -0.256248f Y) (* 1.181053f Z))))
(set (scotopic2 0) (fminf 255.0f (fmaxf 0.0f rgb_r)))
(set (scotopic2 1) (fminf 255.0f (fmaxf 0.0f rgb_g)))
(set (scotopic2 2) (fminf 255.0f (fmaxf 0.0f rgb_b)))))))
(edge store-scotopic-pre-0 (:input atrous0) (store-image :file "night-prefilter-0-atrous0.jpg"))
(edge store-scotopic-pre-1 (:input atrous1) (store-image :file "night-prefilter-1-atrous1.jpg"))
(edge store-scotopic-pre-2 (:input atrous2) (store-image :file "night-prefilter-2-atrous2.jpg"))
(edge store-scotopic-pre-3 (:input prefiltered) (store-image :file "night-prefilter-3-atrous3.jpg"))
(edge store-scotopic-pre-n (:input scotopic2) (store-image :file "night-prefilter-4-scopto.jpg"))
)))
(chp-preamble)
(nightvision-filter :architecture avx :iterations 3)
| null | https://raw.githubusercontent.com/kiselgra/chipotle/392525f14433c334f817ba71c7090fda05e41ef7/examples/src/night.lisp | lisp | (require :chipotle)
(in-package :chipotle)
(lisp
(defun atrous (filter n)
(flet ((blow-up-row (row)
(let ((x (list (first row))))
(loop for y in (rest row)
do (setf x (append x
(make-list (1- (expt 2 n)) :initial-element 0)
(list y))))
(list x)))
(empty-row () (make-list (1+ (* (expt 2 n) (1- (cl:length filter)))) :initial-element 0)))
(let ((x (blow-up-row (first filter))))
(loop for y in (rest filter)
do (setf x (append x
(make-list (1- (expt 2 n)) :initial-element (empty-row))
(blow-up-row y))))
x))))
(defmacro atrous-step (n &key (prefix "atrous") input output (arch 'cuda))
(let ((in (cl:if input input (cintern (format nil "~a~a" prefix (cl:1- n)))))
(out (cl:if output output (cintern (format nil "~a~a" prefix n)))))
`(edge ,(cintern (format nil "compute-~a~a" prefix n))
(:input ,in :output ,out :arch ,arch)
(deflocal :mask ,(atrous '((0.057118 0.124758 0.057118)
(0.124758 0.272496 0.124758)
(0.057118 0.124758 0.057118)) n)
:initially ((float r0 = (/ (,in 0 0 0) 255.0f))
(float g0 = (/ (,in 0 0 1) 255.0f))
(float b0 = (/ (,in 0 0 2) 255.0f))
(float r = 0.0f)
(float g = 0.0f)
(float b = 0.0f)
(float W = 0.0f))
:codelet (macrolet ((mask (rx ry)
`(let ((mh (lisp (floor (/ (cl:length mask) 2)))))
(lisp (nth (+ mh ,ry) (nth (+ mh ,rx) mask))))))
(decl ((float R = (/ (,in rx ry 0) 255.0f))
(float G = (/ (,in rx ry 1) 255.0f))
(float B = (/ (,in rx ry 2) 255.0f))
(float w0 = (float-type (mask rx ry)))
(float rd = (- R r0))
(float gd = (- G g0))
(float bd = (- B b0))
(float w1 = (+ (* rd rd) (* gd gd) (* bd bd))))
(set w1 (* (fminf 1.0f (expf (- (* w1 1.0f)))) w0))
(set W (+ W w1))
(set r (+ r (* R w1))
g (+ g (* G w1))
b (+ b (* B w1)))))
:finally (set (,out 0) (* (/ r W) 255.0f)
(,out 1) (* (/ g W) 255.0f)
(,out 2) (* (/ b W) 255.0f))))))
(defmacro nightvision-filter (&key (iterations 3) (architecture cpu))
(let ((arch (ensure-list architecture)))
`(filter-graph blub
(edge load-base (:output base) (load-image :file "test.jpg"))
(atrous-step 0 :input base :arch (,@arch unsigned-char))
,@(loop for i from 1 to (cl:1- iterations) collect `(atrous-step ,i :arch (,@arch unsigned-char)))
(atrous-step ,iterations :output prefiltered :arch (,@arch unsigned-char))
(edge scoto (:input prefiltered :output scotopic2 :arch (,@arch unsigned-char))
(defpoint ()
(decl ((float r = (prefiltered 0))
(float g = (prefiltered 1))
(float b = (prefiltered 2))
(float X = (+ (* 0.5149f r) (* 0.3244f g) (* 0.1607f b)))
(float Y = (/ (+ (* 0.2654f r) (* 0.6704f g) (* 0.0642f b)) 3.0f))
(float Z = (+ (* 0.0248f r) (* 0.1248f g) (* 0.8504f b)))
(float V = (* Y (- (* 1.33f (+ 1.0f (/ (+ Y Z) X))) 1.68f)))
(float W = (+ X Y Z))
(float luma = (+ (* 0.2126f r) (* 0.7152f g) (* 0.0722f b)))
( / luma 2.0f ) )
(float xl = (/ X W))
(float yl = (/ Y W))
(const float xb = 0.25f)
(const float yb = 0.25f))
(set xl (+ (* (- 1.0f s) xb) (* s xl))
yl (+ (* (- 1.0f s) yb) (* s yl))
Y (+ (* V 0.4468f (- 1.0f s)) (* s Y))
X (/ (* xl Y) yl)
Z (- (/ X yl) X Y))
(decl ((float rgb_r = (+ (* 2.562263f X) (* -1.166107f Y) (* -0.396157f Z)))
(float rgb_g = (+ (* -1.021558f X) (* 1.977828f Y) (* 0.043730f Z)))
(float rgb_b = (+ (* 0.075196f X) (* -0.256248f Y) (* 1.181053f Z))))
(set (scotopic2 0) (fminf 255.0f (fmaxf 0.0f rgb_r)))
(set (scotopic2 1) (fminf 255.0f (fmaxf 0.0f rgb_g)))
(set (scotopic2 2) (fminf 255.0f (fmaxf 0.0f rgb_b)))))))
(edge store-scotopic-pre-0 (:input atrous0) (store-image :file "night-prefilter-0-atrous0.jpg"))
(edge store-scotopic-pre-1 (:input atrous1) (store-image :file "night-prefilter-1-atrous1.jpg"))
(edge store-scotopic-pre-2 (:input atrous2) (store-image :file "night-prefilter-2-atrous2.jpg"))
(edge store-scotopic-pre-3 (:input prefiltered) (store-image :file "night-prefilter-3-atrous3.jpg"))
(edge store-scotopic-pre-n (:input scotopic2) (store-image :file "night-prefilter-4-scopto.jpg"))
)))
(chp-preamble)
(nightvision-filter :architecture avx :iterations 3)
| |
641bf94a3846ba632d13727f7db320f59a03931b711c8b48ba8ca6d928541c27 | rajasegar/cl-djula-tailwind | tailwind-colors.lisp | (defpackage cl-djula-tailwind.colors
(:use :cl)
(:export :*slate-colors*
:*gray-colors*
:*zinc-colors*
:*neutral-colors*
:*stone-colors*
:*red-colors*
:*orange-colors*
:*amber-colors*
:*yellow-colors*
:*lime-colors*
:*green-colors*
:*emerald-colors*
:*teal-colors*
:*cyan-colors*
:*sky-colors*
:*blue-colors*
:*indigo-colors*
:*violet-colors*
:*purple-colors*
:*fuchsia-colors*
:*pink-colors*
:*rose-colors*))
(in-package cl-djula-tailwind.colors)
(defvar *slate-colors* '(("50" . "#f8fafc")
("100" . "#f1f5f9")
("200" . "#e2e8f0")
("300" . "#cbd5e1")
("400" . "#94a3b8")
("500" . "#64748b")
("600" . "#475569")
("700" . "#334155")
("800" . "#1e293b")
("900" . "#0f172a")))
(defvar *gray-colors*
'(("50" . "#f9fafb")
("100" . "#f3f4f6")
("200" . "#e5e7eb")
("300" . "#d1d5db")
("400" . "#9ca3af")
("500" . "#6b7280")
("600" . "#4b5563")
("700" . "#374151")
("800" . "#1f2937")
("900" . "#111827")))
(defvar *zinc-colors* '(("50" . "#fafafa")
("100" . "#f4f4f5")
("200" . "#e4e4e7")
("300" . "#d4d4d8")
("400" . "#a1a1aa")
("500" . "#71717a")
("600" . "#52525b")
("700" . "#3f3f46")
("800" . "#27272a")
("900" . "#18181b")))
(defvar *neutral-colors* '(("50" . "#fafafa")
("100" . "#f5f5f5")
("200" . "#e5e5e5")
("300" . "#d4d4d4")
("400" . "#a3a3a3")
("500" . "#737373")
("600" . "#525252")
("700" . "#404040")
("800" . "#262626")
("900" . "#171717")))
(defvar *stone-colors* '(("50" . "#fafaf9")
("100" . "#f5f5f4")
("200" . "#e7e5e4")
("300" . "#d6d3d1")
("400" . "#a8a29e")
("500" . "#78716c")
("600" . "#57534e")
("700" . "#44403c")
("800" . "#292524")
("900" . "#1c1917")))
(defvar *red-colors* '(("50" . "#fef2f2")
("100" . "#fee2e2")
("200" . "#fecaca")
("300" . "#fca5a5")
("400" . "#f87171")
("500" . "#ef4444")
("600" . "#dc2626")
("700" . "#b91c1c")
("800" . "#991b1b")
("900" . "#7f1d1d")))
(defvar *orange-colors* '(("50" . "#fff7ed")
("100" . "#ffedd5")
("200" . "#fed7aa")
("300" . "#fdba74")
("400" . "#fb923c")
("500" . "#f97316")
("600" . "#ea580c")
("700" . "#c2410c")
("800" . "#9a3412")
("900" . "#7c2d12")))
(defvar *amber-colors* '(("50" . "#fffbeb")
("100" . "#fef3c7")
("200" . "#fde68a")
("300" . "#fcd34d")
("400" . "#fbbf24")
("500" . "#f59e0b")
("600" . "#d97706")
("700" . "#b45309")
("800" . "#92400e")
("900" . "#78350f")))
(defvar *yellow-colors* '(("50" . "#fefce8")
("100" . "#fef9c3")
("200" . "#fef08a")
("300" . "#fde047")
("400" . "#facc15")
("500" . "#eab308")
("600" . "#ca8a04")
("700" . "#a16207")
("800" . "#854d0e")
("900" . "#713f12")))
(defvar *lime-colors* '(("50" . "#f7fee7")
("100" . "#ecfccb")
("200" . "#d9f99d")
("300" . "#bef264")
("400" . "#a3e635")
("500" . "#84cc16")
("600" . "#65a30d")
("700" . "#4d7c0f")
("800" . "#3f6212")
("900" . "#365314")))
(defvar *green-colors* '(("50" . "#f0fdf4")
("100" . "#dcfce7")
("200" . "#bbf7d0")
("300" . "#86efac")
("400" . "#4ade80")
("500" . "#22c55e")
("600" . "#16a34a")
("700" . "#15803d")
("800" . "#166534")
("900" . "#14532d")))
(defvar *emerald-colors* '(("50" . "#ecfdf5")
("100" . "#d1fae5")
("200" . "#a7f3d0")
("300" . "#6ee7b7")
("400" . "#34d399")
("500" . "#10b981")
("600" . "#059669")
("700" . "#047857")
("800" . "#065f46")
("900" . "#064e3b")))
(defvar *teal-colors* '(("50" . "#f0fdfa")
("100" . "#ccfbf1")
("200" . "#99f6e4")
("300" . "#5eead4")
("400" . "#2dd4bf")
("500" . "#14b8a6")
("600" . "#0d9488")
("700" . "#0f766e")
("800" . "#115e59")
("900" . "#134e4a")))
(defvar *cyan-colors* '(("50" . "#ecfeff")
("100" . "#cffafe")
("200" . "#a5f3fc")
("300" . "#67e8f9")
("400" . "#22d3ee")
("500" . "#06b6d4")
("600" . "#0891b2")
("700" . "#0e7490")
("800" . "#155e75")
("900" . "#164e63")))
(defvar *sky-colors* '(("50" . "#f0f9ff")
("100" . "#e0f2fe")
("200" . "#bae6fd")
("300" . "#7dd3fc")
("400" . "#38bdf8")
("500" . "#0ea5e9")
("600" . "#0284c7")
("700" . "#0369a1")
("800" . "#075985")
("900" . "#0c4a6e")))
(defvar *blue-colors* '(("50" . "#eff6ff")
("100" . "#dbeafe")
("200" . "#bfdbfe")
("300" . "#93c5fd")
("400" . "#60a5fa")
("500" . "#3b82f6")
("600" . "#2563eb")
("700" . "#1d4ed8")
("800" . "#1e40af")
("900" . "#1e3a8a")))
(defvar *indigo-colors* '(("50" . "#eef2ff")
("100" . "#e0e7ff")
("200" . "#c7d2fe")
("300" . "#a5b4fc")
("400" . "#818cf8")
("500" . "#6366f1")
("600" . "#4f46e5")
("700" . "#4338ca")
("800" . "#3730a3")
("900" . "#312e81")))
(defvar *violet-colors* '(("50" . "#f5f3ff")
("100" . "#ede9fe")
("200" . "#ddd6fe")
("300" . "#c4b5fd")
("400" . "#a78bfa")
("500" . "#8b5cf6")
("600" . "#7c3aed")
("700" . "#6d28d9")
("800" . "#5b21b6")
("900" . "#4c1d95")))
(defvar *purple-colors* '(("50" . "#faf5ff")
("100" . "#f3e8ff")
("200" . "#e9d5ff")
("300" . "#d8b4fe")
("400" . "#c084fc")
("500" . "#a855f7")
("600" . "#9333ea")
("700" . "#7e22ce")
("800" . "#6b21a8")
("900" . "#581c87")))
(defvar *fuchsia-colors* '(("50" . "#fdf4ff")
("100" . "#fae8ff")
("200" . "#f5d0fe")
("300" . "#f0abfc")
("400" . "#e879f9")
("500" . "#d946ef")
("600" . "#c026d3")
("700" . "#a21caf")
("800" . "#86198f")
("900" . "#701a75")))
(defvar *pink-colors* '(("50" . "#fdf2f8")
("100" . "#fce7f3")
("200" . "#fbcfe8")
("300" . "#f9a8d4")
("400" . "#f472b6")
("500" . "#ec4899")
("600" . "#db2777")
("700" . "#be185d")
("800" . "#9d174d")
("900" . "#831843")))
(defvar *rose-colors* '(("50" . "#fff1f2")
("100" . "#ffe4e6")
("200" . "#fecdd3")
("300" . "#fda4af")
("400" . "#fb7185")
("500" . "#f43f5e")
("600" . "#e11d48")
("700" . "#be123c")
("800" . "#9f1239")
("900" . "#881337")))
| null | https://raw.githubusercontent.com/rajasegar/cl-djula-tailwind/eeef6e3239d55848c76fa2cfeac8a7eead854480/src/tailwind-colors.lisp | lisp | (defpackage cl-djula-tailwind.colors
(:use :cl)
(:export :*slate-colors*
:*gray-colors*
:*zinc-colors*
:*neutral-colors*
:*stone-colors*
:*red-colors*
:*orange-colors*
:*amber-colors*
:*yellow-colors*
:*lime-colors*
:*green-colors*
:*emerald-colors*
:*teal-colors*
:*cyan-colors*
:*sky-colors*
:*blue-colors*
:*indigo-colors*
:*violet-colors*
:*purple-colors*
:*fuchsia-colors*
:*pink-colors*
:*rose-colors*))
(in-package cl-djula-tailwind.colors)
(defvar *slate-colors* '(("50" . "#f8fafc")
("100" . "#f1f5f9")
("200" . "#e2e8f0")
("300" . "#cbd5e1")
("400" . "#94a3b8")
("500" . "#64748b")
("600" . "#475569")
("700" . "#334155")
("800" . "#1e293b")
("900" . "#0f172a")))
(defvar *gray-colors*
'(("50" . "#f9fafb")
("100" . "#f3f4f6")
("200" . "#e5e7eb")
("300" . "#d1d5db")
("400" . "#9ca3af")
("500" . "#6b7280")
("600" . "#4b5563")
("700" . "#374151")
("800" . "#1f2937")
("900" . "#111827")))
(defvar *zinc-colors* '(("50" . "#fafafa")
("100" . "#f4f4f5")
("200" . "#e4e4e7")
("300" . "#d4d4d8")
("400" . "#a1a1aa")
("500" . "#71717a")
("600" . "#52525b")
("700" . "#3f3f46")
("800" . "#27272a")
("900" . "#18181b")))
(defvar *neutral-colors* '(("50" . "#fafafa")
("100" . "#f5f5f5")
("200" . "#e5e5e5")
("300" . "#d4d4d4")
("400" . "#a3a3a3")
("500" . "#737373")
("600" . "#525252")
("700" . "#404040")
("800" . "#262626")
("900" . "#171717")))
(defvar *stone-colors* '(("50" . "#fafaf9")
("100" . "#f5f5f4")
("200" . "#e7e5e4")
("300" . "#d6d3d1")
("400" . "#a8a29e")
("500" . "#78716c")
("600" . "#57534e")
("700" . "#44403c")
("800" . "#292524")
("900" . "#1c1917")))
(defvar *red-colors* '(("50" . "#fef2f2")
("100" . "#fee2e2")
("200" . "#fecaca")
("300" . "#fca5a5")
("400" . "#f87171")
("500" . "#ef4444")
("600" . "#dc2626")
("700" . "#b91c1c")
("800" . "#991b1b")
("900" . "#7f1d1d")))
(defvar *orange-colors* '(("50" . "#fff7ed")
("100" . "#ffedd5")
("200" . "#fed7aa")
("300" . "#fdba74")
("400" . "#fb923c")
("500" . "#f97316")
("600" . "#ea580c")
("700" . "#c2410c")
("800" . "#9a3412")
("900" . "#7c2d12")))
(defvar *amber-colors* '(("50" . "#fffbeb")
("100" . "#fef3c7")
("200" . "#fde68a")
("300" . "#fcd34d")
("400" . "#fbbf24")
("500" . "#f59e0b")
("600" . "#d97706")
("700" . "#b45309")
("800" . "#92400e")
("900" . "#78350f")))
(defvar *yellow-colors* '(("50" . "#fefce8")
("100" . "#fef9c3")
("200" . "#fef08a")
("300" . "#fde047")
("400" . "#facc15")
("500" . "#eab308")
("600" . "#ca8a04")
("700" . "#a16207")
("800" . "#854d0e")
("900" . "#713f12")))
(defvar *lime-colors* '(("50" . "#f7fee7")
("100" . "#ecfccb")
("200" . "#d9f99d")
("300" . "#bef264")
("400" . "#a3e635")
("500" . "#84cc16")
("600" . "#65a30d")
("700" . "#4d7c0f")
("800" . "#3f6212")
("900" . "#365314")))
(defvar *green-colors* '(("50" . "#f0fdf4")
("100" . "#dcfce7")
("200" . "#bbf7d0")
("300" . "#86efac")
("400" . "#4ade80")
("500" . "#22c55e")
("600" . "#16a34a")
("700" . "#15803d")
("800" . "#166534")
("900" . "#14532d")))
(defvar *emerald-colors* '(("50" . "#ecfdf5")
("100" . "#d1fae5")
("200" . "#a7f3d0")
("300" . "#6ee7b7")
("400" . "#34d399")
("500" . "#10b981")
("600" . "#059669")
("700" . "#047857")
("800" . "#065f46")
("900" . "#064e3b")))
(defvar *teal-colors* '(("50" . "#f0fdfa")
("100" . "#ccfbf1")
("200" . "#99f6e4")
("300" . "#5eead4")
("400" . "#2dd4bf")
("500" . "#14b8a6")
("600" . "#0d9488")
("700" . "#0f766e")
("800" . "#115e59")
("900" . "#134e4a")))
(defvar *cyan-colors* '(("50" . "#ecfeff")
("100" . "#cffafe")
("200" . "#a5f3fc")
("300" . "#67e8f9")
("400" . "#22d3ee")
("500" . "#06b6d4")
("600" . "#0891b2")
("700" . "#0e7490")
("800" . "#155e75")
("900" . "#164e63")))
(defvar *sky-colors* '(("50" . "#f0f9ff")
("100" . "#e0f2fe")
("200" . "#bae6fd")
("300" . "#7dd3fc")
("400" . "#38bdf8")
("500" . "#0ea5e9")
("600" . "#0284c7")
("700" . "#0369a1")
("800" . "#075985")
("900" . "#0c4a6e")))
(defvar *blue-colors* '(("50" . "#eff6ff")
("100" . "#dbeafe")
("200" . "#bfdbfe")
("300" . "#93c5fd")
("400" . "#60a5fa")
("500" . "#3b82f6")
("600" . "#2563eb")
("700" . "#1d4ed8")
("800" . "#1e40af")
("900" . "#1e3a8a")))
(defvar *indigo-colors* '(("50" . "#eef2ff")
("100" . "#e0e7ff")
("200" . "#c7d2fe")
("300" . "#a5b4fc")
("400" . "#818cf8")
("500" . "#6366f1")
("600" . "#4f46e5")
("700" . "#4338ca")
("800" . "#3730a3")
("900" . "#312e81")))
(defvar *violet-colors* '(("50" . "#f5f3ff")
("100" . "#ede9fe")
("200" . "#ddd6fe")
("300" . "#c4b5fd")
("400" . "#a78bfa")
("500" . "#8b5cf6")
("600" . "#7c3aed")
("700" . "#6d28d9")
("800" . "#5b21b6")
("900" . "#4c1d95")))
(defvar *purple-colors* '(("50" . "#faf5ff")
("100" . "#f3e8ff")
("200" . "#e9d5ff")
("300" . "#d8b4fe")
("400" . "#c084fc")
("500" . "#a855f7")
("600" . "#9333ea")
("700" . "#7e22ce")
("800" . "#6b21a8")
("900" . "#581c87")))
(defvar *fuchsia-colors* '(("50" . "#fdf4ff")
("100" . "#fae8ff")
("200" . "#f5d0fe")
("300" . "#f0abfc")
("400" . "#e879f9")
("500" . "#d946ef")
("600" . "#c026d3")
("700" . "#a21caf")
("800" . "#86198f")
("900" . "#701a75")))
(defvar *pink-colors* '(("50" . "#fdf2f8")
("100" . "#fce7f3")
("200" . "#fbcfe8")
("300" . "#f9a8d4")
("400" . "#f472b6")
("500" . "#ec4899")
("600" . "#db2777")
("700" . "#be185d")
("800" . "#9d174d")
("900" . "#831843")))
(defvar *rose-colors* '(("50" . "#fff1f2")
("100" . "#ffe4e6")
("200" . "#fecdd3")
("300" . "#fda4af")
("400" . "#fb7185")
("500" . "#f43f5e")
("600" . "#e11d48")
("700" . "#be123c")
("800" . "#9f1239")
("900" . "#881337")))
| |
c32a87eefd753a3535ab959abee5a019883c9cecff152a93a0eb36d8bdc9f5ac | aharisu/Gauche-CV | contour-scanner.scm | (use cv)
(let* ([src (cv-load-image "data/image/lenna.png")]
[gray (make-image (ref src 'width) (ref src 'height) IPL_DEPTH_8U 1)]
[canny (make-image (ref src 'width) (ref src 'height) IPL_DEPTH_8U 1)]
[result (cv-clone-image src)])
(cv-cvt-color src gray CV_BGR2GRAY)
(cv-canny gray canny 50 200)
(let* ([storage (make-cv-mem-storage)]
[scanner (cv-start-find-contours canny storage CV_RETR_TREE CV_CHAIN_APPROX_SIMPLE)])
(let loop ([c (cv-find-next-contour scanner)])
(when c
(cv-draw-contours result c (cv-rgb 255 0 0) (cv-rgb 0 255 0) 0 3 16)
(loop (cv-find-next-contour scanner))))
(cv-end-find-contours scanner))
(cv-named-window "ContourScanner canny")
(cv-show-image "ContourScanner canny" canny)
(cv-named-window "ContourScanner result")
(cv-show-image "ContourScanner result" result)
(cv-wait-key 0))
| null | https://raw.githubusercontent.com/aharisu/Gauche-CV/5e4c51501431c72270765121ea4d92693f11d60b/sample/contour-scanner.scm | scheme | (use cv)
(let* ([src (cv-load-image "data/image/lenna.png")]
[gray (make-image (ref src 'width) (ref src 'height) IPL_DEPTH_8U 1)]
[canny (make-image (ref src 'width) (ref src 'height) IPL_DEPTH_8U 1)]
[result (cv-clone-image src)])
(cv-cvt-color src gray CV_BGR2GRAY)
(cv-canny gray canny 50 200)
(let* ([storage (make-cv-mem-storage)]
[scanner (cv-start-find-contours canny storage CV_RETR_TREE CV_CHAIN_APPROX_SIMPLE)])
(let loop ([c (cv-find-next-contour scanner)])
(when c
(cv-draw-contours result c (cv-rgb 255 0 0) (cv-rgb 0 255 0) 0 3 16)
(loop (cv-find-next-contour scanner))))
(cv-end-find-contours scanner))
(cv-named-window "ContourScanner canny")
(cv-show-image "ContourScanner canny" canny)
(cv-named-window "ContourScanner result")
(cv-show-image "ContourScanner result" result)
(cv-wait-key 0))
| |
ec572497c14c075a0b9dfe1067b374b288b696cf1de04aa9df32147def96e9fe | WhatsApp/eqwalizer | app_a_test_helpers.erl | Copyright ( c ) Meta Platforms , Inc. and affiliates . All rights reserved .
%%%
This source code is licensed under the Apache 2.0 license found in
%%% the LICENSE file in the root directory of this source tree.
-module(app_a_test_helpers).
-typing([eqwalizer]).
-compile([export_all, nowarn_export_all]).
-spec fail() -> error.
fail() -> wrong_ret.
-spec ok() -> ok.
ok() -> ok.
| null | https://raw.githubusercontent.com/WhatsApp/eqwalizer/9935940d71ef65c7bf7a9dfad77d89c0006c288e/mini-elp/test_projects/standard/app_a/test/app_a_test_helpers.erl | erlang |
the LICENSE file in the root directory of this source tree. | Copyright ( c ) Meta Platforms , Inc. and affiliates . All rights reserved .
This source code is licensed under the Apache 2.0 license found in
-module(app_a_test_helpers).
-typing([eqwalizer]).
-compile([export_all, nowarn_export_all]).
-spec fail() -> error.
fail() -> wrong_ret.
-spec ok() -> ok.
ok() -> ok.
|
0eafb4835209127f6825c4ed9a72ec61840294058a10f9fffa855b4d4af1fda5 | AccelerateHS/accelerate-llvm | InlineAssembly.hs | # LANGUAGE FlexibleInstances #
# LANGUAGE GADTs #
# LANGUAGE MultiParamTypeClasses #
{-# OPTIONS_HADDOCK hide #-}
-- |
Module : . InlineAssembly
Copyright : [ 2015 .. 2020 ] The Accelerate Team
-- License : BSD3
--
Maintainer : < >
-- Stability : experimental
Portability : non - portable ( GHC extensions )
--
module LLVM.AST.Type.InlineAssembly (
module LLVM.AST.Type.InlineAssembly,
LLVM.Dialect(..),
) where
import LLVM.AST.Type.Downcast
import qualified LLVM.AST.Type as LLVM
import qualified LLVM.AST.InlineAssembly as LLVM
import Data.ByteString
import Data.ByteString.Short
-- | The 'call' instruction might be a label or inline assembly
--
data InlineAssembly where
InlineAssembly :: ByteString -- assembly
-> ShortByteString -- constraints
-> Bool -- has side effects?
-> Bool -- align stack?
-> LLVM.Dialect
-> InlineAssembly
instance Downcast (LLVM.Type, InlineAssembly) LLVM.InlineAssembly where
downcast (t, InlineAssembly asm cst s a d) =
LLVM.InlineAssembly t asm cst s a d
| null | https://raw.githubusercontent.com/AccelerateHS/accelerate-llvm/cf081587fecec23a19f68bfbd31334166868405e/accelerate-llvm/src/LLVM/AST/Type/InlineAssembly.hs | haskell | # OPTIONS_HADDOCK hide #
|
License : BSD3
Stability : experimental
| The 'call' instruction might be a label or inline assembly
assembly
constraints
has side effects?
align stack? | # LANGUAGE FlexibleInstances #
# LANGUAGE GADTs #
# LANGUAGE MultiParamTypeClasses #
Module : . InlineAssembly
Copyright : [ 2015 .. 2020 ] The Accelerate Team
Maintainer : < >
Portability : non - portable ( GHC extensions )
module LLVM.AST.Type.InlineAssembly (
module LLVM.AST.Type.InlineAssembly,
LLVM.Dialect(..),
) where
import LLVM.AST.Type.Downcast
import qualified LLVM.AST.Type as LLVM
import qualified LLVM.AST.InlineAssembly as LLVM
import Data.ByteString
import Data.ByteString.Short
data InlineAssembly where
-> LLVM.Dialect
-> InlineAssembly
instance Downcast (LLVM.Type, InlineAssembly) LLVM.InlineAssembly where
downcast (t, InlineAssembly asm cst s a d) =
LLVM.InlineAssembly t asm cst s a d
|
728343fdedf501f769ad17311444b41d737b7ea4f0e6bfa994a052a6eb5ea38d | archimag/cliki2 | auth-core.lisp | ;;;; auth-core.lisp
(in-package #:cliki2)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;; core
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defun pack-auth-cookie (name password &key (version 1) (date (get-universal-time)))
(format nil "~A|~A|~A|~A" version name password date))
(defun encrypt-auth-cookie (name password &key (version 1) (date (get-universal-time)))
(let ((result (ironclad:ascii-string-to-byte-array
(pack-auth-cookie name password :version version :date date))))
(ironclad:encrypt-in-place *user-auth-cipher* result)
(ironclad:byte-array-to-hex-string result)))
(defun set-auth-cookie (name password &key (version 1))
(hunchentoot:set-cookie *cookie-auth-name*
:value (encrypt-auth-cookie name password :version version)
:path "/"
:expires (+ (get-universal-time) (* 60 60 24 4))
:http-only t))
;;;; get-auth-cookie
(defun unpack-auth-cookie (str)
(let ((info (split-sequence:split-sequence #\| str)))
(values (first info)
(second info)
(third info)
(fourth info))))
(defun hex-string-to-byte-array (string &key (start 0) (end nil))
(declare (type string string))
(let* ((end (or end (length string)))
(length (/ (- end start) 2))
(key (make-array length :element-type '(unsigned-byte 8))))
(declare (type (simple-array (unsigned-byte 8) (*)) key))
(flet ((char-to-digit (char)
(let ((x (position char "0123456789abcdef" :test #'char-equal)))
(or x (error "Invalid hex key ~A specified" string)))))
(loop for i from 0
for j from start below end by 2
do (setf (aref key i)
(+ (* (char-to-digit (char string j)) 16)
(char-to-digit (char string (1+ j)))))
finally (return key)))))
(defun decrypt-auth-cookie (str)
(ignore-errors
(let ((result (hex-string-to-byte-array str)))
(ironclad:decrypt-in-place *user-auth-cipher*
result)
(unpack-auth-cookie (babel:octets-to-string result :encoding :utf-8)))))
(defun get-auth-cookie ()
(let ((cookie (hunchentoot:cookie-in *cookie-auth-name*)))
(if cookie
(decrypt-auth-cookie cookie))))
(defun run-sing-in (user &key (version 1))
"Set cookie for user name and password"
(setf *user* user)
(set-auth-cookie (user-name user)
(user-password-digest user)
:version version))
(defun run-sign-out ()
"Clear cookie with auth information"
(setf *user* nil)
(hunchentoot:set-cookie *cookie-auth-name*
:value ""
:path "/"))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
- auth - user decorator
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defvar *kdf* (ironclad:make-kdf 'ironclad:pbkdf2 :digest 'ironclad:sha256))
(defun password-digest (password salt)
(ironclad:byte-array-to-hex-string
(ironclad:derive-key *kdf*
(babel:string-to-octets password :encoding :utf-8)
(babel:string-to-octets salt)
1000 128)))
(defun make-random-salt ()
(let ((salt (make-array 50 :element-type '(unsigned-byte 8))))
(dotimes (i (length salt))
(setf (aref salt i) (random 256)))
(ironclad:byte-array-to-hex-string salt)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
- auth - user decorator
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defclass check-auth-user-route (routes:proxy-route) ())
(defun check-user-auth ()
(multiple-value-bind (version name password date) (get-auth-cookie)
(if (and version name password date)
(let ((user (user-with-name name)))
(if (and user
(string= (user-password-digest user)
password)
(or (null (user-role user))
(member (user-role user) '(:moderator :administrator))))
user)))))
(defmethod routes:route-check-conditions ((route check-auth-user-route) bindings)
(let ((*user* (check-user-auth)))
(call-next-method)))
(defmethod restas:process-route ((route check-auth-user-route) bindings)
(let ((*user* (check-user-auth)))
(call-next-method)))
(defun @check-auth-user (origin)
(make-instance 'check-auth-user-route :target origin))
| null | https://raw.githubusercontent.com/archimag/cliki2/f0b6910f040907c70fd842ed76472af2d645c984/src/auth-core.lisp | lisp | auth-core.lisp
core
get-auth-cookie
|
(in-package #:cliki2)
(defun pack-auth-cookie (name password &key (version 1) (date (get-universal-time)))
(format nil "~A|~A|~A|~A" version name password date))
(defun encrypt-auth-cookie (name password &key (version 1) (date (get-universal-time)))
(let ((result (ironclad:ascii-string-to-byte-array
(pack-auth-cookie name password :version version :date date))))
(ironclad:encrypt-in-place *user-auth-cipher* result)
(ironclad:byte-array-to-hex-string result)))
(defun set-auth-cookie (name password &key (version 1))
(hunchentoot:set-cookie *cookie-auth-name*
:value (encrypt-auth-cookie name password :version version)
:path "/"
:expires (+ (get-universal-time) (* 60 60 24 4))
:http-only t))
(defun unpack-auth-cookie (str)
(let ((info (split-sequence:split-sequence #\| str)))
(values (first info)
(second info)
(third info)
(fourth info))))
(defun hex-string-to-byte-array (string &key (start 0) (end nil))
(declare (type string string))
(let* ((end (or end (length string)))
(length (/ (- end start) 2))
(key (make-array length :element-type '(unsigned-byte 8))))
(declare (type (simple-array (unsigned-byte 8) (*)) key))
(flet ((char-to-digit (char)
(let ((x (position char "0123456789abcdef" :test #'char-equal)))
(or x (error "Invalid hex key ~A specified" string)))))
(loop for i from 0
for j from start below end by 2
do (setf (aref key i)
(+ (* (char-to-digit (char string j)) 16)
(char-to-digit (char string (1+ j)))))
finally (return key)))))
(defun decrypt-auth-cookie (str)
(ignore-errors
(let ((result (hex-string-to-byte-array str)))
(ironclad:decrypt-in-place *user-auth-cipher*
result)
(unpack-auth-cookie (babel:octets-to-string result :encoding :utf-8)))))
(defun get-auth-cookie ()
(let ((cookie (hunchentoot:cookie-in *cookie-auth-name*)))
(if cookie
(decrypt-auth-cookie cookie))))
(defun run-sing-in (user &key (version 1))
"Set cookie for user name and password"
(setf *user* user)
(set-auth-cookie (user-name user)
(user-password-digest user)
:version version))
(defun run-sign-out ()
"Clear cookie with auth information"
(setf *user* nil)
(hunchentoot:set-cookie *cookie-auth-name*
:value ""
:path "/"))
- auth - user decorator
(defvar *kdf* (ironclad:make-kdf 'ironclad:pbkdf2 :digest 'ironclad:sha256))
(defun password-digest (password salt)
(ironclad:byte-array-to-hex-string
(ironclad:derive-key *kdf*
(babel:string-to-octets password :encoding :utf-8)
(babel:string-to-octets salt)
1000 128)))
(defun make-random-salt ()
(let ((salt (make-array 50 :element-type '(unsigned-byte 8))))
(dotimes (i (length salt))
(setf (aref salt i) (random 256)))
(ironclad:byte-array-to-hex-string salt)))
- auth - user decorator
(defclass check-auth-user-route (routes:proxy-route) ())
(defun check-user-auth ()
(multiple-value-bind (version name password date) (get-auth-cookie)
(if (and version name password date)
(let ((user (user-with-name name)))
(if (and user
(string= (user-password-digest user)
password)
(or (null (user-role user))
(member (user-role user) '(:moderator :administrator))))
user)))))
(defmethod routes:route-check-conditions ((route check-auth-user-route) bindings)
(let ((*user* (check-user-auth)))
(call-next-method)))
(defmethod restas:process-route ((route check-auth-user-route) bindings)
(let ((*user* (check-user-auth)))
(call-next-method)))
(defun @check-auth-user (origin)
(make-instance 'check-auth-user-route :target origin))
|
2d5710e3dba3277182dbe02aaa6bedf69bafac9b648b87c605c15bd1ffb6d732 | realworldocaml/book | typerepable.ml | open Std_internal
module type S = sig
type t
val typerep_of_t : t Typerep.t
val typename_of_t : t Typename.t
end
module type S1 = sig
type 'a t
val typerep_of_t : 'a Typerep.t -> 'a t Typerep.t
val typename_of_t : 'a Typename.t -> 'a t Typename.t
end
module type S2 = sig
type ('a, 'b) t
val typerep_of_t : 'a Typerep.t -> 'b Typerep.t -> ('a, 'b) t Typerep.t
val typename_of_t : 'a Typename.t -> 'b Typename.t -> ('a, 'b) t Typename.t
end
module type S3 = sig
type ('a, 'b, 'c) t
val typerep_of_t
: 'a Typerep.t
-> 'b Typerep.t
-> 'c Typerep.t
-> ('a, 'b, 'c) t Typerep.t
val typename_of_t
: 'a Typename.t
-> 'b Typename.t
-> 'c Typename.t
-> ('a, 'b, 'c) t Typename.t
end
module type S4 = sig
type ('a, 'b, 'c, 'd) t
val typerep_of_t
: 'a Typerep.t
-> 'b Typerep.t
-> 'c Typerep.t
-> 'd Typerep.t
-> ('a, 'b, 'c, 'd) t Typerep.t
val typename_of_t
: 'a Typename.t
-> 'b Typename.t
-> 'c Typename.t
-> 'd Typename.t
-> ('a, 'b, 'c, 'd) t Typename.t
end
module type S5 = sig
type ('a, 'b, 'c, 'd, 'e) t
val typerep_of_t
: 'a Typerep.t
-> 'b Typerep.t
-> 'c Typerep.t
-> 'd Typerep.t
-> 'e Typerep.t
-> ('a, 'b, 'c, 'd, 'e) t Typerep.t
val typename_of_t
: 'a Typename.t
-> 'b Typename.t
-> 'c Typename.t
-> 'd Typename.t
-> 'e Typename.t
-> ('a, 'b, 'c, 'd, 'e) t Typename.t
end
| null | https://raw.githubusercontent.com/realworldocaml/book/d822fd065f19dbb6324bf83e0143bc73fd77dbf9/duniverse/typerep/lib/typerepable.ml | ocaml | open Std_internal
module type S = sig
type t
val typerep_of_t : t Typerep.t
val typename_of_t : t Typename.t
end
module type S1 = sig
type 'a t
val typerep_of_t : 'a Typerep.t -> 'a t Typerep.t
val typename_of_t : 'a Typename.t -> 'a t Typename.t
end
module type S2 = sig
type ('a, 'b) t
val typerep_of_t : 'a Typerep.t -> 'b Typerep.t -> ('a, 'b) t Typerep.t
val typename_of_t : 'a Typename.t -> 'b Typename.t -> ('a, 'b) t Typename.t
end
module type S3 = sig
type ('a, 'b, 'c) t
val typerep_of_t
: 'a Typerep.t
-> 'b Typerep.t
-> 'c Typerep.t
-> ('a, 'b, 'c) t Typerep.t
val typename_of_t
: 'a Typename.t
-> 'b Typename.t
-> 'c Typename.t
-> ('a, 'b, 'c) t Typename.t
end
module type S4 = sig
type ('a, 'b, 'c, 'd) t
val typerep_of_t
: 'a Typerep.t
-> 'b Typerep.t
-> 'c Typerep.t
-> 'd Typerep.t
-> ('a, 'b, 'c, 'd) t Typerep.t
val typename_of_t
: 'a Typename.t
-> 'b Typename.t
-> 'c Typename.t
-> 'd Typename.t
-> ('a, 'b, 'c, 'd) t Typename.t
end
module type S5 = sig
type ('a, 'b, 'c, 'd, 'e) t
val typerep_of_t
: 'a Typerep.t
-> 'b Typerep.t
-> 'c Typerep.t
-> 'd Typerep.t
-> 'e Typerep.t
-> ('a, 'b, 'c, 'd, 'e) t Typerep.t
val typename_of_t
: 'a Typename.t
-> 'b Typename.t
-> 'c Typename.t
-> 'd Typename.t
-> 'e Typename.t
-> ('a, 'b, 'c, 'd, 'e) t Typename.t
end
| |
2d997f54dc8c60843edf69b805e855ef879310a9be872624ae17cb3eb9cca16b | glguy/intcode | doctests.hs | import Test.DocTest
main :: IO ()
main = doctest ["-isrc", "Intcode", "Intcode.Machine", "Intcode.Opcode", "Intcode.Parse"]
| null | https://raw.githubusercontent.com/glguy/intcode/4dddd6cc4d412fe63dcbb1bd1c703aecadc12b42/doctests.hs | haskell | import Test.DocTest
main :: IO ()
main = doctest ["-isrc", "Intcode", "Intcode.Machine", "Intcode.Opcode", "Intcode.Parse"]
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.