_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 |
|---|---|---|---|---|---|---|---|---|
5634073fb0b875840221b2909adffdb749f60bc55df00eb8deef5c7a0c9e0b26 | b0-system/brzo | answer.ml |
let value = 42
| null | https://raw.githubusercontent.com/b0-system/brzo/79d316a5024025a0112a8569a6335241b4620da8/examples/ocaml-deps/answer.ml | ocaml |
let value = 42
| |
47500c131531b2480cde3f9d7d293def6f67c7027eb0e4105cb3c22d52c93596 | circuithub/rel8 | Name.hs | # language DataKinds #
{-# language FlexibleContexts #-}
# language FlexibleInstances #
# language MultiParamTypeClasses #
# language NamedFieldPuns #
{-# language ScopedTypeVariables #-}
# language TypeApplications #
{-# language TypeFamilies #-}
{-# language UndecidableInstances #-}
# language ViewPatterns #
module Rel8.Table.Name
( namesFromLabels
, namesFromLabelsWith
, showLabels
, showNames
)
where
-- base
import Data.Foldable ( fold )
import Data.Functor.Const ( Const( Const ), getConst )
import Data.List.NonEmpty ( NonEmpty, intersperse, nonEmpty )
import Data.Maybe ( fromMaybe )
import Prelude
-- rel8
import Rel8.Schema.HTable ( htabulate, htabulateA, hfield, hspecs )
import Rel8.Schema.Name ( Name( Name ) )
import Rel8.Schema.Spec ( Spec(..) )
import Rel8.Table ( Table(..) )
-- | Construct a table in the 'Name' context containing the names of all
-- columns. Nested column names will be combined with @/@.
--
-- See also: 'namesFromLabelsWith'.
namesFromLabels :: Table Name a => a
namesFromLabels = namesFromLabelsWith go
where
go = fold . intersperse "/"
-- | Construct a table in the 'Name' context containing the names of all
-- columns. The supplied function can be used to transform column names.
--
-- This function can be used to generically derive the columns for a
' ' . For example ,
--
-- @
myTableSchema : : ( )
myTableSchema =
-- { columns = namesFromLabelsWith last
-- }
-- @
--
will construct a ' ' where each columns names exactly corresponds
to the name of the field .
namesFromLabelsWith :: Table Name a
=> (NonEmpty String -> String) -> a
namesFromLabelsWith f = fromColumns $ htabulate $ \field ->
case hfield hspecs field of
Spec {labels} -> Name (f (renderLabels labels))
showLabels :: forall a. Table (Context a) a => a -> [NonEmpty String]
showLabels _ = getConst $
htabulateA @(Columns a) $ \field -> case hfield hspecs field of
Spec {labels} -> Const (pure (renderLabels labels))
showNames :: forall a. Table Name a => a -> NonEmpty String
showNames (toColumns -> names) = getConst $
htabulateA @(Columns a) $ \field -> case hfield names field of
Name name -> Const (pure name)
renderLabels :: [String] -> NonEmpty String
renderLabels labels = fromMaybe (pure "anon") (nonEmpty labels )
| null | https://raw.githubusercontent.com/circuithub/rel8/5d2b9e4cdaa3ebcdaf49a66f39db0913df020e44/src/Rel8/Table/Name.hs | haskell | # language FlexibleContexts #
# language ScopedTypeVariables #
# language TypeFamilies #
# language UndecidableInstances #
base
rel8
| Construct a table in the 'Name' context containing the names of all
columns. Nested column names will be combined with @/@.
See also: 'namesFromLabelsWith'.
| Construct a table in the 'Name' context containing the names of all
columns. The supplied function can be used to transform column names.
This function can be used to generically derive the columns for a
@
{ columns = namesFromLabelsWith last
}
@
| # language DataKinds #
# language FlexibleInstances #
# language MultiParamTypeClasses #
# language NamedFieldPuns #
# language TypeApplications #
# language ViewPatterns #
module Rel8.Table.Name
( namesFromLabels
, namesFromLabelsWith
, showLabels
, showNames
)
where
import Data.Foldable ( fold )
import Data.Functor.Const ( Const( Const ), getConst )
import Data.List.NonEmpty ( NonEmpty, intersperse, nonEmpty )
import Data.Maybe ( fromMaybe )
import Prelude
import Rel8.Schema.HTable ( htabulate, htabulateA, hfield, hspecs )
import Rel8.Schema.Name ( Name( Name ) )
import Rel8.Schema.Spec ( Spec(..) )
import Rel8.Table ( Table(..) )
namesFromLabels :: Table Name a => a
namesFromLabels = namesFromLabelsWith go
where
go = fold . intersperse "/"
' ' . For example ,
myTableSchema : : ( )
myTableSchema =
will construct a ' ' where each columns names exactly corresponds
to the name of the field .
namesFromLabelsWith :: Table Name a
=> (NonEmpty String -> String) -> a
namesFromLabelsWith f = fromColumns $ htabulate $ \field ->
case hfield hspecs field of
Spec {labels} -> Name (f (renderLabels labels))
showLabels :: forall a. Table (Context a) a => a -> [NonEmpty String]
showLabels _ = getConst $
htabulateA @(Columns a) $ \field -> case hfield hspecs field of
Spec {labels} -> Const (pure (renderLabels labels))
showNames :: forall a. Table Name a => a -> NonEmpty String
showNames (toColumns -> names) = getConst $
htabulateA @(Columns a) $ \field -> case hfield names field of
Name name -> Const (pure name)
renderLabels :: [String] -> NonEmpty String
renderLabels labels = fromMaybe (pure "anon") (nonEmpty labels )
|
5e114253b1a36ac2f19ab96fb99e8f88498c4081342b9794f35b4462c760969e | esl/escalus | escalus_users.erl | %%==============================================================================
Copyright 2010 Erlang Solutions 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(escalus_users).
-behaviour(escalus_user_db).
%% `escalus_user_db` callbacks
-export([start/1,
stop/1,
create_users/2,
delete_users/2]).
%% Public API
-export([create_users/1,
delete_users/1,
get_jid/2,
get_username/2,
get_host/2,
get_server/2,
get_userspec/2,
update_userspec/4,
get_options/2,
get_options/3,
get_options/4,
get_users/1,
get_user_by_name/1,
get_user_by_name/2,
create_user/2,
verify_creation/1,
delete_user/2,
get_usp/2,
is_mod_register_enabled/1
]).
%% Public types
-export_type([user_name/0,
user_spec/0,
named_user/0,
resource_spec/0]).
%% Public types
-type user_name() :: atom().
-type user_spec() :: [{user_option(), any()}].
-type named_user() :: {user_name(), user_spec()}.
-type resource_spec() :: {user_name(), pos_integer()}.
%% Internal types
-type user() :: user_name() | user_spec().
-type host() :: inet:hostname() | inet:ip4_address() | binary().
-type xmpp_domain() :: inet:hostname() | binary().
-include("escalus.hrl").
-include_lib("exml/include/exml.hrl").
%%--------------------------------------------------------------------
%% `escalus_user_db` callbacks
%%--------------------------------------------------------------------
-spec start(escalus:config()) -> any().
start(Config) ->
case auth_type(Config) of
{module, M, Opts} ->
M:start(Opts);
_ ->
ok
end.
-spec stop(escalus:config()) -> any().
stop(Config) ->
case auth_type(Config) of
{module, M, Opts} ->
M:stop(Opts);
_ ->
ok
end.
-spec create_users(escalus:config(), [named_user()]) -> escalus:config().
create_users(Config, Users) ->
case auth_type(Config) of
xmpp ->
create_users_via_xmpp(Config, Users);
{module, M, _} ->
M:create_users(Config, Users)
end.
-spec create_users_via_xmpp(escalus:config(), [named_user()]) -> escalus:config().
create_users_via_xmpp(Config, Users) ->
CreationResults = [create_user(Config, User) || User <- Users],
lists:foreach(fun verify_creation/1, CreationResults),
lists:keystore(escalus_users, 1, Config, {escalus_users, Users}).
-spec delete_users(escalus:config(), [named_user()]) -> escalus:config().
delete_users(Config, Users) ->
case auth_type(Config) of
xmpp ->
[delete_user(Config, User) || User <- Users];
{module, M, _} ->
M:delete_users(Config, Users)
end.
%%--------------------------------------------------------------------
%% Public API
%%--------------------------------------------------------------------
-spec create_users(escalus:config()) -> escalus:config().
create_users(Config) ->
create_users(Config, get_users(all)).
-spec delete_users(escalus:config()) -> escalus:config().
delete_users(Config) ->
delete_users(Config, get_users(all)).
-spec get_jid(escalus:config(), user()) -> binary().
get_jid(Config, User) ->
Username = get_username(Config, User),
Server = get_server(Config, User),
<<Username/binary, "@", Server/binary>>.
-spec get_username(escalus:config(), user()) -> binary().
get_username(Config, User) ->
get_defined_option(Config, User, username, escalus_username).
-spec get_password(escalus:config(), user()) -> binary().
get_password(Config, User) ->
get_defined_option(Config, User, password, escalus_password).
-spec get_host(escalus:config(), user()) -> host().
get_host(Config, User) ->
get_user_option(host, User, escalus_host, Config, get_server(Config, User)).
-spec get_port(escalus:config(), user()) -> inet:port_number().
get_port(Config, User) ->
get_user_option(port, User, escalus_port, Config, 5222).
-spec get_server(escalus:config(), user()) -> xmpp_domain().
get_server(Config, User) ->
get_user_option(server, User, escalus_server, Config, <<"localhost">>).
-spec get_wspath(escalus:config(), user()) -> binary() | 'undefined'.
get_wspath(Config, User) ->
get_user_option(wspath, User, escalus_wspath, Config, undefined).
-spec get_auth_method(escalus:config(), user()) -> {module(), atom()}.
get_auth_method(Config, User) ->
AuthMethod = get_user_option(auth_method, User,
escalus_auth_method, Config,
<<"PLAIN">>),
get_auth_method(AuthMethod).
-spec get_auth_method(binary() | {module(), atom()}) -> {module(), atom()}.
get_auth_method(<<"PLAIN">>) ->
{escalus_auth, auth_plain};
get_auth_method(<<"DIGEST-MD5">>) ->
{escalus_auth, auth_digest_md5};
get_auth_method(<<"SASL-ANON">>) ->
{escalus_auth, auth_sasl_anon};
%% SCRAM Regular
get_auth_method(<<"SCRAM-SHA-1">>) ->
{escalus_auth, auth_sasl_scram_sha1};
get_auth_method(<<"SCRAM-SHA-224">>) ->
{escalus_auth, auth_sasl_scram_sha224};
get_auth_method(<<"SCRAM-SHA-256">>) ->
{escalus_auth, auth_sasl_scram_sha256};
get_auth_method(<<"SCRAM-SHA-384">>) ->
{escalus_auth, auth_sasl_scram_sha384};
get_auth_method(<<"SCRAM-SHA-512">>) ->
{escalus_auth, auth_sasl_scram_sha512};
SCRAM PLUS
get_auth_method(<<"SCRAM-SHA-1-PLUS">>) ->
{escalus_auth, auth_sasl_scram_sha1_plus};
get_auth_method(<<"SCRAM-SHA-224-PLUS">>) ->
{escalus_auth, auth_sasl_scram_sha224_plus};
get_auth_method(<<"SCRAM-SHA-256-PLUS">>) ->
{escalus_auth, auth_sasl_scram_sha256_plus};
get_auth_method(<<"SCRAM-SHA-384-PLUS">>) ->
{escalus_auth, auth_sasl_scram_sha384_plus};
get_auth_method(<<"SCRAM-SHA-512-PLUS">>) ->
{escalus_auth, auth_sasl_scram_sha512_plus};
get_auth_method(<<"X-OAUTH">>) ->
{escalus_auth, auth_sasl_oauth};
get_auth_method({Mod, Fun}) when is_atom(Mod), is_atom(Fun) ->
{Mod, Fun}.
-spec get_usp(escalus:config(), user()) -> [binary() | xmpp_domain()].
get_usp(Config, User) ->
[get_username(Config, User),
get_server(Config, User),
get_password(Config, User)].
TODO : get_options/2 and get_userspec/2 are redundant - remove one
%% TODO: this list of options should be complete and formal!
-spec get_options(escalus:config(), user()) -> escalus:config().
get_options(Config, User) ->
[{username, get_username(Config, User)},
{server, get_server(Config, User)},
{host, get_host(Config, User)},
{port, get_port(Config, User)},
{auth, get_auth_method(Config, User)},
{wspath, get_wspath(Config, User)}
| get_userspec(Config, User)].
-spec get_options(escalus:config(), user(), binary()) -> escalus:config().
get_options(Config, User, Resource) ->
[{resource, Resource} | get_options(Config, User)].
-spec get_options(escalus:config(), user(),
binary(), escalus_event:event_client()) -> escalus:config().
get_options(Config, User, Resource, EventClient) ->
[{event_client, EventClient} | get_options(Config, User, Resource)].
-spec get_userspec(escalus:config(), user_name() | user_spec())
-> user_spec().
get_userspec(Config, Username) when is_atom(Username) ->
Users = escalus_config:get_config(escalus_users, Config),
{Username, UserSpec} = lists:keyfind(Username, 1, Users),
UserSpec;
get_userspec(_Config, UserSpec) when is_list(UserSpec) ->
UserSpec.
-spec update_userspec(escalus:config(), atom(), atom(), any()) ->
escalus:config().
update_userspec(Config, UserName, Option, Value) ->
UserSpec = escalus_users:get_userspec(Config, UserName),
NewUserSpec = lists:keystore(Option, 1, UserSpec, {Option, Value}),
Users = escalus_config:get_config(escalus_users, Config),
NewUsers = lists:keystore(UserName, 1, Users, {UserName, NewUserSpec}),
lists:keystore(escalus_users, 1, Config, {escalus_users, NewUsers}).
-spec get_users(all | [user_name()] | {by_name, [user_name()]}) -> [named_user()].
get_users(all) ->
escalus_ct:get_config(escalus_users);
get_users(Names) when is_list(Names) ->
All = get_users(all),
[ get_user_by_name(Name, All) || Name <- Names ];
%% TODO: remove the `by_name` clause after a deprecation period
get_users({by_name, Names}) ->
escalus_compat:complain("passing {by_name, Names} is deprecated; "
"pass Names directly instead"),
get_users(Names).
-spec get_user_by_name(user_name(), escalus:config()) -> {user_name(), escalus:config()}.
get_user_by_name(Name, Users) ->
is_valid_user_name(Name) orelse error({invalid_user_name, Name}, [Name, Users]),
{Name, _} = proplists:lookup(Name, Users).
is_valid_user_name(Name) when is_atom(Name) -> true;
is_valid_user_name(_) -> false.
-spec get_user_by_name(user_name()) -> {user_name(), escalus:config()}.
get_user_by_name(Name) ->
get_user_by_name(Name, get_users(all)).
-spec create_user(escalus:config(), named_user()) -> any().
create_user(Config, {_Name, Options}) ->
ClientProps0 = get_options(Config, Options),
{ok, Conn, _} = escalus_connection:start(ClientProps0,
[start_stream,
stream_features,
maybe_use_ssl]),
escalus_connection:send(Conn, escalus_stanza:get_registration_fields()),
{ok, result, RegisterInstrs} = wait_for_result(Conn),
Answers = get_answers(Conn#client.props, RegisterInstrs),
escalus_connection:send(Conn, escalus_stanza:register_account(Answers)),
Result = wait_for_result(Conn),
escalus_connection:stop(Conn),
Result.
-spec verify_creation({ok, _, _} | {error, _, _}) -> ok.
verify_creation({ok, result, _}) ->
ok;
verify_creation({ok, conflict, Raw}) ->
RawStr = exml:to_iolist(Raw),
error_logger:info_msg("user already existed: ~s~n", [RawStr]);
verify_creation({error, Error, Raw}) ->
RawStr = exml:to_iolist(Raw),
error_logger:error_msg("error when trying to register user: ~s~n", [RawStr]),
error(Error).
-spec delete_user(escalus:config(), named_user()) ->
{ok, _, _} | {error, _, _}.
delete_user(Config, {_Name, UserSpec}) ->
Options = get_options(Config, UserSpec),
{ok, Conn, _} = escalus_connection:start(Options),
escalus_connection:send(Conn, escalus_stanza:remove_account()),
Result = wait_for_result(Conn),
try
{ok, result, _} = Result,
StreamError = escalus_connection:get_stanza(Conn, stream_error),
escalus:assert(is_stream_error, [<<"conflict">>, <<"User removed">>], StreamError),
StreamEnd = escalus_connection:get_stanza(Conn, stream_end),
escalus:assert(is_stream_end, StreamEnd),
escalus_connection:wait_for_close(Conn)
catch C:R:S ->
error_logger:error_msg("error when trying to delete user: ~p:~p, stacktrace: ~p~n", [C, R, S]),
escalus_connection:stop(Conn)
end,
Result.
-spec auth_type([proplists:property()]) -> {module, atom(), list()} | xmpp.
auth_type(Config) ->
auth_type(escalus_config:get_config(escalus_user_db, Config, undefined), Config).
auth_type({module, M, Args}, _Config) -> {module, M, Args};
auth_type({module, M}, _Config) -> {module, M, []};
auth_type(_, Config) ->
case try_check_mod_register(Config) of
false -> {module, escalus_ejabberd, []};
true -> xmpp
end.
try_check_mod_register(Config) ->
try is_mod_register_enabled(Config)
catch _:_ -> false
end.
-spec is_mod_register_enabled(escalus:config()) -> boolean().
is_mod_register_enabled(Config) ->
Server = escalus_config:get_config(escalus_server, Config, <<"localhost">>),
Host = escalus_config:get_config(escalus_host, Config, Server),
Port = escalus_config:get_config(escalus_port, Config, 5222),
ClientProps = [{server, Server}, {host, Host}, {port, Port}],
{ok, Conn, _} = escalus_connection:start(ClientProps,
[start_stream,
stream_features,
maybe_use_ssl]),
escalus_connection:send(Conn, escalus_stanza:get_registration_fields()),
Result = case wait_for_result(Conn) of
{error, _, _} ->
false;
_ ->
true
end,
escalus_connection:stop(Conn),
Result.
%%--------------------------------------------------------------------
%% Helpers
%%--------------------------------------------------------------------
-type user_option() :: 'username' %% binary()
| 'server' %% binary()
| 'password' %% binary()
| 'compression' %% <<"zlib">> | false
| 'ssl' %% 'false' | 'optional',
%% shouldn't there also be 'required'?
' tcp ' | ' ' | ' ws ' , anything else ?
BOSH path
| 'port' %% TCP port
| 'wspath' %% WebSocket path - unify with `path`?
| 'host' %% IP address? DNS name?
< < " PLAIN " > > | < < " DIGETS - MD5 " > >
| < < " SASL - ANON " > > | < < " SCRAM - SHA-1 " > >
%% | Other
| 'connection_steps' %% [escalus_session:step()]
| 'parser_opts' %% a list of exml parser opts,
%% e.g. infinite_stream
| received_stanza_handlers %% list of escalus_connection:stanza_handler()
| sent_stanza_handlers %% similar as above but for sent stanzas
.
-type ejabberd_option() :: 'ejabberd_node'
| 'ejabberd_cookie'
| 'ejabberd_domain'.
-type escalus_option() :: 'escalus_server'
| 'escalus_username'
| 'escalus_password'
| 'escalus_host'
| 'escalus_port'
| 'escalus_auth_method'
| 'escalus_wspath'
.
-type long_option() :: ejabberd_option() | escalus_option().
-type option_value() :: any().
%% get_user_option is a wrapper on escalus_config:get_config/5,
which can take either UserSpec ( a proplist ) or user name ( atom )
as the second argument
-spec get_user_option(user_option(), user(), long_option(),
escalus:config(), option_value()) -> option_value().
get_user_option(Short, Name, Long, Config, Default) when is_atom(Name) ->
{Name, Spec} = case lists:keysearch(escalus_users, 1, Config) of
false ->
get_user_by_name(Name);
{value, {_, Users}} ->
get_user_by_name(Name, Users)
end,
get_user_option(Short, Spec, Long, Config, Default);
get_user_option(Short, Spec, Long, Config, Default) ->
escalus_config:get_config(Short, Spec, Long, Config, Default).
-spec get_defined_option(escalus:config(), user(),
user_option(), long_option()) -> option_value().
get_defined_option(Config, Name, Short, Long) ->
case get_user_option(Short, Name, Long, Config, undefined) of
undefined ->
escalus_ct:fail({undefined_option, Short, Name});
Value ->
Value
end.
-spec wait_for_result(escalus:client()) -> {ok, result, exml:element()}
| {ok, conflict, exml:element()}
| {error, Error, exml:cdata()}
when Error :: 'failed_to_register' | 'bad_response' | 'timeout'.
wait_for_result(Client) ->
case escalus_connection:get_stanza_safe(Client, 5000) of
{error, timeout} ->
{error, timeout, #xmlcdata{content = <<"timeout">>}};
{Stanza, _} ->
case response_type(Stanza) of
result ->
{ok, result, Stanza};
conflict ->
{ok, conflict, Stanza};
error ->
{error, failed_to_register, Stanza};
_ ->
{error, bad_response, Stanza}
end
end.
response_type(#xmlel{name = <<"iq">>} = IQ) ->
case exml_query:attr(IQ, <<"type">>) of
<<"result">> ->
result;
<<"error">> ->
case exml_query:path(IQ, [{element, <<"error">>},
{attr, <<"code">>}]) of
<<"409">> ->
conflict;
_ ->
error
end;
_ ->
other
end;
response_type(_) ->
other.
get_answers(UserSpec, InstrStanza) ->
BinSpec = [{list_to_binary(atom_to_list(K)), V} || {K, V} <- UserSpec],
Query = exml_query:subelement(InstrStanza, <<"query">>),
ChildrenNames = [N || #xmlel{name = N} <- Query#xmlel.children],
NoInstr = ChildrenNames -- [<<"instructions">>],
[#xmlel{name=K,
children=[#xmlcdata{content = proplists:get_value(K, BinSpec)}]}
|| K <- NoInstr].
| null | https://raw.githubusercontent.com/esl/escalus/63652d3e914e40104623539f438f91174992fecc/src/escalus_users.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.
==============================================================================
`escalus_user_db` callbacks
Public API
Public types
Public types
Internal types
--------------------------------------------------------------------
`escalus_user_db` callbacks
--------------------------------------------------------------------
--------------------------------------------------------------------
Public API
--------------------------------------------------------------------
SCRAM Regular
TODO: this list of options should be complete and formal!
TODO: remove the `by_name` clause after a deprecation period
--------------------------------------------------------------------
Helpers
--------------------------------------------------------------------
binary()
binary()
binary()
<<"zlib">> | false
'false' | 'optional',
shouldn't there also be 'required'?
TCP port
WebSocket path - unify with `path`?
IP address? DNS name?
| Other
[escalus_session:step()]
a list of exml parser opts,
e.g. infinite_stream
list of escalus_connection:stanza_handler()
similar as above but for sent stanzas
get_user_option is a wrapper on escalus_config:get_config/5, | Copyright 2010 Erlang Solutions Ltd.
Licensed under the Apache License , Version 2.0 ( the " License " ) ;
distributed under the License is distributed on an " AS IS " BASIS ,
-module(escalus_users).
-behaviour(escalus_user_db).
-export([start/1,
stop/1,
create_users/2,
delete_users/2]).
-export([create_users/1,
delete_users/1,
get_jid/2,
get_username/2,
get_host/2,
get_server/2,
get_userspec/2,
update_userspec/4,
get_options/2,
get_options/3,
get_options/4,
get_users/1,
get_user_by_name/1,
get_user_by_name/2,
create_user/2,
verify_creation/1,
delete_user/2,
get_usp/2,
is_mod_register_enabled/1
]).
-export_type([user_name/0,
user_spec/0,
named_user/0,
resource_spec/0]).
-type user_name() :: atom().
-type user_spec() :: [{user_option(), any()}].
-type named_user() :: {user_name(), user_spec()}.
-type resource_spec() :: {user_name(), pos_integer()}.
-type user() :: user_name() | user_spec().
-type host() :: inet:hostname() | inet:ip4_address() | binary().
-type xmpp_domain() :: inet:hostname() | binary().
-include("escalus.hrl").
-include_lib("exml/include/exml.hrl").
-spec start(escalus:config()) -> any().
start(Config) ->
case auth_type(Config) of
{module, M, Opts} ->
M:start(Opts);
_ ->
ok
end.
-spec stop(escalus:config()) -> any().
stop(Config) ->
case auth_type(Config) of
{module, M, Opts} ->
M:stop(Opts);
_ ->
ok
end.
-spec create_users(escalus:config(), [named_user()]) -> escalus:config().
create_users(Config, Users) ->
case auth_type(Config) of
xmpp ->
create_users_via_xmpp(Config, Users);
{module, M, _} ->
M:create_users(Config, Users)
end.
-spec create_users_via_xmpp(escalus:config(), [named_user()]) -> escalus:config().
create_users_via_xmpp(Config, Users) ->
CreationResults = [create_user(Config, User) || User <- Users],
lists:foreach(fun verify_creation/1, CreationResults),
lists:keystore(escalus_users, 1, Config, {escalus_users, Users}).
-spec delete_users(escalus:config(), [named_user()]) -> escalus:config().
delete_users(Config, Users) ->
case auth_type(Config) of
xmpp ->
[delete_user(Config, User) || User <- Users];
{module, M, _} ->
M:delete_users(Config, Users)
end.
-spec create_users(escalus:config()) -> escalus:config().
create_users(Config) ->
create_users(Config, get_users(all)).
-spec delete_users(escalus:config()) -> escalus:config().
delete_users(Config) ->
delete_users(Config, get_users(all)).
-spec get_jid(escalus:config(), user()) -> binary().
get_jid(Config, User) ->
Username = get_username(Config, User),
Server = get_server(Config, User),
<<Username/binary, "@", Server/binary>>.
-spec get_username(escalus:config(), user()) -> binary().
get_username(Config, User) ->
get_defined_option(Config, User, username, escalus_username).
-spec get_password(escalus:config(), user()) -> binary().
get_password(Config, User) ->
get_defined_option(Config, User, password, escalus_password).
-spec get_host(escalus:config(), user()) -> host().
get_host(Config, User) ->
get_user_option(host, User, escalus_host, Config, get_server(Config, User)).
-spec get_port(escalus:config(), user()) -> inet:port_number().
get_port(Config, User) ->
get_user_option(port, User, escalus_port, Config, 5222).
-spec get_server(escalus:config(), user()) -> xmpp_domain().
get_server(Config, User) ->
get_user_option(server, User, escalus_server, Config, <<"localhost">>).
-spec get_wspath(escalus:config(), user()) -> binary() | 'undefined'.
get_wspath(Config, User) ->
get_user_option(wspath, User, escalus_wspath, Config, undefined).
-spec get_auth_method(escalus:config(), user()) -> {module(), atom()}.
get_auth_method(Config, User) ->
AuthMethod = get_user_option(auth_method, User,
escalus_auth_method, Config,
<<"PLAIN">>),
get_auth_method(AuthMethod).
-spec get_auth_method(binary() | {module(), atom()}) -> {module(), atom()}.
get_auth_method(<<"PLAIN">>) ->
{escalus_auth, auth_plain};
get_auth_method(<<"DIGEST-MD5">>) ->
{escalus_auth, auth_digest_md5};
get_auth_method(<<"SASL-ANON">>) ->
{escalus_auth, auth_sasl_anon};
get_auth_method(<<"SCRAM-SHA-1">>) ->
{escalus_auth, auth_sasl_scram_sha1};
get_auth_method(<<"SCRAM-SHA-224">>) ->
{escalus_auth, auth_sasl_scram_sha224};
get_auth_method(<<"SCRAM-SHA-256">>) ->
{escalus_auth, auth_sasl_scram_sha256};
get_auth_method(<<"SCRAM-SHA-384">>) ->
{escalus_auth, auth_sasl_scram_sha384};
get_auth_method(<<"SCRAM-SHA-512">>) ->
{escalus_auth, auth_sasl_scram_sha512};
SCRAM PLUS
get_auth_method(<<"SCRAM-SHA-1-PLUS">>) ->
{escalus_auth, auth_sasl_scram_sha1_plus};
get_auth_method(<<"SCRAM-SHA-224-PLUS">>) ->
{escalus_auth, auth_sasl_scram_sha224_plus};
get_auth_method(<<"SCRAM-SHA-256-PLUS">>) ->
{escalus_auth, auth_sasl_scram_sha256_plus};
get_auth_method(<<"SCRAM-SHA-384-PLUS">>) ->
{escalus_auth, auth_sasl_scram_sha384_plus};
get_auth_method(<<"SCRAM-SHA-512-PLUS">>) ->
{escalus_auth, auth_sasl_scram_sha512_plus};
get_auth_method(<<"X-OAUTH">>) ->
{escalus_auth, auth_sasl_oauth};
get_auth_method({Mod, Fun}) when is_atom(Mod), is_atom(Fun) ->
{Mod, Fun}.
-spec get_usp(escalus:config(), user()) -> [binary() | xmpp_domain()].
get_usp(Config, User) ->
[get_username(Config, User),
get_server(Config, User),
get_password(Config, User)].
TODO : get_options/2 and get_userspec/2 are redundant - remove one
-spec get_options(escalus:config(), user()) -> escalus:config().
get_options(Config, User) ->
[{username, get_username(Config, User)},
{server, get_server(Config, User)},
{host, get_host(Config, User)},
{port, get_port(Config, User)},
{auth, get_auth_method(Config, User)},
{wspath, get_wspath(Config, User)}
| get_userspec(Config, User)].
-spec get_options(escalus:config(), user(), binary()) -> escalus:config().
get_options(Config, User, Resource) ->
[{resource, Resource} | get_options(Config, User)].
-spec get_options(escalus:config(), user(),
binary(), escalus_event:event_client()) -> escalus:config().
get_options(Config, User, Resource, EventClient) ->
[{event_client, EventClient} | get_options(Config, User, Resource)].
-spec get_userspec(escalus:config(), user_name() | user_spec())
-> user_spec().
get_userspec(Config, Username) when is_atom(Username) ->
Users = escalus_config:get_config(escalus_users, Config),
{Username, UserSpec} = lists:keyfind(Username, 1, Users),
UserSpec;
get_userspec(_Config, UserSpec) when is_list(UserSpec) ->
UserSpec.
-spec update_userspec(escalus:config(), atom(), atom(), any()) ->
escalus:config().
update_userspec(Config, UserName, Option, Value) ->
UserSpec = escalus_users:get_userspec(Config, UserName),
NewUserSpec = lists:keystore(Option, 1, UserSpec, {Option, Value}),
Users = escalus_config:get_config(escalus_users, Config),
NewUsers = lists:keystore(UserName, 1, Users, {UserName, NewUserSpec}),
lists:keystore(escalus_users, 1, Config, {escalus_users, NewUsers}).
-spec get_users(all | [user_name()] | {by_name, [user_name()]}) -> [named_user()].
get_users(all) ->
escalus_ct:get_config(escalus_users);
get_users(Names) when is_list(Names) ->
All = get_users(all),
[ get_user_by_name(Name, All) || Name <- Names ];
get_users({by_name, Names}) ->
escalus_compat:complain("passing {by_name, Names} is deprecated; "
"pass Names directly instead"),
get_users(Names).
-spec get_user_by_name(user_name(), escalus:config()) -> {user_name(), escalus:config()}.
get_user_by_name(Name, Users) ->
is_valid_user_name(Name) orelse error({invalid_user_name, Name}, [Name, Users]),
{Name, _} = proplists:lookup(Name, Users).
is_valid_user_name(Name) when is_atom(Name) -> true;
is_valid_user_name(_) -> false.
-spec get_user_by_name(user_name()) -> {user_name(), escalus:config()}.
get_user_by_name(Name) ->
get_user_by_name(Name, get_users(all)).
-spec create_user(escalus:config(), named_user()) -> any().
create_user(Config, {_Name, Options}) ->
ClientProps0 = get_options(Config, Options),
{ok, Conn, _} = escalus_connection:start(ClientProps0,
[start_stream,
stream_features,
maybe_use_ssl]),
escalus_connection:send(Conn, escalus_stanza:get_registration_fields()),
{ok, result, RegisterInstrs} = wait_for_result(Conn),
Answers = get_answers(Conn#client.props, RegisterInstrs),
escalus_connection:send(Conn, escalus_stanza:register_account(Answers)),
Result = wait_for_result(Conn),
escalus_connection:stop(Conn),
Result.
-spec verify_creation({ok, _, _} | {error, _, _}) -> ok.
verify_creation({ok, result, _}) ->
ok;
verify_creation({ok, conflict, Raw}) ->
RawStr = exml:to_iolist(Raw),
error_logger:info_msg("user already existed: ~s~n", [RawStr]);
verify_creation({error, Error, Raw}) ->
RawStr = exml:to_iolist(Raw),
error_logger:error_msg("error when trying to register user: ~s~n", [RawStr]),
error(Error).
-spec delete_user(escalus:config(), named_user()) ->
{ok, _, _} | {error, _, _}.
delete_user(Config, {_Name, UserSpec}) ->
Options = get_options(Config, UserSpec),
{ok, Conn, _} = escalus_connection:start(Options),
escalus_connection:send(Conn, escalus_stanza:remove_account()),
Result = wait_for_result(Conn),
try
{ok, result, _} = Result,
StreamError = escalus_connection:get_stanza(Conn, stream_error),
escalus:assert(is_stream_error, [<<"conflict">>, <<"User removed">>], StreamError),
StreamEnd = escalus_connection:get_stanza(Conn, stream_end),
escalus:assert(is_stream_end, StreamEnd),
escalus_connection:wait_for_close(Conn)
catch C:R:S ->
error_logger:error_msg("error when trying to delete user: ~p:~p, stacktrace: ~p~n", [C, R, S]),
escalus_connection:stop(Conn)
end,
Result.
-spec auth_type([proplists:property()]) -> {module, atom(), list()} | xmpp.
auth_type(Config) ->
auth_type(escalus_config:get_config(escalus_user_db, Config, undefined), Config).
auth_type({module, M, Args}, _Config) -> {module, M, Args};
auth_type({module, M}, _Config) -> {module, M, []};
auth_type(_, Config) ->
case try_check_mod_register(Config) of
false -> {module, escalus_ejabberd, []};
true -> xmpp
end.
try_check_mod_register(Config) ->
try is_mod_register_enabled(Config)
catch _:_ -> false
end.
-spec is_mod_register_enabled(escalus:config()) -> boolean().
is_mod_register_enabled(Config) ->
Server = escalus_config:get_config(escalus_server, Config, <<"localhost">>),
Host = escalus_config:get_config(escalus_host, Config, Server),
Port = escalus_config:get_config(escalus_port, Config, 5222),
ClientProps = [{server, Server}, {host, Host}, {port, Port}],
{ok, Conn, _} = escalus_connection:start(ClientProps,
[start_stream,
stream_features,
maybe_use_ssl]),
escalus_connection:send(Conn, escalus_stanza:get_registration_fields()),
Result = case wait_for_result(Conn) of
{error, _, _} ->
false;
_ ->
true
end,
escalus_connection:stop(Conn),
Result.
' tcp ' | ' ' | ' ws ' , anything else ?
BOSH path
< < " PLAIN " > > | < < " DIGETS - MD5 " > >
| < < " SASL - ANON " > > | < < " SCRAM - SHA-1 " > >
.
-type ejabberd_option() :: 'ejabberd_node'
| 'ejabberd_cookie'
| 'ejabberd_domain'.
-type escalus_option() :: 'escalus_server'
| 'escalus_username'
| 'escalus_password'
| 'escalus_host'
| 'escalus_port'
| 'escalus_auth_method'
| 'escalus_wspath'
.
-type long_option() :: ejabberd_option() | escalus_option().
-type option_value() :: any().
which can take either UserSpec ( a proplist ) or user name ( atom )
as the second argument
-spec get_user_option(user_option(), user(), long_option(),
escalus:config(), option_value()) -> option_value().
get_user_option(Short, Name, Long, Config, Default) when is_atom(Name) ->
{Name, Spec} = case lists:keysearch(escalus_users, 1, Config) of
false ->
get_user_by_name(Name);
{value, {_, Users}} ->
get_user_by_name(Name, Users)
end,
get_user_option(Short, Spec, Long, Config, Default);
get_user_option(Short, Spec, Long, Config, Default) ->
escalus_config:get_config(Short, Spec, Long, Config, Default).
-spec get_defined_option(escalus:config(), user(),
user_option(), long_option()) -> option_value().
get_defined_option(Config, Name, Short, Long) ->
case get_user_option(Short, Name, Long, Config, undefined) of
undefined ->
escalus_ct:fail({undefined_option, Short, Name});
Value ->
Value
end.
-spec wait_for_result(escalus:client()) -> {ok, result, exml:element()}
| {ok, conflict, exml:element()}
| {error, Error, exml:cdata()}
when Error :: 'failed_to_register' | 'bad_response' | 'timeout'.
wait_for_result(Client) ->
case escalus_connection:get_stanza_safe(Client, 5000) of
{error, timeout} ->
{error, timeout, #xmlcdata{content = <<"timeout">>}};
{Stanza, _} ->
case response_type(Stanza) of
result ->
{ok, result, Stanza};
conflict ->
{ok, conflict, Stanza};
error ->
{error, failed_to_register, Stanza};
_ ->
{error, bad_response, Stanza}
end
end.
response_type(#xmlel{name = <<"iq">>} = IQ) ->
case exml_query:attr(IQ, <<"type">>) of
<<"result">> ->
result;
<<"error">> ->
case exml_query:path(IQ, [{element, <<"error">>},
{attr, <<"code">>}]) of
<<"409">> ->
conflict;
_ ->
error
end;
_ ->
other
end;
response_type(_) ->
other.
get_answers(UserSpec, InstrStanza) ->
BinSpec = [{list_to_binary(atom_to_list(K)), V} || {K, V} <- UserSpec],
Query = exml_query:subelement(InstrStanza, <<"query">>),
ChildrenNames = [N || #xmlel{name = N} <- Query#xmlel.children],
NoInstr = ChildrenNames -- [<<"instructions">>],
[#xmlel{name=K,
children=[#xmlcdata{content = proplists:get_value(K, BinSpec)}]}
|| K <- NoInstr].
|
d016d48b878024a1ff8076c344dbfe198f679aded4bd7b16d4f40254c5a070fd | graninas/Functional-Design-and-Architecture | Main.hs | module Main where
import qualified Listing1
import qualified Listing2
main :: IO ()
main = pure ()
| null | https://raw.githubusercontent.com/graninas/Functional-Design-and-Architecture/1736abc16d3e4917fc466010dcc182746af2fd0e/Second-Edition-Manning-Publications/BookSamples/CH03/Section3p1/Main.hs | haskell | module Main where
import qualified Listing1
import qualified Listing2
main :: IO ()
main = pure ()
| |
e666440caa4b48a32985c9d53e6ea2b87d5cef8a6a5b645f62add08a0ee22f6a | input-output-hk/hydra | Util.hs | # LANGUAGE TypeApplications #
# OPTIONS_GHC -Wno - deprecations #
module Test.Util where
import Hydra.Prelude
import Test.Hydra.Prelude hiding (shouldBe)
import Control.Monad.Class.MonadSay (say)
import Control.Monad.IOSim (
Failure (FailureException),
IOSim,
SimTrace,
runSimTrace,
selectTraceEventsDynamic',
traceM,
traceResult,
)
import Control.Tracer (Tracer (Tracer))
import Data.Aeson (encode)
import qualified Data.Aeson as Aeson
import Data.List (isInfixOf)
import Hydra.Ledger.Simple (SimpleTx)
import Hydra.Node (HydraNodeLog)
import Test.HUnit.Lang (FailureReason (ExpectedButGot), HUnitFailure (HUnitFailure))
import Test.QuickCheck (forAll, withMaxSuccess)
| Run given ' action ' in ' ' and rethrow any exceptions .
shouldRunInSim ::
(forall s. IOSim s a) ->
IO a
shouldRunInSim action =
case traceResult False tr of
Right x -> pure x
Left (FailureException (SomeException ex)) -> do
dumpTrace
throwIO ex
Left ex -> do
dumpTrace
throwIO ex
where
tr = runSimTrace action
dumpTrace = say (toString $ printTrace (Proxy :: Proxy (HydraNodeLog SimpleTx)) tr)
| Utility function to dump logs given a ` SimTrace ` .
printTrace :: forall log a. (Typeable log, ToJSON log) => Proxy log -> SimTrace a -> Text
printTrace _ tr =
unlines . map (decodeUtf8 . Aeson.encode) $
selectTraceEventsDynamic' @_ @log tr
| Lifted variant of Hspec 's ' shouldBe ' .
shouldBe :: (HasCallStack, MonadThrow m, Eq a, Show a) => a -> a -> m ()
shouldBe actual expected =
unless (actual == expected) $
throwIO $ HUnitFailure location reason
where
reason = ExpectedButGot Nothing (show expected) (show actual)
| Lifted variant of Hspec 's ' shouldReturn ' .
shouldReturn :: (HasCallStack, MonadThrow m, Eq a, Show a) => m a -> a -> m ()
shouldReturn ma expected = ma >>= (`shouldBe` expected)
| Lifted variant of Hspec 's ' shouldSatisfy ' .
shouldSatisfy :: (HasCallStack, MonadThrow m, Show a) => a -> (a -> Bool) -> m ()
shouldSatisfy v p
| p v = pure ()
| otherwise = failure $ "predicate failed on: " <> show v
| Lifted variant of Hspec 's ' shouldNotBe ' .
shouldNotBe :: (HasCallStack, MonadThrow m, Eq a, Show a) => a -> a -> m ()
shouldNotBe actual expected
| actual /= expected = pure ()
| otherwise = failure $ "not expected: " <> show actual
| Lifted variant of Hspec 's ' ' .
shouldContain :: (HasCallStack, MonadThrow m, Eq a, Show a) => [a] -> [a] -> m ()
shouldContain actual expected
| expected `isInfixOf` actual = pure ()
| otherwise = failure $ show actual <> " does not contain " <> show expected
| A ' Tracer ' that works in ' ' monad .
-- This tracer uses the 'Output' event which uses converts value traced to 'Dynamic'
which requires ' Typeable ' constraint . To retrieve the trace use ' selectTraceEventsDynamic '
-- applied to the correct type.
traceInIOSim :: Typeable a => Tracer (IOSim s) a
traceInIOSim = Tracer traceM
| Useful when one needs to /also/ trace logs to ` stderr ` .
Thanks to the monoidal nature of ` Tracer ` it 's straightforward to add this to
-- any existing tracer:
--
-- @@
-- someCode tracer = do
-- foo <- makeFoo
( tr < > traceDebug ) SomeTraceFoo
-- ...
-- @@
traceDebug :: (Applicative m, ToJSON a) => Tracer m a
traceDebug = Tracer (\a -> trace (decodeUtf8 $ encode a) $ pure ())
| This creates an hspec test case about a property which ensures the given generator
-- does not produce equals values within a reasonable number of generated values.
propCollisionResistant :: (Show a, Eq a) => String -> Gen a -> Spec
propCollisionResistant name gen =
prop (name <> " is reasonably collision resistant") $
withMaxSuccess 100_000 $
forAll gen $ \a ->
forAll gen $ \b ->
a /= b
| null | https://raw.githubusercontent.com/input-output-hk/hydra/c46541576ae6937f8f710a2353aa43293d03845f/hydra-node/test/Test/Util.hs | haskell | This tracer uses the 'Output' event which uses converts value traced to 'Dynamic'
applied to the correct type.
any existing tracer:
@@
someCode tracer = do
foo <- makeFoo
...
@@
does not produce equals values within a reasonable number of generated values. | # LANGUAGE TypeApplications #
# OPTIONS_GHC -Wno - deprecations #
module Test.Util where
import Hydra.Prelude
import Test.Hydra.Prelude hiding (shouldBe)
import Control.Monad.Class.MonadSay (say)
import Control.Monad.IOSim (
Failure (FailureException),
IOSim,
SimTrace,
runSimTrace,
selectTraceEventsDynamic',
traceM,
traceResult,
)
import Control.Tracer (Tracer (Tracer))
import Data.Aeson (encode)
import qualified Data.Aeson as Aeson
import Data.List (isInfixOf)
import Hydra.Ledger.Simple (SimpleTx)
import Hydra.Node (HydraNodeLog)
import Test.HUnit.Lang (FailureReason (ExpectedButGot), HUnitFailure (HUnitFailure))
import Test.QuickCheck (forAll, withMaxSuccess)
| Run given ' action ' in ' ' and rethrow any exceptions .
shouldRunInSim ::
(forall s. IOSim s a) ->
IO a
shouldRunInSim action =
case traceResult False tr of
Right x -> pure x
Left (FailureException (SomeException ex)) -> do
dumpTrace
throwIO ex
Left ex -> do
dumpTrace
throwIO ex
where
tr = runSimTrace action
dumpTrace = say (toString $ printTrace (Proxy :: Proxy (HydraNodeLog SimpleTx)) tr)
| Utility function to dump logs given a ` SimTrace ` .
printTrace :: forall log a. (Typeable log, ToJSON log) => Proxy log -> SimTrace a -> Text
printTrace _ tr =
unlines . map (decodeUtf8 . Aeson.encode) $
selectTraceEventsDynamic' @_ @log tr
| Lifted variant of Hspec 's ' shouldBe ' .
shouldBe :: (HasCallStack, MonadThrow m, Eq a, Show a) => a -> a -> m ()
shouldBe actual expected =
unless (actual == expected) $
throwIO $ HUnitFailure location reason
where
reason = ExpectedButGot Nothing (show expected) (show actual)
| Lifted variant of Hspec 's ' shouldReturn ' .
shouldReturn :: (HasCallStack, MonadThrow m, Eq a, Show a) => m a -> a -> m ()
shouldReturn ma expected = ma >>= (`shouldBe` expected)
| Lifted variant of Hspec 's ' shouldSatisfy ' .
shouldSatisfy :: (HasCallStack, MonadThrow m, Show a) => a -> (a -> Bool) -> m ()
shouldSatisfy v p
| p v = pure ()
| otherwise = failure $ "predicate failed on: " <> show v
| Lifted variant of Hspec 's ' shouldNotBe ' .
shouldNotBe :: (HasCallStack, MonadThrow m, Eq a, Show a) => a -> a -> m ()
shouldNotBe actual expected
| actual /= expected = pure ()
| otherwise = failure $ "not expected: " <> show actual
| Lifted variant of Hspec 's ' ' .
shouldContain :: (HasCallStack, MonadThrow m, Eq a, Show a) => [a] -> [a] -> m ()
shouldContain actual expected
| expected `isInfixOf` actual = pure ()
| otherwise = failure $ show actual <> " does not contain " <> show expected
| A ' Tracer ' that works in ' ' monad .
which requires ' Typeable ' constraint . To retrieve the trace use ' selectTraceEventsDynamic '
traceInIOSim :: Typeable a => Tracer (IOSim s) a
traceInIOSim = Tracer traceM
| Useful when one needs to /also/ trace logs to ` stderr ` .
Thanks to the monoidal nature of ` Tracer ` it 's straightforward to add this to
( tr < > traceDebug ) SomeTraceFoo
traceDebug :: (Applicative m, ToJSON a) => Tracer m a
traceDebug = Tracer (\a -> trace (decodeUtf8 $ encode a) $ pure ())
| This creates an hspec test case about a property which ensures the given generator
propCollisionResistant :: (Show a, Eq a) => String -> Gen a -> Spec
propCollisionResistant name gen =
prop (name <> " is reasonably collision resistant") $
withMaxSuccess 100_000 $
forAll gen $ \a ->
forAll gen $ \b ->
a /= b
|
476b9566cb7b4e31a7263efe0d97612c243d2f9224356afcaa73ded8f1c8995c | cyverse-archive/DiscoveryEnvironmentBackend | validators.clj | (ns clojure-commons.validators
(:use [slingshot.slingshot :only [try+ throw+]])
(:require [clojure-commons.exception :as cx])
(:import [clojure.lang IPersistentMap]))
(defn ^Boolean nonnegative-int?
"Indicates whether or not the unparsed field value contains a nonnegative integer.
Parameters:
str-val - the unparsed value
Returns:
It returns true if str-val contains a 32-bit integer value that is zero or positive, otherwise
it returns false."
[^String str-val]
(boolean
(try+
(<= 0 (Integer/parseInt str-val))
(catch Object _))))
(defn- check-missing
[handle-missing a-map required]
(let [not-valid? #(not (contains? a-map %))]
(when (some not-valid? required)
(handle-missing (filter not-valid? required)))))
(defn- check-valid
[handle-invalid kvs validators]
(let [invalid? (fn [[k v]] (when-let [valid? (get validators k)]
(not (valid? v))))
invalids (->> kvs
seq
(filter invalid?)
flatten
(apply hash-map))]
(when-not (empty? invalids)
(handle-invalid invalids))))
(defn- throw-missing-fields
[fields]
(throw+ {:type ::cx/missing-request-field, :fields fields}))
(defn- throw-bad-fields
[fields]
(throw+ {:type ::cx/bad-request-field, :fields (keys fields)}))
(defn validate-map
[a-map func-map]
(check-missing throw-missing-fields a-map (keys func-map))
(check-valid throw-bad-fields a-map func-map))
(defn validate-field
([field-name field-value]
(validate-field field-name field-value (comp not nil?)))
([field-name field-value valid?]
(when-not (valid? field-value)
(throw+ {:type ::cx/bad-request-field
:field field-name
:value field-value}))))
(defn- throw-missing-params
[params]
(throw+ {:type ::cx/missing-query-params
:parameters params}))
(defn- throw-bad-params
[params]
(throw+ {:type ::cx/bad-query-params
:parameters params}))
(defn validate-query-params
"Given a set of URL query parameters and a set of corresponding validation functions, this
function first verifies that the query parameters are present, and then validates the values.
The validation map is a mapping of the parameter name to its validator. Each validator is a
predicate that accepts the unparsed parameter value and returns whether or not the value is
valid. The validation map serves a second purpose. It indicates whether or not the parameter is
required. The presence of the parameter in the map indicates that it is required.
Parameters:
params - the parameter map. It is a map of parameter names to their unparsed values. It
should have the following form.
{:<param-1> <value-1>
:<param-2> <value-2>
...
:<param-n> <value-n>}
validators - the validation map. It should have the following form.
{:<param-1> <validator-1>
:<param-2> <validator-2>
...
:<param-n> <validator-n>}
Each validator should be a function of the form (^Boolean [^String]).
Throws:
If any of the parameters are missing, a map with the following fields is thrown.
:error_code - ERR_MISSING_QUERY_PARAMETER
:parameters - [a list of keys associated with the missing parameters]
If all of the parameters are present, but some of them have bad values, a map with the
following fields is thrown.
:error_code - ERR_BAD_QUERY_PARAMETER
:parameters - The params map filtered for those parameters with bad values."
[^IPersistentMap params ^IPersistentMap validators]
(check-missing throw-missing-params params (keys validators))
(check-valid throw-bad-params params validators))
(defn user-owns-app?
"Checks if the given user owns the given app, determined by comparing the user's email with the
app's integrator_email."
[{:keys [email]} {:keys [integrator_email]}]
(= email integrator_email))
| null | https://raw.githubusercontent.com/cyverse-archive/DiscoveryEnvironmentBackend/7f6177078c1a1cb6d11e62f12cfe2e22d669635b/libs/iplant-clojure-commons/src/clojure_commons/validators.clj | clojure | (ns clojure-commons.validators
(:use [slingshot.slingshot :only [try+ throw+]])
(:require [clojure-commons.exception :as cx])
(:import [clojure.lang IPersistentMap]))
(defn ^Boolean nonnegative-int?
"Indicates whether or not the unparsed field value contains a nonnegative integer.
Parameters:
str-val - the unparsed value
Returns:
It returns true if str-val contains a 32-bit integer value that is zero or positive, otherwise
it returns false."
[^String str-val]
(boolean
(try+
(<= 0 (Integer/parseInt str-val))
(catch Object _))))
(defn- check-missing
[handle-missing a-map required]
(let [not-valid? #(not (contains? a-map %))]
(when (some not-valid? required)
(handle-missing (filter not-valid? required)))))
(defn- check-valid
[handle-invalid kvs validators]
(let [invalid? (fn [[k v]] (when-let [valid? (get validators k)]
(not (valid? v))))
invalids (->> kvs
seq
(filter invalid?)
flatten
(apply hash-map))]
(when-not (empty? invalids)
(handle-invalid invalids))))
(defn- throw-missing-fields
[fields]
(throw+ {:type ::cx/missing-request-field, :fields fields}))
(defn- throw-bad-fields
[fields]
(throw+ {:type ::cx/bad-request-field, :fields (keys fields)}))
(defn validate-map
[a-map func-map]
(check-missing throw-missing-fields a-map (keys func-map))
(check-valid throw-bad-fields a-map func-map))
(defn validate-field
([field-name field-value]
(validate-field field-name field-value (comp not nil?)))
([field-name field-value valid?]
(when-not (valid? field-value)
(throw+ {:type ::cx/bad-request-field
:field field-name
:value field-value}))))
(defn- throw-missing-params
[params]
(throw+ {:type ::cx/missing-query-params
:parameters params}))
(defn- throw-bad-params
[params]
(throw+ {:type ::cx/bad-query-params
:parameters params}))
(defn validate-query-params
"Given a set of URL query parameters and a set of corresponding validation functions, this
function first verifies that the query parameters are present, and then validates the values.
The validation map is a mapping of the parameter name to its validator. Each validator is a
predicate that accepts the unparsed parameter value and returns whether or not the value is
valid. The validation map serves a second purpose. It indicates whether or not the parameter is
required. The presence of the parameter in the map indicates that it is required.
Parameters:
params - the parameter map. It is a map of parameter names to their unparsed values. It
should have the following form.
{:<param-1> <value-1>
:<param-2> <value-2>
...
:<param-n> <value-n>}
validators - the validation map. It should have the following form.
{:<param-1> <validator-1>
:<param-2> <validator-2>
...
:<param-n> <validator-n>}
Each validator should be a function of the form (^Boolean [^String]).
Throws:
If any of the parameters are missing, a map with the following fields is thrown.
:error_code - ERR_MISSING_QUERY_PARAMETER
:parameters - [a list of keys associated with the missing parameters]
If all of the parameters are present, but some of them have bad values, a map with the
following fields is thrown.
:error_code - ERR_BAD_QUERY_PARAMETER
:parameters - The params map filtered for those parameters with bad values."
[^IPersistentMap params ^IPersistentMap validators]
(check-missing throw-missing-params params (keys validators))
(check-valid throw-bad-params params validators))
(defn user-owns-app?
"Checks if the given user owns the given app, determined by comparing the user's email with the
app's integrator_email."
[{:keys [email]} {:keys [integrator_email]}]
(= email integrator_email))
| |
0c2b480d3697c1d310c91b02b879402d9bc8d0715e92d0ee6ffbdd53a0c16055 | palletops/log-config | wrap.clj | (ns com.palletops.log-config.timbre.wrap
"Add logging and profiling to your functions dynamically."
(:require
[taoensso.timbre :refer [log logf]]))
(defn wrap
"Wrap a function with a set of function wrappers."
[f f-info [wrapper & wrappers]]
(if (seq wrappers)
(wrap (wrapper f f-info) f-info wrappers)
(wrapper f f-info)))
(defn wrap-var
"Add a function wrapper to a Var, v, if it is a plain function.
The wrapping can be undone by calling unwrap-var."
[v wrappers]
{:pre [(var? v)]}
(let [f @v
f-info (meta v)]
(when (and (fn? f) (not (:macro f-info)) (not (::original f-info)))
(doto v
(alter-meta! assoc ::original f)
(alter-var-root wrap f-info wrappers)))))
(defn unwrap-var
"Remove function wrappers from a Var, v."
[v]
{:pre [(var? v)]}
(when-let [f (::original (meta v))]
(doto v
(alter-var-root (constantly f))
(alter-meta! dissoc ::original))))
(defn wrap-ns-vars
"Replaces each function from the given namespace with a wrapped version.
Can be undone with wrap-ns-vars. ns should be a namespace
object or a symbol. "
[ns wrappers]
(let [ns-fn-vars (->> ns ns-interns vals (filter (comp fn? var-get)))]
(doseq [v ns-fn-vars]
(wrap-var v wrappers))))
(defn unwrap-ns-vars
"Remove function wrappers from the functions in a given namespace."
[ns]
(let [ns-fn-vars (->> ns ns-interns vals (filter (comp fn? var-get)))]
(doseq [v ns-fn-vars]
(unwrap-var v))))
(defn fn-entry-logger
"Return a wrapper function to wrap functions with entry logging at
the specified log level."
[level]
(fn [f {:keys [name]}]
(fn entry-logger [& args]
(log level name args)
(apply f args))))
(defn fn-exit-logger
"Return a wrapper function to wrap functions with exit logging at
the specified log level."
[level]
(fn [f {:keys [name]}]
(fn entry-logger [& args]
(let [r (apply f args)]
(log level name "->" r)
r))))
(defn log-ns-fns
"Log entry and exit of all functions in a namespace."
[ns level]
(wrap-ns-vars ns [(fn-entry-logger level)(fn-exit-logger level)]))
| null | https://raw.githubusercontent.com/palletops/log-config/ff924ac9ea900999324ce44645b2969781cf4b12/src/com/palletops/log_config/timbre/wrap.clj | clojure | (ns com.palletops.log-config.timbre.wrap
"Add logging and profiling to your functions dynamically."
(:require
[taoensso.timbre :refer [log logf]]))
(defn wrap
"Wrap a function with a set of function wrappers."
[f f-info [wrapper & wrappers]]
(if (seq wrappers)
(wrap (wrapper f f-info) f-info wrappers)
(wrapper f f-info)))
(defn wrap-var
"Add a function wrapper to a Var, v, if it is a plain function.
The wrapping can be undone by calling unwrap-var."
[v wrappers]
{:pre [(var? v)]}
(let [f @v
f-info (meta v)]
(when (and (fn? f) (not (:macro f-info)) (not (::original f-info)))
(doto v
(alter-meta! assoc ::original f)
(alter-var-root wrap f-info wrappers)))))
(defn unwrap-var
"Remove function wrappers from a Var, v."
[v]
{:pre [(var? v)]}
(when-let [f (::original (meta v))]
(doto v
(alter-var-root (constantly f))
(alter-meta! dissoc ::original))))
(defn wrap-ns-vars
"Replaces each function from the given namespace with a wrapped version.
Can be undone with wrap-ns-vars. ns should be a namespace
object or a symbol. "
[ns wrappers]
(let [ns-fn-vars (->> ns ns-interns vals (filter (comp fn? var-get)))]
(doseq [v ns-fn-vars]
(wrap-var v wrappers))))
(defn unwrap-ns-vars
"Remove function wrappers from the functions in a given namespace."
[ns]
(let [ns-fn-vars (->> ns ns-interns vals (filter (comp fn? var-get)))]
(doseq [v ns-fn-vars]
(unwrap-var v))))
(defn fn-entry-logger
"Return a wrapper function to wrap functions with entry logging at
the specified log level."
[level]
(fn [f {:keys [name]}]
(fn entry-logger [& args]
(log level name args)
(apply f args))))
(defn fn-exit-logger
"Return a wrapper function to wrap functions with exit logging at
the specified log level."
[level]
(fn [f {:keys [name]}]
(fn entry-logger [& args]
(let [r (apply f args)]
(log level name "->" r)
r))))
(defn log-ns-fns
"Log entry and exit of all functions in a namespace."
[ns level]
(wrap-ns-vars ns [(fn-entry-logger level)(fn-exit-logger level)]))
| |
6eb362dfca557006caeec4491221f80f530b09dd929eec29970c082742500c27 | janestreet/memtrace_viewer_with_deps | fqueue_tests.ml | open Core_kernel
let%test_unit "Fqueue round trip via list" =
Quickcheck.test
(List.quickcheck_generator Int.quickcheck_generator)
~sexp_of:[%sexp_of: int list]
~f:(fun a ->
let b = Fqueue.of_list a in
let c = Fqueue.to_list b in
let d = Fqueue.of_list c in
[%test_result: int list] ~expect:a c;
[%test_result: int Fqueue.t] ~expect:b d)
~examples:[ []; [ 1 ]; [ 1; 2 ]; [ 1; 2; 3 ] ]
;;
| null | https://raw.githubusercontent.com/janestreet/memtrace_viewer_with_deps/5a9e1f927f5f8333e2d71c8d3ca03a45587422c4/vendor/core_kernel/test/src/fqueue_tests.ml | ocaml | open Core_kernel
let%test_unit "Fqueue round trip via list" =
Quickcheck.test
(List.quickcheck_generator Int.quickcheck_generator)
~sexp_of:[%sexp_of: int list]
~f:(fun a ->
let b = Fqueue.of_list a in
let c = Fqueue.to_list b in
let d = Fqueue.of_list c in
[%test_result: int list] ~expect:a c;
[%test_result: int Fqueue.t] ~expect:b d)
~examples:[ []; [ 1 ]; [ 1; 2 ]; [ 1; 2; 3 ] ]
;;
| |
a672f83f116b8f50d64e6121a3da00e052b10042fca076dda0591b420fd8847d | jgpc42/insn | annotation.clj | (ns ^:no-doc insn.annotation
"Annotation visitor fns."
(:require [insn.util :as util])
(:import [org.objectweb.asm AnnotationVisitor ClassVisitor FieldVisitor MethodVisitor]
[java.lang.annotation Retention RetentionPolicy]))
(declare visit*)
(defn- visit1
"Mostly taken from `clojure.core/add-annotation`."
[^AnnotationVisitor v ename x]
(cond
(vector? x)
(let [av (.visitArray v ename)]
(doseq [xval x]
(visit1 av "value" xval))
(.visitEnd av))
(seq? x)
(let [[nname nval] x
ndesc (util/type-desc nname)
av (.visitAnnotation v ename ndesc)]
(visit* av nval))
:else
(let [x (if (symbol? x) (eval x) x)]
(cond
(instance? Enum x)
(let [edesc (util/type-desc (.getDeclaringClass ^Enum x))]
(.visitEnum v ename edesc (str x)))
(class? x)
(.visit v ename (util/type x))
:else
(.visit v ename x)))))
(defn- visit*
"Apply each annotation map entry to `visit1` and finalize the
annotation visitor."
[^AnnotationVisitor av aval]
(let [aval (if (map? aval) aval {"value" aval})]
(doseq [[k v] aval]
(visit1 av (name k) v))
(.visitEnd av)))
(defn ^:internal visit
"Based on `clojure.core/add-annotations`."
([xv anns] (visit xv -1 anns))
([xv ^long idx anns]
(doseq [[aname aval] (seq anns)]
(let [aclass (if (class? aname)
aname
(resolve (symbol aname)))
visible? (when-let [^Retention r (.getAnnotation ^Class aclass Retention)]
(= (.value r) RetentionPolicy/RUNTIME))
adesc (util/type-desc aclass)
av (condp instance? xv
MethodVisitor
(if (>= idx 0)
(.visitParameterAnnotation ^MethodVisitor xv idx adesc visible?)
(.visitAnnotation ^MethodVisitor xv adesc visible?))
FieldVisitor
(.visitAnnotation ^FieldVisitor xv adesc visible?)
ClassVisitor
(.visitAnnotation ^ClassVisitor xv adesc visible?))]
(visit* av aval)))))
| null | https://raw.githubusercontent.com/jgpc42/insn/3c12bb3c70e54e5091b79764c9776f72726266be/src/insn/annotation.clj | clojure | (ns ^:no-doc insn.annotation
"Annotation visitor fns."
(:require [insn.util :as util])
(:import [org.objectweb.asm AnnotationVisitor ClassVisitor FieldVisitor MethodVisitor]
[java.lang.annotation Retention RetentionPolicy]))
(declare visit*)
(defn- visit1
"Mostly taken from `clojure.core/add-annotation`."
[^AnnotationVisitor v ename x]
(cond
(vector? x)
(let [av (.visitArray v ename)]
(doseq [xval x]
(visit1 av "value" xval))
(.visitEnd av))
(seq? x)
(let [[nname nval] x
ndesc (util/type-desc nname)
av (.visitAnnotation v ename ndesc)]
(visit* av nval))
:else
(let [x (if (symbol? x) (eval x) x)]
(cond
(instance? Enum x)
(let [edesc (util/type-desc (.getDeclaringClass ^Enum x))]
(.visitEnum v ename edesc (str x)))
(class? x)
(.visit v ename (util/type x))
:else
(.visit v ename x)))))
(defn- visit*
"Apply each annotation map entry to `visit1` and finalize the
annotation visitor."
[^AnnotationVisitor av aval]
(let [aval (if (map? aval) aval {"value" aval})]
(doseq [[k v] aval]
(visit1 av (name k) v))
(.visitEnd av)))
(defn ^:internal visit
"Based on `clojure.core/add-annotations`."
([xv anns] (visit xv -1 anns))
([xv ^long idx anns]
(doseq [[aname aval] (seq anns)]
(let [aclass (if (class? aname)
aname
(resolve (symbol aname)))
visible? (when-let [^Retention r (.getAnnotation ^Class aclass Retention)]
(= (.value r) RetentionPolicy/RUNTIME))
adesc (util/type-desc aclass)
av (condp instance? xv
MethodVisitor
(if (>= idx 0)
(.visitParameterAnnotation ^MethodVisitor xv idx adesc visible?)
(.visitAnnotation ^MethodVisitor xv adesc visible?))
FieldVisitor
(.visitAnnotation ^FieldVisitor xv adesc visible?)
ClassVisitor
(.visitAnnotation ^ClassVisitor xv adesc visible?))]
(visit* av aval)))))
| |
65eba835dfbbfd60c86442432314d09febd8739e658ff6ee4aad89accf6b435c | openweb-nl/open-bank-mark | process.clj | (ns nl.openweb.test.process
(:require [clj-docker-client.core :as docker]))
(defonce docker-conn (atom nil))
(defn init
[]
(reset! docker-conn (docker/connect))
(docker/stats @docker-conn "db")
(docker/stats @docker-conn "command-handler")
(docker/stats @docker-conn "kafka-1")
(docker/stats @docker-conn "kafka-2")
(docker/stats @docker-conn "kafka-3")
(docker/stats @docker-conn "graphql-endpoint"))
(defn get-info
[]
(let [db-stats (docker/stats @docker-conn "db")
ch-stats (docker/stats @docker-conn "command-handler")
k1-stats (docker/stats @docker-conn "kafka-1")
k2-stats (docker/stats @docker-conn "kafka-2")
k3-stats (docker/stats @docker-conn "kafka-3")
ge-stats (docker/stats @docker-conn "graphql-endpoint")]
[(:cpu-pct db-stats)
(:mem-mib db-stats)
(:cpu-pct ch-stats)
(:mem-mib ch-stats)
(+ (:cpu-pct k1-stats) (:cpu-pct k2-stats) (:cpu-pct k3-stats))
(+ (:mem-mib k1-stats) (:mem-mib k2-stats) (:mem-mib k3-stats))
(:cpu-pct ge-stats)
(:mem-mib ge-stats)]
))
(defn close
[]
(docker/disconnect @docker-conn)
(reset! docker-conn nil)) | null | https://raw.githubusercontent.com/openweb-nl/open-bank-mark/786c940dafb39c36fdbcae736fe893af9c00ef17/test/src/nl/openweb/test/process.clj | clojure | (ns nl.openweb.test.process
(:require [clj-docker-client.core :as docker]))
(defonce docker-conn (atom nil))
(defn init
[]
(reset! docker-conn (docker/connect))
(docker/stats @docker-conn "db")
(docker/stats @docker-conn "command-handler")
(docker/stats @docker-conn "kafka-1")
(docker/stats @docker-conn "kafka-2")
(docker/stats @docker-conn "kafka-3")
(docker/stats @docker-conn "graphql-endpoint"))
(defn get-info
[]
(let [db-stats (docker/stats @docker-conn "db")
ch-stats (docker/stats @docker-conn "command-handler")
k1-stats (docker/stats @docker-conn "kafka-1")
k2-stats (docker/stats @docker-conn "kafka-2")
k3-stats (docker/stats @docker-conn "kafka-3")
ge-stats (docker/stats @docker-conn "graphql-endpoint")]
[(:cpu-pct db-stats)
(:mem-mib db-stats)
(:cpu-pct ch-stats)
(:mem-mib ch-stats)
(+ (:cpu-pct k1-stats) (:cpu-pct k2-stats) (:cpu-pct k3-stats))
(+ (:mem-mib k1-stats) (:mem-mib k2-stats) (:mem-mib k3-stats))
(:cpu-pct ge-stats)
(:mem-mib ge-stats)]
))
(defn close
[]
(docker/disconnect @docker-conn)
(reset! docker-conn nil)) | |
d5f08e19fe14e23e36a1415b61742df983609294479bf0d77add891899c1f025 | clj-pour/pour | core_test.clj | (ns pour.core-test
(:require [clojure.test :refer :all]
[pour.core :as pour]
[datomic.api :as d]))
(defrecord Test [a b])
(deftest seqy
(is (not (pour/seqy? {:db/id 123})))
(is (not (pour/seqy? {})))
(is (not (pour/seqy? nil)))
(is (not (pour/seqy? "hi")))
(is (not (pour/seqy? (->Test 1 2))))
(is (pour/seqy? []))
(is (pour/seqy? (list)))
(is (pour/seqy? (lazy-seq (range 100))))
(is (pour/seqy? (lazy-cat [] [])))
(is (pour/seqy? '()))
(is (pour/seqy? #{})))
(deftest datomic-entities
(testing "Datomic entities should not be treated as sequences"
(let [uri "datomic:mem-test"
_ (d/create-database uri)
conn (d/connect uri)]
(is (not (pour/seqy? (d/entity (d/db conn) :db/ident)))))))
(defn union-no-match? [union-key value]
nil)
(deftest nils
(testing "missing query should throw"
(let [!e (atom nil)]
(try
(pour/pour nil nil)
(catch Throwable e
(reset! !e e)))
(is (instance? Throwable @!e))
(is (= (ex-message @!e) "Missing query"))))
(is (= nil (pour/pour [:a :b] nil)) "nil values are skipped")
(testing "nil values on provided keys should mean that the key is also not present in the output"
(let [result (pour/pour [:a] {:a nil})]
(is (= {} result))))
(testing "union no match"
(let [q '[{(:a {:union-dispatch pour.core-test/union-no-match?})
{:bar [:baz]}}]
value {:a {:b {:c 1}}}
result (pour/pour q value)]
(is (= {} result)
"Dispatch function never matches and returns nil, empty output")))
(testing "resolvers that return nil don't close the return channel"
(let [nil-resolver (fn [_ _]
nil)
env {:resolvers {:test/nil-resolver nil-resolver}}
q '[:a
:b
:c
:test/nil-resolver]
v {:a 1 :b 2 :c 3}]
(is (= (pour/pour env q v)
{:a 1 :b 2 :c 3})))))
(deftest pour
(testing "baseline"
(let [constant-resolver (fn [env node]
::constant)
v {:bar 1
:hi :i-should-be-ignored
:me :also
:another {:thing :gah}
:other [{:foo1 :a
:not-here :nono}
{:foo1 :b
:not-here :nono}]}
q '[:foo
(:bar {:as :hi})
{:another [:thing]}
{:other [:foo1]}]
env {:resolvers {:foo constant-resolver}}]
(is (= (pour/pour env q v)
{:foo ::constant
:hi 1
:another {:thing :gah}
:other [{:foo1 :a}
{:foo1 :b}]})))))
(deftest empty-seqs
(testing "via resolver"
(let [empty-resolver (constantly (list))
v {}
q '[{:empty/resolver [:a :b]}]
env {:resolvers {:empty/resolver empty-resolver}}]
(is (= {}
(pour/pour env q v))))))
(defn sleepyresolver
"Debug resolver that passes through v after a delay"
[time v]
(fn [& args]
(Thread/sleep time)
v))
(deftest async
(testing "values should be resolved in parallel as far as possible"
(let [d1 (sleepyresolver 25 :d1)
d2 (sleepyresolver 50 :d2)
d3 (sleepyresolver 100 :d3)
d4 (sleepyresolver 30 :d4)
env {:resolvers {:d1 d1
:d2 d2
:d3 d3
:d4 d4}}
q '[{:a [:a :b]}
:d1
:d2
:d3
:d4
{(:d1 {:as :foo}) [:d1 :d2 :d3 :d4 :should :be :ignored]}]
start (System/currentTimeMillis)
_ (is (= (pour/pour env q {:a {:a 1}})
{:a {:a 1},
:d1 :d1,
:d2 :d2,
:d3 :d3,
:d4 :d4,
:foo {:d1 :d1,
:d2 :d2
:d3 :d3
:d4 :d4}}))
duration (- (System/currentTimeMillis) start)]
(is (< duration 250)))))
(deftest pipe
(testing "pipe resolver should pass through the left hand side to the nested query"
(let [v {:me "value"}
q '[{(:pipe {:as :aaa}) [:me]}]]
(is (= (pour/pour q v)
{:aaa {:me "value"}})))))
(deftest params
(testing "as param allows renaming the key"
(let [root {:name "person"
:age 30}
result (pour/pour '[(:name {:as :aliased})]
root)]
(is (= (:aliased result)
(:name root))))
(testing "default param should provide a value in the case the resolved value is nil only, passing boolean false through"
(let [root {:name "person"
:boolean false}
result (pour/pour '[(:missing {:default 100})
(:boolean {:default true})]
root)]
(is (false? (:boolean result)))
(is (= (:missing result)
100))))))
(deftest unions
(let [root {:stuff [{:id 1
:record :one}
{:id 2
:type :two}]}
result (pour/pour [{:stuff {:record [:record :id]
:type [:type :id]}}]
root)]
(is (= result
{:stuff [{:id 1
:record :one}
{:id 2
:type :two}]}))))
(defn custom-dispatch [union-key value]
(= (:type value) union-key))
(def not-a-function 1)
(deftest union-dispatch
(testing "dispatch is not a function calls through to on-error, result of on-error function is not used as resolved value"
(let [errors (atom [])
root {:routing {:type :a
:slug-a "slug-a"}}
q '[{(:routing {:union-dispatch pour.core-test/not-a-function})
{:b [:slug-b]
:c [:slug-c]
:a [:slug-a]}}]
result (pour/pour {:on-error #(swap! errors conj %)} q root)]
(is (= result {}))
(is (= (.getMessage (first @errors))
"Union-dispatch reference provided is not a function"))
(is (= (ex-data (first @errors))
{:params {:union-dispatch 'pour.core-test/not-a-function}}))))
(testing "dispatch on a value of a map"
(let [root {:routing {:type :a
:slug-a "slug-a"}}
q '[{(:routing {:union-dispatch pour.core-test/custom-dispatch})
{:b [:slug-b]
:c [:slug-c]
:a [:slug-a]}}]
result (pour/pour q root)]
(is (= result {:routing {:slug-a "slug-a"}}))))
(testing "allow providing a custom union dispatch function as a parameter"
(let [root {:stuff [{:type :one
:id 123
:product :book
:something "hi"}
{:type :two
:id 456
:product :book
:another "thing"}]}
result (pour/pour '[{(:stuff {:union-dispatch pour.core-test/custom-dispatch})
{:one [:type :something]
:two [:type :another]}}]
root)]
(is (= result
{:stuff [{:type :one
:something "hi"}
{:type :two
:another "thing"}]})))))
| null | https://raw.githubusercontent.com/clj-pour/pour/2ba06996e9d2fc4d34a28933d1c8d24c306a60db/test/pour/core_test.clj | clojure | (ns pour.core-test
(:require [clojure.test :refer :all]
[pour.core :as pour]
[datomic.api :as d]))
(defrecord Test [a b])
(deftest seqy
(is (not (pour/seqy? {:db/id 123})))
(is (not (pour/seqy? {})))
(is (not (pour/seqy? nil)))
(is (not (pour/seqy? "hi")))
(is (not (pour/seqy? (->Test 1 2))))
(is (pour/seqy? []))
(is (pour/seqy? (list)))
(is (pour/seqy? (lazy-seq (range 100))))
(is (pour/seqy? (lazy-cat [] [])))
(is (pour/seqy? '()))
(is (pour/seqy? #{})))
(deftest datomic-entities
(testing "Datomic entities should not be treated as sequences"
(let [uri "datomic:mem-test"
_ (d/create-database uri)
conn (d/connect uri)]
(is (not (pour/seqy? (d/entity (d/db conn) :db/ident)))))))
(defn union-no-match? [union-key value]
nil)
(deftest nils
(testing "missing query should throw"
(let [!e (atom nil)]
(try
(pour/pour nil nil)
(catch Throwable e
(reset! !e e)))
(is (instance? Throwable @!e))
(is (= (ex-message @!e) "Missing query"))))
(is (= nil (pour/pour [:a :b] nil)) "nil values are skipped")
(testing "nil values on provided keys should mean that the key is also not present in the output"
(let [result (pour/pour [:a] {:a nil})]
(is (= {} result))))
(testing "union no match"
(let [q '[{(:a {:union-dispatch pour.core-test/union-no-match?})
{:bar [:baz]}}]
value {:a {:b {:c 1}}}
result (pour/pour q value)]
(is (= {} result)
"Dispatch function never matches and returns nil, empty output")))
(testing "resolvers that return nil don't close the return channel"
(let [nil-resolver (fn [_ _]
nil)
env {:resolvers {:test/nil-resolver nil-resolver}}
q '[:a
:b
:c
:test/nil-resolver]
v {:a 1 :b 2 :c 3}]
(is (= (pour/pour env q v)
{:a 1 :b 2 :c 3})))))
(deftest pour
(testing "baseline"
(let [constant-resolver (fn [env node]
::constant)
v {:bar 1
:hi :i-should-be-ignored
:me :also
:another {:thing :gah}
:other [{:foo1 :a
:not-here :nono}
{:foo1 :b
:not-here :nono}]}
q '[:foo
(:bar {:as :hi})
{:another [:thing]}
{:other [:foo1]}]
env {:resolvers {:foo constant-resolver}}]
(is (= (pour/pour env q v)
{:foo ::constant
:hi 1
:another {:thing :gah}
:other [{:foo1 :a}
{:foo1 :b}]})))))
(deftest empty-seqs
(testing "via resolver"
(let [empty-resolver (constantly (list))
v {}
q '[{:empty/resolver [:a :b]}]
env {:resolvers {:empty/resolver empty-resolver}}]
(is (= {}
(pour/pour env q v))))))
(defn sleepyresolver
"Debug resolver that passes through v after a delay"
[time v]
(fn [& args]
(Thread/sleep time)
v))
(deftest async
(testing "values should be resolved in parallel as far as possible"
(let [d1 (sleepyresolver 25 :d1)
d2 (sleepyresolver 50 :d2)
d3 (sleepyresolver 100 :d3)
d4 (sleepyresolver 30 :d4)
env {:resolvers {:d1 d1
:d2 d2
:d3 d3
:d4 d4}}
q '[{:a [:a :b]}
:d1
:d2
:d3
:d4
{(:d1 {:as :foo}) [:d1 :d2 :d3 :d4 :should :be :ignored]}]
start (System/currentTimeMillis)
_ (is (= (pour/pour env q {:a {:a 1}})
{:a {:a 1},
:d1 :d1,
:d2 :d2,
:d3 :d3,
:d4 :d4,
:foo {:d1 :d1,
:d2 :d2
:d3 :d3
:d4 :d4}}))
duration (- (System/currentTimeMillis) start)]
(is (< duration 250)))))
(deftest pipe
(testing "pipe resolver should pass through the left hand side to the nested query"
(let [v {:me "value"}
q '[{(:pipe {:as :aaa}) [:me]}]]
(is (= (pour/pour q v)
{:aaa {:me "value"}})))))
(deftest params
(testing "as param allows renaming the key"
(let [root {:name "person"
:age 30}
result (pour/pour '[(:name {:as :aliased})]
root)]
(is (= (:aliased result)
(:name root))))
(testing "default param should provide a value in the case the resolved value is nil only, passing boolean false through"
(let [root {:name "person"
:boolean false}
result (pour/pour '[(:missing {:default 100})
(:boolean {:default true})]
root)]
(is (false? (:boolean result)))
(is (= (:missing result)
100))))))
(deftest unions
(let [root {:stuff [{:id 1
:record :one}
{:id 2
:type :two}]}
result (pour/pour [{:stuff {:record [:record :id]
:type [:type :id]}}]
root)]
(is (= result
{:stuff [{:id 1
:record :one}
{:id 2
:type :two}]}))))
(defn custom-dispatch [union-key value]
(= (:type value) union-key))
(def not-a-function 1)
(deftest union-dispatch
(testing "dispatch is not a function calls through to on-error, result of on-error function is not used as resolved value"
(let [errors (atom [])
root {:routing {:type :a
:slug-a "slug-a"}}
q '[{(:routing {:union-dispatch pour.core-test/not-a-function})
{:b [:slug-b]
:c [:slug-c]
:a [:slug-a]}}]
result (pour/pour {:on-error #(swap! errors conj %)} q root)]
(is (= result {}))
(is (= (.getMessage (first @errors))
"Union-dispatch reference provided is not a function"))
(is (= (ex-data (first @errors))
{:params {:union-dispatch 'pour.core-test/not-a-function}}))))
(testing "dispatch on a value of a map"
(let [root {:routing {:type :a
:slug-a "slug-a"}}
q '[{(:routing {:union-dispatch pour.core-test/custom-dispatch})
{:b [:slug-b]
:c [:slug-c]
:a [:slug-a]}}]
result (pour/pour q root)]
(is (= result {:routing {:slug-a "slug-a"}}))))
(testing "allow providing a custom union dispatch function as a parameter"
(let [root {:stuff [{:type :one
:id 123
:product :book
:something "hi"}
{:type :two
:id 456
:product :book
:another "thing"}]}
result (pour/pour '[{(:stuff {:union-dispatch pour.core-test/custom-dispatch})
{:one [:type :something]
:two [:type :another]}}]
root)]
(is (= result
{:stuff [{:type :one
:something "hi"}
{:type :two
:another "thing"}]})))))
| |
cf1827be24a910945b4cf87ffee22622e8e060e9661fbb3f696f6e9ebcae1e2b | johnridesabike/acutis | error_test.ml | open Acutis
module RenderSync = Render.Make (Sync) (Acutis_json.Data)
let render ?(json = "{}") src () =
let temp = Compile.(from_string ~fname:"<test>" Components.empty src) in
let json = Yojson.Basic.from_string json in
ignore @@ RenderSync.make temp json
exception E = Error.Acutis_error
let illegal_chars () =
let open Alcotest in
check_raises "Illegal character 1"
(E "File \"<test>\", 1:9-1:10\nSyntax error.\n") (render "{% match*");
check_raises "Illegal character 2"
(E "File \"<test>\", 1:4-1:5\nSyntax error.\n") (render "{% .a %}");
check_raises "Illegal character 3"
(E "File \"<test>\", 1:12-1:13\nSyntax error.\n") (render "{% match a %%}");
check_raises "Illegal character 4"
(E "File \"<test>\", 1:6-1:7\nSyntax error.\n") (render "{{ a }%}")
let number_parsing () =
let open Alcotest in
check_raises "A number greater than the maximum integer is a syntax error."
(E "File \"<test>\", 1:10-1:29\nSyntax error.\n")
(render "{% match 9999999999999999999")
let illegal_names () =
let open Alcotest in
check_raises "Illegal name: echo null"
(E "File \"<test>\", 1:4-1:8\nSyntax error.\n") (render "{{ null }}");
check_raises "Illegal name: echo false"
(E "File \"<test>\", 1:4-1:9\nSyntax error.\n") (render "{{ false }}");
check_raises "Illegal name: echo true"
(E "File \"<test>\", 1:4-1:8\nSyntax error.\n") (render "{{ true }}");
check_raises "Illegal name: _"
(E
"File \"<test>\", 1:9-1:10\n\
Type error.\n\
Underscore ('_') is not a valid name.")
(render "{% map [_] with x %} {{ x }} {% /map %}")
let unterminated () =
let open Alcotest in
check_raises "Unterminated strings"
(E "File \"<test>\", 1:6-1:6\nSyntax error.\n") (render {|{{ "a|});
check_raises "Unterminated comments"
(E "File \"<test>\", 1:11-1:11\nSyntax error.\n") (render "{* {* a *}");
check_raises "Unterminated expressions"
(E "File \"<test>\", 1:9-1:9\nSyntax error.\n") (render "{% match")
let illegal_escape () =
let open Alcotest in
check_raises "Illegal escape sequence"
(E "File \"<test>\", 1:5-1:6\nSyntax error.\n") (render {|{{ "\a" }}|})
let parser_errors () =
let open Alcotest in
check_raises "Missing a closing component name"
(E "File \"<test>\", 1:19-1:20\nParse error.\nExpected a component name.\n")
(render "{% A %} abcd {% / a %}");
check_raises "Unclosed components (this one is confusing.)"
(E "File \"<test>\", 1:16-1:16\nParse error.\nUnclosed component.\n")
(render "{% A /A %} abcd");
check_raises "Unexpected tokens (1)"
(E
"File \"<test>\", 1:4-1:5\n\
Parse error.\n\
Expected a '%}', 'match', 'map', 'map_dict', or a component name.\n")
(render "{% a %}");
check_raises "Unexpected tokens (2)"
(E
"File \"<test>\", 1:5-1:6\n\
Parse error.\n\
Expected a '%}', 'match', 'map', 'map_dict', or a component name.\n")
(render "{%~ a %}");
check_raises "Unexpected tokens (3)"
(E
"File \"<test>\", 1:5-1:9\n\
Parse error.\n\
Expected a '%}', 'match', 'map', 'map_dict', or a component name.\n")
(render "{%~ with %}");
check_raises "Unexpected tokens (4)"
(E
"File \"<test>\", 1:10-1:11\n\
Parse error.\n\
Expected a '%}', 'match', 'map', 'map_dict', or a component name.\n")
(render "{% %}{%~ a %}");
check_raises "Unexpected tokens (5)"
(E "File \"<test>\", 1:40-1:41\nParse error.\nExpected a '%}'.\n")
(render "{% A %} {% match a with _ %} {% /match /A %}");
check_raises "Unexpected tokens (inside # blocks)"
(E
"File \"<test>\", 1:20-1:24\n\
Parse error.\n\
Expected a '%}', '#', 'match', 'map', 'map_dict', or a component name.\n")
(render "{% A a=#%} abcd {% with /A %}");
check_raises "Bad pattern (1)"
(E
"File \"<test>\", 1:10-1:13\n\
Parse error.\n\
This is not a valid pattern.\n")
(render "{% match ABC with a %} {% /match %}");
check_raises "Bad pattern (2)"
(E
"File \"<test>\", 1:11-1:14\n\
Parse error.\n\
This is not a valid pattern.\n")
(render "{% match !ABC with a %} {% /match %}");
check_raises "Bad pattern (3)"
(E
"File \"<test>\", 1:11-1:14\n\
Parse error.\n\
This is not a valid pattern.\n")
(render "{% match !ABC with a %} {% /match %}");
check_raises "Bad pattern (4)"
(E
"File \"<test>\", 1:11-1:14\n\
Parse error.\n\
This is not a valid pattern.\n")
(render "{% match @ABC with a %} {% /match %}");
check_raises "Bad pattern (5)"
(E
"File \"<test>\", 1:13-1:16\n\
Parse error.\n\
This is not a valid pattern.\n")
(render "{% match a, ABC with a %} {% /match %}");
check_raises "Bad pattern (6)"
(E
"File \"<test>\", 1:13-1:16\n\
Parse error.\n\
This is not a valid pattern.\n")
(render "{% map_dict ABC with a %} {% /map_dict %}");
check_raises "Bad pattern (7)"
(E "File \"<test>\", 1:8-1:11\nParse error.\nThis is not a valid pattern.\n")
(render "{% map ABC with a %} {% /map %}");
check_raises "Bad pattern (8)"
(E
"File \"<test>\", 1:14-1:18\n\
Parse error.\n\
This is not a valid pattern.\n")
(render "{% match {a: with %} {% /match %}");
check_raises "Bad pattern (9)"
(E
"File \"<test>\", 1:12-1:16\n\
Parse error.\n\
This is not a valid pattern.\n")
(render "{% match ( with %} {% /match %}");
check_raises "Bad pattern (10)"
(E
"File \"<test>\", 1:12-1:16\n\
Parse error.\n\
This is not a valid pattern.\n")
(render "{% match [ with %} {% /match %}");
check_raises "Bad pattern (11)"
(E
"File \"<test>\", 1:15-1:19\n\
Parse error.\n\
This is not a valid pattern.\n")
(render "{% match [... with %} {% /match %}");
check_raises "Bad pattern (12)"
(E
"File \"<test>\", 1:14-1:18\n\
Parse error.\n\
This is not a valid pattern.\n")
(render "{% match [a, with %} {% /match %}");
check_raises "Bad pattern (13)"
(E
"File \"<test>\", 1:18-1:22\n\
Parse error.\n\
This is not a valid pattern.\n")
(render "{% match [a, ... with %} {% /match %}");
check_raises "Unclosed < (4)"
(E
"File \"<test>\", 1:14-1:18\n\
Parse error.\n\
This is not a valid pattern.\n")
(render "{% match <a: with %} {% /match %}");
check_raises "Illegal pattern after with"
(E
"File \"<test>\", 1:17-1:20\n\
Parse error.\n\
This is not a valid pattern.\n")
(render "{% match a with Abc %} {% /match %}");
check_raises "Bad pattern (14)"
(E "File \"<test>\", 1:8-1:11\nParse error.\nThis is not a valid pattern.\n")
(render "{% Z a=ABC / %}");
check_raises "Bad echo (1)"
(E "File \"<test>\", 1:4-1:5\nParse error.\nThis is not a valid echo.\n")
(render "{{ ? }}");
check_raises "Bad echo (2)"
(E "File \"<test>\", 1:5-1:6\nParse error.\nThis is not a valid echo.\n")
(render "{{{ A }}}");
check_raises "Bad echo (3)"
(E "File \"<test>\", 1:8-1:9\nParse error.\nThis is not a valid echo.\n")
(render "{{ a ? ? }}");
check_raises "Bad echo (4)"
(E "File \"<test>\", 1:7-1:8\nParse error.\nThis is not a valid echo.\n")
(render "{{ %i ? }}");
check_raises "Bad echo (5)"
(E "File \"<test>\", 1:7-1:9\nParse error.\nExpected a '?' or '}}}'.\n")
(render "{{{ a }}");
check_raises "Bad echo (6)"
(E "File \"<test>\", 1:6-1:9\nParse error.\nExpected a '?' or '}}'.\n")
(render "{{ a }}}");
check_raises "Bad echo format (1)"
(E
"File \"<test>\", 1:6-1:7\n\
Parse error.\n\
This is missing a format specification.\n")
(render "{{ % a }}");
check_raises "Bad echo format (2)"
(E "File \"<test>\", 1:6-1:7\nParse error.\nExpected an 'i' format type.\n")
(render "{{ %,b a }}");
check_raises "Bad echo format (3)"
(E "File \"<test>\", 1:6-1:7\nParse error.\nExpected a number.\n")
(render "{{ %.f a }}");
check_raises "Bad echo format (4)"
(E
"File \"<test>\", 1:7-1:8\n\
Parse error.\n\
Expected an 'f', 'e', or 'g' format type.\n")
(render "{{ %.2b a }}");
check_raises "Bad prop (1)"
(E
"File \"<test>\", 1:6-1:10\n\
Parse error.\n\
This is not a valid component prop.\n")
(render "{% Z null=1 / %}");
check_raises "Bad prop (2)"
(E
"File \"<test>\", 1:8-1:9\n\
Parse error.\n\
This is not a valid component prop.\n")
(render "{% A a # %}");
check_raises "Bad prop (3)"
(E
"File \"<test>\", 1:8-1:9\n\
Parse error.\n\
This is not a valid component prop.\n")
(render "{% A b # %}");
check_raises "Illegal field name (1)"
(E
"File \"<test>\", 1:12-1:16\n\
Parse error.\n\
This is not a valid field name.\n")
(render "{% match { with %} {% /match %}");
check_raises "Illegal field name (2)"
(E
"File \"<test>\", 1:13-1:17\n\
Parse error.\n\
This is not a valid field name.\n")
(render "{% match {@ with %} {% /match %}");
check_raises "Illegal field name (3)"
(E
"File \"<test>\", 1:14-1:18\n\
Parse error.\n\
This is not a valid field name.\n")
(render "{% match {a, with %} {% /match %}");
check_raises "Illegal field name (4)"
(E
"File \"<test>\", 1:12-1:16\n\
Parse error.\n\
This is not a valid field name.\n")
(render "{% match < with %} {% /match %}");
check_raises "Illegal field name (5)"
(E
"File \"<test>\", 1:14-1:18\n\
Parse error.\n\
This is not a valid field name.\n")
(render "{% match <a, with %} {% /match %}");
check_raises "Unclosed { (1)"
(E
"File \"<test>\", 1:13-1:17\n\
Parse error.\n\
Expected a ',', ':', or '}'.\n")
(render "{% match {a with %} {% /match %}");
check_raises "Unclosed { (2)"
(E "File \"<test>\", 1:15-1:19\nParse error.\nExpected a ':'.\n")
(render "{% match {\"a\" with %} {% /match %}");
check_raises "Unclosed { (2)"
(E "File \"<test>\", 1:15-1:19\nParse error.\nExpected a ',' or '}'.\n")
(render "{% match {a:0 with %} {% /match %}");
check_raises "Unclosed ("
(E "File \"<test>\", 1:13-1:17\nParse error.\nExpected a ',' or ')'.\n")
(render "{% match (a with %} {% /match %}");
check_raises "Unclosed [ (1)"
(E
"File \"<test>\", 1:13-1:17\n\
Parse error.\n\
Expected a ',', '...', or ']'.\n")
(render "{% match [a with %} {% /match %}");
check_raises "Unclosed [ (2)"
(E "File \"<test>\", 1:19-1:23\nParse error.\nExpected a ']'.\n")
(render "{% match [a, ...b with %} {% /match %}");
check_raises "Unclosed < (1)"
(E
"File \"<test>\", 1:13-1:17\n\
Parse error.\n\
Expected a ',', ':', or '>'.\n")
(render "{% match <a with %} {% /match %}");
check_raises "Unclosed < (2)"
(E "File \"<test>\", 1:15-1:19\nParse error.\nExpected a ':'.\n")
(render "{% match <\"a\" with %} {% /match %}");
check_raises "Unclosed < (3)"
(E "File \"<test>\", 1:15-1:19\nParse error.\nExpected a ',' or '>'.\n")
(render "{% match <a:0 with %} {% /match %}");
check_raises "Missing commas in match/map patterns (1)"
(E
"File \"<test>\", 1:12-1:13\n\
Parse error.\n\
Sequential patterns must be separated by a ','.\n")
(render "{% match a b with a b %} {% /match %}");
check_raises "Missing commas in match/map patterns (2)"
(E
"File \"<test>\", 1:19-1:20\n\
Parse error.\n\
Sequential patterns must be separated by a ','.\n")
(render "{% match a with a b %} {% /match %}");
check_raises "Missing commas in match/map patterns (3)"
(E
"File \"<test>\", 1:15-1:16\n\
Parse error.\n\
Sequential patterns must be separated by a ','.\n")
(render "{% map_dict a b with a %} {% /map_dict %}");
check_raises "Missing commas in match/map patterns (4)"
(E
"File \"<test>\", 1:10-1:11\n\
Parse error.\n\
Sequential patterns must be separated by a ','.\n")
(render "{% map a b with a %} {% /map %}");
check_raises "Unmatched match"
(E
"File \"<test>\", 1:26-1:26\n\
Parse error.\n\
Unclosed block. Expected a '{% /' somewhere.\n")
(render "{% match x with true %} b");
check_raises "Missing /match"
(E "File \"<test>\", 1:26-1:29\nParse error.\nExpected a '/match'.\n")
(render "{% match x with x %} {% /map %}");
check_raises "Missing /map"
(E "File \"<test>\", 1:24-1:29\nParse error.\nExpected a '/map'.\n")
(render "{% map x with x %} {% /match %}");
check_raises "Missing /map_dict"
(E "File \"<test>\", 1:29-1:32\nParse error.\nExpected a '/map_dict'.\n")
(render "{% map_dict x with x %} {% /map %}");
check_raises "Unseparated echoes"
(E "File \"<test>\", 1:6-1:7\nParse error.\nExpected a '?' or '}}'.\n")
(render "{{ a b }}");
check_raises "# Blocks must contain text"
(E "File \"<test>\", 1:10-1:13\nParse error.\nExpected a '%}'.\n")
(render "{% A a=# abc # / %}")
let dup_record_field () =
let open Alcotest in
check_raises "Duplicate field"
(E "File \"<test>\", 1:18-1:30\nParse error.\nDuplicate field 'a'.")
(render {|{% match a with {a: 0, a: "a"} %} {% with _ %} {% /match %}|});
check_raises "Duplicate tag field"
(E "File \"<test>\", 1:18-1:31\nParse error.\nDuplicate field 'a'.")
(render {|{% match a with {@a: 0, a: "a"} %} {% with _ %} {% /match %}|});
check_raises "Duplicate dict field"
(E "File \"<test>\", 1:18-1:30\nParse error.\nDuplicate field 'a'.")
(render {|{% match a with <a: 0, a: "a"> %} {% with _ %} {% /match %}|});
check_raises "Multiple record tags"
(E
"File \"<test>\", 1:18-1:32\n\
Parse error.\n\
This tagged record has multiple tags.")
(render {|{% match a with {@a: 0, @b: "a"} %} {% with _ %} {% /match %}|})
let pat_count_mismatch () =
let open Alcotest in
check_raises "Pattern count mismatch 1"
(E "File \"<test>\", 1:4-1:42\nType error.\nPattern count mismatch.")
(render "{% match a, b, c with 1, 2 %} d {% /match %}");
check_raises "Pattern count mismatch 2"
(E "File \"<test>\", 1:30-1:42\nType error.\nPattern count mismatch.")
(render "{% match a with 1, 2 %} d {% with 1, 2, 3 %} z {% /match %}");
check_raises "Pattern count mismatch (map)"
(E
"File \"<test>\", 1:4-1:56\n\
Type error.\n\
Expressions 'map' and 'map_dict' can only have one or two patterns for \
each\n\
'with' expression.")
(render "{% map a with 1, 2, 3 %} d {% with 4, 5, 6 %} z {% /map %}")
let dup_name_destructure () =
let open Alcotest in
check_raises "You can't bind a name more than once when destructuring."
(E
"File \"<test>\", 1:21-1:22\n\
Type error.\n\
The name 'x' is already bound in this pattern.")
(render "{% match a with [x, x] %} a {% with _ %} b {% /match %}")
let type_error_echo () =
let open Alcotest in
check_raises "Echoed string literals cannot appear before a ?."
(E
"File \"<test>\", 1:4-1:8\n\
Type error.\n\
Echoed string literals cannot appear before a ?.")
(render {|{{ "ab" ? "cd" }}|})
let type_error_const () =
let open Alcotest in
check_raises "String <> int"
(E
"File \"<test>\", 1:32-1:33\n\
Type error.\n\
Type mismatch.\n\
Expected:\n\
\ string\n\
Received:\n\
\ int")
(render {|{% match a with "a" %} {% with 1 %} {% with _ %} {% /match %}|});
check_raises "Float <> int"
(E
"File \"<test>\", 1:32-1:33\n\
Type error.\n\
Type mismatch.\n\
Expected:\n\
\ float\n\
Received:\n\
\ int")
(render {|{% match a with 0.0 %} {% with 1 %} {% with _ %} {% /match %}|});
check_raises "String <> float"
(E
"File \"<test>\", 1:32-1:35\n\
Type error.\n\
Type mismatch.\n\
Expected:\n\
\ string\n\
Received:\n\
\ float")
(render {|{% match a with "a" %} {% with 1.0 %} {% with _ %} {% /match %}|});
check_raises "Map list key type mismatch."
(E
"File \"<test>\", 1:4-1:55\n\
Type error.\n\
Type mismatch.\n\
Expected:\n\
\ int\n\
Received:\n\
\ string")
(render "{% map [1] with a, \"b\" %} {{ a }} {% with _ %} {% /map %}");
check_raises "Map dict key type mismatch."
(E
"File \"<test>\", 1:4-2:13\n\
Type error.\n\
Type mismatch.\n\
Expected:\n\
\ string\n\
Received:\n\
\ int")
(render
"{% map_dict <\"a\": 1> with a, 1 %} {{ a }} {% with _ %}\n\
{% /map_dict %}")
let type_error_nest () =
let open Alcotest in
check_raises "[int] <> [string]"
(E
"File \"<test>\", 2:10-2:11\n\
Type error.\n\
Type mismatch.\n\
Expected:\n\
\ [int]\n\
Received:\n\
\ [string]")
(render
"{% match a with [\"a\"] %} {% with _ %} {% /match %}\n\
{% match a with [1] %} {% with _ %} {% /match %}");
check_raises "{a: int} <> {a: float}"
(E
"File \"<test>\", 2:10-2:11\n\
Type error.\n\
Type mismatch.\n\
Expected:\n\
\ {a: float}\n\
Received:\n\
\ {a: int}")
(render
"{% match a with {a: 1} %} {% with _ %} {% /match %}\n\
{% match a with {a: 0.0} %} {% with _ %} {% /match %}");
check_raises "(string, _) <> (float, _)"
(E
"File \"<test>\", 2:10-2:11\n\
Type error.\n\
Type mismatch.\n\
Expected:\n\
\ (float, string)\n\
Received:\n\
\ (string, string)")
(render
"{% match a with (\"a\", a) %} {{ a }} {% with _ %} {% /match %}\n\
{% match a with (1.0, a) %} {{ a }} {% with _ %} {% /match %}");
check_raises "Tagged record <> untagged record"
(E
"File \"<test>\", 2:10-2:11\n\
Type error.\n\
Type mismatch.\n\
Expected:\n\
\ {a: int}\n\
Received:\n\
\ {@a: 1} | ...")
(render
"{% match a with {@a: 1} %} {% with _ %} {% /match %}\n\
{% match a with {a: 1} %} {% with _ %} {% /match %}");
check_raises "Dict <> record"
(E
"File \"<test>\", 2:10-2:11\n\
Type error.\n\
Type mismatch.\n\
Expected:\n\
\ {a: int}\n\
Received:\n\
\ <int>")
(render
"{% match a with <a: 1> %} {% with _ %} {% /match %}\n\
{% match a with {a: 1} %} {% with _ %} {% /match %}");
check_raises "?int <> int"
(E
"File \"<test>\", 2:10-2:11\n\
Type error.\n\
Type mismatch.\n\
Expected:\n\
\ int\n\
Received:\n\
\ ?int")
(render
"{% match a with !1 %} {% with _ %} {% /match %}\n\
{% match a with 1 %} {% with _ %} {% /match %}");
check_raises "2-tuple <> 3-tuple"
(E
"File \"<test>\", 2:10-2:11\n\
Type error.\n\
Type mismatch.\n\
Expected:\n\
\ (int, int, int)\n\
Received:\n\
\ (int, int)")
(render
"{% match a with (1, 2) %} {% with _ %} {% /match %}\n\
{% match a with (1, 2, 3) %} {% with _ %} {% /match %}")
let type_error_record () =
let open Alcotest in
check_raises "Records with missing fields (1)"
(E
"File \"<test>\", 1:26-1:32\n\
Type error.\n\
Type mismatch.\n\
Expected:\n\
\ {a: int}\n\
Received:\n\
\ {b: _}")
(render
"{% map [(1, {a: 1}), (2, {b: 2})] with (i, {a}) %}\n\
\ {{ %i i }} {{ %i a }} {% /map %}");
check_raises "Records with missing fields (2)"
(E
"File \"<test>\", 1:10-1:16\n\
Type error.\n\
Type mismatch.\n\
Expected:\n\
\ {a: _, b: _}\n\
Received:\n\
\ {a: _}")
(render "{% match {a: 1} with {a: _, b: _} %} {% /match %}");
let comps =
Compile.Components.(
make [ parse_string ~fname:"a.acutis" ~name:"A" "{{ a }}" ])
in
check_raises "Records with missing fields (Component)"
(E
"File \"<test>\", 1:4-1:7\n\
Type error.\n\
This is missing key 'a' of type:\n\
\ string") (fun () ->
ignore @@ Compile.from_string ~fname:"<test>" comps "{% A / %}")
let type_error_enum () =
let open Alcotest in
check_raises "Closed enum <> open enum"
(E
"File \"<test>\", 2:10-2:11\n\
Type error.\n\
Type mismatch.\n\
Expected:\n\
\ @1\n\
Received:\n\
\ @1 | @2 | ...")
(render
"{% match a with @1 %} {% with @2 %} {% with _ %} {% /match %}\n\
{% match a with @1 %} {% /match %}");
check_raises "Enum vars with no subset are reported."
(E
"File \"<test>\", 3:12-3:13\n\
Type error.\n\
Type mismatch.\n\
Expected:\n\
\ @1 | @2\n\
Received:\n\
\ @3 | @4")
(render
"{% match a with @1 %} {% with @2 %} {% /match %}\n\
{% match b with @3 %} {% with @4 %} {% /match %}\n\
{% map [a, b] with _ %} {% /map %}");
check_raises "Enum vars + literals with no subset are reported."
(E
"File \"<test>\", 2:12-2:14\n\
Type error.\n\
Type mismatch.\n\
Expected:\n\
\ @1 | @2\n\
Received:\n\
\ @3 | ...")
(render
"{% match a with @1 %} {% with @2 %} {% /match %}\n\
{% map [a, @3] with _ %} {% /map %}");
check_raises "Enum literals with no subset are reported (1)."
(E
"File \"<test>\", 1:10-1:12\n\
Type error.\n\
Type mismatch.\n\
Expected:\n\
\ @1\n\
Received:\n\
\ @0 | ...")
(render "{% match @0 with @1 %} {% /match %}");
check_raises "Enum literals with no subset are reported (2)."
(E
"File \"<test>\", 1:10-1:12\n\
Type error.\n\
Type mismatch.\n\
Expected:\n\
\ @\"a\"\n\
Received:\n\
\ @0 | ...")
(render "{% match @0 with @\"a\" %} {% /match %}");
check_raises "| false | true <> only false"
(E
"File \"<test>\", 1:10-1:14\n\
Type error.\n\
Type mismatch.\n\
Expected:\n\
\ false\n\
Received:\n\
\ false | true")
(render "{% match true with false %} {% /match %}")
let type_error_union () =
let open Alcotest in
check_raises "Int tag <> string tag"
(E
"File \"<test>\", 1:38-1:52\n\
Type error.\n\
Type mismatch.\n\
Expected:\n\
\ {@tag: 0}\n\
Received:\n\
\ {@tag: \"a\", b: _}")
(render
"{% match a with {@tag: 0} %} {% with {@tag: \"a\", b} %} {{ b }}\n\
{% /match %}");
check_raises "Random other tags don't compile."
(E
"File \"<test>\", 1:24-1:25\n\
Parse error.\n\
Only literal integer, string, and boolean values may be union tags.\n")
(render "{% match a with {@tag: []} %} {% /match %}");
check_raises "Tag names must be coherent."
(E
"File \"<test>\", 1:36-1:46\n\
Type error.\n\
Type mismatch.\n\
Expected:\n\
\ {@a: 0}\n\
Received:\n\
\ {@b: 1, c: _}")
(render
"{% match a with {@a: 0} %} {% with {@b: 1, c} %} {{ c }} {% /match %}")
let vars_with_clauses () =
let open Alcotest in
check_raises "Variable names must be coherent."
(E
"File \"<test>\", 2:16-2:17\n\
Type error.\n\
Variable 'b' must occur in each 'with' pattern.")
(render
"{% match a, b\n\
\ with null, !b\n\
\ with !a, null %}\n\
{% with !_, !_ with null, null %}\n\
{% /match %}");
check_raises "Variable types must be coherent."
(E
"File \"<test>\", 1:38-1:39\n\
Type error.\n\
Type mismatch.\n\
Expected:\n\
\ int\n\
Received:\n\
\ string")
(render
"{% match a, b with 1, \"a\" %} {% with a, _ with _, a %} {% /match %}")
let component_typechecker () =
let open Alcotest in
check_raises "Component names match"
(E
"File \"<test>\", 1:4-1:14\n\
Type error.\n\
Component name mismatch.\n\
Expected:\n\
\ A.\n\
Received:\n\
\ B.")
(render "{% A %} {% /B %}")
let unused_bindings () =
let open Alcotest in
check_raises "Basic unused bindings are reported."
(E
"File \"<test>\", 1:18-1:19\n\
Type error.\n\
This variable is bound but never used:\n\
\ x")
(render "{% match a with {x} %} {% /match %}");
check_raises "Unused bindings are reported in the order they appear."
(E
"File \"<test>\", 1:21-1:22\n\
Type error.\n\
This variable is bound but never used:\n\
\ y")
(render
"{% match a with {x, y} %}\n\
\ {% match x with {z} %} {% /match %}\n\
{% /match %}");
check_raises "Shadowing bindings can report them as unused."
(E
"File \"<test>\", 1:26-1:27\n\
Type error.\n\
This variable is bound but never used:\n\
\ y")
(render
"{% match a, b with {x}, {y} %}\n\
\ {% match x with {y} %} {{ y }} {%/ match %}\n\
{% /match %}")
let matching_unused () =
let open Alcotest in
check_raises "Basic pattern (1)."
(E "File \"<test>\", 4:4-4:19\nMatching error.\nThis match case is unused.")
(render
"{% match a, b, c\n\
\ with 10, 11, 12 %}\n\
{% with _x, 21, 22 %}\n\
{% with 10, 11, 12 %}\n\
{% /match %}");
check_raises "Basic pattern (2)."
(E "File \"<test>\", 6:4-6:19\nMatching error.\nThis match case is unused.")
(render
"{% match a, b, c\n\
\ with 10, 11, 12 %}\n\
{% with _x, 21, 22 %}\n\
{% with 30, 31, 32 %}\n\
{% with 30, _y, 42 %}\n\
{% with 30, 31, 42 %}\n\
{% /match %}");
check_raises "Nest patterns merge into wildcard patterns correctly (1)."
(E "File \"<test>\", 1:33-1:48\nMatching error.\nThis match case is unused.")
(render "{% match a, b with _x, _y %} {% with (_, _), 40 %} {% /match %}");
check_raises "Nest patterns merge into wildcard patterns correctly (2)."
(E "File \"<test>\", 4:4-4:22\nMatching error.\nThis match case is unused.")
(render
"{% match a, b\n\
\ with _x, 1 %}\n\
{% with (\"a\", \"b\"), 10 %}\n\
{% with (\"a\", \"b\"), 1 %}\n\
{% /match %}")
let parmatch () =
let open Alcotest in
check_raises "Partial matching with integers."
(E
"File \"<test>\", 1:4-1:55\n\
Matching error.\n\
This pattern-matching is not exhaustive.\n\
Here's an example of a pattern which is not matched:\n\
\ _")
(render "{% match a with 0 with 10 with 20 with 30 %} {% /match %}");
check_raises "Partial matching with lists (1)."
(E
"File \"<test>\", 1:4-1:41\n\
Matching error.\n\
This pattern-matching is not exhaustive.\n\
Here's an example of a pattern which is not matched:\n\
\ [_, ..._]")
(render "{% match a with [] with [_] %} {% /match %}");
check_raises "Partial matching with lists (2)."
(E
"File \"<test>\", 1:4-1:33\n\
Matching error.\n\
This pattern-matching is not exhaustive.\n\
Here's an example of a pattern which is not matched:\n\
\ []")
(render "{% match a with [_] %} {% /match %}");
check_raises "Partial matching with Nullables (1)."
(E
"File \"<test>\", 1:4-1:34\n\
Matching error.\n\
This pattern-matching is not exhaustive.\n\
Here's an example of a pattern which is not matched:\n\
\ !_")
(render "{% match a with null %} {% /match %}");
check_raises "Partial matching with Nullables (2)."
(E
"File \"<test>\", 1:4-1:32\n\
Matching error.\n\
This pattern-matching is not exhaustive.\n\
Here's an example of a pattern which is not matched:\n\
\ null")
(render "{% match a with !_ %} {% /match %}");
check_raises "Partial matching with Nullables (3)."
(E
"File \"<test>\", 1:4-1:48\n\
Matching error.\n\
This pattern-matching is not exhaustive.\n\
Here's an example of a pattern which is not matched:\n\
\ !_")
(render "{% match a with !1 %} {% with null %} {% /match %}");
check_raises "Partial matching with enums nested in nullables."
(E
"File \"<test>\", 1:4-1:58\n\
Matching error.\n\
This pattern-matching is not exhaustive.\n\
Here's an example of a pattern which is not matched:\n\
\ !@1, _")
(render "{% match a, b with !@1, 2 %} {% with null, _ %} {% /match %}");
check_raises "Partial matching with records."
(E
"File \"<test>\", 1:4-1:56\n\
Matching error.\n\
This pattern-matching is not exhaustive.\n\
Here's an example of a pattern which is not matched:\n\
\ {a: _, b: _}")
(render "{% match a with {b: 10} %} {% with {a: 20} %} {% /match %}");
check_raises "Partial matching with dictionaries."
(E
"File \"<test>\", 1:4-1:61\n\
Matching error.\n\
This pattern-matching is not exhaustive.\n\
Here's an example of a pattern which is not matched:\n\
\ _")
(render "{% match a with <a: true> %} {% with <a: false> %} {% /match %}");
check_raises "Partial matching with unions (1)."
(E
"File \"<test>\", 1:4-2:10\n\
Matching error.\n\
This pattern-matching is not exhaustive.\n\
Here's an example of a pattern which is not matched:\n\
\ {@tag: 0, a: _}")
(render
"{% match a with {@tag: 0, a: 10} %} {% with {@tag: 1, b: 20} %}\n\
{% /match %}");
check_raises "Partial matching with unions (2)."
(E
"File \"<test>\", 1:4-2:10\n\
Matching error.\n\
This pattern-matching is not exhaustive.\n\
Here's an example of a pattern which is not matched:\n\
\ {@tag: false, b: _}")
(render
"{% match a with {@tag: true, a: 10} %}{% with {@tag: false, b: 20} %}\n\
{% /match %}");
check_raises "Partial matching with unions (3)."
(E
"File \"<test>\", 1:4-2:10\n\
Matching error.\n\
This pattern-matching is not exhaustive.\n\
Here's an example of a pattern which is not matched:\n\
\ {@tag: true, a: _}")
(render
"{% match a with {@tag: true, a: 10} %} {% with {@tag: false, b: _} %}\n\
{% /match %}");
check_raises "Partial matching with records."
(E
"File \"<test>\", 1:4-3:10\n\
Matching error.\n\
This pattern-matching is not exhaustive.\n\
Here's an example of a pattern which is not matched:\n\
\ {favoriteColor: _, firstName: _}")
(render
"{% match a with {firstName: name, favoriteColor: \"green\"} %}\n\
{{ name }}'s favorite color is green.\n\
{% /match %}");
check_raises "Partial lists print correctly."
(E
"File \"<test>\", 1:5-5:10\n\
Matching error.\n\
This pattern-matching is not exhaustive.\n\
Here's an example of a pattern which is not matched:\n\
\ {@kind: \"anonymous\", books: _}")
(render
"{%~ match author\n\
\ with {@kind: \"person\", name: _, books: [_newest, ..._older]} %}\n\
{%~ with {@kind: \"anonymous\", books: []} %}\n\
\ This author hasn't published any books.\n\
{% /match %}")
let merge_expanded_trees () =
let open Alcotest in
check_raises "Both nil and cons paths fail to merge into a wildcard."
(E "File \"<test>\", 6:9-6:19\nMatching error.\nThis match case is unused.")
(render
{|
{% match a, b
with 1, _ %}
{% with _, !1 %}
{% with _, null %}
{% with 1, !2 %}
{% with _, _ %}
{% /match %}|})
let bad_block () =
let open Alcotest in
check_raises "Template blocks are not allowed in destructure patterns."
(E
"File \"<test>\", 1:21-1:28\n\
Type error.\n\
Template blocks are not allowed in a destructure pattern.")
(render "{% match a with {b: #%} {%#} %} {% /match %}")
let component_graph () =
let open Alcotest in
let a =
Compile.Components.parse_string ~fname:"a.acutis" ~name:"A" "{% B /%}"
in
let b =
Compile.Components.parse_string ~fname:"b.acutis" ~name:"B" "{% C /%}"
in
let c =
Compile.Components.parse_string ~fname:"c.acutis" ~name:"C" "{% D /%}"
in
let d =
Compile.Components.parse_string ~fname:"d.acutis" ~name:"D" "{% B /%}"
in
check_raises "Cyclic dependencies are reported."
(E "Compile error.\nDependency cycle detected.\nA -> B -> C -> D -> B")
(fun () -> ignore @@ Compile.Components.make [ a; b; c; d ]);
check_raises "Missing components are reported."
(E "Compile error.\nMissing template:\n D\nRequired by:\n C") (fun () ->
ignore @@ Compile.Components.make [ a; b; c ]);
check_raises "Missing components are reported (by root)."
(E "Compile error.\nMissing template:\n A\nRequired by:\n <test>")
(render "{% A /%}");
check_raises "Duplicate names are reported."
(E "Compile error.\nThere are multiple components with the name 'A'.")
(fun () -> ignore @@ Compile.Components.make [ a; b; a ])
let known_broken () =
let open Alcotest in
check_raises
"This error is incorrect. The compiler fails to detect the first unused \
wildcard case. I'm not fixing this error yet, but I'm keeping this test \
to track when it changes."
(E "File \"<test>\", 1:43-1:49\nMatching error.\nThis match case is unused.")
(render "{% match a with (_, _) %} {% with _ %} {% with _ %} {% /match %}")
let decode_mismatch () =
let open Alcotest in
check_raises "Basic type mismatch."
(E
"File \"<test>\"\n\
Render error.\n\
The data supplied does not match this template's interface.\n\
Path:\n\
\ input -> \"a\" -> \"b\".\n\
Expected type:\n\
\ string\n\
Received value:\n\
\ []")
(render "{% match a with {b} %} {{ b }} {% /match %}"
~json:{|{"a": {"b": []}}|});
let json = {|{"a": "a", "b": true, "c": []}|} in
check_raises "Map type mismatch (1)."
(E
"File \"<test>\"\n\
Render error.\n\
The data supplied does not match this template's interface.\n\
Path:\n\
\ input -> \"a\".\n\
Expected type:\n\
\ [{a: string}]\n\
Received value:\n\
\ \"a\"")
(render "{% map a with {a} %}{{ a }}{% /map %}" ~json);
check_raises "Map type mismatch (2)."
(E
"File \"<test>\"\n\
Render error.\n\
The data supplied does not match this template's interface.\n\
Path:\n\
\ input -> \"a\".\n\
Expected type:\n\
\ [int]\n\
Received value:\n\
\ \"a\"")
(render "{% map [1, 2, ...a] with a %}{{ %i a }}{% /map %}" ~json);
check_raises "Missing bindings are reported"
(E
"File \"<test>\"\n\
Render error.\n\
The data supplied does not match this template's interface.\n\
Path:\n\
\ input.\n\
Expected type:\n\
\ {z: string}\n\
Input is missing key:\n\
\ z")
(render "{{ z }}" ~json);
check_raises "Bad enums are reported: boolean."
(E
"File \"<test>\"\n\
Render error.\n\
The data supplied does not match this template's interface.\n\
Path:\n\
\ input -> \"b\".\n\
Expected type:\n\
\ false\n\
This type does not allow the given value:\n\
\ true")
(render "{% match b with false %} {% /match %}" ~json);
check_raises "Bad enums are reported: int."
(E
"File \"<test>\"\n\
Render error.\n\
The data supplied does not match this template's interface.\n\
Path:\n\
\ input -> \"a\".\n\
Expected type:\n\
\ @1 | @2\n\
This type does not allow the given value:\n\
\ 3")
(render "{% match a with @1 %} {% with @2 %} {% /match %}"
~json:{|{"a": 3}|});
check_raises "Bad enums are reported: int."
(E
"File \"<test>\"\n\
Render error.\n\
The data supplied does not match this template's interface.\n\
Path:\n\
\ input -> \"a\".\n\
Expected type:\n\
\ @\"a\" | @\"b\"\n\
This type does not allow the given value:\n\
\ \"c\"")
(render "{% match a with @\"a\" %} {% with @\"b\" %} {% /match %}"
~json:{|{"a": "c"}|});
check_raises "Tuple size mismatch."
(E
"File \"<test>\"\n\
Render error.\n\
The data supplied does not match this template's interface.\n\
Path:\n\
\ input -> \"a\".\n\
Expected type:\n\
\ (string, string)\n\
Received value:\n\
\ [ \"a\" ]")
(render "{% match a with (a, b) %} {{ a }} {{ b }} {% /match %}"
~json:{|{"a": ["a"]}|});
check_raises "Bad unions are reported (1)."
(E
"File \"<test>\"\n\
Render error.\n\
The data supplied does not match this template's interface.\n\
Path:\n\
\ input -> \"a\".\n\
Expected type:\n\
\ {@tag: 1, a: string}\n\
Received value:\n\
\ { \"tag\": \"a\", \"a\": \"a\" }")
(render "{% match a with {@tag: 1, a} %} {{ a }} {% /match %}"
~json:{|{"a": {"tag": "a", "a": "a"}}|});
check_raises "Bad unions are reported (2)."
(E
"File \"<test>\"\n\
Render error.\n\
The data supplied does not match this template's interface.\n\
Path:\n\
\ input -> \"a\".\n\
Expected type:\n\
\ {@tag: 1, a: string}\n\
Received value:\n\
\ { \"tag\": 2, \"a\": \"a\" }")
(render "{% match a with {@tag: 1, a} %} {{ a }} {% /match %}"
~json:{|{"a": {"tag": 2, "a": "a"}}|});
check_raises "Looong paths format correctly."
(E
"File \"<test>\"\n\
Render error.\n\
The data supplied does not match this template's interface.\n\
Path:\n\
\ input -> \"abc\" -> \"def\" -> \"ghi\" -> \"jkl\" -> \"mno\" -> \
\"pqr\" -> \"stu\"\n\
\ -> \"vwx\" -> \"yz\".\n\
Expected type:\n\
\ int\n\
Received value:\n\
\ \"a\"")
(render
"{% match abc\n\
with {def: {ghi: {jkl: {mno: {pqr: {stu: {vwx: {yz: 1}}}}}}}} %}\n\
{% with _ %} {% /match %}"
~json:
{|{"abc":
{"def": {"ghi": {"jkl": {"mno": {"pqr": {"stu": {"vwx":
{"yz": "a"}}}}}}}}
}|})
let interface_parse () =
let open Alcotest in
check_raises "Invalid field names."
(E
"File \"<test>\", 1:27-1:31\n\
Parse error.\n\
This is not a valid field name.\n")
(render "{% interface a = {a: int, with: string } / %}");
check_raises "Missing , or }."
(E "File \"<test>\", 1:26-1:27\nParse error.\nExpected a ',' or '}'.\n")
(render "{% interface a = {a: int b: string } / %}");
check_raises "Bad prop name (1)."
(E
"File \"<test>\", 1:14-1:18\n\
Parse error.\n\
This is not a valid prop name.\n")
(render "{% interface with = int / %}");
check_raises "Bad prop name (2)."
(E
"File \"<test>\", 1:22-1:26\n\
Parse error.\n\
This is not a valid prop name.\n")
(render "{% interface x = int with = int / %}");
check_raises "Bad token after a variant (1)."
(E
"File \"<test>\", 1:24-1:28\n\
Parse error.\n\
This is not a valid prop name. You possibly forgot a '|'.\n")
(render "{% interface x={@a: 1} with / %}");
check_raises "Bad token after a variant (2)."
(E
"File \"<test>\", 1:21-1:25\n\
Parse error.\n\
This is not a valid prop name. You possibly forgot a '|'.\n")
(render "{% interface x=@\"a\" with / %}");
check_raises "Bad token after a variant (3)."
(E
"File \"<test>\", 1:19-1:23\n\
Parse error.\n\
This is not a valid prop name. You possibly forgot a '|'.\n")
(render "{% interface x=@0 with / %}");
check_raises "Bad token after a variant (4)."
(E
"File \"<test>\", 1:22-1:26\n\
Parse error.\n\
This is not a valid prop name. You possibly forgot a '|'.\n")
(render "{% interface x=false with / %}");
check_raises "Missing equals."
(E "File \"<test>\", 1:16-1:19\nParse error.\nExpected an '='.\n")
(render "{% interface x int / %}");
check_raises "Invalid type (1)."
(E "File \"<test>\", 1:16-1:20\nParse error.\nThis is not a valid type.\n")
(render "{% interface x=with / %}");
check_raises "Invalid type (2)."
(E "File \"<test>\", 1:17-1:21\nParse error.\nThis is not a valid type.\n")
(render "{% interface x=?with / %}");
check_raises "Invalid type (3)."
(E "File \"<test>\", 1:17-1:21\nParse error.\nThis is not a valid type.\n")
(render "{% interface x=[with] / %}");
check_raises "Invalid type (4)."
(E "File \"<test>\", 1:17-1:21\nParse error.\nThis is not a valid type.\n")
(render "{% interface x={with: int} / %}");
check_raises "Invalid type (5)."
(E "File \"<test>\", 1:18-1:22\nParse error.\nThis is not a valid type.\n")
(render "{% interface x={@with: 1} / %}");
check_raises "Invalid type (6)."
(E "File \"<test>\", 1:20-1:24\nParse error.\nThis is not a valid type.\n")
(render "{% interface x={a: with} / %}");
check_raises "Invalid type (7)."
(E "File \"<test>\", 1:17-1:21\nParse error.\nThis is not a valid type.\n")
(render "{% interface x=<with> / %}");
check_raises "Invalid type (8)."
(E "File \"<test>\", 1:17-1:21\nParse error.\nThis is not a valid type.\n")
(render "{% interface x=(with) / %}");
check_raises "Invalid type (9)."
(E "File \"<test>\", 1:22-1:26\nParse error.\nThis is not a valid type.\n")
(render "{% interface x=(int, with) / %}");
check_raises "Missing colon (1)."
(E "File \"<test>\", 1:19-1:20\nParse error.\nExpected a ':'.\n")
(render "{% interface x={a b} / %}");
check_raises "Missing colon (2)."
(E "File \"<test>\", 1:20-1:21\nParse error.\nExpected a ':'.\n")
(render "{% interface x={@a b} / %}");
check_raises "Bad enum"
(E
"File \"<test>\", 1:17-1:18\n\
Parse error.\n\
Expected a string or an integer.\n")
(render "{% interface x=@a / %}");
check_raises "Bad token after record pipe."
(E
"File \"<test>\", 1:26-1:27\n\
Parse error.\n\
Expected a record type or an '...'.\n")
(render "{% interface x={@a: 1} | y / %}");
check_raises "Bad token after string enum pipe."
(E
"File \"<test>\", 1:23-1:24\n\
Parse error.\n\
Expected an enum value or an '...'.\n")
(render "{% interface x=@\"a\" | y / %}");
check_raises "Bad token after int enum pipe."
(E
"File \"<test>\", 1:21-1:22\n\
Parse error.\n\
Expected an enum value or an '...'.\n")
(render "{% interface x=@0 | y / %}");
check_raises "Missing >"
(E "File \"<test>\", 1:20-1:21\nParse error.\nExpected a '>'.\n")
(render "{% interface x=<int} / %}");
check_raises "Missing ]"
(E "File \"<test>\", 1:20-1:21\nParse error.\nExpected a ']'.\n")
(render "{% interface x=[int} / %}");
check_raises "Missing )"
(E "File \"<test>\", 1:20-1:21\nParse error.\nExpected a ')'.\n")
(render "{% interface x=(int} / %}");
check_raises "Bad string enum"
(E "File \"<test>\", 1:24-1:25\nParse error.\nExpected a string.\n")
(render "{% interface x=@\"a\" | @0 / %}");
check_raises "Bad int enum"
(E "File \"<test>\", 1:22-1:25\nParse error.\nExpected an integer.\n")
(render "{% interface x=@0 | @\"a\" / %}");
check_raises "Bad boolean"
(E "File \"<test>\", 1:24-1:25\nParse error.\nExpected a boolean.\n")
(render "{% interface x=false | @0 / %}")
let interface_type_parse () =
let open Alcotest in
check_raises "Duplicate declarations"
(E
"File \"<test>\", 1:20-1:28\n\
Type error.\n\
Prop 'x' is already defined in the interface.")
(render "{% interface x=int x=string / %}");
check_raises "Non-existent type names."
(E "File \"<test>\", 1:16-1:20\nType error.\nThere is no type named 'lmao'.")
(render "{% interface x=lmao / %}");
check_raises "Untagged unions (1)"
(E
"File \"<test>\", 1:18-1:26\n\
Type error.\n\
You cannot union records without a '@' tag field.")
(render "{% interface x = {a: int} | {b: string} / %}");
check_raises "Untagged unions (2)"
(E
"File \"<test>\", 1:38-1:49\n\
Type error.\n\
You cannot union records without a '@' tag field.")
(render "{% interface x = {@tag: 1, a: int} | {b: string} / %}");
check_raises "Tagged unions with mismatched tag names"
(E
"File \"<test>\", 1:30-1:42\n\
Type error.\n\
This record has tag field '@badtag' instead of '@tag'.")
(render "{% interface x = {@tag: 1} | {@badtag: 2} / %}");
check_raises "Duplicate tags."
(E
"File \"<test>\", 1:30-1:39\n\
Type error.\n\
Tag value '1' is already used in this union.")
(render "{% interface x = {@tag: 1} | {@tag: 1} / %}");
check_raises "Tag type error: int <> string."
(E
"File \"<test>\", 1:37-1:40\n\
Type error.\n\
Type mismatch.\n\
Expected:\n\
\ int\n\
Received:\n\
\ string")
(render "{% interface x = {@tag: 1} | {@tag: \"a\"} / %}");
check_raises "Tag type error: string <> bool."
(E
"File \"<test>\", 1:39-1:43\n\
Type error.\n\
Type mismatch.\n\
Expected:\n\
\ string\n\
Received:\n\
\ true")
(render "{% interface x = {@tag: \"a\"} | {@tag: true} / %}");
check_raises "Tag type error: bool <> int."
(E
"File \"<test>\", 1:41-1:44\n\
Type error.\n\
Type mismatch.\n\
Expected:\n\
\ false | true\n\
Received:\n\
\ int")
(render "{% interface x = {@tag: false} | {@tag: 100} / %}")
let interface_typecheck () =
let open Alcotest in
check_raises "Interface type error: bool <> int."
(E
"File \"<test>\", 1:14-1:21\n\
Type error.\n\
This interface does not match the implementation.\n\
Prop name:\n\
\ x\n\
Interface:\n\
\ int\n\
Implementation:\n\
\ true")
(render "{% interface x = int / %}{% match x with true %}{% /match %}");
check_raises "Interface is missing props."
(E
"File \"<test>\", 1:4-1:23\n\
Type error.\n\
This interface does not match the implementation.\n\
Missing prop name:\n\
\ y\n\
Of type:\n\
\ string")
(render "{% interface x = int / %} {{ y }}");
check_raises "Interface is missing record fields."
(E
"File \"<test>\", 1:14-1:26\n\
Type error.\n\
This interface does not match the implementation.\n\
Prop name:\n\
\ x\n\
Interface:\n\
\ {a: int}\n\
Implementation:\n\
\ {a: string, b: string}")
(render
"{% interface x = {a: int} / %} \n\
{% match x with {a, b} %} {{ a }} {{ b }} {% /match %}");
check_raises "Interface is missing enum cases."
(E
"File \"<test>\", 1:14-1:31\n\
Type error.\n\
This interface does not match the implementation.\n\
Prop name:\n\
\ x\n\
Interface:\n\
\ @0 | @1 | ...\n\
Implementation:\n\
\ @0 | @1 | @2 | ...")
(render
"{% interface x = @0 | @1 | ... / %} \n\
{% match x with @0 %} {% with @1 %} {% with @2 %} {% with _ %}\n\
{% /match %}");
check_raises "Interface is missing union cases."
(E
"File \"<test>\", 1:14-1:53\n\
Type error.\n\
This interface does not match the implementation.\n\
Prop name:\n\
\ x\n\
Interface:\n\
\ {@tag: 0} | {@tag: 1, a: int} | ...\n\
Implementation:\n\
\ {@tag: 0} | {@tag: 1, a: string} | {@tag: 2, b: string} | ...")
(render
"{% interface x = {@tag: 0} | {@tag: 1, a: int} | ... / %} \n\
{% match x\n\
\ with {@tag: 0} %}\n\
{% with {@tag: 1, a} %} {{ a }}\n\
{% with {@tag: 2, b} %} {{ b }}\n\
{% with _ %}\n\
{% /match %}");
check_raises "Unknown is not equal to any other type."
(E
"File \"<test>\", 1:14-1:19\n\
Type error.\n\
This interface does not match the implementation.\n\
Prop name:\n\
\ x\n\
Interface:\n\
\ _\n\
Implementation:\n\
\ string")
(render "{% interface x = _ / %} {{ x }}")
let () =
let open Alcotest in
run "Errors"
[
( "Parser & lexer errors",
[
test_case "Illegal characters" `Quick illegal_chars;
test_case "Number parsing" `Quick number_parsing;
test_case "Illegal names" `Quick illegal_names;
test_case "Unterminated sections" `Quick unterminated;
test_case "Illegal escape sequences" `Quick illegal_escape;
test_case "Duplicate fields" `Quick dup_record_field;
test_case "Parser errors" `Quick parser_errors;
test_case "Interface parser errors" `Quick interface_parse;
test_case "Interface type parser errors" `Quick interface_type_parse;
] );
( "Type clash",
[
test_case "Echoes" `Quick type_error_echo;
test_case "Constants" `Quick type_error_const;
test_case "Nested types" `Quick type_error_nest;
test_case "Records" `Quick type_error_record;
test_case "Enums" `Quick type_error_enum;
test_case "Tagged unions" `Quick type_error_union;
test_case "Interface type errors" `Quick interface_typecheck;
] );
( "Typechecker errors",
[
test_case "Pattern count mismatch" `Quick pat_count_mismatch;
test_case "Multiple names bound" `Quick dup_name_destructure;
test_case "Variables in with clauses" `Quick vars_with_clauses;
test_case "Component errors" `Quick component_typechecker;
test_case "Unused bindings" `Quick unused_bindings;
] );
( "Matching errors",
[
test_case "Unused patterns" `Quick matching_unused;
test_case "Partial patterns" `Quick parmatch;
test_case "Partial patterns with complex trees" `Quick
merge_expanded_trees;
test_case "Other errors" `Quick bad_block;
] );
( "Other compile errors",
[
test_case "Dependency graphs" `Quick component_graph;
test_case "Known broken cases" `Quick known_broken;
] );
("Render errors", [ test_case "Decode errors" `Quick decode_mismatch ]);
]
| null | https://raw.githubusercontent.com/johnridesabike/acutis/f9144c8890c43627376e28991023a9dbe1b8d3f9/test/error_test.ml | ocaml | open Acutis
module RenderSync = Render.Make (Sync) (Acutis_json.Data)
let render ?(json = "{}") src () =
let temp = Compile.(from_string ~fname:"<test>" Components.empty src) in
let json = Yojson.Basic.from_string json in
ignore @@ RenderSync.make temp json
exception E = Error.Acutis_error
let illegal_chars () =
let open Alcotest in
check_raises "Illegal character 1"
(E "File \"<test>\", 1:9-1:10\nSyntax error.\n") (render "{% match*");
check_raises "Illegal character 2"
(E "File \"<test>\", 1:4-1:5\nSyntax error.\n") (render "{% .a %}");
check_raises "Illegal character 3"
(E "File \"<test>\", 1:12-1:13\nSyntax error.\n") (render "{% match a %%}");
check_raises "Illegal character 4"
(E "File \"<test>\", 1:6-1:7\nSyntax error.\n") (render "{{ a }%}")
let number_parsing () =
let open Alcotest in
check_raises "A number greater than the maximum integer is a syntax error."
(E "File \"<test>\", 1:10-1:29\nSyntax error.\n")
(render "{% match 9999999999999999999")
let illegal_names () =
let open Alcotest in
check_raises "Illegal name: echo null"
(E "File \"<test>\", 1:4-1:8\nSyntax error.\n") (render "{{ null }}");
check_raises "Illegal name: echo false"
(E "File \"<test>\", 1:4-1:9\nSyntax error.\n") (render "{{ false }}");
check_raises "Illegal name: echo true"
(E "File \"<test>\", 1:4-1:8\nSyntax error.\n") (render "{{ true }}");
check_raises "Illegal name: _"
(E
"File \"<test>\", 1:9-1:10\n\
Type error.\n\
Underscore ('_') is not a valid name.")
(render "{% map [_] with x %} {{ x }} {% /map %}")
let unterminated () =
let open Alcotest in
check_raises "Unterminated strings"
(E "File \"<test>\", 1:6-1:6\nSyntax error.\n") (render {|{{ "a|});
check_raises "Unterminated comments"
(E "File \"<test>\", 1:11-1:11\nSyntax error.\n") (render "{* {* a *}");
check_raises "Unterminated expressions"
(E "File \"<test>\", 1:9-1:9\nSyntax error.\n") (render "{% match")
let illegal_escape () =
let open Alcotest in
check_raises "Illegal escape sequence"
(E "File \"<test>\", 1:5-1:6\nSyntax error.\n") (render {|{{ "\a" }}|})
let parser_errors () =
let open Alcotest in
check_raises "Missing a closing component name"
(E "File \"<test>\", 1:19-1:20\nParse error.\nExpected a component name.\n")
(render "{% A %} abcd {% / a %}");
check_raises "Unclosed components (this one is confusing.)"
(E "File \"<test>\", 1:16-1:16\nParse error.\nUnclosed component.\n")
(render "{% A /A %} abcd");
check_raises "Unexpected tokens (1)"
(E
"File \"<test>\", 1:4-1:5\n\
Parse error.\n\
Expected a '%}', 'match', 'map', 'map_dict', or a component name.\n")
(render "{% a %}");
check_raises "Unexpected tokens (2)"
(E
"File \"<test>\", 1:5-1:6\n\
Parse error.\n\
Expected a '%}', 'match', 'map', 'map_dict', or a component name.\n")
(render "{%~ a %}");
check_raises "Unexpected tokens (3)"
(E
"File \"<test>\", 1:5-1:9\n\
Parse error.\n\
Expected a '%}', 'match', 'map', 'map_dict', or a component name.\n")
(render "{%~ with %}");
check_raises "Unexpected tokens (4)"
(E
"File \"<test>\", 1:10-1:11\n\
Parse error.\n\
Expected a '%}', 'match', 'map', 'map_dict', or a component name.\n")
(render "{% %}{%~ a %}");
check_raises "Unexpected tokens (5)"
(E "File \"<test>\", 1:40-1:41\nParse error.\nExpected a '%}'.\n")
(render "{% A %} {% match a with _ %} {% /match /A %}");
check_raises "Unexpected tokens (inside # blocks)"
(E
"File \"<test>\", 1:20-1:24\n\
Parse error.\n\
Expected a '%}', '#', 'match', 'map', 'map_dict', or a component name.\n")
(render "{% A a=#%} abcd {% with /A %}");
check_raises "Bad pattern (1)"
(E
"File \"<test>\", 1:10-1:13\n\
Parse error.\n\
This is not a valid pattern.\n")
(render "{% match ABC with a %} {% /match %}");
check_raises "Bad pattern (2)"
(E
"File \"<test>\", 1:11-1:14\n\
Parse error.\n\
This is not a valid pattern.\n")
(render "{% match !ABC with a %} {% /match %}");
check_raises "Bad pattern (3)"
(E
"File \"<test>\", 1:11-1:14\n\
Parse error.\n\
This is not a valid pattern.\n")
(render "{% match !ABC with a %} {% /match %}");
check_raises "Bad pattern (4)"
(E
"File \"<test>\", 1:11-1:14\n\
Parse error.\n\
This is not a valid pattern.\n")
(render "{% match @ABC with a %} {% /match %}");
check_raises "Bad pattern (5)"
(E
"File \"<test>\", 1:13-1:16\n\
Parse error.\n\
This is not a valid pattern.\n")
(render "{% match a, ABC with a %} {% /match %}");
check_raises "Bad pattern (6)"
(E
"File \"<test>\", 1:13-1:16\n\
Parse error.\n\
This is not a valid pattern.\n")
(render "{% map_dict ABC with a %} {% /map_dict %}");
check_raises "Bad pattern (7)"
(E "File \"<test>\", 1:8-1:11\nParse error.\nThis is not a valid pattern.\n")
(render "{% map ABC with a %} {% /map %}");
check_raises "Bad pattern (8)"
(E
"File \"<test>\", 1:14-1:18\n\
Parse error.\n\
This is not a valid pattern.\n")
(render "{% match {a: with %} {% /match %}");
check_raises "Bad pattern (9)"
(E
"File \"<test>\", 1:12-1:16\n\
Parse error.\n\
This is not a valid pattern.\n")
(render "{% match ( with %} {% /match %}");
check_raises "Bad pattern (10)"
(E
"File \"<test>\", 1:12-1:16\n\
Parse error.\n\
This is not a valid pattern.\n")
(render "{% match [ with %} {% /match %}");
check_raises "Bad pattern (11)"
(E
"File \"<test>\", 1:15-1:19\n\
Parse error.\n\
This is not a valid pattern.\n")
(render "{% match [... with %} {% /match %}");
check_raises "Bad pattern (12)"
(E
"File \"<test>\", 1:14-1:18\n\
Parse error.\n\
This is not a valid pattern.\n")
(render "{% match [a, with %} {% /match %}");
check_raises "Bad pattern (13)"
(E
"File \"<test>\", 1:18-1:22\n\
Parse error.\n\
This is not a valid pattern.\n")
(render "{% match [a, ... with %} {% /match %}");
check_raises "Unclosed < (4)"
(E
"File \"<test>\", 1:14-1:18\n\
Parse error.\n\
This is not a valid pattern.\n")
(render "{% match <a: with %} {% /match %}");
check_raises "Illegal pattern after with"
(E
"File \"<test>\", 1:17-1:20\n\
Parse error.\n\
This is not a valid pattern.\n")
(render "{% match a with Abc %} {% /match %}");
check_raises "Bad pattern (14)"
(E "File \"<test>\", 1:8-1:11\nParse error.\nThis is not a valid pattern.\n")
(render "{% Z a=ABC / %}");
check_raises "Bad echo (1)"
(E "File \"<test>\", 1:4-1:5\nParse error.\nThis is not a valid echo.\n")
(render "{{ ? }}");
check_raises "Bad echo (2)"
(E "File \"<test>\", 1:5-1:6\nParse error.\nThis is not a valid echo.\n")
(render "{{{ A }}}");
check_raises "Bad echo (3)"
(E "File \"<test>\", 1:8-1:9\nParse error.\nThis is not a valid echo.\n")
(render "{{ a ? ? }}");
check_raises "Bad echo (4)"
(E "File \"<test>\", 1:7-1:8\nParse error.\nThis is not a valid echo.\n")
(render "{{ %i ? }}");
check_raises "Bad echo (5)"
(E "File \"<test>\", 1:7-1:9\nParse error.\nExpected a '?' or '}}}'.\n")
(render "{{{ a }}");
check_raises "Bad echo (6)"
(E "File \"<test>\", 1:6-1:9\nParse error.\nExpected a '?' or '}}'.\n")
(render "{{ a }}}");
check_raises "Bad echo format (1)"
(E
"File \"<test>\", 1:6-1:7\n\
Parse error.\n\
This is missing a format specification.\n")
(render "{{ % a }}");
check_raises "Bad echo format (2)"
(E "File \"<test>\", 1:6-1:7\nParse error.\nExpected an 'i' format type.\n")
(render "{{ %,b a }}");
check_raises "Bad echo format (3)"
(E "File \"<test>\", 1:6-1:7\nParse error.\nExpected a number.\n")
(render "{{ %.f a }}");
check_raises "Bad echo format (4)"
(E
"File \"<test>\", 1:7-1:8\n\
Parse error.\n\
Expected an 'f', 'e', or 'g' format type.\n")
(render "{{ %.2b a }}");
check_raises "Bad prop (1)"
(E
"File \"<test>\", 1:6-1:10\n\
Parse error.\n\
This is not a valid component prop.\n")
(render "{% Z null=1 / %}");
check_raises "Bad prop (2)"
(E
"File \"<test>\", 1:8-1:9\n\
Parse error.\n\
This is not a valid component prop.\n")
(render "{% A a # %}");
check_raises "Bad prop (3)"
(E
"File \"<test>\", 1:8-1:9\n\
Parse error.\n\
This is not a valid component prop.\n")
(render "{% A b # %}");
check_raises "Illegal field name (1)"
(E
"File \"<test>\", 1:12-1:16\n\
Parse error.\n\
This is not a valid field name.\n")
(render "{% match { with %} {% /match %}");
check_raises "Illegal field name (2)"
(E
"File \"<test>\", 1:13-1:17\n\
Parse error.\n\
This is not a valid field name.\n")
(render "{% match {@ with %} {% /match %}");
check_raises "Illegal field name (3)"
(E
"File \"<test>\", 1:14-1:18\n\
Parse error.\n\
This is not a valid field name.\n")
(render "{% match {a, with %} {% /match %}");
check_raises "Illegal field name (4)"
(E
"File \"<test>\", 1:12-1:16\n\
Parse error.\n\
This is not a valid field name.\n")
(render "{% match < with %} {% /match %}");
check_raises "Illegal field name (5)"
(E
"File \"<test>\", 1:14-1:18\n\
Parse error.\n\
This is not a valid field name.\n")
(render "{% match <a, with %} {% /match %}");
check_raises "Unclosed { (1)"
(E
"File \"<test>\", 1:13-1:17\n\
Parse error.\n\
Expected a ',', ':', or '}'.\n")
(render "{% match {a with %} {% /match %}");
check_raises "Unclosed { (2)"
(E "File \"<test>\", 1:15-1:19\nParse error.\nExpected a ':'.\n")
(render "{% match {\"a\" with %} {% /match %}");
check_raises "Unclosed { (2)"
(E "File \"<test>\", 1:15-1:19\nParse error.\nExpected a ',' or '}'.\n")
(render "{% match {a:0 with %} {% /match %}");
check_raises "Unclosed ("
(E "File \"<test>\", 1:13-1:17\nParse error.\nExpected a ',' or ')'.\n")
(render "{% match (a with %} {% /match %}");
check_raises "Unclosed [ (1)"
(E
"File \"<test>\", 1:13-1:17\n\
Parse error.\n\
Expected a ',', '...', or ']'.\n")
(render "{% match [a with %} {% /match %}");
check_raises "Unclosed [ (2)"
(E "File \"<test>\", 1:19-1:23\nParse error.\nExpected a ']'.\n")
(render "{% match [a, ...b with %} {% /match %}");
check_raises "Unclosed < (1)"
(E
"File \"<test>\", 1:13-1:17\n\
Parse error.\n\
Expected a ',', ':', or '>'.\n")
(render "{% match <a with %} {% /match %}");
check_raises "Unclosed < (2)"
(E "File \"<test>\", 1:15-1:19\nParse error.\nExpected a ':'.\n")
(render "{% match <\"a\" with %} {% /match %}");
check_raises "Unclosed < (3)"
(E "File \"<test>\", 1:15-1:19\nParse error.\nExpected a ',' or '>'.\n")
(render "{% match <a:0 with %} {% /match %}");
check_raises "Missing commas in match/map patterns (1)"
(E
"File \"<test>\", 1:12-1:13\n\
Parse error.\n\
Sequential patterns must be separated by a ','.\n")
(render "{% match a b with a b %} {% /match %}");
check_raises "Missing commas in match/map patterns (2)"
(E
"File \"<test>\", 1:19-1:20\n\
Parse error.\n\
Sequential patterns must be separated by a ','.\n")
(render "{% match a with a b %} {% /match %}");
check_raises "Missing commas in match/map patterns (3)"
(E
"File \"<test>\", 1:15-1:16\n\
Parse error.\n\
Sequential patterns must be separated by a ','.\n")
(render "{% map_dict a b with a %} {% /map_dict %}");
check_raises "Missing commas in match/map patterns (4)"
(E
"File \"<test>\", 1:10-1:11\n\
Parse error.\n\
Sequential patterns must be separated by a ','.\n")
(render "{% map a b with a %} {% /map %}");
check_raises "Unmatched match"
(E
"File \"<test>\", 1:26-1:26\n\
Parse error.\n\
Unclosed block. Expected a '{% /' somewhere.\n")
(render "{% match x with true %} b");
check_raises "Missing /match"
(E "File \"<test>\", 1:26-1:29\nParse error.\nExpected a '/match'.\n")
(render "{% match x with x %} {% /map %}");
check_raises "Missing /map"
(E "File \"<test>\", 1:24-1:29\nParse error.\nExpected a '/map'.\n")
(render "{% map x with x %} {% /match %}");
check_raises "Missing /map_dict"
(E "File \"<test>\", 1:29-1:32\nParse error.\nExpected a '/map_dict'.\n")
(render "{% map_dict x with x %} {% /map %}");
check_raises "Unseparated echoes"
(E "File \"<test>\", 1:6-1:7\nParse error.\nExpected a '?' or '}}'.\n")
(render "{{ a b }}");
check_raises "# Blocks must contain text"
(E "File \"<test>\", 1:10-1:13\nParse error.\nExpected a '%}'.\n")
(render "{% A a=# abc # / %}")
let dup_record_field () =
let open Alcotest in
check_raises "Duplicate field"
(E "File \"<test>\", 1:18-1:30\nParse error.\nDuplicate field 'a'.")
(render {|{% match a with {a: 0, a: "a"} %} {% with _ %} {% /match %}|});
check_raises "Duplicate tag field"
(E "File \"<test>\", 1:18-1:31\nParse error.\nDuplicate field 'a'.")
(render {|{% match a with {@a: 0, a: "a"} %} {% with _ %} {% /match %}|});
check_raises "Duplicate dict field"
(E "File \"<test>\", 1:18-1:30\nParse error.\nDuplicate field 'a'.")
(render {|{% match a with <a: 0, a: "a"> %} {% with _ %} {% /match %}|});
check_raises "Multiple record tags"
(E
"File \"<test>\", 1:18-1:32\n\
Parse error.\n\
This tagged record has multiple tags.")
(render {|{% match a with {@a: 0, @b: "a"} %} {% with _ %} {% /match %}|})
let pat_count_mismatch () =
let open Alcotest in
check_raises "Pattern count mismatch 1"
(E "File \"<test>\", 1:4-1:42\nType error.\nPattern count mismatch.")
(render "{% match a, b, c with 1, 2 %} d {% /match %}");
check_raises "Pattern count mismatch 2"
(E "File \"<test>\", 1:30-1:42\nType error.\nPattern count mismatch.")
(render "{% match a with 1, 2 %} d {% with 1, 2, 3 %} z {% /match %}");
check_raises "Pattern count mismatch (map)"
(E
"File \"<test>\", 1:4-1:56\n\
Type error.\n\
Expressions 'map' and 'map_dict' can only have one or two patterns for \
each\n\
'with' expression.")
(render "{% map a with 1, 2, 3 %} d {% with 4, 5, 6 %} z {% /map %}")
let dup_name_destructure () =
let open Alcotest in
check_raises "You can't bind a name more than once when destructuring."
(E
"File \"<test>\", 1:21-1:22\n\
Type error.\n\
The name 'x' is already bound in this pattern.")
(render "{% match a with [x, x] %} a {% with _ %} b {% /match %}")
let type_error_echo () =
let open Alcotest in
check_raises "Echoed string literals cannot appear before a ?."
(E
"File \"<test>\", 1:4-1:8\n\
Type error.\n\
Echoed string literals cannot appear before a ?.")
(render {|{{ "ab" ? "cd" }}|})
let type_error_const () =
let open Alcotest in
check_raises "String <> int"
(E
"File \"<test>\", 1:32-1:33\n\
Type error.\n\
Type mismatch.\n\
Expected:\n\
\ string\n\
Received:\n\
\ int")
(render {|{% match a with "a" %} {% with 1 %} {% with _ %} {% /match %}|});
check_raises "Float <> int"
(E
"File \"<test>\", 1:32-1:33\n\
Type error.\n\
Type mismatch.\n\
Expected:\n\
\ float\n\
Received:\n\
\ int")
(render {|{% match a with 0.0 %} {% with 1 %} {% with _ %} {% /match %}|});
check_raises "String <> float"
(E
"File \"<test>\", 1:32-1:35\n\
Type error.\n\
Type mismatch.\n\
Expected:\n\
\ string\n\
Received:\n\
\ float")
(render {|{% match a with "a" %} {% with 1.0 %} {% with _ %} {% /match %}|});
check_raises "Map list key type mismatch."
(E
"File \"<test>\", 1:4-1:55\n\
Type error.\n\
Type mismatch.\n\
Expected:\n\
\ int\n\
Received:\n\
\ string")
(render "{% map [1] with a, \"b\" %} {{ a }} {% with _ %} {% /map %}");
check_raises "Map dict key type mismatch."
(E
"File \"<test>\", 1:4-2:13\n\
Type error.\n\
Type mismatch.\n\
Expected:\n\
\ string\n\
Received:\n\
\ int")
(render
"{% map_dict <\"a\": 1> with a, 1 %} {{ a }} {% with _ %}\n\
{% /map_dict %}")
let type_error_nest () =
let open Alcotest in
check_raises "[int] <> [string]"
(E
"File \"<test>\", 2:10-2:11\n\
Type error.\n\
Type mismatch.\n\
Expected:\n\
\ [int]\n\
Received:\n\
\ [string]")
(render
"{% match a with [\"a\"] %} {% with _ %} {% /match %}\n\
{% match a with [1] %} {% with _ %} {% /match %}");
check_raises "{a: int} <> {a: float}"
(E
"File \"<test>\", 2:10-2:11\n\
Type error.\n\
Type mismatch.\n\
Expected:\n\
\ {a: float}\n\
Received:\n\
\ {a: int}")
(render
"{% match a with {a: 1} %} {% with _ %} {% /match %}\n\
{% match a with {a: 0.0} %} {% with _ %} {% /match %}");
check_raises "(string, _) <> (float, _)"
(E
"File \"<test>\", 2:10-2:11\n\
Type error.\n\
Type mismatch.\n\
Expected:\n\
\ (float, string)\n\
Received:\n\
\ (string, string)")
(render
"{% match a with (\"a\", a) %} {{ a }} {% with _ %} {% /match %}\n\
{% match a with (1.0, a) %} {{ a }} {% with _ %} {% /match %}");
check_raises "Tagged record <> untagged record"
(E
"File \"<test>\", 2:10-2:11\n\
Type error.\n\
Type mismatch.\n\
Expected:\n\
\ {a: int}\n\
Received:\n\
\ {@a: 1} | ...")
(render
"{% match a with {@a: 1} %} {% with _ %} {% /match %}\n\
{% match a with {a: 1} %} {% with _ %} {% /match %}");
check_raises "Dict <> record"
(E
"File \"<test>\", 2:10-2:11\n\
Type error.\n\
Type mismatch.\n\
Expected:\n\
\ {a: int}\n\
Received:\n\
\ <int>")
(render
"{% match a with <a: 1> %} {% with _ %} {% /match %}\n\
{% match a with {a: 1} %} {% with _ %} {% /match %}");
check_raises "?int <> int"
(E
"File \"<test>\", 2:10-2:11\n\
Type error.\n\
Type mismatch.\n\
Expected:\n\
\ int\n\
Received:\n\
\ ?int")
(render
"{% match a with !1 %} {% with _ %} {% /match %}\n\
{% match a with 1 %} {% with _ %} {% /match %}");
check_raises "2-tuple <> 3-tuple"
(E
"File \"<test>\", 2:10-2:11\n\
Type error.\n\
Type mismatch.\n\
Expected:\n\
\ (int, int, int)\n\
Received:\n\
\ (int, int)")
(render
"{% match a with (1, 2) %} {% with _ %} {% /match %}\n\
{% match a with (1, 2, 3) %} {% with _ %} {% /match %}")
let type_error_record () =
let open Alcotest in
check_raises "Records with missing fields (1)"
(E
"File \"<test>\", 1:26-1:32\n\
Type error.\n\
Type mismatch.\n\
Expected:\n\
\ {a: int}\n\
Received:\n\
\ {b: _}")
(render
"{% map [(1, {a: 1}), (2, {b: 2})] with (i, {a}) %}\n\
\ {{ %i i }} {{ %i a }} {% /map %}");
check_raises "Records with missing fields (2)"
(E
"File \"<test>\", 1:10-1:16\n\
Type error.\n\
Type mismatch.\n\
Expected:\n\
\ {a: _, b: _}\n\
Received:\n\
\ {a: _}")
(render "{% match {a: 1} with {a: _, b: _} %} {% /match %}");
let comps =
Compile.Components.(
make [ parse_string ~fname:"a.acutis" ~name:"A" "{{ a }}" ])
in
check_raises "Records with missing fields (Component)"
(E
"File \"<test>\", 1:4-1:7\n\
Type error.\n\
This is missing key 'a' of type:\n\
\ string") (fun () ->
ignore @@ Compile.from_string ~fname:"<test>" comps "{% A / %}")
let type_error_enum () =
let open Alcotest in
check_raises "Closed enum <> open enum"
(E
"File \"<test>\", 2:10-2:11\n\
Type error.\n\
Type mismatch.\n\
Expected:\n\
\ @1\n\
Received:\n\
\ @1 | @2 | ...")
(render
"{% match a with @1 %} {% with @2 %} {% with _ %} {% /match %}\n\
{% match a with @1 %} {% /match %}");
check_raises "Enum vars with no subset are reported."
(E
"File \"<test>\", 3:12-3:13\n\
Type error.\n\
Type mismatch.\n\
Expected:\n\
\ @1 | @2\n\
Received:\n\
\ @3 | @4")
(render
"{% match a with @1 %} {% with @2 %} {% /match %}\n\
{% match b with @3 %} {% with @4 %} {% /match %}\n\
{% map [a, b] with _ %} {% /map %}");
check_raises "Enum vars + literals with no subset are reported."
(E
"File \"<test>\", 2:12-2:14\n\
Type error.\n\
Type mismatch.\n\
Expected:\n\
\ @1 | @2\n\
Received:\n\
\ @3 | ...")
(render
"{% match a with @1 %} {% with @2 %} {% /match %}\n\
{% map [a, @3] with _ %} {% /map %}");
check_raises "Enum literals with no subset are reported (1)."
(E
"File \"<test>\", 1:10-1:12\n\
Type error.\n\
Type mismatch.\n\
Expected:\n\
\ @1\n\
Received:\n\
\ @0 | ...")
(render "{% match @0 with @1 %} {% /match %}");
check_raises "Enum literals with no subset are reported (2)."
(E
"File \"<test>\", 1:10-1:12\n\
Type error.\n\
Type mismatch.\n\
Expected:\n\
\ @\"a\"\n\
Received:\n\
\ @0 | ...")
(render "{% match @0 with @\"a\" %} {% /match %}");
check_raises "| false | true <> only false"
(E
"File \"<test>\", 1:10-1:14\n\
Type error.\n\
Type mismatch.\n\
Expected:\n\
\ false\n\
Received:\n\
\ false | true")
(render "{% match true with false %} {% /match %}")
let type_error_union () =
let open Alcotest in
check_raises "Int tag <> string tag"
(E
"File \"<test>\", 1:38-1:52\n\
Type error.\n\
Type mismatch.\n\
Expected:\n\
\ {@tag: 0}\n\
Received:\n\
\ {@tag: \"a\", b: _}")
(render
"{% match a with {@tag: 0} %} {% with {@tag: \"a\", b} %} {{ b }}\n\
{% /match %}");
check_raises "Random other tags don't compile."
(E
"File \"<test>\", 1:24-1:25\n\
Parse error.\n\
Only literal integer, string, and boolean values may be union tags.\n")
(render "{% match a with {@tag: []} %} {% /match %}");
check_raises "Tag names must be coherent."
(E
"File \"<test>\", 1:36-1:46\n\
Type error.\n\
Type mismatch.\n\
Expected:\n\
\ {@a: 0}\n\
Received:\n\
\ {@b: 1, c: _}")
(render
"{% match a with {@a: 0} %} {% with {@b: 1, c} %} {{ c }} {% /match %}")
let vars_with_clauses () =
let open Alcotest in
check_raises "Variable names must be coherent."
(E
"File \"<test>\", 2:16-2:17\n\
Type error.\n\
Variable 'b' must occur in each 'with' pattern.")
(render
"{% match a, b\n\
\ with null, !b\n\
\ with !a, null %}\n\
{% with !_, !_ with null, null %}\n\
{% /match %}");
check_raises "Variable types must be coherent."
(E
"File \"<test>\", 1:38-1:39\n\
Type error.\n\
Type mismatch.\n\
Expected:\n\
\ int\n\
Received:\n\
\ string")
(render
"{% match a, b with 1, \"a\" %} {% with a, _ with _, a %} {% /match %}")
let component_typechecker () =
let open Alcotest in
check_raises "Component names match"
(E
"File \"<test>\", 1:4-1:14\n\
Type error.\n\
Component name mismatch.\n\
Expected:\n\
\ A.\n\
Received:\n\
\ B.")
(render "{% A %} {% /B %}")
let unused_bindings () =
let open Alcotest in
check_raises "Basic unused bindings are reported."
(E
"File \"<test>\", 1:18-1:19\n\
Type error.\n\
This variable is bound but never used:\n\
\ x")
(render "{% match a with {x} %} {% /match %}");
check_raises "Unused bindings are reported in the order they appear."
(E
"File \"<test>\", 1:21-1:22\n\
Type error.\n\
This variable is bound but never used:\n\
\ y")
(render
"{% match a with {x, y} %}\n\
\ {% match x with {z} %} {% /match %}\n\
{% /match %}");
check_raises "Shadowing bindings can report them as unused."
(E
"File \"<test>\", 1:26-1:27\n\
Type error.\n\
This variable is bound but never used:\n\
\ y")
(render
"{% match a, b with {x}, {y} %}\n\
\ {% match x with {y} %} {{ y }} {%/ match %}\n\
{% /match %}")
let matching_unused () =
let open Alcotest in
check_raises "Basic pattern (1)."
(E "File \"<test>\", 4:4-4:19\nMatching error.\nThis match case is unused.")
(render
"{% match a, b, c\n\
\ with 10, 11, 12 %}\n\
{% with _x, 21, 22 %}\n\
{% with 10, 11, 12 %}\n\
{% /match %}");
check_raises "Basic pattern (2)."
(E "File \"<test>\", 6:4-6:19\nMatching error.\nThis match case is unused.")
(render
"{% match a, b, c\n\
\ with 10, 11, 12 %}\n\
{% with _x, 21, 22 %}\n\
{% with 30, 31, 32 %}\n\
{% with 30, _y, 42 %}\n\
{% with 30, 31, 42 %}\n\
{% /match %}");
check_raises "Nest patterns merge into wildcard patterns correctly (1)."
(E "File \"<test>\", 1:33-1:48\nMatching error.\nThis match case is unused.")
(render "{% match a, b with _x, _y %} {% with (_, _), 40 %} {% /match %}");
check_raises "Nest patterns merge into wildcard patterns correctly (2)."
(E "File \"<test>\", 4:4-4:22\nMatching error.\nThis match case is unused.")
(render
"{% match a, b\n\
\ with _x, 1 %}\n\
{% with (\"a\", \"b\"), 10 %}\n\
{% with (\"a\", \"b\"), 1 %}\n\
{% /match %}")
let parmatch () =
let open Alcotest in
check_raises "Partial matching with integers."
(E
"File \"<test>\", 1:4-1:55\n\
Matching error.\n\
This pattern-matching is not exhaustive.\n\
Here's an example of a pattern which is not matched:\n\
\ _")
(render "{% match a with 0 with 10 with 20 with 30 %} {% /match %}");
check_raises "Partial matching with lists (1)."
(E
"File \"<test>\", 1:4-1:41\n\
Matching error.\n\
This pattern-matching is not exhaustive.\n\
Here's an example of a pattern which is not matched:\n\
\ [_, ..._]")
(render "{% match a with [] with [_] %} {% /match %}");
check_raises "Partial matching with lists (2)."
(E
"File \"<test>\", 1:4-1:33\n\
Matching error.\n\
This pattern-matching is not exhaustive.\n\
Here's an example of a pattern which is not matched:\n\
\ []")
(render "{% match a with [_] %} {% /match %}");
check_raises "Partial matching with Nullables (1)."
(E
"File \"<test>\", 1:4-1:34\n\
Matching error.\n\
This pattern-matching is not exhaustive.\n\
Here's an example of a pattern which is not matched:\n\
\ !_")
(render "{% match a with null %} {% /match %}");
check_raises "Partial matching with Nullables (2)."
(E
"File \"<test>\", 1:4-1:32\n\
Matching error.\n\
This pattern-matching is not exhaustive.\n\
Here's an example of a pattern which is not matched:\n\
\ null")
(render "{% match a with !_ %} {% /match %}");
check_raises "Partial matching with Nullables (3)."
(E
"File \"<test>\", 1:4-1:48\n\
Matching error.\n\
This pattern-matching is not exhaustive.\n\
Here's an example of a pattern which is not matched:\n\
\ !_")
(render "{% match a with !1 %} {% with null %} {% /match %}");
check_raises "Partial matching with enums nested in nullables."
(E
"File \"<test>\", 1:4-1:58\n\
Matching error.\n\
This pattern-matching is not exhaustive.\n\
Here's an example of a pattern which is not matched:\n\
\ !@1, _")
(render "{% match a, b with !@1, 2 %} {% with null, _ %} {% /match %}");
check_raises "Partial matching with records."
(E
"File \"<test>\", 1:4-1:56\n\
Matching error.\n\
This pattern-matching is not exhaustive.\n\
Here's an example of a pattern which is not matched:\n\
\ {a: _, b: _}")
(render "{% match a with {b: 10} %} {% with {a: 20} %} {% /match %}");
check_raises "Partial matching with dictionaries."
(E
"File \"<test>\", 1:4-1:61\n\
Matching error.\n\
This pattern-matching is not exhaustive.\n\
Here's an example of a pattern which is not matched:\n\
\ _")
(render "{% match a with <a: true> %} {% with <a: false> %} {% /match %}");
check_raises "Partial matching with unions (1)."
(E
"File \"<test>\", 1:4-2:10\n\
Matching error.\n\
This pattern-matching is not exhaustive.\n\
Here's an example of a pattern which is not matched:\n\
\ {@tag: 0, a: _}")
(render
"{% match a with {@tag: 0, a: 10} %} {% with {@tag: 1, b: 20} %}\n\
{% /match %}");
check_raises "Partial matching with unions (2)."
(E
"File \"<test>\", 1:4-2:10\n\
Matching error.\n\
This pattern-matching is not exhaustive.\n\
Here's an example of a pattern which is not matched:\n\
\ {@tag: false, b: _}")
(render
"{% match a with {@tag: true, a: 10} %}{% with {@tag: false, b: 20} %}\n\
{% /match %}");
check_raises "Partial matching with unions (3)."
(E
"File \"<test>\", 1:4-2:10\n\
Matching error.\n\
This pattern-matching is not exhaustive.\n\
Here's an example of a pattern which is not matched:\n\
\ {@tag: true, a: _}")
(render
"{% match a with {@tag: true, a: 10} %} {% with {@tag: false, b: _} %}\n\
{% /match %}");
check_raises "Partial matching with records."
(E
"File \"<test>\", 1:4-3:10\n\
Matching error.\n\
This pattern-matching is not exhaustive.\n\
Here's an example of a pattern which is not matched:\n\
\ {favoriteColor: _, firstName: _}")
(render
"{% match a with {firstName: name, favoriteColor: \"green\"} %}\n\
{{ name }}'s favorite color is green.\n\
{% /match %}");
check_raises "Partial lists print correctly."
(E
"File \"<test>\", 1:5-5:10\n\
Matching error.\n\
This pattern-matching is not exhaustive.\n\
Here's an example of a pattern which is not matched:\n\
\ {@kind: \"anonymous\", books: _}")
(render
"{%~ match author\n\
\ with {@kind: \"person\", name: _, books: [_newest, ..._older]} %}\n\
{%~ with {@kind: \"anonymous\", books: []} %}\n\
\ This author hasn't published any books.\n\
{% /match %}")
let merge_expanded_trees () =
let open Alcotest in
check_raises "Both nil and cons paths fail to merge into a wildcard."
(E "File \"<test>\", 6:9-6:19\nMatching error.\nThis match case is unused.")
(render
{|
{% match a, b
with 1, _ %}
{% with _, !1 %}
{% with _, null %}
{% with 1, !2 %}
{% with _, _ %}
{% /match %}|})
let bad_block () =
let open Alcotest in
check_raises "Template blocks are not allowed in destructure patterns."
(E
"File \"<test>\", 1:21-1:28\n\
Type error.\n\
Template blocks are not allowed in a destructure pattern.")
(render "{% match a with {b: #%} {%#} %} {% /match %}")
let component_graph () =
let open Alcotest in
let a =
Compile.Components.parse_string ~fname:"a.acutis" ~name:"A" "{% B /%}"
in
let b =
Compile.Components.parse_string ~fname:"b.acutis" ~name:"B" "{% C /%}"
in
let c =
Compile.Components.parse_string ~fname:"c.acutis" ~name:"C" "{% D /%}"
in
let d =
Compile.Components.parse_string ~fname:"d.acutis" ~name:"D" "{% B /%}"
in
check_raises "Cyclic dependencies are reported."
(E "Compile error.\nDependency cycle detected.\nA -> B -> C -> D -> B")
(fun () -> ignore @@ Compile.Components.make [ a; b; c; d ]);
check_raises "Missing components are reported."
(E "Compile error.\nMissing template:\n D\nRequired by:\n C") (fun () ->
ignore @@ Compile.Components.make [ a; b; c ]);
check_raises "Missing components are reported (by root)."
(E "Compile error.\nMissing template:\n A\nRequired by:\n <test>")
(render "{% A /%}");
check_raises "Duplicate names are reported."
(E "Compile error.\nThere are multiple components with the name 'A'.")
(fun () -> ignore @@ Compile.Components.make [ a; b; a ])
let known_broken () =
let open Alcotest in
check_raises
"This error is incorrect. The compiler fails to detect the first unused \
wildcard case. I'm not fixing this error yet, but I'm keeping this test \
to track when it changes."
(E "File \"<test>\", 1:43-1:49\nMatching error.\nThis match case is unused.")
(render "{% match a with (_, _) %} {% with _ %} {% with _ %} {% /match %}")
let decode_mismatch () =
let open Alcotest in
check_raises "Basic type mismatch."
(E
"File \"<test>\"\n\
Render error.\n\
The data supplied does not match this template's interface.\n\
Path:\n\
\ input -> \"a\" -> \"b\".\n\
Expected type:\n\
\ string\n\
Received value:\n\
\ []")
(render "{% match a with {b} %} {{ b }} {% /match %}"
~json:{|{"a": {"b": []}}|});
let json = {|{"a": "a", "b": true, "c": []}|} in
check_raises "Map type mismatch (1)."
(E
"File \"<test>\"\n\
Render error.\n\
The data supplied does not match this template's interface.\n\
Path:\n\
\ input -> \"a\".\n\
Expected type:\n\
\ [{a: string}]\n\
Received value:\n\
\ \"a\"")
(render "{% map a with {a} %}{{ a }}{% /map %}" ~json);
check_raises "Map type mismatch (2)."
(E
"File \"<test>\"\n\
Render error.\n\
The data supplied does not match this template's interface.\n\
Path:\n\
\ input -> \"a\".\n\
Expected type:\n\
\ [int]\n\
Received value:\n\
\ \"a\"")
(render "{% map [1, 2, ...a] with a %}{{ %i a }}{% /map %}" ~json);
check_raises "Missing bindings are reported"
(E
"File \"<test>\"\n\
Render error.\n\
The data supplied does not match this template's interface.\n\
Path:\n\
\ input.\n\
Expected type:\n\
\ {z: string}\n\
Input is missing key:\n\
\ z")
(render "{{ z }}" ~json);
check_raises "Bad enums are reported: boolean."
(E
"File \"<test>\"\n\
Render error.\n\
The data supplied does not match this template's interface.\n\
Path:\n\
\ input -> \"b\".\n\
Expected type:\n\
\ false\n\
This type does not allow the given value:\n\
\ true")
(render "{% match b with false %} {% /match %}" ~json);
check_raises "Bad enums are reported: int."
(E
"File \"<test>\"\n\
Render error.\n\
The data supplied does not match this template's interface.\n\
Path:\n\
\ input -> \"a\".\n\
Expected type:\n\
\ @1 | @2\n\
This type does not allow the given value:\n\
\ 3")
(render "{% match a with @1 %} {% with @2 %} {% /match %}"
~json:{|{"a": 3}|});
check_raises "Bad enums are reported: int."
(E
"File \"<test>\"\n\
Render error.\n\
The data supplied does not match this template's interface.\n\
Path:\n\
\ input -> \"a\".\n\
Expected type:\n\
\ @\"a\" | @\"b\"\n\
This type does not allow the given value:\n\
\ \"c\"")
(render "{% match a with @\"a\" %} {% with @\"b\" %} {% /match %}"
~json:{|{"a": "c"}|});
check_raises "Tuple size mismatch."
(E
"File \"<test>\"\n\
Render error.\n\
The data supplied does not match this template's interface.\n\
Path:\n\
\ input -> \"a\".\n\
Expected type:\n\
\ (string, string)\n\
Received value:\n\
\ [ \"a\" ]")
(render "{% match a with (a, b) %} {{ a }} {{ b }} {% /match %}"
~json:{|{"a": ["a"]}|});
check_raises "Bad unions are reported (1)."
(E
"File \"<test>\"\n\
Render error.\n\
The data supplied does not match this template's interface.\n\
Path:\n\
\ input -> \"a\".\n\
Expected type:\n\
\ {@tag: 1, a: string}\n\
Received value:\n\
\ { \"tag\": \"a\", \"a\": \"a\" }")
(render "{% match a with {@tag: 1, a} %} {{ a }} {% /match %}"
~json:{|{"a": {"tag": "a", "a": "a"}}|});
check_raises "Bad unions are reported (2)."
(E
"File \"<test>\"\n\
Render error.\n\
The data supplied does not match this template's interface.\n\
Path:\n\
\ input -> \"a\".\n\
Expected type:\n\
\ {@tag: 1, a: string}\n\
Received value:\n\
\ { \"tag\": 2, \"a\": \"a\" }")
(render "{% match a with {@tag: 1, a} %} {{ a }} {% /match %}"
~json:{|{"a": {"tag": 2, "a": "a"}}|});
check_raises "Looong paths format correctly."
(E
"File \"<test>\"\n\
Render error.\n\
The data supplied does not match this template's interface.\n\
Path:\n\
\ input -> \"abc\" -> \"def\" -> \"ghi\" -> \"jkl\" -> \"mno\" -> \
\"pqr\" -> \"stu\"\n\
\ -> \"vwx\" -> \"yz\".\n\
Expected type:\n\
\ int\n\
Received value:\n\
\ \"a\"")
(render
"{% match abc\n\
with {def: {ghi: {jkl: {mno: {pqr: {stu: {vwx: {yz: 1}}}}}}}} %}\n\
{% with _ %} {% /match %}"
~json:
{|{"abc":
{"def": {"ghi": {"jkl": {"mno": {"pqr": {"stu": {"vwx":
{"yz": "a"}}}}}}}}
}|})
let interface_parse () =
let open Alcotest in
check_raises "Invalid field names."
(E
"File \"<test>\", 1:27-1:31\n\
Parse error.\n\
This is not a valid field name.\n")
(render "{% interface a = {a: int, with: string } / %}");
check_raises "Missing , or }."
(E "File \"<test>\", 1:26-1:27\nParse error.\nExpected a ',' or '}'.\n")
(render "{% interface a = {a: int b: string } / %}");
check_raises "Bad prop name (1)."
(E
"File \"<test>\", 1:14-1:18\n\
Parse error.\n\
This is not a valid prop name.\n")
(render "{% interface with = int / %}");
check_raises "Bad prop name (2)."
(E
"File \"<test>\", 1:22-1:26\n\
Parse error.\n\
This is not a valid prop name.\n")
(render "{% interface x = int with = int / %}");
check_raises "Bad token after a variant (1)."
(E
"File \"<test>\", 1:24-1:28\n\
Parse error.\n\
This is not a valid prop name. You possibly forgot a '|'.\n")
(render "{% interface x={@a: 1} with / %}");
check_raises "Bad token after a variant (2)."
(E
"File \"<test>\", 1:21-1:25\n\
Parse error.\n\
This is not a valid prop name. You possibly forgot a '|'.\n")
(render "{% interface x=@\"a\" with / %}");
check_raises "Bad token after a variant (3)."
(E
"File \"<test>\", 1:19-1:23\n\
Parse error.\n\
This is not a valid prop name. You possibly forgot a '|'.\n")
(render "{% interface x=@0 with / %}");
check_raises "Bad token after a variant (4)."
(E
"File \"<test>\", 1:22-1:26\n\
Parse error.\n\
This is not a valid prop name. You possibly forgot a '|'.\n")
(render "{% interface x=false with / %}");
check_raises "Missing equals."
(E "File \"<test>\", 1:16-1:19\nParse error.\nExpected an '='.\n")
(render "{% interface x int / %}");
check_raises "Invalid type (1)."
(E "File \"<test>\", 1:16-1:20\nParse error.\nThis is not a valid type.\n")
(render "{% interface x=with / %}");
check_raises "Invalid type (2)."
(E "File \"<test>\", 1:17-1:21\nParse error.\nThis is not a valid type.\n")
(render "{% interface x=?with / %}");
check_raises "Invalid type (3)."
(E "File \"<test>\", 1:17-1:21\nParse error.\nThis is not a valid type.\n")
(render "{% interface x=[with] / %}");
check_raises "Invalid type (4)."
(E "File \"<test>\", 1:17-1:21\nParse error.\nThis is not a valid type.\n")
(render "{% interface x={with: int} / %}");
check_raises "Invalid type (5)."
(E "File \"<test>\", 1:18-1:22\nParse error.\nThis is not a valid type.\n")
(render "{% interface x={@with: 1} / %}");
check_raises "Invalid type (6)."
(E "File \"<test>\", 1:20-1:24\nParse error.\nThis is not a valid type.\n")
(render "{% interface x={a: with} / %}");
check_raises "Invalid type (7)."
(E "File \"<test>\", 1:17-1:21\nParse error.\nThis is not a valid type.\n")
(render "{% interface x=<with> / %}");
check_raises "Invalid type (8)."
(E "File \"<test>\", 1:17-1:21\nParse error.\nThis is not a valid type.\n")
(render "{% interface x=(with) / %}");
check_raises "Invalid type (9)."
(E "File \"<test>\", 1:22-1:26\nParse error.\nThis is not a valid type.\n")
(render "{% interface x=(int, with) / %}");
check_raises "Missing colon (1)."
(E "File \"<test>\", 1:19-1:20\nParse error.\nExpected a ':'.\n")
(render "{% interface x={a b} / %}");
check_raises "Missing colon (2)."
(E "File \"<test>\", 1:20-1:21\nParse error.\nExpected a ':'.\n")
(render "{% interface x={@a b} / %}");
check_raises "Bad enum"
(E
"File \"<test>\", 1:17-1:18\n\
Parse error.\n\
Expected a string or an integer.\n")
(render "{% interface x=@a / %}");
check_raises "Bad token after record pipe."
(E
"File \"<test>\", 1:26-1:27\n\
Parse error.\n\
Expected a record type or an '...'.\n")
(render "{% interface x={@a: 1} | y / %}");
check_raises "Bad token after string enum pipe."
(E
"File \"<test>\", 1:23-1:24\n\
Parse error.\n\
Expected an enum value or an '...'.\n")
(render "{% interface x=@\"a\" | y / %}");
check_raises "Bad token after int enum pipe."
(E
"File \"<test>\", 1:21-1:22\n\
Parse error.\n\
Expected an enum value or an '...'.\n")
(render "{% interface x=@0 | y / %}");
check_raises "Missing >"
(E "File \"<test>\", 1:20-1:21\nParse error.\nExpected a '>'.\n")
(render "{% interface x=<int} / %}");
check_raises "Missing ]"
(E "File \"<test>\", 1:20-1:21\nParse error.\nExpected a ']'.\n")
(render "{% interface x=[int} / %}");
check_raises "Missing )"
(E "File \"<test>\", 1:20-1:21\nParse error.\nExpected a ')'.\n")
(render "{% interface x=(int} / %}");
check_raises "Bad string enum"
(E "File \"<test>\", 1:24-1:25\nParse error.\nExpected a string.\n")
(render "{% interface x=@\"a\" | @0 / %}");
check_raises "Bad int enum"
(E "File \"<test>\", 1:22-1:25\nParse error.\nExpected an integer.\n")
(render "{% interface x=@0 | @\"a\" / %}");
check_raises "Bad boolean"
(E "File \"<test>\", 1:24-1:25\nParse error.\nExpected a boolean.\n")
(render "{% interface x=false | @0 / %}")
let interface_type_parse () =
let open Alcotest in
check_raises "Duplicate declarations"
(E
"File \"<test>\", 1:20-1:28\n\
Type error.\n\
Prop 'x' is already defined in the interface.")
(render "{% interface x=int x=string / %}");
check_raises "Non-existent type names."
(E "File \"<test>\", 1:16-1:20\nType error.\nThere is no type named 'lmao'.")
(render "{% interface x=lmao / %}");
check_raises "Untagged unions (1)"
(E
"File \"<test>\", 1:18-1:26\n\
Type error.\n\
You cannot union records without a '@' tag field.")
(render "{% interface x = {a: int} | {b: string} / %}");
check_raises "Untagged unions (2)"
(E
"File \"<test>\", 1:38-1:49\n\
Type error.\n\
You cannot union records without a '@' tag field.")
(render "{% interface x = {@tag: 1, a: int} | {b: string} / %}");
check_raises "Tagged unions with mismatched tag names"
(E
"File \"<test>\", 1:30-1:42\n\
Type error.\n\
This record has tag field '@badtag' instead of '@tag'.")
(render "{% interface x = {@tag: 1} | {@badtag: 2} / %}");
check_raises "Duplicate tags."
(E
"File \"<test>\", 1:30-1:39\n\
Type error.\n\
Tag value '1' is already used in this union.")
(render "{% interface x = {@tag: 1} | {@tag: 1} / %}");
check_raises "Tag type error: int <> string."
(E
"File \"<test>\", 1:37-1:40\n\
Type error.\n\
Type mismatch.\n\
Expected:\n\
\ int\n\
Received:\n\
\ string")
(render "{% interface x = {@tag: 1} | {@tag: \"a\"} / %}");
check_raises "Tag type error: string <> bool."
(E
"File \"<test>\", 1:39-1:43\n\
Type error.\n\
Type mismatch.\n\
Expected:\n\
\ string\n\
Received:\n\
\ true")
(render "{% interface x = {@tag: \"a\"} | {@tag: true} / %}");
check_raises "Tag type error: bool <> int."
(E
"File \"<test>\", 1:41-1:44\n\
Type error.\n\
Type mismatch.\n\
Expected:\n\
\ false | true\n\
Received:\n\
\ int")
(render "{% interface x = {@tag: false} | {@tag: 100} / %}")
let interface_typecheck () =
let open Alcotest in
check_raises "Interface type error: bool <> int."
(E
"File \"<test>\", 1:14-1:21\n\
Type error.\n\
This interface does not match the implementation.\n\
Prop name:\n\
\ x\n\
Interface:\n\
\ int\n\
Implementation:\n\
\ true")
(render "{% interface x = int / %}{% match x with true %}{% /match %}");
check_raises "Interface is missing props."
(E
"File \"<test>\", 1:4-1:23\n\
Type error.\n\
This interface does not match the implementation.\n\
Missing prop name:\n\
\ y\n\
Of type:\n\
\ string")
(render "{% interface x = int / %} {{ y }}");
check_raises "Interface is missing record fields."
(E
"File \"<test>\", 1:14-1:26\n\
Type error.\n\
This interface does not match the implementation.\n\
Prop name:\n\
\ x\n\
Interface:\n\
\ {a: int}\n\
Implementation:\n\
\ {a: string, b: string}")
(render
"{% interface x = {a: int} / %} \n\
{% match x with {a, b} %} {{ a }} {{ b }} {% /match %}");
check_raises "Interface is missing enum cases."
(E
"File \"<test>\", 1:14-1:31\n\
Type error.\n\
This interface does not match the implementation.\n\
Prop name:\n\
\ x\n\
Interface:\n\
\ @0 | @1 | ...\n\
Implementation:\n\
\ @0 | @1 | @2 | ...")
(render
"{% interface x = @0 | @1 | ... / %} \n\
{% match x with @0 %} {% with @1 %} {% with @2 %} {% with _ %}\n\
{% /match %}");
check_raises "Interface is missing union cases."
(E
"File \"<test>\", 1:14-1:53\n\
Type error.\n\
This interface does not match the implementation.\n\
Prop name:\n\
\ x\n\
Interface:\n\
\ {@tag: 0} | {@tag: 1, a: int} | ...\n\
Implementation:\n\
\ {@tag: 0} | {@tag: 1, a: string} | {@tag: 2, b: string} | ...")
(render
"{% interface x = {@tag: 0} | {@tag: 1, a: int} | ... / %} \n\
{% match x\n\
\ with {@tag: 0} %}\n\
{% with {@tag: 1, a} %} {{ a }}\n\
{% with {@tag: 2, b} %} {{ b }}\n\
{% with _ %}\n\
{% /match %}");
check_raises "Unknown is not equal to any other type."
(E
"File \"<test>\", 1:14-1:19\n\
Type error.\n\
This interface does not match the implementation.\n\
Prop name:\n\
\ x\n\
Interface:\n\
\ _\n\
Implementation:\n\
\ string")
(render "{% interface x = _ / %} {{ x }}")
let () =
let open Alcotest in
run "Errors"
[
( "Parser & lexer errors",
[
test_case "Illegal characters" `Quick illegal_chars;
test_case "Number parsing" `Quick number_parsing;
test_case "Illegal names" `Quick illegal_names;
test_case "Unterminated sections" `Quick unterminated;
test_case "Illegal escape sequences" `Quick illegal_escape;
test_case "Duplicate fields" `Quick dup_record_field;
test_case "Parser errors" `Quick parser_errors;
test_case "Interface parser errors" `Quick interface_parse;
test_case "Interface type parser errors" `Quick interface_type_parse;
] );
( "Type clash",
[
test_case "Echoes" `Quick type_error_echo;
test_case "Constants" `Quick type_error_const;
test_case "Nested types" `Quick type_error_nest;
test_case "Records" `Quick type_error_record;
test_case "Enums" `Quick type_error_enum;
test_case "Tagged unions" `Quick type_error_union;
test_case "Interface type errors" `Quick interface_typecheck;
] );
( "Typechecker errors",
[
test_case "Pattern count mismatch" `Quick pat_count_mismatch;
test_case "Multiple names bound" `Quick dup_name_destructure;
test_case "Variables in with clauses" `Quick vars_with_clauses;
test_case "Component errors" `Quick component_typechecker;
test_case "Unused bindings" `Quick unused_bindings;
] );
( "Matching errors",
[
test_case "Unused patterns" `Quick matching_unused;
test_case "Partial patterns" `Quick parmatch;
test_case "Partial patterns with complex trees" `Quick
merge_expanded_trees;
test_case "Other errors" `Quick bad_block;
] );
( "Other compile errors",
[
test_case "Dependency graphs" `Quick component_graph;
test_case "Known broken cases" `Quick known_broken;
] );
("Render errors", [ test_case "Decode errors" `Quick decode_mismatch ]);
]
| |
e83c1daeddf0cfcc4be35d3191c152c0d6f716360f663a92f0c7906d99636ffe | Concordium/concordium-client | SchemaParsingSpec.hs | -- This module contains unit tests testing that the client can correctly parse
-- specific JSON files according to the given schema.
# OPTIONS_GHC -Wno - deprecations #
module SimpleClientTests.SchemaParsingSpec where
import qualified Data.ByteString as BS
import qualified Data.Aeson as AE
import Concordium.Client.Types.Contract.Parameter
import Concordium.Client.Types.Contract.Schema
import Test.Hspec
import Test.HUnit
import Control.Monad.List (forM, forM_, when)
import Data.Serialize (runPut)
schemaParsingSpec :: Spec
schemaParsingSpec = describe "Smart contract schemas" $ do
schemaV1Parsing
schemaV2Parsing
schemaV3Parsing1
schemaV3Parsing2
-- Test that parsing a parameter that contains a
-- - ULEB128 value in the amount field.
- a set of 32 - byte bytearrays
-- - an Option<32-byte bytearray> value
-- works correctly.
schemaV1Parsing :: Spec
schemaV1Parsing = specify "Parse v1 schema" $ do
schemaBytes <- BS.readFile "test/data/schema0.schema"
json <- AE.decodeFileStrict "test/data/json0.json"
case (decodeVersionedModuleSchema schemaBytes, json) of
(Left err, _) -> assertFailure $ "Could not parse schema: " ++ err
(_, Nothing) -> assertFailure $ "json0 is not valid JSON."
(Right moduleSchema, Just value) ->
case lookupParameterSchema moduleSchema (ReceiveFuncName "recorder" "record") of
Nothing -> assertFailure "Schema missing for 'recorder'."
Just schema -> case putJSONUsingSchema schema value of
Left err -> assertFailure $ "Could not convert JSON according to the provided schema: " ++ err
Right _ -> return ()
-- | Test that parses a simple (String) parameter using a v2 schema.
schemaV2Parsing :: Spec
schemaV2Parsing = specify "Parse v2 schema" $ do
schemaBytes <- BS.readFile "test/data/schema1.schema"
json <- AE.decodeFileStrict "test/data/json1.json"
case (decodeVersionedModuleSchema schemaBytes, json) of
(Left err, _) -> assertFailure $ "Could not parse schema: " ++ err
(_, Nothing) -> assertFailure "json1 is not valid JSON."
(Right moduleSchema, Just value) ->
case lookupParameterSchema moduleSchema (ReceiveFuncName "schema" "receive") of
Nothing -> assertFailure "Schema missing for 'schema' contract."
Just schema -> case putJSONUsingSchema schema value of
Left err -> assertFailure $ "Could not convert JSON according to the provided schema: " ++ err
Right _ -> return ()
| Module schema V3 test data prefix .
prefix :: FilePath
prefix = "test/data/cis2_wCCD/"
-- | Read and parse the schema file used for testing
getSchema :: IO SchemaType
getSchema = do
schemaBytes <- BS.readFile $ prefix <> "cis2_wCCD_schema.bin"
moduleSchema <- case decodeVersionedModuleSchema schemaBytes of
(Left err) -> assertFailure $ "Could not parse schema: " ++ err
(Right moduleSchema) -> return moduleSchema
case lookupEventSchema moduleSchema "cis2_wCCD" of
Just schema -> return schema
Nothing -> assertFailure "No schema for named contract 'cis2_wCCD'."
| Test that deserializing and serializing a bytestring using a module schema containing TaggedEnum is the identity function .
schemaV3Parsing1 :: Spec
schemaV3Parsing1 = specify "Deserializing and serializing a bytestring using a module schema containing TaggedEnum is the identity function" $ do
schema <- getSchema
-- Assert that raw inputs can be deserialized to JSON according to schema.
json <- forM [0,1] $ \(i :: Integer) -> do
eventBytes <- BS.readFile $ prefix <> "event" <> show i <> ".bin"
case deserializeWithSchema schema eventBytes of
Left err -> assertFailure $ "Unable to decode event " <> show i <> ": " <> err
Right val -> return (i, eventBytes, val)
-- Assert that deserialized values can be encoded to the
forM_ json $ \(i, bs, val) -> do
case serializeWithSchema schema val of
Left err -> assertFailure $ "Unable to encode event " <> show i <> ": " <> err
Right bytes -> do
when (bytes /= bs) $ assertFailure ""
| Test that serializing JSON output using a module schema containing a TaggedEnum yields the corresponding expected raw output .
schemaV3Parsing2 :: Spec
schemaV3Parsing2 = specify "Serialize JSON using a module schema containing TaggedEnum" $ do
schema <- getSchema
-- Assert that we can parse and serialize all JSON files according to schema.
res <- forM [0,1] $ \(i :: Integer) -> do
json <- AE.decodeFileStrict $ prefix <> "event" <> show i <> ".json"
case json of
Just value -> case putJSONUsingSchema schema value of
Left err -> assertFailure $ "Could not convert JSON according to the provided schema: " ++ err
Right str -> return (i, str)
_ -> assertFailure "Input is not valid JSON."
-- Assert that serialized JSON files match expected binary output.
forM_ res $ \(i, put) -> do
eventBytes <- BS.readFile $ prefix <> "event" <> show i <> ".bin"
when (runPut put /= eventBytes) $ assertFailure $ "Serialized JSON does not match expected output for event " <> show i <> "." | null | https://raw.githubusercontent.com/Concordium/concordium-client/c1d23d2779579df9af82b7fffdf2c88e296a7fc6/test/SimpleClientTests/SchemaParsingSpec.hs | haskell | This module contains unit tests testing that the client can correctly parse
specific JSON files according to the given schema.
Test that parsing a parameter that contains a
- ULEB128 value in the amount field.
- an Option<32-byte bytearray> value
works correctly.
| Test that parses a simple (String) parameter using a v2 schema.
| Read and parse the schema file used for testing
Assert that raw inputs can be deserialized to JSON according to schema.
Assert that deserialized values can be encoded to the
Assert that we can parse and serialize all JSON files according to schema.
Assert that serialized JSON files match expected binary output. | # OPTIONS_GHC -Wno - deprecations #
module SimpleClientTests.SchemaParsingSpec where
import qualified Data.ByteString as BS
import qualified Data.Aeson as AE
import Concordium.Client.Types.Contract.Parameter
import Concordium.Client.Types.Contract.Schema
import Test.Hspec
import Test.HUnit
import Control.Monad.List (forM, forM_, when)
import Data.Serialize (runPut)
schemaParsingSpec :: Spec
schemaParsingSpec = describe "Smart contract schemas" $ do
schemaV1Parsing
schemaV2Parsing
schemaV3Parsing1
schemaV3Parsing2
- a set of 32 - byte bytearrays
schemaV1Parsing :: Spec
schemaV1Parsing = specify "Parse v1 schema" $ do
schemaBytes <- BS.readFile "test/data/schema0.schema"
json <- AE.decodeFileStrict "test/data/json0.json"
case (decodeVersionedModuleSchema schemaBytes, json) of
(Left err, _) -> assertFailure $ "Could not parse schema: " ++ err
(_, Nothing) -> assertFailure $ "json0 is not valid JSON."
(Right moduleSchema, Just value) ->
case lookupParameterSchema moduleSchema (ReceiveFuncName "recorder" "record") of
Nothing -> assertFailure "Schema missing for 'recorder'."
Just schema -> case putJSONUsingSchema schema value of
Left err -> assertFailure $ "Could not convert JSON according to the provided schema: " ++ err
Right _ -> return ()
schemaV2Parsing :: Spec
schemaV2Parsing = specify "Parse v2 schema" $ do
schemaBytes <- BS.readFile "test/data/schema1.schema"
json <- AE.decodeFileStrict "test/data/json1.json"
case (decodeVersionedModuleSchema schemaBytes, json) of
(Left err, _) -> assertFailure $ "Could not parse schema: " ++ err
(_, Nothing) -> assertFailure "json1 is not valid JSON."
(Right moduleSchema, Just value) ->
case lookupParameterSchema moduleSchema (ReceiveFuncName "schema" "receive") of
Nothing -> assertFailure "Schema missing for 'schema' contract."
Just schema -> case putJSONUsingSchema schema value of
Left err -> assertFailure $ "Could not convert JSON according to the provided schema: " ++ err
Right _ -> return ()
| Module schema V3 test data prefix .
prefix :: FilePath
prefix = "test/data/cis2_wCCD/"
getSchema :: IO SchemaType
getSchema = do
schemaBytes <- BS.readFile $ prefix <> "cis2_wCCD_schema.bin"
moduleSchema <- case decodeVersionedModuleSchema schemaBytes of
(Left err) -> assertFailure $ "Could not parse schema: " ++ err
(Right moduleSchema) -> return moduleSchema
case lookupEventSchema moduleSchema "cis2_wCCD" of
Just schema -> return schema
Nothing -> assertFailure "No schema for named contract 'cis2_wCCD'."
| Test that deserializing and serializing a bytestring using a module schema containing TaggedEnum is the identity function .
schemaV3Parsing1 :: Spec
schemaV3Parsing1 = specify "Deserializing and serializing a bytestring using a module schema containing TaggedEnum is the identity function" $ do
schema <- getSchema
json <- forM [0,1] $ \(i :: Integer) -> do
eventBytes <- BS.readFile $ prefix <> "event" <> show i <> ".bin"
case deserializeWithSchema schema eventBytes of
Left err -> assertFailure $ "Unable to decode event " <> show i <> ": " <> err
Right val -> return (i, eventBytes, val)
forM_ json $ \(i, bs, val) -> do
case serializeWithSchema schema val of
Left err -> assertFailure $ "Unable to encode event " <> show i <> ": " <> err
Right bytes -> do
when (bytes /= bs) $ assertFailure ""
| Test that serializing JSON output using a module schema containing a TaggedEnum yields the corresponding expected raw output .
schemaV3Parsing2 :: Spec
schemaV3Parsing2 = specify "Serialize JSON using a module schema containing TaggedEnum" $ do
schema <- getSchema
res <- forM [0,1] $ \(i :: Integer) -> do
json <- AE.decodeFileStrict $ prefix <> "event" <> show i <> ".json"
case json of
Just value -> case putJSONUsingSchema schema value of
Left err -> assertFailure $ "Could not convert JSON according to the provided schema: " ++ err
Right str -> return (i, str)
_ -> assertFailure "Input is not valid JSON."
forM_ res $ \(i, put) -> do
eventBytes <- BS.readFile $ prefix <> "event" <> show i <> ".bin"
when (runPut put /= eventBytes) $ assertFailure $ "Serialized JSON does not match expected output for event " <> show i <> "." |
609f951b8d28f6b5b7fa00da6767a4b2de6464d5e027b9ceb6ab9e08ed700f92 | lokke-org/lokke | test.scm | Copyright ( C ) 2019 - 2021 < >
SPDX - License - Identifier : LGPL-2.1 - or - later OR EPL-1.0 +
(define-module (lokke ns clojure test)
#:use-module ((lokke scm test-anything) #:select (tap-test-runner))
#:use-module ((srfi srfi-64)
#:select (test-assert
test-begin
test-end
test-equal
test-error
test-group
test-runner-current
test-runner-fail-count))
#:export (begin-tests
deftest
end-tests
is
testing)
#:duplicates (merge-generics replace warn-override-core warn last))
(define* (begin-tests suite-name)
(when (equal? "tap" (getenv "LOKKE_TEST_PROTOCOL"))
(test-runner-current (tap-test-runner)))
(test-begin (if (symbol? suite-name)
(symbol->string suite-name)
suite-name)))
(define-syntax testing
(syntax-rules ()
((_ what test ...) (test-group what (begin #t test ...)))))
;; FIXME: support *load-tests*?
;; FIXME: deftest should of course not be executing the code immediately
(define-syntax-rule (deftest name body ...)
(testing (symbol->string 'name)
body ...))
(define* (end-tests #:optional suite-name #:key exit?)
(let ((failed (test-runner-fail-count (test-runner-current))))
(if suite-name
(test-end (if (symbol? suite-name)
(symbol->string suite-name)
suite-name))
(test-end))
(when exit?
(exit (if (zero? failed) 0 2)))))
;; For now just supports (is x) and (is (= x y)), since that's easy to
do with srfi-64 , but this will almost certainly need an overhaul ,
;; and/or moving away from the srfi, and mere syntax pattern matching.
(define-syntax is
(syntax-rules (= thrown?) ;; FIXME: change literals to explicit pattern guards?
((_ (= expected expression)) (test-equal expected expression))
((_ (= expected expression) msg) (test-equal msg expected expression))
((_ (thrown? ex-type body ...)) (test-error ex-type body ...))
((_ expression) (test-assert expression))
((_ expression msg) (test-assert msg expression))))
| null | https://raw.githubusercontent.com/lokke-org/lokke/12b1ba89352338a69b1f7aeee15026c2e6ddd30e/mod/lokke/ns/clojure/test.scm | scheme | FIXME: support *load-tests*?
FIXME: deftest should of course not be executing the code immediately
For now just supports (is x) and (is (= x y)), since that's easy to
and/or moving away from the srfi, and mere syntax pattern matching.
FIXME: change literals to explicit pattern guards? | Copyright ( C ) 2019 - 2021 < >
SPDX - License - Identifier : LGPL-2.1 - or - later OR EPL-1.0 +
(define-module (lokke ns clojure test)
#:use-module ((lokke scm test-anything) #:select (tap-test-runner))
#:use-module ((srfi srfi-64)
#:select (test-assert
test-begin
test-end
test-equal
test-error
test-group
test-runner-current
test-runner-fail-count))
#:export (begin-tests
deftest
end-tests
is
testing)
#:duplicates (merge-generics replace warn-override-core warn last))
(define* (begin-tests suite-name)
(when (equal? "tap" (getenv "LOKKE_TEST_PROTOCOL"))
(test-runner-current (tap-test-runner)))
(test-begin (if (symbol? suite-name)
(symbol->string suite-name)
suite-name)))
(define-syntax testing
(syntax-rules ()
((_ what test ...) (test-group what (begin #t test ...)))))
(define-syntax-rule (deftest name body ...)
(testing (symbol->string 'name)
body ...))
(define* (end-tests #:optional suite-name #:key exit?)
(let ((failed (test-runner-fail-count (test-runner-current))))
(if suite-name
(test-end (if (symbol? suite-name)
(symbol->string suite-name)
suite-name))
(test-end))
(when exit?
(exit (if (zero? failed) 0 2)))))
do with srfi-64 , but this will almost certainly need an overhaul ,
(define-syntax is
((_ (= expected expression)) (test-equal expected expression))
((_ (= expected expression) msg) (test-equal msg expected expression))
((_ (thrown? ex-type body ...)) (test-error ex-type body ...))
((_ expression) (test-assert expression))
((_ expression msg) (test-assert msg expression))))
|
dfde3460297a67f1fdc32e5b958e3ed665bb6916ff04ecd984266dfffa98f6ac | CloudI/CloudI | ranch1_listener_sup.erl | Copyright ( c ) 2011 - 2016 , < >
%%
%% Permission to use, copy, modify, and/or distribute this software for any
%% purpose with or without fee is hereby granted, provided that the above
%% copyright notice and this permission notice appear in all copies.
%%
THE SOFTWARE IS PROVIDED " AS IS " 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(ranch1_listener_sup).
-behaviour(supervisor).
-export([start_link/6]).
-export([init/1]).
-spec start_link(ranch1:ref(), non_neg_integer(), module(), any(), module(), any())
-> {ok, pid()}.
start_link(Ref, NumAcceptors, Transport, TransOpts, Protocol, ProtoOpts) ->
MaxConns = proplists:get_value(max_connections, TransOpts, 1024),
ranch1_server:set_new_listener_opts(Ref, MaxConns, ProtoOpts),
supervisor:start_link(?MODULE, {
Ref, NumAcceptors, Transport, TransOpts, Protocol
}).
init({Ref, NumAcceptors, Transport, TransOpts, Protocol}) ->
AckTimeout = proplists:get_value(ack_timeout, TransOpts, 5000),
ConnType = proplists:get_value(connection_type, TransOpts, worker),
Shutdown = proplists:get_value(shutdown, TransOpts, 5000),
ChildSpecs = [
{ranch1_conns_sup, {ranch1_conns_sup, start_link,
[Ref, ConnType, Shutdown, Transport, AckTimeout, Protocol]},
permanent, infinity, supervisor, [ranch1_conns_sup]},
{ranch1_acceptors_sup, {ranch1_acceptors_sup, start_link,
[Ref, NumAcceptors, Transport, TransOpts]},
permanent, infinity, supervisor, [ranch1_acceptors_sup]}
],
{ok, {{rest_for_one, 1, 5}, ChildSpecs}}.
| null | https://raw.githubusercontent.com/CloudI/CloudI/3e45031c7ee3e974ead2612ea7dd06c9edf973c9/src/external/cloudi_x_ranch1/src/ranch1_listener_sup.erl | erlang |
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. | Copyright ( c ) 2011 - 2016 , < >
THE SOFTWARE IS PROVIDED " AS IS " AND THE AUTHOR DISCLAIMS ALL WARRANTIES
ANY SPECIAL , DIRECT , INDIRECT , OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE , DATA OR PROFITS , WHETHER IN AN
-module(ranch1_listener_sup).
-behaviour(supervisor).
-export([start_link/6]).
-export([init/1]).
-spec start_link(ranch1:ref(), non_neg_integer(), module(), any(), module(), any())
-> {ok, pid()}.
start_link(Ref, NumAcceptors, Transport, TransOpts, Protocol, ProtoOpts) ->
MaxConns = proplists:get_value(max_connections, TransOpts, 1024),
ranch1_server:set_new_listener_opts(Ref, MaxConns, ProtoOpts),
supervisor:start_link(?MODULE, {
Ref, NumAcceptors, Transport, TransOpts, Protocol
}).
init({Ref, NumAcceptors, Transport, TransOpts, Protocol}) ->
AckTimeout = proplists:get_value(ack_timeout, TransOpts, 5000),
ConnType = proplists:get_value(connection_type, TransOpts, worker),
Shutdown = proplists:get_value(shutdown, TransOpts, 5000),
ChildSpecs = [
{ranch1_conns_sup, {ranch1_conns_sup, start_link,
[Ref, ConnType, Shutdown, Transport, AckTimeout, Protocol]},
permanent, infinity, supervisor, [ranch1_conns_sup]},
{ranch1_acceptors_sup, {ranch1_acceptors_sup, start_link,
[Ref, NumAcceptors, Transport, TransOpts]},
permanent, infinity, supervisor, [ranch1_acceptors_sup]}
],
{ok, {{rest_for_one, 1, 5}, ChildSpecs}}.
|
fa9fdbde03f83d4b01b4455c7ba509e342f219aa428b9acbfbfb5a8f078a6d0b | kronkltd/jiksnu | user_test.clj | (ns jiksnu.modules.core.model.user-test
(:require [clj-factory.core :refer [factory fseq]]
[jiksnu.modules.core.actions.domain-actions :as actions.domain]
[jiksnu.modules.core.actions.user-actions :as actions.user]
[jiksnu.mock :as mock]
[jiksnu.modules.core.model.domain :as model.domain]
[jiksnu.modules.core.model.user :refer :all]
[jiksnu.test-helper :as th]
[midje.sweet :refer :all])
(:import jiksnu.modules.core.model.User))
(th/module-test ["jiksnu.modules.core"])
(facts "#'count-records"
(fact "when there aren't any items"
(drop!)
(count-records) => 0)
(fact "when there are items"
(drop!)
(let [n 15]
(dotimes [i n]
(mock/a-user-exists))
(count-records) => n)))
(facts "#'delete"
(let [item (mock/a-user-exists)]
(delete item) => item
(fetch-by-id (:_id item)) => nil))
(facts "#'drop!"
(dotimes [i 1]
(mock/a-user-exists))
(drop!)
(count-records) => 0)
(facts "#'fetch-by-id"
(fact "when the item doesn't exist"
(let [id "acct:"]
(fetch-by-id id) => nil?))
(fact "when the item exists"
(let [item (mock/a-user-exists)]
(fetch-by-id (:_id item)) => item)))
(facts "#'create"
(fact "when given valid params"
(let [params (actions.user/prepare-create
(factory :local-user))]
(create params) => (partial instance? User)))
(fact "when given invalid params"
(create {}) => (throws RuntimeException)))
(facts "#'fetch-all"
(fact "when there are no items"
(drop!)
(fetch-all) => empty?)
(fact "when there is more than a page of items"
(drop!)
(let [n 25]
(dotimes [i n]
(mock/a-user-exists))
(fetch-all) => #(= (count %) 20)
(fetch-all {} {:page 2}) => #(= (count %) (- n 20)))))
(facts "#'get-domain"
(fact "when passed nil"
(get-domain nil) => (throws Exception))
(fact "when passed a user"
(let [domain-a (actions.domain/current-domain)
user-a (mock/a-user-exists)]
(get-domain user-a) => domain-a)))
(facts "#'local?"
(fact "when passed a user"
(fact "and it's domain is the same as the current domain"
(let [user (mock/a-user-exists)]
(local? user) => true))
(fact "and it's domain is different from the current domain"
(let [user (mock/a-remote-user-exists)]
(local? user) => false))))
(facts "#'display-name"
(display-name .user.) => string?)
(facts "#'get-user"
(fact "when the user is found"
(let [user (mock/a-user-exists)
username (:username user)
domain (actions.user/get-domain user)]
(get-user username (:_id domain)) => user))
(fact "when the user is not found"
(drop!)
(let [username (fseq :id)
domain (mock/a-domain-exists)]
(get-user username (:_id domain)) => nil)))
(facts "#'fetch-by-domain"
(let [domain (actions.domain/current-domain)
user (mock/a-user-exists)]
(fetch-by-domain domain) => (contains user)))
(facts "#'user-meta-uri"
(fact "when the user's domain does not have a lrdd link"
(model.domain/drop!)
(let [user (mock/a-user-exists)]
(user-meta-uri user) => (throws RuntimeException)))
(fact "when the user's domain has a lrdd link"
(let [domain (mock/a-remote-domain-exists)
links [{:rel "lrdd"
:template "={uri}"}]]
(model.domain/add-links domain links)
(let [user (mock/a-remote-user-exists {:domain domain})]
(user-meta-uri user) => (str "=" (get-uri user))))))
| null | https://raw.githubusercontent.com/kronkltd/jiksnu/8c91e9b1fddcc0224b028e573f7c3ca2f227e516/test/jiksnu/modules/core/model/user_test.clj | clojure | (ns jiksnu.modules.core.model.user-test
(:require [clj-factory.core :refer [factory fseq]]
[jiksnu.modules.core.actions.domain-actions :as actions.domain]
[jiksnu.modules.core.actions.user-actions :as actions.user]
[jiksnu.mock :as mock]
[jiksnu.modules.core.model.domain :as model.domain]
[jiksnu.modules.core.model.user :refer :all]
[jiksnu.test-helper :as th]
[midje.sweet :refer :all])
(:import jiksnu.modules.core.model.User))
(th/module-test ["jiksnu.modules.core"])
(facts "#'count-records"
(fact "when there aren't any items"
(drop!)
(count-records) => 0)
(fact "when there are items"
(drop!)
(let [n 15]
(dotimes [i n]
(mock/a-user-exists))
(count-records) => n)))
(facts "#'delete"
(let [item (mock/a-user-exists)]
(delete item) => item
(fetch-by-id (:_id item)) => nil))
(facts "#'drop!"
(dotimes [i 1]
(mock/a-user-exists))
(drop!)
(count-records) => 0)
(facts "#'fetch-by-id"
(fact "when the item doesn't exist"
(let [id "acct:"]
(fetch-by-id id) => nil?))
(fact "when the item exists"
(let [item (mock/a-user-exists)]
(fetch-by-id (:_id item)) => item)))
(facts "#'create"
(fact "when given valid params"
(let [params (actions.user/prepare-create
(factory :local-user))]
(create params) => (partial instance? User)))
(fact "when given invalid params"
(create {}) => (throws RuntimeException)))
(facts "#'fetch-all"
(fact "when there are no items"
(drop!)
(fetch-all) => empty?)
(fact "when there is more than a page of items"
(drop!)
(let [n 25]
(dotimes [i n]
(mock/a-user-exists))
(fetch-all) => #(= (count %) 20)
(fetch-all {} {:page 2}) => #(= (count %) (- n 20)))))
(facts "#'get-domain"
(fact "when passed nil"
(get-domain nil) => (throws Exception))
(fact "when passed a user"
(let [domain-a (actions.domain/current-domain)
user-a (mock/a-user-exists)]
(get-domain user-a) => domain-a)))
(facts "#'local?"
(fact "when passed a user"
(fact "and it's domain is the same as the current domain"
(let [user (mock/a-user-exists)]
(local? user) => true))
(fact "and it's domain is different from the current domain"
(let [user (mock/a-remote-user-exists)]
(local? user) => false))))
(facts "#'display-name"
(display-name .user.) => string?)
(facts "#'get-user"
(fact "when the user is found"
(let [user (mock/a-user-exists)
username (:username user)
domain (actions.user/get-domain user)]
(get-user username (:_id domain)) => user))
(fact "when the user is not found"
(drop!)
(let [username (fseq :id)
domain (mock/a-domain-exists)]
(get-user username (:_id domain)) => nil)))
(facts "#'fetch-by-domain"
(let [domain (actions.domain/current-domain)
user (mock/a-user-exists)]
(fetch-by-domain domain) => (contains user)))
(facts "#'user-meta-uri"
(fact "when the user's domain does not have a lrdd link"
(model.domain/drop!)
(let [user (mock/a-user-exists)]
(user-meta-uri user) => (throws RuntimeException)))
(fact "when the user's domain has a lrdd link"
(let [domain (mock/a-remote-domain-exists)
links [{:rel "lrdd"
:template "={uri}"}]]
(model.domain/add-links domain links)
(let [user (mock/a-remote-user-exists {:domain domain})]
(user-meta-uri user) => (str "=" (get-uri user))))))
| |
a502dc0fde84fadb671cee57c60b86ad047806b55073169ab06f2006c714c471 | the-little-typer/pie | pie-info.rkt | #lang racket/base
(require (for-syntax racket/base syntax/parse))
(provide (all-defined-out))
(define-syntax (define-pie-keyword stx)
(syntax-parse stx
[(_ kw:id)
#'(define-syntax (kw inner-stx)
(syntax-parse inner-stx
#:literals (kw)
[kw #'(void)]
[(kw e (... ...)) #'(void e (... ...))]))]))
(define-syntax (define-pie-keywords stx)
(syntax-parse stx
[(_ kw:id ...)
#'(begin
(define-pie-keyword kw)
...)]))
(define-pie-keywords
U
Nat zero add1 which-Nat iter-Nat rec-Nat ind-Nat
-> → Π Pi ∏ λ lambda
quote Atom
car cdr cons Σ Sigma Pair
Trivial sole
List :: nil rec-List ind-List
Absurd ind-Absurd
= same replace trans cong symm ind-=
Vec vecnil vec:: head tail ind-Vec
Either left right ind-Either
TODO the
check-same claim define)
| null | https://raw.githubusercontent.com/the-little-typer/pie/a698d4cacd6823b5161221596d34bd17ce5282b8/pie-info.rkt | racket | #lang racket/base
(require (for-syntax racket/base syntax/parse))
(provide (all-defined-out))
(define-syntax (define-pie-keyword stx)
(syntax-parse stx
[(_ kw:id)
#'(define-syntax (kw inner-stx)
(syntax-parse inner-stx
#:literals (kw)
[kw #'(void)]
[(kw e (... ...)) #'(void e (... ...))]))]))
(define-syntax (define-pie-keywords stx)
(syntax-parse stx
[(_ kw:id ...)
#'(begin
(define-pie-keyword kw)
...)]))
(define-pie-keywords
U
Nat zero add1 which-Nat iter-Nat rec-Nat ind-Nat
-> → Π Pi ∏ λ lambda
quote Atom
car cdr cons Σ Sigma Pair
Trivial sole
List :: nil rec-List ind-List
Absurd ind-Absurd
= same replace trans cong symm ind-=
Vec vecnil vec:: head tail ind-Vec
Either left right ind-Either
TODO the
check-same claim define)
| |
51950c0f161ef62861a2363ad872f8c7216e5ec8c7fea38732548aec43b5dcbc | grasswire/chat-app | Queries.hs | # LANGUAGE TypeFamilies , OverloadedStrings , TypeSynonymInstances , FlexibleContexts #
module Queries where
import Import hiding ((==.), (>=.))
import qualified Database.Esqueleto as E
import Database.Esqueleto ((==.), (^.), (&&.), val, (?.))
import Database.Persist.Sql (rawSql)
import Database.Persist.Sql (fromSqlKey)
-- list of all channels along with their current members for the given user
usersChannelsWithMembers :: MonadIO m => Key User -> SqlPersistT m [(Entity Channel, E.Value (Maybe (Key User)))]
usersChannelsWithMembers userKey = do
myChannels <- userMemberships userKey
E.select $
E.from $ \(channel `E.LeftOuterJoin` membership) -> do
E.on (E.just (channel ^. ChannelId) ==. membership ?. MembershipChannel)
E.where_ (channel ^. ChannelId `E.in_` E.valList (E.unValue <$> myChannels) &&. membership ?. MembershipInChannel ==. E.just (E.val True))
return (channel, membership ?. MembershipUser)
usersChannels :: MonadIO m => Key User -> SqlPersistT m [Entity Channel]
usersChannels userKey = do
myChannels <- userMemberships userKey
E.select $
E.from $ \channel -> do
E.where_ (channel ^. ChannelId `E.in_` E.valList (E.unValue <$> myChannels))
return channel
-- list of users who are or were members of any channel I'm a member of
usersInUserChannels :: MonadIO m => Key User -> SqlPersistT m [Entity User]
usersInUserChannels userKey = do
myChannels <- userMemberships userKey
users <- usersInMyChans myChannels
E.select $
E.from $ \user -> do
E.where_ (user ^. UserId `E.in_` E.valList (E.unValue <$> users))
return user
where usersInMyChans chans = E.select $
E.from $ \membership -> do
E.where_ (membership ^. MembershipChannel `E.in_` E.valList (E.unValue <$> chans))
return (membership ^. MembershipUser)
-- list of current members for a given channel
membersByChannel :: MonadIO m => Key Channel -> SqlPersistT m [Key User]
membersByChannel chanKey = do
users <- E.select $
E.from $ \membership -> do
E.where_ (membership ^. MembershipChannel ==. val chanKey &&. membership ^. MembershipInChannel ==. E.val True)
return (membership ^. MembershipUser)
return (E.unValue <$> users)
-- list of users who are or were members for a given channel
usersByChannel :: MonadIO m => Key Channel -> SqlPersistT m [Entity User]
usersByChannel channel = do
users <- usersInChan
E.select $
E.from $ \user -> do
E.where_ (user ^. UserId `E.in_` E.valList (E.unValue <$> users))
return user
where usersInChan = E.select $
E.from $ \membership -> do
E.where_ (membership ^. MembershipChannel ==. val channel)
return (membership ^. MembershipUser)
userMemberships :: MonadIO m => Key User -> SqlPersistT m [E.Value (Key Channel)]
userMemberships userKey = E.select $
E.from $ \membership -> do
E.where_ (membership ^. MembershipUser ==. val userKey)
return (membership ^. MembershipChannel)
messageHistorySql :: Text
messageHistorySql = "select ?? from (select ROW_NUMBER() over (partition by channel order by timestamp desc)" <>
-- "as r, t.* from message t) message join shouldbechannel c on (c.id = message.channel) where message.r <= ? and message.channel in (" <>
"as r, t.* from message t) message join shouldbechannel c on (c.id = message.channel) where message.r <= ? and message.channel in ?" -- <>
-- intercalate "," (pack . show . fromSqlKey <$> channels) <> ");"
messageHistory :: MonadIO m => Int -> [Key Channel] -> ReaderT SqlBackend m [(Entity Message, Entity Channel)]
rawSql ( messageHistorySql ) [ PersistInt64 $ fromIntegral limit , PersistList ( PersistInt64 . fromSqlKey < $ > channels ) ] | null | https://raw.githubusercontent.com/grasswire/chat-app/a8ae4e782cacd902d7ec9c68c40a939cc5cabb0a/backend/Queries.hs | haskell | list of all channels along with their current members for the given user
list of users who are or were members of any channel I'm a member of
list of current members for a given channel
list of users who are or were members for a given channel
"as r, t.* from message t) message join shouldbechannel c on (c.id = message.channel) where message.r <= ? and message.channel in (" <>
<>
intercalate "," (pack . show . fromSqlKey <$> channels) <> ");" | # LANGUAGE TypeFamilies , OverloadedStrings , TypeSynonymInstances , FlexibleContexts #
module Queries where
import Import hiding ((==.), (>=.))
import qualified Database.Esqueleto as E
import Database.Esqueleto ((==.), (^.), (&&.), val, (?.))
import Database.Persist.Sql (rawSql)
import Database.Persist.Sql (fromSqlKey)
usersChannelsWithMembers :: MonadIO m => Key User -> SqlPersistT m [(Entity Channel, E.Value (Maybe (Key User)))]
usersChannelsWithMembers userKey = do
myChannels <- userMemberships userKey
E.select $
E.from $ \(channel `E.LeftOuterJoin` membership) -> do
E.on (E.just (channel ^. ChannelId) ==. membership ?. MembershipChannel)
E.where_ (channel ^. ChannelId `E.in_` E.valList (E.unValue <$> myChannels) &&. membership ?. MembershipInChannel ==. E.just (E.val True))
return (channel, membership ?. MembershipUser)
usersChannels :: MonadIO m => Key User -> SqlPersistT m [Entity Channel]
usersChannels userKey = do
myChannels <- userMemberships userKey
E.select $
E.from $ \channel -> do
E.where_ (channel ^. ChannelId `E.in_` E.valList (E.unValue <$> myChannels))
return channel
usersInUserChannels :: MonadIO m => Key User -> SqlPersistT m [Entity User]
usersInUserChannels userKey = do
myChannels <- userMemberships userKey
users <- usersInMyChans myChannels
E.select $
E.from $ \user -> do
E.where_ (user ^. UserId `E.in_` E.valList (E.unValue <$> users))
return user
where usersInMyChans chans = E.select $
E.from $ \membership -> do
E.where_ (membership ^. MembershipChannel `E.in_` E.valList (E.unValue <$> chans))
return (membership ^. MembershipUser)
membersByChannel :: MonadIO m => Key Channel -> SqlPersistT m [Key User]
membersByChannel chanKey = do
users <- E.select $
E.from $ \membership -> do
E.where_ (membership ^. MembershipChannel ==. val chanKey &&. membership ^. MembershipInChannel ==. E.val True)
return (membership ^. MembershipUser)
return (E.unValue <$> users)
usersByChannel :: MonadIO m => Key Channel -> SqlPersistT m [Entity User]
usersByChannel channel = do
users <- usersInChan
E.select $
E.from $ \user -> do
E.where_ (user ^. UserId `E.in_` E.valList (E.unValue <$> users))
return user
where usersInChan = E.select $
E.from $ \membership -> do
E.where_ (membership ^. MembershipChannel ==. val channel)
return (membership ^. MembershipUser)
userMemberships :: MonadIO m => Key User -> SqlPersistT m [E.Value (Key Channel)]
userMemberships userKey = E.select $
E.from $ \membership -> do
E.where_ (membership ^. MembershipUser ==. val userKey)
return (membership ^. MembershipChannel)
messageHistorySql :: Text
messageHistorySql = "select ?? from (select ROW_NUMBER() over (partition by channel order by timestamp desc)" <>
messageHistory :: MonadIO m => Int -> [Key Channel] -> ReaderT SqlBackend m [(Entity Message, Entity Channel)]
rawSql ( messageHistorySql ) [ PersistInt64 $ fromIntegral limit , PersistList ( PersistInt64 . fromSqlKey < $ > channels ) ] |
1158f177585eb40c3b78beef9e8230375e97474f600a450d4557520b319c5153 | Bogdanp/racket-dbg | server.rkt | #lang racket/base
(require racket/contract
"private/server.rkt")
(provide
(contract-out
[serve (->* ()
(#:host string?
#:port (integer-in 0 65535))
(-> void?))]))
| null | https://raw.githubusercontent.com/Bogdanp/racket-dbg/b17598a24d8c27a0b815d3fcae4da177a39378b1/dbg/server.rkt | racket | #lang racket/base
(require racket/contract
"private/server.rkt")
(provide
(contract-out
[serve (->* ()
(#:host string?
#:port (integer-in 0 65535))
(-> void?))]))
| |
4c20fe8d2c31aa7f1818619d9a253912165e8af685831a04975ac7888700d039 | Metaxal/quickscript-extra | info.rkt | #lang info
(define collection "quickscript-extra")
(define deps '("base"
"quickscript"
"at-exp-lib"
"drracket"
"gui-lib"
"pict-lib"
"racket-index"
"scribble-lib"
"search-list-box"
"srfi-lite-lib"
"net-lib"
"web-server-lib"))
(define build-deps '(#;"scribble-lib" "racket-doc" "rackunit-lib"))
(define scribblings '(("scribblings/quickscript-extra.scrbl" ())))
(define pkg-desc "Description Here")
(define version "0.0")
(define pkg-authors '(orseau))
| null | https://raw.githubusercontent.com/Metaxal/quickscript-extra/5cf24dd1b621a7cf0f23ee441f52334eafc45665/info.rkt | racket | "scribble-lib" "racket-doc" "rackunit-lib")) | #lang info
(define collection "quickscript-extra")
(define deps '("base"
"quickscript"
"at-exp-lib"
"drracket"
"gui-lib"
"pict-lib"
"racket-index"
"scribble-lib"
"search-list-box"
"srfi-lite-lib"
"net-lib"
"web-server-lib"))
(define scribblings '(("scribblings/quickscript-extra.scrbl" ())))
(define pkg-desc "Description Here")
(define version "0.0")
(define pkg-authors '(orseau))
|
d991ccd22b94483aa7c3a8ed5fb1db363bae8f45b4e00bf65d67f04e47972d07 | idris-lang/Idris-dev | ProofState.hs | |
Module : . Core . ProofState
Description : Proof state implementation .
License : : The Idris Community .
Implements a proof state , some primitive tactics for manipulating
proofs , and some high level commands for introducing new theorems ,
evaluation / checking inside the proof system , etc .
Module : Idris.Core.ProofState
Description : Proof state implementation.
License : BSD3
Maintainer : The Idris Community.
Implements a proof state, some primitive tactics for manipulating
proofs, and some high level commands for introducing new theorems,
evaluation/checking inside the proof system, etc.
-}
# LANGUAGE CPP , FlexibleContexts , FlexibleInstances , MultiParamTypeClasses ,
PatternGuards #
PatternGuards #-}
module Idris.Core.ProofState(
ProofState(..), newProof, envAtFocus, goalAtFocus
, Tactic(..), Goal(..), processTactic, nowElaboratingPS
, doneElaboratingAppPS, doneElaboratingArgPS, dropGiven
, keepGiven, getProvenance
) where
import Idris.Core.Evaluate
import Idris.Core.ProofTerm
import Idris.Core.TT
import Idris.Core.Typecheck
import Idris.Core.Unify
import Idris.Core.WHNF
import Util.Pretty hiding (fill)
import Control.Monad.State.Strict
import Data.List
#if (MIN_VERSION_base(4,11,0))
import Prelude hiding ((<>))
#endif
data ProofState = PS { thname :: Name,
holes :: [Name], -- ^ holes still to be solved
usedns :: [Name], -- ^ used names, don't use again
nextname :: Int, -- ^ name supply, for locally unique names
global_nextname :: Int, -- ^ a mirror of the global name supply,
-- for generating things like type tags
-- in reflection
pterm :: ProofTerm, -- ^ current proof term
ptype :: Type, -- ^ original goal
dontunify :: [Name], -- ^ explicitly given by programmer, leave it
unified :: (Name, [(Name, Term)]),
notunified :: [(Name, Term)],
dotted :: [(Name, [Name])], -- ^ dot pattern holes + environment
-- either hole or something in env must turn up in the 'notunified' list during elaboration
solved :: Maybe (Name, Term),
problems :: Fails,
injective :: [Name],
deferred :: [Name], -- ^ names we'll need to define
implementations :: [Name], -- ^ implementation arguments (for interfaces)
autos :: [(Name, ([FailContext], [Name]))], -- ^ unsolved 'auto' implicits with their holes
psnames :: [Name], -- ^ Local names okay to use in proof search
previous :: Maybe ProofState, -- ^ for undo
context :: Context,
datatypes :: Ctxt TypeInfo,
plog :: String,
unifylog :: Bool,
done :: Bool,
recents :: [Name],
while_elaborating :: [FailContext],
constraint_ns :: String
}
data Tactic = Attack
| Claim Name Raw
| ClaimFn Name Name Raw
| Reorder Name
| Exact Raw
| Fill Raw
| MatchFill Raw
| PrepFill Name [Name]
| CompleteFill
| Regret
| Solve
| StartUnify Name
| EndUnify
| UnifyAll
| Compute
| ComputeLet Name
| Simplify
| WHNF_Compute
| WHNF_ComputeArgs
| EvalIn Raw
| CheckIn Raw
| Intro (Maybe Name)
| IntroTy Raw (Maybe Name)
| Forall Name RigCount (Maybe ImplicitInfo) Raw
| LetBind Name RigCount Raw Raw
| ExpandLet Name Term
| Rewrite Raw
| Equiv Raw
| PatVar Name
| PatBind Name RigCount
| Focus Name
| Defer [Name] [Name] Name
| DeferType Name Raw [Name]
| Implementation Name
| AutoArg Name
| SetInjective Name
| MoveLast Name
| MatchProblems Bool
| UnifyProblems
| UnifyGoal Raw
| UnifyTerms Raw Raw
| ProofState
| Undo
| QED
deriving Show
-- Some utilites on proof and tactic states
instance Show ProofState where
show ps | [] <- holes ps
= show (thname ps) ++ ": no more goals"
show ps | (h : hs) <- holes ps
= let tm = pterm ps
nm = thname ps
OK g = goal (Just h) tm
wkenv = premises g in
"Other goals: " ++ show hs ++ "\n" ++
showPs wkenv (reverse wkenv) ++ "\n" ++
"-------------------------------- (" ++ show nm ++
") -------\n " ++
show h ++ " : " ++ showG wkenv (goalType g) ++ "\n"
where showPs env [] = ""
showPs env ((n, _, Let _ t v):bs)
= " " ++ show n ++ " : " ++
showEnv env ({- normalise ctxt env -} t) ++ " = " ++
showEnv env ({- normalise ctxt env -} v) ++
"\n" ++ showPs env bs
showPs env ((n, _, b):bs)
= " " ++ show n ++ " : " ++
showEnv env ({- normalise ctxt env -} (binderTy b)) ++
"\n" ++ showPs env bs
normalise ctxt ps
" =?= " ++ showEnv ps v
showG ps b = showEnv ps (binderTy b)
instance Pretty ProofState OutputAnnotation where
pretty ps | [] <- holes ps =
pretty (thname ps) <+> colon <+> text " no more goals."
pretty ps | (h : hs) <- holes ps =
let tm = pterm ps
OK g = goal (Just h) tm
nm = thname ps in
let wkEnv = premises g in
text "Other goals" <+> colon <+> pretty hs <+>
prettyPs wkEnv (reverse wkEnv) <+>
text "---------- " <+> text "Focussing on" <> colon <+> pretty nm <+> text " ----------" <+>
pretty h <+> colon <+> prettyGoal wkEnv (goalType g)
where
prettyGoal ps (Guess t v) =
prettyEnv ps t <+> text "=?=" <+> prettyEnv ps v
prettyGoal ps b = prettyEnv ps $ binderTy b
prettyPs env [] = empty
prettyPs env ((n, _, Let _ t v):bs) =
nest nestingSize (pretty n <+> colon <+>
prettyEnv env t <+> text "=" <+> prettyEnv env v <+>
nest nestingSize (prettyPs env bs))
prettyPs env ((n, _, b):bs) =
nest nestingSize (pretty n <+> colon <+> prettyEnv env (binderTy b) <+>
nest nestingSize (prettyPs env bs))
holeName i = sMN i "hole"
qshow :: Fails -> String
qshow fs = show (map (\ (x, y, hs, env, _, _, t) -> (t, map fstEnv env, x, y, hs)) fs)
match_unify' :: Context -> Env ->
(TT Name, Maybe Provenance) ->
(TT Name, Maybe Provenance) ->
StateT TState TC [(Name, TT Name)]
match_unify' ctxt env (topx, xfrom) (topy, yfrom) =
do ps <- get
let while = while_elaborating ps
let inj = injective ps
traceWhen (unifylog ps)
("Matching " ++ show (topx, topy) ++
" in " ++ show env ++
"\nHoles: " ++ show (holes ps)
++ "\n"
++ "\n" ++ show (getProofTerm (pterm ps)) ++ "\n\n"
) $
case match_unify ctxt env (topx, xfrom) (topy, yfrom) inj (holes ps) while of
OK u -> traceWhen (unifylog ps)
("Matched " ++ show u) $
do let (h, ns) = unified ps
put (ps { unified = (h, u ++ ns) })
return u
Error e -> traceWhen (unifylog ps)
("No match " ++ show e) $
do put (ps { problems = (topx, topy, True,
env, e, while, Match) :
problems ps })
return []
-- traceWhen (unifylog ps)
-- ("Matched " ++ show (topx, topy) ++ " without " ++ show dont ++
-- "\nSolved: " ++ show u
+ + " \nCurrent problems:\n " + + qshow ( problems ps )
-- + + show ( pterm ps )
+ + " \n---------- " ) $
mergeSolutions :: Env -> [(Name, TT Name)] -> StateT TState TC [(Name, TT Name)]
mergeSolutions env ns = merge [] ns
where
merge acc [] = return (reverse acc)
merge acc ((n, t) : ns)
| Just t' <- lookup n ns
= do ps <- get
let probs = problems ps
put (ps { problems = probs ++ [(t,t',True,env,
CantUnify True (t, Nothing) (t', Nothing) (Msg "") (errEnv env) 0,
[], Unify)] })
merge acc ns
| otherwise = merge ((n, t): acc) ns
dropSwaps :: [(Name, TT Name)] -> [(Name, TT Name)]
dropSwaps [] = []
dropSwaps (p@(x, P _ y _) : xs) | solvedIn y x xs = dropSwaps xs
where solvedIn _ _ [] = False
solvedIn y x ((y', P _ x' _) : xs) | y == y' && x == x' = True
solvedIn y x (_ : xs) = solvedIn y x xs
dropSwaps (p : xs) = p : dropSwaps xs
unify' :: Context -> Env ->
(TT Name, Maybe Provenance) ->
(TT Name, Maybe Provenance) ->
StateT TState TC [(Name, TT Name)]
unify' ctxt env (topx, xfrom) (topy, yfrom) =
do ps <- get
let while = while_elaborating ps
let dont = dontunify ps
let inj = injective ps
(u, fails) <- traceWhen (unifylog ps)
("Trying " ++ show (topx, topy) ++
"\nNormalised " ++ show (normalise ctxt env topx,
normalise ctxt env topy) ++
" in\n" ++ show env ++
"\nHoles: " ++ show (holes ps)
++ "\nInjective: " ++ show (injective ps)
++ "\n") $
lift $ unify ctxt env (topx, xfrom) (topy, yfrom) inj (holes ps)
(map fst (notunified ps)) while
let notu = filter (\ (n, t) -> case t of
-- P _ _ _ -> False
_ -> n `elem` dont) u
traceWhen (unifylog ps)
("Unified " ++ show (topx, topy) ++ " without " ++ show dont ++
"\nSolved: " ++ show u ++ "\nNew problems: " ++ qshow fails
++ "\nNot unified:\n" ++ show (notunified ps)
++ "\nCurrent problems:\n" ++ qshow (problems ps)
+ + show ( pterm ps )
++ "\n----------") $
do let (h, ns) = unified ps
-- solve in results (maybe unify should do this itself...)
let u' = map (\(n, sol) -> (n, updateSolvedTerm u sol)) u
-- if a metavar has multiple solutions, make a new unification
-- problem for each.
uns <- mergeSolutions env (u' ++ ns)
ps <- get
let (ns_p, probs') = updateProblems ps uns (fails ++ problems ps)
let ns' = dropSwaps ns_p
let (notu', probs_notu) = mergeNotunified env (holes ps) (notu ++ notunified ps)
traceWhen (unifylog ps)
("Now solved: " ++ show ns' ++
"\nNow problems: " ++ qshow (probs' ++ probs_notu) ++
"\nNow injective: " ++ show (updateInj u (injective ps))) $
put (ps { problems = probs' ++ probs_notu,
unified = (h, ns'),
injective = updateInj u (injective ps),
notunified = notu' })
return u
where updateInj ((n, a) : us) inj
| (P _ n' _, _) <- unApply a,
n `elem` inj = updateInj us (n':inj)
| (P _ n' _, _) <- unApply a,
n' `elem` inj = updateInj us (n:inj)
updateInj (_ : us) inj = updateInj us inj
updateInj [] inj = inj
nowElaboratingPS :: FC -> Name -> Name -> ProofState -> ProofState
nowElaboratingPS fc f arg ps = ps { while_elaborating = FailContext fc f arg : while_elaborating ps }
dropUntil :: (a -> Bool) -> [a] -> [a]
dropUntil p [] = []
dropUntil p (x:xs) | p x = xs
| otherwise = dropUntil p xs
doneElaboratingAppPS :: Name -> ProofState -> ProofState
doneElaboratingAppPS f ps = let while = while_elaborating ps
while' = dropUntil (\ (FailContext _ f' _) -> f == f') while
in ps { while_elaborating = while' }
doneElaboratingArgPS :: Name -> Name -> ProofState -> ProofState
doneElaboratingArgPS f x ps = let while = while_elaborating ps
while' = dropUntil (\ (FailContext _ f' x') -> f == f' && x == x') while
in ps { while_elaborating = while' }
getName :: Monad m => String -> StateT TState m Name
getName tag = do ps <- get
let n = nextname ps
put (ps { nextname = n+1 })
return $ sMN n tag
action :: Monad m => (ProofState -> ProofState) -> StateT TState m ()
action a = do ps <- get
put (a ps)
query :: Monad m => (ProofState -> r) -> StateT TState m r
query q = do ps <- get
return $ q ps
addLog :: Monad m => String -> StateT TState m ()
addLog str = action (\ps -> ps { plog = plog ps ++ str ++ "\n" })
newProof :: Name -- ^ the name of what's to be elaborated
-> String -- ^ current source file
-> Context -- ^ the current global context
-> Ctxt TypeInfo -- ^ the value of the idris_datatypes field of IState
-> Int -- ^ the value of the idris_name field of IState
-> Type -- ^ the goal type
-> ProofState
newProof n tcns ctxt datatypes globalNames ty =
let h = holeName 0
ty' = vToP ty
in PS n [h] [] 1 globalNames (mkProofTerm (Bind h (Hole ty')
(P Bound h ty'))) ty [] (h, []) [] []
Nothing [] []
[] [] [] []
Nothing ctxt datatypes "" False False [] [] tcns
type TState = ProofState -- [TacticAction])
type RunTactic = RunTactic' TState
envAtFocus :: ProofState -> TC Env
envAtFocus ps
| not $ null (holes ps) = do g <- goal (Just (head (holes ps))) (pterm ps)
return (premises g)
| otherwise = fail $ "No holes in " ++ show (getProofTerm (pterm ps))
goalAtFocus :: ProofState -> TC (Binder Type)
goalAtFocus ps
| not $ null (holes ps) = do g <- goal (Just (head (holes ps))) (pterm ps)
return (goalType g)
| otherwise = Error . Msg $ "No goal in " ++ show (holes ps) ++ show (getProofTerm (pterm ps))
tactic :: Hole -> RunTactic -> StateT TState TC ()
tactic h f = do ps <- get
(tm', _) <- atHole h f (context ps) [] (pterm ps)
ps <- get -- might have changed while processing
put (ps { pterm = tm' })
computeLet :: Context -> Name -> Term -> Term
computeLet ctxt n tm = cl [] tm where
cl env (Bind n' (Let r t v) sc)
| n' == n = let v' = normalise ctxt env v in
Bind n' (Let r t v') sc
cl env (Bind n' b sc) = Bind n' (fmap (cl env) b) (cl ((n, Rig0, b):env) sc)
cl env (App s f a) = App s (cl env f) (cl env a)
cl env t = t
attack :: RunTactic
attack ctxt env (Bind x (Hole t) sc)
= do h <- getName "hole"
action (\ps -> ps { holes = h : holes ps })
return $ Bind x (Guess t (newtm h)) sc
where
newtm h = Bind h (Hole t) (P Bound h t)
attack ctxt env _ = fail "Not an attackable hole"
claim :: Name -> Raw -> RunTactic
claim n ty ctxt env t =
do (tyv, tyt) <- lift $ check ctxt env ty
lift $ isType ctxt env tyt
action (\ps -> let (g:gs) = holes ps in
ps { holes = g : n : gs } )
return $ Bind n (Hole tyv) t
-- If the current goal is 'retty', make a claim which is a function that
-- can compute a retty from argty (i.e a claim 'argty -> retty')
claimFn :: Name -> Name -> Raw -> RunTactic
claimFn n bn argty ctxt env t@(Bind x (Hole retty) sc) =
do (tyv, tyt) <- lift $ check ctxt env argty
lift $ isType ctxt env tyt
action (\ps -> let (g:gs) = holes ps in
ps { holes = g : n : gs } )
return $ Bind n (Hole (Bind bn (Pi RigW Nothing tyv tyt) retty)) t
claimFn _ _ _ ctxt env _ = fail "Can't make function type here"
reorder_claims :: RunTactic
reorder_claims ctxt env t
= -- trace (showSep "\n" (map show (scvs t))) $
let (bs, sc) = scvs t []
newbs = reverse (sortB (reverse bs)) in
traceWhen (bs /= newbs) (show bs ++ "\n ==> \n" ++ show newbs) $
return (bindAll newbs sc)
where scvs (Bind n b@(Hole _) sc) acc = scvs sc ((n, b):acc)
scvs sc acc = (reverse acc, sc)
sortB :: [(Name, Binder (TT Name))] -> [(Name, Binder (TT Name))]
sortB [] = []
sortB (x:xs) | all (noOcc x) xs = x : sortB xs
| otherwise = sortB (insertB x xs)
insertB x [] = [x]
insertB x (y:ys) | all (noOcc x) (y:ys) = x : y : ys
| otherwise = y : insertB x ys
noOcc (n, _) (_, Let _ t v) = noOccurrence n t && noOccurrence n v
noOcc (n, _) (_, Guess t v) = noOccurrence n t && noOccurrence n v
noOcc (n, _) (_, b) = noOccurrence n (binderTy b)
focus :: Name -> RunTactic
focus n ctxt env t = do action (\ps -> let hs = holes ps in
if n `elem` hs
then ps { holes = n : (hs \\ [n]) }
else ps)
ps <- get
return t
movelast :: Name -> RunTactic
movelast n ctxt env t = do action (\ps -> let hs = holes ps in
if n `elem` hs
then ps { holes = (hs \\ [n]) ++ [n] }
else ps)
return t
implementationArg :: Name -> RunTactic
implementationArg n ctxt env (Bind x (Hole t) sc)
= do action (\ps -> let hs = holes ps
is = implementations ps in
ps { holes = (hs \\ [x]) ++ [x],
implementations = x:is })
return (Bind x (Hole t) sc)
implementationArg n ctxt env _
= fail "The current focus is not a hole."
autoArg :: Name -> RunTactic
autoArg n ctxt env (Bind x (Hole t) sc)
= do action (\ps -> case lookup x (autos ps) of
Nothing ->
let hs = holes ps in
ps { holes = (hs \\ [x]) ++ [x],
autos = (x, (while_elaborating ps, refsIn t)) : autos ps }
Just _ -> ps)
return (Bind x (Hole t) sc)
autoArg n ctxt env _
= fail "The current focus not a hole."
setinj :: Name -> RunTactic
setinj n ctxt env (Bind x b sc)
= do action (\ps -> let is = injective ps in
ps { injective = n : is })
return (Bind x b sc)
defer :: [Name] -> [Name] -> Name -> RunTactic
defer dropped linused n ctxt env (Bind x (Hole t) (P nt x' ty)) | x == x' =
do let env' = filter (\(n, _, t) -> n `notElem` dropped) env
action (\ps -> let hs = holes ps in
ps { usedns = n : usedns ps,
holes = hs \\ [x] })
ps <- get
return (Bind n (GHole (length env') (psnames ps) (mkTy (reverse env') t))
(mkApp (P Ref n ty) (map getP (reverse env'))))
where
mkTy [] t = t
mkTy ((n,rig,b) : bs) t = Bind n (Pi (setRig rig n) Nothing (binderTy b) (TType (UVar [] 0))) (mkTy bs t)
setRig Rig1 n | n `elem` linused = Rig0
setRig rig n = rig
getP (n, rig, b) = P Bound n (binderTy b)
defer dropped linused n ctxt env _ = fail "Can't defer a non-hole focus."
-- as defer, but build the type and application explicitly
deferType :: Name -> Raw -> [Name] -> RunTactic
deferType n fty_in args ctxt env (Bind x (Hole t) (P nt x' ty)) | x == x' =
do (fty, _) <- lift $ check ctxt env fty_in
action (\ps -> let hs = holes ps
ds = deferred ps in
ps { holes = hs \\ [x],
deferred = n : ds })
return (Bind n (GHole 0 [] fty)
(mkApp (P Ref n ty) (map getP args)))
where
getP n = case lookupBinder n env of
Just b -> P Bound n (binderTy b)
Nothing -> error ("deferType can't find " ++ show n)
deferType _ _ _ _ _ _ = fail "Can't defer a non-hole focus."
unifyGoal :: Raw -> RunTactic
unifyGoal tm ctxt env h@(Bind x b sc) =
do (tmv, _) <- lift $ check ctxt env tm
ns' <- unify' ctxt env (binderTy b, Nothing) (tmv, Nothing)
return h
unifyGoal _ _ _ _ = fail "The focus is not a binder."
unifyTerms :: Raw -> Raw -> RunTactic
unifyTerms tm1 tm2 ctxt env h =
do (tm1v, _) <- lift $ check ctxt env tm1
(tm2v, _) <- lift $ check ctxt env tm2
ns' <- unify' ctxt env (tm1v, Nothing) (tm2v, Nothing)
return h
exact :: Raw -> RunTactic
exact guess ctxt env (Bind x (Hole ty) sc) =
do (val, valty) <- lift $ check ctxt env guess
lift $ converts ctxt env valty ty
return $ Bind x (Guess ty val) sc
exact _ _ _ _ = fail "Can't fill here."
-- As exact, but attempts to solve other goals by unification
fill :: Raw -> RunTactic
fill guess ctxt env (Bind x (Hole ty) sc) =
do (val, valty) <- lift $ check ctxt env guess
unify' ctxt env (valty, Just $ SourceTerm val)
(ty, Just (chkPurpose val ty))
return $ Bind x (Guess ty val) sc
where
-- some expected types show up commonly in errors and indicate a
-- specific problem.
-- argTy -> retTy suggests a function applied to too many arguments
chkPurpose val (Bind _ (Pi _ _ (P _ (MN _ _) _) _) (P _ (MN _ _) _))
= TooManyArgs val
chkPurpose _ _ = ExpectedType
fill _ _ _ _ = fail "Can't fill here."
-- As fill, but attempts to solve other goals by matching
match_fill :: Raw -> RunTactic
match_fill guess ctxt env (Bind x (Hole ty) sc) =
do (val, valty) <- lift $ check ctxt env guess
match_unify' ctxt env (valty, Just $ SourceTerm val)
(ty, Just ExpectedType)
return $ Bind x (Guess ty val) sc
match_fill _ _ _ _ = fail "Can't fill here."
prep_fill :: Name -> [Name] -> RunTactic
prep_fill f as ctxt env (Bind x (Hole ty) sc) =
do let val = mkApp (P Ref f Erased) (map (\n -> P Ref n Erased) as)
return $ Bind x (Guess ty val) sc
prep_fill f as ctxt env t = fail $ "Can't prepare fill at " ++ show t
complete_fill :: RunTactic
complete_fill ctxt env (Bind x (Guess ty val) sc) =
do let guess = forget val
(val', valty) <- lift $ check ctxt env guess
unify' ctxt env (valty, Just $ SourceTerm val')
(ty, Just ExpectedType)
return $ Bind x (Guess ty val) sc
complete_fill ctxt env t = fail $ "Can't complete fill at " ++ show t
-- When solving something in the 'dont unify' set, we should check
-- that the guess we are solving it with unifies with the thing unification
-- found for it, if anything.
solve :: RunTactic
solve ctxt env (Bind x (Guess ty val) sc)
= do ps <- get
dropdots <-
case lookup x (notunified ps) of
Just (P _ h _)
| h == x -> return [] -- Can't solve itself!
trace ( " NEED MATCH : " + + show ( x , tm , ) + + " \nIN " + + show ( pterm ps ) ) $
do match_unify' ctxt env (tm, Just InferredVal)
(val, Just GivenVal)
return [x]
_ -> return []
action (\ps -> ps { holes = traceWhen (unifylog ps) ("Dropping hole " ++ show x) $
holes ps \\ [x],
solved = Just (x, val),
dontunify = filter (/= x) (dontunify ps),
notunified = updateNotunified [(x,val)]
(notunified ps),
recents = x : recents ps,
implementations = implementations ps \\ [x],
dotted = dropUnified dropdots (dotted ps) })
let (locked, _) = tryLock (holes ps \\ [x]) (updsubst x val sc) in
return locked
where dropUnified ddots [] = []
dropUnified ddots ((x, es) : ds)
| x `elem` ddots || any (\e -> e `elem` ddots) es
= dropUnified ddots ds
| otherwise = (x, es) : dropUnified ddots ds
tryLock :: [Name] -> Term -> (Term, Bool)
tryLock hs tm@(App Complete _ _) = (tm, True)
tryLock hs tm@(App s f a) =
let (f', fl) = tryLock hs f
(a', al) = tryLock hs a in
if fl && al then (App Complete f' a', True)
else (App s f' a', False)
tryLock hs t@(P _ n _) = (t, not $ n `elem` hs)
tryLock hs t@(Bind n (Hole _) sc) = (t, False)
tryLock hs t@(Bind n (Guess _ _) sc) = (t, False)
tryLock hs t@(Bind n (Let r ty val) sc)
= let (ty', tyl) = tryLock hs ty
(val', vall) = tryLock hs val
(sc', scl) = tryLock hs sc in
(Bind n (Let r ty' val') sc', tyl && vall && scl)
tryLock hs t@(Bind n b sc)
= let (bt', btl) = tryLock hs (binderTy b)
(sc', scl) = tryLock hs sc in
(Bind n (b { binderTy = bt' }) sc', btl && scl)
tryLock hs t = (t, True)
solve _ _ h@(Bind x t sc)
= do ps <- get
case findType x sc of
Just t -> lift $ tfail (CantInferType (show t))
_ -> lift $ tfail (IncompleteTerm h)
where findType x (Bind n (Let r t v) sc)
= findType x v `mplus` findType x sc
findType x (Bind n t sc)
| P _ x' _ <- binderTy t, x == x' = Just n
| otherwise = findType x sc
findType x _ = Nothing
introTy :: Raw -> Maybe Name -> RunTactic
introTy ty mn ctxt env (Bind x (Hole t) (P _ x' _)) | x == x' =
do let n = case mn of
Just name -> name
Nothing -> x
let t' = case t of
x@(Bind y (Pi _ _ s _) _) -> x
_ -> normalise ctxt env t
(tyv, tyt) <- lift $ check ctxt env ty
case t' of
Bind y (Pi rig _ s _) t -> let t' = updsubst y (P Bound n s) t in
do unify' ctxt env (s, Nothing) (tyv, Nothing)
return $ Bind n (Lam rig tyv) (Bind x (Hole t') (P Bound x t'))
_ -> lift $ tfail $ CantIntroduce t'
introTy ty n ctxt env _ = fail "Can't introduce here."
intro :: Maybe Name -> RunTactic
intro mn ctxt env (Bind x (Hole t) (P _ x' _)) | x == x' =
do let t' = case t of
x@(Bind y (Pi _ _ s _) _) -> x
_ -> normalise ctxt env t
case t' of
Bind y (Pi rig _ s _) t ->
let n = case mn of
Just name -> name
Nothing -> y
-- It's important that this be subst and not updsubst,
-- because we want to substitute even in portions of
-- terms that we know do not contain holes.
t' = subst y (P Bound n s) t
in return $ Bind n (Lam rig s) (Bind x (Hole t') (P Bound x t'))
_ -> lift $ tfail $ CantIntroduce t'
intro n ctxt env _ = fail "Can't introduce here."
forAll :: Name -> RigCount -> Maybe ImplicitInfo -> Raw -> RunTactic
forAll n rig impl ty ctxt env (Bind x (Hole t) (P _ x' _)) | x == x' =
do (tyv, tyt) <- lift $ check ctxt env ty
unify' ctxt env (tyt, Nothing) (TType (UVar [] 0), Nothing)
unify' ctxt env (t, Nothing) (TType (UVar [] 0), Nothing)
return $ Bind n (Pi rig impl tyv (TType (UVar [] 0))) (Bind x (Hole t) (P Bound x t))
forAll n rig impl ty ctxt env _ = fail "Can't pi bind here"
patvar :: Name -> RunTactic
patvar n ctxt env (Bind x (Hole t) sc) =
do action (\ps -> ps { holes = traceWhen (unifylog ps) ("Dropping pattern hole " ++ show x) $
holes ps \\ [x],
solved = Just (x, P Bound n t),
dontunify = filter (/=x) (dontunify ps),
notunified = updateNotunified [(x,P Bound n t)]
(notunified ps),
injective = addInj n x (injective ps)
})
return $ Bind n (PVar RigW t) (updsubst x (P Bound n t) sc)
where addInj n x ps | x `elem` ps = n : ps
| otherwise = ps
patvar n ctxt env tm = fail $ "Can't add pattern var at " ++ show tm
letbind :: Name -> RigCount -> Raw -> Raw -> RunTactic
letbind n rig ty val ctxt env (Bind x (Hole t) (P _ x' _)) | x == x' =
do (tyv, tyt) <- lift $ check ctxt env ty
(valv, valt) <- lift $ check ctxt env val
lift $ isType ctxt env tyt
return $ Bind n (Let rig tyv valv) (Bind x (Hole t) (P Bound x t))
letbind n rig ty val ctxt env _ = fail "Can't let bind here"
expandLet :: Name -> Term -> RunTactic
expandLet n v ctxt env tm =
return $ updsubst n v tm
rewrite :: Raw -> RunTactic
rewrite tm ctxt env (Bind x (Hole t) xp@(P _ x' _)) | x == x' =
do (tmv, tmt) <- lift $ check ctxt env tm
let tmt' = normalise ctxt env tmt
case unApply tmt' of
(P _ (UN q) _, [lt,rt,l,r]) | q == txt "=" ->
do let p = Bind rname (Lam RigW lt) (mkP (P Bound rname lt) r l t)
let newt = mkP l r l t
let sc = forget $ (Bind x (Hole newt)
(mkApp (P Ref (sUN "replace") (TType (UVal 0)))
[lt, l, r, p, tmv, xp]))
(scv, sct) <- lift $ check ctxt env sc
return scv
_ -> lift $ tfail (NotEquality tmv tmt')
where rname = sMN 0 "replaced"
rewrite _ _ _ _ = fail "Can't rewrite here"
-- To make the P for rewrite, replace syntactic occurrences of l in ty with
an x , and put \x : lt in front
mkP :: TT Name -> TT Name -> TT Name -> TT Name -> TT Name
mkP lt l r ty | l == ty = lt
mkP lt l r (App s f a) = let f' = if (r /= f) then mkP lt l r f else f
a' = if (r /= a) then mkP lt l r a else a in
App s f' a'
mkP lt l r (Bind n b sc)
= let b' = mkPB b
sc' = if (r /= sc) then mkP lt l r sc else sc in
Bind n b' sc'
where mkPB (Let c t v) = let t' = if (r /= t) then mkP lt l r t else t
v' = if (r /= v) then mkP lt l r v else v in
Let c t' v'
mkPB b = let ty = binderTy b
ty' = if (r /= ty) then mkP lt l r ty else ty in
b { binderTy = ty' }
mkP lt l r x = x
equiv :: Raw -> RunTactic
equiv tm ctxt env (Bind x (Hole t) sc) =
do (tmv, tmt) <- lift $ check ctxt env tm
lift $ converts ctxt env tmv t
return $ Bind x (Hole tmv) sc
equiv tm ctxt env _ = fail "Can't equiv here"
patbind :: Name -> RigCount -> RunTactic
patbind n rig ctxt env (Bind x (Hole t) (P _ x' _)) | x == x' =
do let t' = case t of
x@(Bind y (PVTy s) t) -> x
_ -> normalise ctxt env t
case t' of
Bind y (PVTy s) t -> let t' = updsubst y (P Bound n s) t in
return $ Bind n (PVar rig s) (Bind x (Hole t') (P Bound x t'))
_ -> fail "Nothing to pattern bind"
patbind n _ ctxt env _ = fail "Can't pattern bind here"
compute :: RunTactic
compute ctxt env (Bind x (Hole ty) sc) =
do return $ Bind x (Hole (normalise ctxt env ty)) sc
compute ctxt env t = return t
whnf_compute :: RunTactic
whnf_compute ctxt env (Bind x (Hole ty) sc) =
do let ty' = whnf ctxt env ty in
return $ Bind x (Hole ty') sc
whnf_compute ctxt env t = return t
whnf_compute_args :: RunTactic
whnf_compute_args ctxt env (Bind x (Hole ty) sc) =
do let ty' = whnfArgs ctxt env ty in
return $ Bind x (Hole ty') sc
whnf_compute_args ctxt env t = return t
-- reduce let bindings only
simplify :: RunTactic
simplify ctxt env (Bind x (Hole ty) sc) =
do return $ Bind x (Hole (fst (specialise ctxt env [] ty))) sc
simplify ctxt env t = return t
check_in :: Raw -> RunTactic
check_in t ctxt env tm =
do (val, valty) <- lift $ check ctxt env t
addLog (showEnv env val ++ " : " ++ showEnv env valty)
return tm
eval_in :: Raw -> RunTactic
eval_in t ctxt env tm =
do (val, valty) <- lift $ check ctxt env t
let val' = normalise ctxt env val
let valty' = normalise ctxt env valty
addLog (showEnv env val ++ " : " ++
showEnv env valty ++
-- " in " ++ show env ++
" ==>\n " ++
showEnv env val' ++ " : " ++
showEnv env valty')
return tm
start_unify :: Name -> RunTactic
start_unify n ctxt env tm = do -- action (\ps -> ps { unified = (n, []) })
return tm
solve_unified :: RunTactic
solve_unified ctxt env tm =
do ps <- get
let (_, ns) = unified ps
let unify = dropGiven (dontunify ps) ns (holes ps)
action (\ps -> ps { holes = traceWhen (unifylog ps) ("Dropping holes " ++ show (map fst unify)) $
holes ps \\ map fst unify,
recents = recents ps ++ map fst unify })
action (\ps -> ps { pterm = updateSolved unify (pterm ps) })
return (updateSolvedTerm unify tm)
dropGiven du [] hs = []
dropGiven du ((n, P Bound t ty) : us) hs
| n `elem` du && not (t `elem` du)
&& n `elem` hs && t `elem` hs
= (t, P Bound n ty) : dropGiven du us hs
dropGiven du (u@(n, _) : us) hs
| n `elem` du = dropGiven du us hs
( u@ ( _ , P a n ty ) : us ) | n ` elem ` du = dropGiven du us
dropGiven du (u : us) hs = u : dropGiven du us hs
keepGiven du [] hs = []
keepGiven du ((n, P Bound t ty) : us) hs
| n `elem` du && not (t `elem` du)
&& n `elem` hs && t `elem` hs
= keepGiven du us hs
keepGiven du (u@(n, _) : us) hs
| n `elem` du = u : keepGiven du us hs
keepGiven du (u : us) hs = keepGiven du us hs
updateEnv [] e = e
updateEnv ns [] = []
updateEnv ns ((n, rig, b) : env)
= (n, rig, fmap (updateSolvedTerm ns) b) : updateEnv ns env
updateProv ns (SourceTerm t) = SourceTerm $ updateSolvedTerm ns t
updateProv ns p = p
updateError [] err = err
updateError ns (At f e) = At f (updateError ns e)
updateError ns (Elaborating s n ty e) = Elaborating s n ty (updateError ns e)
updateError ns (ElaboratingArg f a env e)
= ElaboratingArg f a env (updateError ns e)
updateError ns (CantUnify b (l,lp) (r,rp) e xs sc)
= CantUnify b (updateSolvedTerm ns l, fmap (updateProv ns) lp)
(updateSolvedTerm ns r, fmap (updateProv ns) rp) (updateError ns e) xs sc
updateError ns e = e
mergeNotunified :: Env -> [Name] -> [(Name, Term)] -> ([(Name, Term)], Fails)
mergeNotunified env holes ns = mnu ns [] [] where
mnu [] ns_acc ps_acc = (reverse ns_acc, reverse ps_acc)
mnu ((n, t):ns) ns_acc ps_acc
| Just t' <- lookup n ns, t /= t'
= mnu ns ((n,t') : ns_acc)
((t,t',True, env,CantUnify True (t, Nothing) (t', Nothing) (Msg "") [] 0, [],Match) : ps_acc)
| otherwise = mnu ns ((n,t) : ns_acc) ps_acc
updateNotunified [] nu = nu
updateNotunified ns nu = up nu where
up [] = []
up ((n, t) : nus) = let t' = updateSolvedTerm ns t in
((n, t') : up nus)
getProvenance :: Err -> (Maybe Provenance, Maybe Provenance)
getProvenance (CantUnify _ (_, lp) (_, rp) _ _ _) = (lp, rp)
getProvenance _ = (Nothing, Nothing)
setReady (x, y, _, env, err, c, at) = (x, y, True, env, err, c, at)
updateProblems :: ProofState -> [(Name, TT Name)] -> Fails
-> ([(Name, TT Name)], Fails)
[ ] ps inj holes = ( [ ] , ps )
updateProblems ps updates probs = rec 10 updates probs
where
-- keep trying if we make progress, but not too many times...
rec 0 us fs = (us, fs)
rec n us fs = case up us [] fs of
res@(_, []) -> res
res@(us', _) | length us' == length us -> res
(us', fs') -> rec (n - 1) us' fs'
hs = holes ps
inj = injective ps
ctxt = context ps
ulog = unifylog ps
usupp = map fst (notunified ps)
dont = dontunify ps
up ns acc [] = (ns, map (updateNs ns) (reverse acc))
up ns acc (prob@(x, y, ready, env, err, while, um) : ps) =
let (x', newx) = updateSolvedTerm' ns x
(y', newy) = updateSolvedTerm' ns y
(lp, rp) = getProvenance err
err' = updateError ns err
env' = updateEnv ns env in
if newx || newy || ready ||
any (\n -> n `elem` inj) (refsIn x ++ refsIn y) then
case unify ctxt env' (x', lp) (y', rp) inj hs usupp while of
OK (v, []) -> traceWhen ulog ("DID " ++ show (x',y',ready,v,dont)) $
let v' = filter (\(n, _) -> n `notElem` dont) v in
up (ns ++ v') acc ps
trace ( " FAILED " + + show ( , e ) ) $
up ns ((x',y',False,env',err',while,um) : acc) ps
else -- trace ("SKIPPING " ++ show (x,y,ready)) $
up ns ((x',y', False, env',err', while, um) : acc) ps
updateNs ns (x, y, t, env, err, fc, fa)
= let (x', newx) = updateSolvedTerm' ns x
(y', newy) = updateSolvedTerm' ns y in
(x', y', newx || newy,
updateEnv ns env, updateError ns err, fc, fa)
orderUpdateSolved :: [(Name, Term)] -> ProofTerm -> (ProofTerm, [Name])
orderUpdateSolved ns tm = update [] ns tm
where
update done [] t = (t, done)
update done ((n, P _ n' _) : ns) t | n == n' = update done ns t
update done (n : ns) t = update (fst n : done)
(map (updateMatch n) ns)
(updateSolved [n] t)
-- Update the later solutions too
updateMatch n (x, tm) = (x, updateSolvedTerm [n] tm)
-- attempt to solve remaining problems with match_unify
matchProblems :: Bool -> ProofState -> [(Name, TT Name)] -> Fails
-> ([(Name, TT Name)], Fails)
matchProblems all ps updates probs = up updates probs where
hs = holes ps
inj = injective ps
ctxt = context ps
up ns [] = (ns, [])
up ns ((x, y, ready, env, err, while, um) : ps)
| all || um == Match =
let x' = updateSolvedTerm ns x
y' = updateSolvedTerm ns y
(lp, rp) = getProvenance err
err' = updateError ns err
env' = updateEnv ns env in
case match_unify ctxt env' (x', lp) (y', rp) inj hs while of
OK v -> -- trace ("Added " ++ show v ++ " from " ++ show (x', y')) $
up (ns ++ v) ps
_ -> let (ns', ps') = up ns ps in
(ns', (x', y', True, env', err', while, um) : ps')
up ns (p : ps) = let (ns', ps') = up ns ps in
(ns', p : ps')
processTactic :: Tactic -> ProofState -> TC (ProofState, String)
processTactic QED ps = case holes ps of
[] -> do let tm = {- normalise (context ps) [] -} getProofTerm (pterm ps)
(tm', ty', _) <- recheck (constraint_ns ps) (context ps) [] (forget tm) tm
return (ps { done = True, pterm = mkProofTerm tm' },
"Proof complete: " ++ showEnv [] tm')
_ -> fail "Still holes to fill."
processTactic ProofState ps = return (ps, showEnv [] (getProofTerm (pterm ps)))
processTactic Undo ps = case previous ps of
Nothing -> Error . Msg $ "Nothing to undo."
Just pold -> return (pold, "")
processTactic EndUnify ps
= let (h, ns_in) = unified ps
ns = dropGiven (dontunify ps) ns_in (holes ps)
ns' = map (\ (n, t) -> (n, updateSolvedTerm ns t)) ns
(ns'', probs') = updateProblems ps ns' (problems ps)
tm' = updateSolved ns'' (pterm ps) in
traceWhen (unifylog ps) ("(EndUnify) Dropping holes: " ++ show (map fst ns'')) $
return (ps { pterm = tm',
unified = (h, []),
problems = probs',
notunified = updateNotunified ns'' (notunified ps),
recents = recents ps ++ map fst ns'',
holes = holes ps \\ map fst ns'' }, "")
processTactic UnifyAll ps
= let tm' = updateSolved (notunified ps) (pterm ps) in
return (ps { pterm = tm',
notunified = [],
recents = recents ps ++ map fst (notunified ps),
holes = holes ps \\ map fst (notunified ps) }, "")
processTactic (Reorder n) ps
= do ps' <- execStateT (tactic (Just n) reorder_claims) ps
return (ps' { previous = Just ps, plog = "" }, plog ps')
processTactic (ComputeLet n) ps
= return (ps { pterm = mkProofTerm $
computeLet (context ps) n
(getProofTerm (pterm ps)) }, "")
processTactic UnifyProblems ps
= do let (ns', probs') = updateProblems ps [] (map setReady (problems ps))
(pterm', dropped) = orderUpdateSolved ns' (pterm ps)
traceWhen (unifylog ps) ("(UnifyProblems) Dropping holes: " ++ show dropped) $
return (ps { pterm = pterm', solved = Nothing, problems = probs',
previous = Just ps, plog = "",
notunified = updateNotunified ns' (notunified ps),
recents = recents ps ++ dropped,
dotted = filter (notIn ns') (dotted ps),
holes = holes ps \\ dropped }, plog ps)
where notIn ns (h, _) = h `notElem` map fst ns
processTactic (MatchProblems all) ps
= do let (ns', probs') = matchProblems all ps [] (map setReady (problems ps))
(ns'', probs'') = matchProblems all ps ns' probs'
(pterm', dropped) = orderUpdateSolved ns'' (resetProofTerm (pterm ps))
traceWhen (unifylog ps) ("(MatchProblems) Dropping holes: " ++ show dropped) $
return (ps { pterm = pterm', solved = Nothing, problems = probs'',
previous = Just ps, plog = "",
notunified = updateNotunified ns'' (notunified ps),
recents = recents ps ++ dropped,
holes = holes ps \\ dropped }, plog ps)
processTactic t ps
= case holes ps of
[] -> case t of
Focus _ -> return (ps, "") -- harmless to refocus when done, since
-- 'focus' doesn't fail
_ -> fail $ "Proof done, nothing to run tactic on: " ++ show t ++
"\n" ++ show (getProofTerm (pterm ps))
(h:_) -> do ps' <- execStateT (process t h) ps
let (ns_in, probs')
= case solved ps' of
Just s -> traceWhen (unifylog ps)
("SOLVED " ++ show s ++ " " ++ show (dontunify ps')) $
updateProblems ps' [s] (problems ps')
_ -> ([], problems ps')
-- rechecking problems may find more solutions, so
-- apply them here
let ns' = dropGiven (dontunify ps') ns_in (holes ps')
let pterm'' = updateSolved ns' (pterm ps')
traceWhen (unifylog ps)
("Updated problems after solve " ++ qshow probs' ++ "\n" ++
"(Toplevel) Dropping holes: " ++ show (map fst ns') ++ "\n" ++
"Holes were: " ++ show (holes ps')) $
return (ps' { pterm = pterm'',
solved = Nothing,
problems = probs',
notunified = updateNotunified ns' (notunified ps'),
previous = Just ps, plog = "",
recents = recents ps' ++ map fst ns',
holes = holes ps' \\ (map fst ns')
}, plog ps')
process :: Tactic -> Name -> StateT TState TC ()
process EndUnify _
= do ps <- get
let (h, _) = unified ps
tactic (Just h) solve_unified
process t h = tactic (Just h) (mktac t)
where mktac Attack = attack
mktac (Claim n r) = claim n r
mktac (ClaimFn n bn r) = claimFn n bn r
mktac (Exact r) = exact r
mktac (Fill r) = fill r
mktac (MatchFill r) = match_fill r
mktac (PrepFill n ns) = prep_fill n ns
mktac CompleteFill = complete_fill
mktac Solve = solve
mktac (StartUnify n) = start_unify n
mktac Compute = compute
mktac Simplify = Idris.Core.ProofState.simplify
mktac WHNF_Compute = whnf_compute
mktac WHNF_ComputeArgs = whnf_compute_args
mktac (Intro n) = intro n
mktac (IntroTy ty n) = introTy ty n
mktac (Forall n r i t) = forAll n r i t
mktac (LetBind n r t v) = letbind n r t v
mktac (ExpandLet n b) = expandLet n b
mktac (Rewrite t) = rewrite t
mktac (Equiv t) = equiv t
mktac (PatVar n) = patvar n
mktac (PatBind n rig) = patbind n rig
mktac (CheckIn r) = check_in r
mktac (EvalIn r) = eval_in r
mktac (Focus n) = focus n
mktac (Defer ns ls n) = defer ns ls n
mktac (DeferType n t a) = deferType n t a
mktac (Implementation n)= implementationArg n
mktac (AutoArg n) = autoArg n
mktac (SetInjective n) = setinj n
mktac (MoveLast n) = movelast n
mktac (UnifyGoal r) = unifyGoal r
mktac (UnifyTerms x y) = unifyTerms x y
| null | https://raw.githubusercontent.com/idris-lang/Idris-dev/d30e505cfabfce97bdfdd940464f74fe14100c22/src/Idris/Core/ProofState.hs | haskell | ^ holes still to be solved
^ used names, don't use again
^ name supply, for locally unique names
^ a mirror of the global name supply,
for generating things like type tags
in reflection
^ current proof term
^ original goal
^ explicitly given by programmer, leave it
^ dot pattern holes + environment
either hole or something in env must turn up in the 'notunified' list during elaboration
^ names we'll need to define
^ implementation arguments (for interfaces)
^ unsolved 'auto' implicits with their holes
^ Local names okay to use in proof search
^ for undo
Some utilites on proof and tactic states
normalise ctxt env
normalise ctxt env
normalise ctxt env
traceWhen (unifylog ps)
("Matched " ++ show (topx, topy) ++ " without " ++ show dont ++
"\nSolved: " ++ show u
+ + show ( pterm ps )
P _ _ _ -> False
solve in results (maybe unify should do this itself...)
if a metavar has multiple solutions, make a new unification
problem for each.
^ the name of what's to be elaborated
^ current source file
^ the current global context
^ the value of the idris_datatypes field of IState
^ the value of the idris_name field of IState
^ the goal type
[TacticAction])
might have changed while processing
If the current goal is 'retty', make a claim which is a function that
can compute a retty from argty (i.e a claim 'argty -> retty')
trace (showSep "\n" (map show (scvs t))) $
as defer, but build the type and application explicitly
As exact, but attempts to solve other goals by unification
some expected types show up commonly in errors and indicate a
specific problem.
argTy -> retTy suggests a function applied to too many arguments
As fill, but attempts to solve other goals by matching
When solving something in the 'dont unify' set, we should check
that the guess we are solving it with unifies with the thing unification
found for it, if anything.
Can't solve itself!
It's important that this be subst and not updsubst,
because we want to substitute even in portions of
terms that we know do not contain holes.
To make the P for rewrite, replace syntactic occurrences of l in ty with
reduce let bindings only
" in " ++ show env ++
action (\ps -> ps { unified = (n, []) })
keep trying if we make progress, but not too many times...
trace ("SKIPPING " ++ show (x,y,ready)) $
Update the later solutions too
attempt to solve remaining problems with match_unify
trace ("Added " ++ show v ++ " from " ++ show (x', y')) $
normalise (context ps) []
harmless to refocus when done, since
'focus' doesn't fail
rechecking problems may find more solutions, so
apply them here | |
Module : . Core . ProofState
Description : Proof state implementation .
License : : The Idris Community .
Implements a proof state , some primitive tactics for manipulating
proofs , and some high level commands for introducing new theorems ,
evaluation / checking inside the proof system , etc .
Module : Idris.Core.ProofState
Description : Proof state implementation.
License : BSD3
Maintainer : The Idris Community.
Implements a proof state, some primitive tactics for manipulating
proofs, and some high level commands for introducing new theorems,
evaluation/checking inside the proof system, etc.
-}
# LANGUAGE CPP , FlexibleContexts , FlexibleInstances , MultiParamTypeClasses ,
PatternGuards #
PatternGuards #-}
module Idris.Core.ProofState(
ProofState(..), newProof, envAtFocus, goalAtFocus
, Tactic(..), Goal(..), processTactic, nowElaboratingPS
, doneElaboratingAppPS, doneElaboratingArgPS, dropGiven
, keepGiven, getProvenance
) where
import Idris.Core.Evaluate
import Idris.Core.ProofTerm
import Idris.Core.TT
import Idris.Core.Typecheck
import Idris.Core.Unify
import Idris.Core.WHNF
import Util.Pretty hiding (fill)
import Control.Monad.State.Strict
import Data.List
#if (MIN_VERSION_base(4,11,0))
import Prelude hiding ((<>))
#endif
data ProofState = PS { thname :: Name,
unified :: (Name, [(Name, Term)]),
notunified :: [(Name, Term)],
solved :: Maybe (Name, Term),
problems :: Fails,
injective :: [Name],
context :: Context,
datatypes :: Ctxt TypeInfo,
plog :: String,
unifylog :: Bool,
done :: Bool,
recents :: [Name],
while_elaborating :: [FailContext],
constraint_ns :: String
}
data Tactic = Attack
| Claim Name Raw
| ClaimFn Name Name Raw
| Reorder Name
| Exact Raw
| Fill Raw
| MatchFill Raw
| PrepFill Name [Name]
| CompleteFill
| Regret
| Solve
| StartUnify Name
| EndUnify
| UnifyAll
| Compute
| ComputeLet Name
| Simplify
| WHNF_Compute
| WHNF_ComputeArgs
| EvalIn Raw
| CheckIn Raw
| Intro (Maybe Name)
| IntroTy Raw (Maybe Name)
| Forall Name RigCount (Maybe ImplicitInfo) Raw
| LetBind Name RigCount Raw Raw
| ExpandLet Name Term
| Rewrite Raw
| Equiv Raw
| PatVar Name
| PatBind Name RigCount
| Focus Name
| Defer [Name] [Name] Name
| DeferType Name Raw [Name]
| Implementation Name
| AutoArg Name
| SetInjective Name
| MoveLast Name
| MatchProblems Bool
| UnifyProblems
| UnifyGoal Raw
| UnifyTerms Raw Raw
| ProofState
| Undo
| QED
deriving Show
instance Show ProofState where
show ps | [] <- holes ps
= show (thname ps) ++ ": no more goals"
show ps | (h : hs) <- holes ps
= let tm = pterm ps
nm = thname ps
OK g = goal (Just h) tm
wkenv = premises g in
"Other goals: " ++ show hs ++ "\n" ++
showPs wkenv (reverse wkenv) ++ "\n" ++
"-------------------------------- (" ++ show nm ++
") -------\n " ++
show h ++ " : " ++ showG wkenv (goalType g) ++ "\n"
where showPs env [] = ""
showPs env ((n, _, Let _ t v):bs)
= " " ++ show n ++ " : " ++
"\n" ++ showPs env bs
showPs env ((n, _, b):bs)
= " " ++ show n ++ " : " ++
"\n" ++ showPs env bs
normalise ctxt ps
" =?= " ++ showEnv ps v
showG ps b = showEnv ps (binderTy b)
instance Pretty ProofState OutputAnnotation where
pretty ps | [] <- holes ps =
pretty (thname ps) <+> colon <+> text " no more goals."
pretty ps | (h : hs) <- holes ps =
let tm = pterm ps
OK g = goal (Just h) tm
nm = thname ps in
let wkEnv = premises g in
text "Other goals" <+> colon <+> pretty hs <+>
prettyPs wkEnv (reverse wkEnv) <+>
text "---------- " <+> text "Focussing on" <> colon <+> pretty nm <+> text " ----------" <+>
pretty h <+> colon <+> prettyGoal wkEnv (goalType g)
where
prettyGoal ps (Guess t v) =
prettyEnv ps t <+> text "=?=" <+> prettyEnv ps v
prettyGoal ps b = prettyEnv ps $ binderTy b
prettyPs env [] = empty
prettyPs env ((n, _, Let _ t v):bs) =
nest nestingSize (pretty n <+> colon <+>
prettyEnv env t <+> text "=" <+> prettyEnv env v <+>
nest nestingSize (prettyPs env bs))
prettyPs env ((n, _, b):bs) =
nest nestingSize (pretty n <+> colon <+> prettyEnv env (binderTy b) <+>
nest nestingSize (prettyPs env bs))
holeName i = sMN i "hole"
qshow :: Fails -> String
qshow fs = show (map (\ (x, y, hs, env, _, _, t) -> (t, map fstEnv env, x, y, hs)) fs)
match_unify' :: Context -> Env ->
(TT Name, Maybe Provenance) ->
(TT Name, Maybe Provenance) ->
StateT TState TC [(Name, TT Name)]
match_unify' ctxt env (topx, xfrom) (topy, yfrom) =
do ps <- get
let while = while_elaborating ps
let inj = injective ps
traceWhen (unifylog ps)
("Matching " ++ show (topx, topy) ++
" in " ++ show env ++
"\nHoles: " ++ show (holes ps)
++ "\n"
++ "\n" ++ show (getProofTerm (pterm ps)) ++ "\n\n"
) $
case match_unify ctxt env (topx, xfrom) (topy, yfrom) inj (holes ps) while of
OK u -> traceWhen (unifylog ps)
("Matched " ++ show u) $
do let (h, ns) = unified ps
put (ps { unified = (h, u ++ ns) })
return u
Error e -> traceWhen (unifylog ps)
("No match " ++ show e) $
do put (ps { problems = (topx, topy, True,
env, e, while, Match) :
problems ps })
return []
+ + " \nCurrent problems:\n " + + qshow ( problems ps )
+ + " \n---------- " ) $
mergeSolutions :: Env -> [(Name, TT Name)] -> StateT TState TC [(Name, TT Name)]
mergeSolutions env ns = merge [] ns
where
merge acc [] = return (reverse acc)
merge acc ((n, t) : ns)
| Just t' <- lookup n ns
= do ps <- get
let probs = problems ps
put (ps { problems = probs ++ [(t,t',True,env,
CantUnify True (t, Nothing) (t', Nothing) (Msg "") (errEnv env) 0,
[], Unify)] })
merge acc ns
| otherwise = merge ((n, t): acc) ns
dropSwaps :: [(Name, TT Name)] -> [(Name, TT Name)]
dropSwaps [] = []
dropSwaps (p@(x, P _ y _) : xs) | solvedIn y x xs = dropSwaps xs
where solvedIn _ _ [] = False
solvedIn y x ((y', P _ x' _) : xs) | y == y' && x == x' = True
solvedIn y x (_ : xs) = solvedIn y x xs
dropSwaps (p : xs) = p : dropSwaps xs
unify' :: Context -> Env ->
(TT Name, Maybe Provenance) ->
(TT Name, Maybe Provenance) ->
StateT TState TC [(Name, TT Name)]
unify' ctxt env (topx, xfrom) (topy, yfrom) =
do ps <- get
let while = while_elaborating ps
let dont = dontunify ps
let inj = injective ps
(u, fails) <- traceWhen (unifylog ps)
("Trying " ++ show (topx, topy) ++
"\nNormalised " ++ show (normalise ctxt env topx,
normalise ctxt env topy) ++
" in\n" ++ show env ++
"\nHoles: " ++ show (holes ps)
++ "\nInjective: " ++ show (injective ps)
++ "\n") $
lift $ unify ctxt env (topx, xfrom) (topy, yfrom) inj (holes ps)
(map fst (notunified ps)) while
let notu = filter (\ (n, t) -> case t of
_ -> n `elem` dont) u
traceWhen (unifylog ps)
("Unified " ++ show (topx, topy) ++ " without " ++ show dont ++
"\nSolved: " ++ show u ++ "\nNew problems: " ++ qshow fails
++ "\nNot unified:\n" ++ show (notunified ps)
++ "\nCurrent problems:\n" ++ qshow (problems ps)
+ + show ( pterm ps )
++ "\n----------") $
do let (h, ns) = unified ps
let u' = map (\(n, sol) -> (n, updateSolvedTerm u sol)) u
uns <- mergeSolutions env (u' ++ ns)
ps <- get
let (ns_p, probs') = updateProblems ps uns (fails ++ problems ps)
let ns' = dropSwaps ns_p
let (notu', probs_notu) = mergeNotunified env (holes ps) (notu ++ notunified ps)
traceWhen (unifylog ps)
("Now solved: " ++ show ns' ++
"\nNow problems: " ++ qshow (probs' ++ probs_notu) ++
"\nNow injective: " ++ show (updateInj u (injective ps))) $
put (ps { problems = probs' ++ probs_notu,
unified = (h, ns'),
injective = updateInj u (injective ps),
notunified = notu' })
return u
where updateInj ((n, a) : us) inj
| (P _ n' _, _) <- unApply a,
n `elem` inj = updateInj us (n':inj)
| (P _ n' _, _) <- unApply a,
n' `elem` inj = updateInj us (n:inj)
updateInj (_ : us) inj = updateInj us inj
updateInj [] inj = inj
nowElaboratingPS :: FC -> Name -> Name -> ProofState -> ProofState
nowElaboratingPS fc f arg ps = ps { while_elaborating = FailContext fc f arg : while_elaborating ps }
dropUntil :: (a -> Bool) -> [a] -> [a]
dropUntil p [] = []
dropUntil p (x:xs) | p x = xs
| otherwise = dropUntil p xs
doneElaboratingAppPS :: Name -> ProofState -> ProofState
doneElaboratingAppPS f ps = let while = while_elaborating ps
while' = dropUntil (\ (FailContext _ f' _) -> f == f') while
in ps { while_elaborating = while' }
doneElaboratingArgPS :: Name -> Name -> ProofState -> ProofState
doneElaboratingArgPS f x ps = let while = while_elaborating ps
while' = dropUntil (\ (FailContext _ f' x') -> f == f' && x == x') while
in ps { while_elaborating = while' }
getName :: Monad m => String -> StateT TState m Name
getName tag = do ps <- get
let n = nextname ps
put (ps { nextname = n+1 })
return $ sMN n tag
action :: Monad m => (ProofState -> ProofState) -> StateT TState m ()
action a = do ps <- get
put (a ps)
query :: Monad m => (ProofState -> r) -> StateT TState m r
query q = do ps <- get
return $ q ps
addLog :: Monad m => String -> StateT TState m ()
addLog str = action (\ps -> ps { plog = plog ps ++ str ++ "\n" })
-> ProofState
newProof n tcns ctxt datatypes globalNames ty =
let h = holeName 0
ty' = vToP ty
in PS n [h] [] 1 globalNames (mkProofTerm (Bind h (Hole ty')
(P Bound h ty'))) ty [] (h, []) [] []
Nothing [] []
[] [] [] []
Nothing ctxt datatypes "" False False [] [] tcns
type RunTactic = RunTactic' TState
envAtFocus :: ProofState -> TC Env
envAtFocus ps
| not $ null (holes ps) = do g <- goal (Just (head (holes ps))) (pterm ps)
return (premises g)
| otherwise = fail $ "No holes in " ++ show (getProofTerm (pterm ps))
goalAtFocus :: ProofState -> TC (Binder Type)
goalAtFocus ps
| not $ null (holes ps) = do g <- goal (Just (head (holes ps))) (pterm ps)
return (goalType g)
| otherwise = Error . Msg $ "No goal in " ++ show (holes ps) ++ show (getProofTerm (pterm ps))
tactic :: Hole -> RunTactic -> StateT TState TC ()
tactic h f = do ps <- get
(tm', _) <- atHole h f (context ps) [] (pterm ps)
put (ps { pterm = tm' })
computeLet :: Context -> Name -> Term -> Term
computeLet ctxt n tm = cl [] tm where
cl env (Bind n' (Let r t v) sc)
| n' == n = let v' = normalise ctxt env v in
Bind n' (Let r t v') sc
cl env (Bind n' b sc) = Bind n' (fmap (cl env) b) (cl ((n, Rig0, b):env) sc)
cl env (App s f a) = App s (cl env f) (cl env a)
cl env t = t
attack :: RunTactic
attack ctxt env (Bind x (Hole t) sc)
= do h <- getName "hole"
action (\ps -> ps { holes = h : holes ps })
return $ Bind x (Guess t (newtm h)) sc
where
newtm h = Bind h (Hole t) (P Bound h t)
attack ctxt env _ = fail "Not an attackable hole"
claim :: Name -> Raw -> RunTactic
claim n ty ctxt env t =
do (tyv, tyt) <- lift $ check ctxt env ty
lift $ isType ctxt env tyt
action (\ps -> let (g:gs) = holes ps in
ps { holes = g : n : gs } )
return $ Bind n (Hole tyv) t
claimFn :: Name -> Name -> Raw -> RunTactic
claimFn n bn argty ctxt env t@(Bind x (Hole retty) sc) =
do (tyv, tyt) <- lift $ check ctxt env argty
lift $ isType ctxt env tyt
action (\ps -> let (g:gs) = holes ps in
ps { holes = g : n : gs } )
return $ Bind n (Hole (Bind bn (Pi RigW Nothing tyv tyt) retty)) t
claimFn _ _ _ ctxt env _ = fail "Can't make function type here"
reorder_claims :: RunTactic
reorder_claims ctxt env t
let (bs, sc) = scvs t []
newbs = reverse (sortB (reverse bs)) in
traceWhen (bs /= newbs) (show bs ++ "\n ==> \n" ++ show newbs) $
return (bindAll newbs sc)
where scvs (Bind n b@(Hole _) sc) acc = scvs sc ((n, b):acc)
scvs sc acc = (reverse acc, sc)
sortB :: [(Name, Binder (TT Name))] -> [(Name, Binder (TT Name))]
sortB [] = []
sortB (x:xs) | all (noOcc x) xs = x : sortB xs
| otherwise = sortB (insertB x xs)
insertB x [] = [x]
insertB x (y:ys) | all (noOcc x) (y:ys) = x : y : ys
| otherwise = y : insertB x ys
noOcc (n, _) (_, Let _ t v) = noOccurrence n t && noOccurrence n v
noOcc (n, _) (_, Guess t v) = noOccurrence n t && noOccurrence n v
noOcc (n, _) (_, b) = noOccurrence n (binderTy b)
focus :: Name -> RunTactic
focus n ctxt env t = do action (\ps -> let hs = holes ps in
if n `elem` hs
then ps { holes = n : (hs \\ [n]) }
else ps)
ps <- get
return t
movelast :: Name -> RunTactic
movelast n ctxt env t = do action (\ps -> let hs = holes ps in
if n `elem` hs
then ps { holes = (hs \\ [n]) ++ [n] }
else ps)
return t
implementationArg :: Name -> RunTactic
implementationArg n ctxt env (Bind x (Hole t) sc)
= do action (\ps -> let hs = holes ps
is = implementations ps in
ps { holes = (hs \\ [x]) ++ [x],
implementations = x:is })
return (Bind x (Hole t) sc)
implementationArg n ctxt env _
= fail "The current focus is not a hole."
autoArg :: Name -> RunTactic
autoArg n ctxt env (Bind x (Hole t) sc)
= do action (\ps -> case lookup x (autos ps) of
Nothing ->
let hs = holes ps in
ps { holes = (hs \\ [x]) ++ [x],
autos = (x, (while_elaborating ps, refsIn t)) : autos ps }
Just _ -> ps)
return (Bind x (Hole t) sc)
autoArg n ctxt env _
= fail "The current focus not a hole."
setinj :: Name -> RunTactic
setinj n ctxt env (Bind x b sc)
= do action (\ps -> let is = injective ps in
ps { injective = n : is })
return (Bind x b sc)
defer :: [Name] -> [Name] -> Name -> RunTactic
defer dropped linused n ctxt env (Bind x (Hole t) (P nt x' ty)) | x == x' =
do let env' = filter (\(n, _, t) -> n `notElem` dropped) env
action (\ps -> let hs = holes ps in
ps { usedns = n : usedns ps,
holes = hs \\ [x] })
ps <- get
return (Bind n (GHole (length env') (psnames ps) (mkTy (reverse env') t))
(mkApp (P Ref n ty) (map getP (reverse env'))))
where
mkTy [] t = t
mkTy ((n,rig,b) : bs) t = Bind n (Pi (setRig rig n) Nothing (binderTy b) (TType (UVar [] 0))) (mkTy bs t)
setRig Rig1 n | n `elem` linused = Rig0
setRig rig n = rig
getP (n, rig, b) = P Bound n (binderTy b)
defer dropped linused n ctxt env _ = fail "Can't defer a non-hole focus."
deferType :: Name -> Raw -> [Name] -> RunTactic
deferType n fty_in args ctxt env (Bind x (Hole t) (P nt x' ty)) | x == x' =
do (fty, _) <- lift $ check ctxt env fty_in
action (\ps -> let hs = holes ps
ds = deferred ps in
ps { holes = hs \\ [x],
deferred = n : ds })
return (Bind n (GHole 0 [] fty)
(mkApp (P Ref n ty) (map getP args)))
where
getP n = case lookupBinder n env of
Just b -> P Bound n (binderTy b)
Nothing -> error ("deferType can't find " ++ show n)
deferType _ _ _ _ _ _ = fail "Can't defer a non-hole focus."
unifyGoal :: Raw -> RunTactic
unifyGoal tm ctxt env h@(Bind x b sc) =
do (tmv, _) <- lift $ check ctxt env tm
ns' <- unify' ctxt env (binderTy b, Nothing) (tmv, Nothing)
return h
unifyGoal _ _ _ _ = fail "The focus is not a binder."
unifyTerms :: Raw -> Raw -> RunTactic
unifyTerms tm1 tm2 ctxt env h =
do (tm1v, _) <- lift $ check ctxt env tm1
(tm2v, _) <- lift $ check ctxt env tm2
ns' <- unify' ctxt env (tm1v, Nothing) (tm2v, Nothing)
return h
exact :: Raw -> RunTactic
exact guess ctxt env (Bind x (Hole ty) sc) =
do (val, valty) <- lift $ check ctxt env guess
lift $ converts ctxt env valty ty
return $ Bind x (Guess ty val) sc
exact _ _ _ _ = fail "Can't fill here."
fill :: Raw -> RunTactic
fill guess ctxt env (Bind x (Hole ty) sc) =
do (val, valty) <- lift $ check ctxt env guess
unify' ctxt env (valty, Just $ SourceTerm val)
(ty, Just (chkPurpose val ty))
return $ Bind x (Guess ty val) sc
where
chkPurpose val (Bind _ (Pi _ _ (P _ (MN _ _) _) _) (P _ (MN _ _) _))
= TooManyArgs val
chkPurpose _ _ = ExpectedType
fill _ _ _ _ = fail "Can't fill here."
match_fill :: Raw -> RunTactic
match_fill guess ctxt env (Bind x (Hole ty) sc) =
do (val, valty) <- lift $ check ctxt env guess
match_unify' ctxt env (valty, Just $ SourceTerm val)
(ty, Just ExpectedType)
return $ Bind x (Guess ty val) sc
match_fill _ _ _ _ = fail "Can't fill here."
prep_fill :: Name -> [Name] -> RunTactic
prep_fill f as ctxt env (Bind x (Hole ty) sc) =
do let val = mkApp (P Ref f Erased) (map (\n -> P Ref n Erased) as)
return $ Bind x (Guess ty val) sc
prep_fill f as ctxt env t = fail $ "Can't prepare fill at " ++ show t
complete_fill :: RunTactic
complete_fill ctxt env (Bind x (Guess ty val) sc) =
do let guess = forget val
(val', valty) <- lift $ check ctxt env guess
unify' ctxt env (valty, Just $ SourceTerm val')
(ty, Just ExpectedType)
return $ Bind x (Guess ty val) sc
complete_fill ctxt env t = fail $ "Can't complete fill at " ++ show t
solve :: RunTactic
solve ctxt env (Bind x (Guess ty val) sc)
= do ps <- get
dropdots <-
case lookup x (notunified ps) of
Just (P _ h _)
trace ( " NEED MATCH : " + + show ( x , tm , ) + + " \nIN " + + show ( pterm ps ) ) $
do match_unify' ctxt env (tm, Just InferredVal)
(val, Just GivenVal)
return [x]
_ -> return []
action (\ps -> ps { holes = traceWhen (unifylog ps) ("Dropping hole " ++ show x) $
holes ps \\ [x],
solved = Just (x, val),
dontunify = filter (/= x) (dontunify ps),
notunified = updateNotunified [(x,val)]
(notunified ps),
recents = x : recents ps,
implementations = implementations ps \\ [x],
dotted = dropUnified dropdots (dotted ps) })
let (locked, _) = tryLock (holes ps \\ [x]) (updsubst x val sc) in
return locked
where dropUnified ddots [] = []
dropUnified ddots ((x, es) : ds)
| x `elem` ddots || any (\e -> e `elem` ddots) es
= dropUnified ddots ds
| otherwise = (x, es) : dropUnified ddots ds
tryLock :: [Name] -> Term -> (Term, Bool)
tryLock hs tm@(App Complete _ _) = (tm, True)
tryLock hs tm@(App s f a) =
let (f', fl) = tryLock hs f
(a', al) = tryLock hs a in
if fl && al then (App Complete f' a', True)
else (App s f' a', False)
tryLock hs t@(P _ n _) = (t, not $ n `elem` hs)
tryLock hs t@(Bind n (Hole _) sc) = (t, False)
tryLock hs t@(Bind n (Guess _ _) sc) = (t, False)
tryLock hs t@(Bind n (Let r ty val) sc)
= let (ty', tyl) = tryLock hs ty
(val', vall) = tryLock hs val
(sc', scl) = tryLock hs sc in
(Bind n (Let r ty' val') sc', tyl && vall && scl)
tryLock hs t@(Bind n b sc)
= let (bt', btl) = tryLock hs (binderTy b)
(sc', scl) = tryLock hs sc in
(Bind n (b { binderTy = bt' }) sc', btl && scl)
tryLock hs t = (t, True)
solve _ _ h@(Bind x t sc)
= do ps <- get
case findType x sc of
Just t -> lift $ tfail (CantInferType (show t))
_ -> lift $ tfail (IncompleteTerm h)
where findType x (Bind n (Let r t v) sc)
= findType x v `mplus` findType x sc
findType x (Bind n t sc)
| P _ x' _ <- binderTy t, x == x' = Just n
| otherwise = findType x sc
findType x _ = Nothing
introTy :: Raw -> Maybe Name -> RunTactic
introTy ty mn ctxt env (Bind x (Hole t) (P _ x' _)) | x == x' =
do let n = case mn of
Just name -> name
Nothing -> x
let t' = case t of
x@(Bind y (Pi _ _ s _) _) -> x
_ -> normalise ctxt env t
(tyv, tyt) <- lift $ check ctxt env ty
case t' of
Bind y (Pi rig _ s _) t -> let t' = updsubst y (P Bound n s) t in
do unify' ctxt env (s, Nothing) (tyv, Nothing)
return $ Bind n (Lam rig tyv) (Bind x (Hole t') (P Bound x t'))
_ -> lift $ tfail $ CantIntroduce t'
introTy ty n ctxt env _ = fail "Can't introduce here."
intro :: Maybe Name -> RunTactic
intro mn ctxt env (Bind x (Hole t) (P _ x' _)) | x == x' =
do let t' = case t of
x@(Bind y (Pi _ _ s _) _) -> x
_ -> normalise ctxt env t
case t' of
Bind y (Pi rig _ s _) t ->
let n = case mn of
Just name -> name
Nothing -> y
t' = subst y (P Bound n s) t
in return $ Bind n (Lam rig s) (Bind x (Hole t') (P Bound x t'))
_ -> lift $ tfail $ CantIntroduce t'
intro n ctxt env _ = fail "Can't introduce here."
forAll :: Name -> RigCount -> Maybe ImplicitInfo -> Raw -> RunTactic
forAll n rig impl ty ctxt env (Bind x (Hole t) (P _ x' _)) | x == x' =
do (tyv, tyt) <- lift $ check ctxt env ty
unify' ctxt env (tyt, Nothing) (TType (UVar [] 0), Nothing)
unify' ctxt env (t, Nothing) (TType (UVar [] 0), Nothing)
return $ Bind n (Pi rig impl tyv (TType (UVar [] 0))) (Bind x (Hole t) (P Bound x t))
forAll n rig impl ty ctxt env _ = fail "Can't pi bind here"
patvar :: Name -> RunTactic
patvar n ctxt env (Bind x (Hole t) sc) =
do action (\ps -> ps { holes = traceWhen (unifylog ps) ("Dropping pattern hole " ++ show x) $
holes ps \\ [x],
solved = Just (x, P Bound n t),
dontunify = filter (/=x) (dontunify ps),
notunified = updateNotunified [(x,P Bound n t)]
(notunified ps),
injective = addInj n x (injective ps)
})
return $ Bind n (PVar RigW t) (updsubst x (P Bound n t) sc)
where addInj n x ps | x `elem` ps = n : ps
| otherwise = ps
patvar n ctxt env tm = fail $ "Can't add pattern var at " ++ show tm
letbind :: Name -> RigCount -> Raw -> Raw -> RunTactic
letbind n rig ty val ctxt env (Bind x (Hole t) (P _ x' _)) | x == x' =
do (tyv, tyt) <- lift $ check ctxt env ty
(valv, valt) <- lift $ check ctxt env val
lift $ isType ctxt env tyt
return $ Bind n (Let rig tyv valv) (Bind x (Hole t) (P Bound x t))
letbind n rig ty val ctxt env _ = fail "Can't let bind here"
expandLet :: Name -> Term -> RunTactic
expandLet n v ctxt env tm =
return $ updsubst n v tm
rewrite :: Raw -> RunTactic
rewrite tm ctxt env (Bind x (Hole t) xp@(P _ x' _)) | x == x' =
do (tmv, tmt) <- lift $ check ctxt env tm
let tmt' = normalise ctxt env tmt
case unApply tmt' of
(P _ (UN q) _, [lt,rt,l,r]) | q == txt "=" ->
do let p = Bind rname (Lam RigW lt) (mkP (P Bound rname lt) r l t)
let newt = mkP l r l t
let sc = forget $ (Bind x (Hole newt)
(mkApp (P Ref (sUN "replace") (TType (UVal 0)))
[lt, l, r, p, tmv, xp]))
(scv, sct) <- lift $ check ctxt env sc
return scv
_ -> lift $ tfail (NotEquality tmv tmt')
where rname = sMN 0 "replaced"
rewrite _ _ _ _ = fail "Can't rewrite here"
an x , and put \x : lt in front
mkP :: TT Name -> TT Name -> TT Name -> TT Name -> TT Name
mkP lt l r ty | l == ty = lt
mkP lt l r (App s f a) = let f' = if (r /= f) then mkP lt l r f else f
a' = if (r /= a) then mkP lt l r a else a in
App s f' a'
mkP lt l r (Bind n b sc)
= let b' = mkPB b
sc' = if (r /= sc) then mkP lt l r sc else sc in
Bind n b' sc'
where mkPB (Let c t v) = let t' = if (r /= t) then mkP lt l r t else t
v' = if (r /= v) then mkP lt l r v else v in
Let c t' v'
mkPB b = let ty = binderTy b
ty' = if (r /= ty) then mkP lt l r ty else ty in
b { binderTy = ty' }
mkP lt l r x = x
equiv :: Raw -> RunTactic
equiv tm ctxt env (Bind x (Hole t) sc) =
do (tmv, tmt) <- lift $ check ctxt env tm
lift $ converts ctxt env tmv t
return $ Bind x (Hole tmv) sc
equiv tm ctxt env _ = fail "Can't equiv here"
patbind :: Name -> RigCount -> RunTactic
patbind n rig ctxt env (Bind x (Hole t) (P _ x' _)) | x == x' =
do let t' = case t of
x@(Bind y (PVTy s) t) -> x
_ -> normalise ctxt env t
case t' of
Bind y (PVTy s) t -> let t' = updsubst y (P Bound n s) t in
return $ Bind n (PVar rig s) (Bind x (Hole t') (P Bound x t'))
_ -> fail "Nothing to pattern bind"
patbind n _ ctxt env _ = fail "Can't pattern bind here"
compute :: RunTactic
compute ctxt env (Bind x (Hole ty) sc) =
do return $ Bind x (Hole (normalise ctxt env ty)) sc
compute ctxt env t = return t
whnf_compute :: RunTactic
whnf_compute ctxt env (Bind x (Hole ty) sc) =
do let ty' = whnf ctxt env ty in
return $ Bind x (Hole ty') sc
whnf_compute ctxt env t = return t
whnf_compute_args :: RunTactic
whnf_compute_args ctxt env (Bind x (Hole ty) sc) =
do let ty' = whnfArgs ctxt env ty in
return $ Bind x (Hole ty') sc
whnf_compute_args ctxt env t = return t
simplify :: RunTactic
simplify ctxt env (Bind x (Hole ty) sc) =
do return $ Bind x (Hole (fst (specialise ctxt env [] ty))) sc
simplify ctxt env t = return t
check_in :: Raw -> RunTactic
check_in t ctxt env tm =
do (val, valty) <- lift $ check ctxt env t
addLog (showEnv env val ++ " : " ++ showEnv env valty)
return tm
eval_in :: Raw -> RunTactic
eval_in t ctxt env tm =
do (val, valty) <- lift $ check ctxt env t
let val' = normalise ctxt env val
let valty' = normalise ctxt env valty
addLog (showEnv env val ++ " : " ++
showEnv env valty ++
" ==>\n " ++
showEnv env val' ++ " : " ++
showEnv env valty')
return tm
start_unify :: Name -> RunTactic
return tm
solve_unified :: RunTactic
solve_unified ctxt env tm =
do ps <- get
let (_, ns) = unified ps
let unify = dropGiven (dontunify ps) ns (holes ps)
action (\ps -> ps { holes = traceWhen (unifylog ps) ("Dropping holes " ++ show (map fst unify)) $
holes ps \\ map fst unify,
recents = recents ps ++ map fst unify })
action (\ps -> ps { pterm = updateSolved unify (pterm ps) })
return (updateSolvedTerm unify tm)
dropGiven du [] hs = []
dropGiven du ((n, P Bound t ty) : us) hs
| n `elem` du && not (t `elem` du)
&& n `elem` hs && t `elem` hs
= (t, P Bound n ty) : dropGiven du us hs
dropGiven du (u@(n, _) : us) hs
| n `elem` du = dropGiven du us hs
( u@ ( _ , P a n ty ) : us ) | n ` elem ` du = dropGiven du us
dropGiven du (u : us) hs = u : dropGiven du us hs
keepGiven du [] hs = []
keepGiven du ((n, P Bound t ty) : us) hs
| n `elem` du && not (t `elem` du)
&& n `elem` hs && t `elem` hs
= keepGiven du us hs
keepGiven du (u@(n, _) : us) hs
| n `elem` du = u : keepGiven du us hs
keepGiven du (u : us) hs = keepGiven du us hs
updateEnv [] e = e
updateEnv ns [] = []
updateEnv ns ((n, rig, b) : env)
= (n, rig, fmap (updateSolvedTerm ns) b) : updateEnv ns env
updateProv ns (SourceTerm t) = SourceTerm $ updateSolvedTerm ns t
updateProv ns p = p
updateError [] err = err
updateError ns (At f e) = At f (updateError ns e)
updateError ns (Elaborating s n ty e) = Elaborating s n ty (updateError ns e)
updateError ns (ElaboratingArg f a env e)
= ElaboratingArg f a env (updateError ns e)
updateError ns (CantUnify b (l,lp) (r,rp) e xs sc)
= CantUnify b (updateSolvedTerm ns l, fmap (updateProv ns) lp)
(updateSolvedTerm ns r, fmap (updateProv ns) rp) (updateError ns e) xs sc
updateError ns e = e
mergeNotunified :: Env -> [Name] -> [(Name, Term)] -> ([(Name, Term)], Fails)
mergeNotunified env holes ns = mnu ns [] [] where
mnu [] ns_acc ps_acc = (reverse ns_acc, reverse ps_acc)
mnu ((n, t):ns) ns_acc ps_acc
| Just t' <- lookup n ns, t /= t'
= mnu ns ((n,t') : ns_acc)
((t,t',True, env,CantUnify True (t, Nothing) (t', Nothing) (Msg "") [] 0, [],Match) : ps_acc)
| otherwise = mnu ns ((n,t) : ns_acc) ps_acc
updateNotunified [] nu = nu
updateNotunified ns nu = up nu where
up [] = []
up ((n, t) : nus) = let t' = updateSolvedTerm ns t in
((n, t') : up nus)
getProvenance :: Err -> (Maybe Provenance, Maybe Provenance)
getProvenance (CantUnify _ (_, lp) (_, rp) _ _ _) = (lp, rp)
getProvenance _ = (Nothing, Nothing)
setReady (x, y, _, env, err, c, at) = (x, y, True, env, err, c, at)
updateProblems :: ProofState -> [(Name, TT Name)] -> Fails
-> ([(Name, TT Name)], Fails)
[ ] ps inj holes = ( [ ] , ps )
updateProblems ps updates probs = rec 10 updates probs
where
rec 0 us fs = (us, fs)
rec n us fs = case up us [] fs of
res@(_, []) -> res
res@(us', _) | length us' == length us -> res
(us', fs') -> rec (n - 1) us' fs'
hs = holes ps
inj = injective ps
ctxt = context ps
ulog = unifylog ps
usupp = map fst (notunified ps)
dont = dontunify ps
up ns acc [] = (ns, map (updateNs ns) (reverse acc))
up ns acc (prob@(x, y, ready, env, err, while, um) : ps) =
let (x', newx) = updateSolvedTerm' ns x
(y', newy) = updateSolvedTerm' ns y
(lp, rp) = getProvenance err
err' = updateError ns err
env' = updateEnv ns env in
if newx || newy || ready ||
any (\n -> n `elem` inj) (refsIn x ++ refsIn y) then
case unify ctxt env' (x', lp) (y', rp) inj hs usupp while of
OK (v, []) -> traceWhen ulog ("DID " ++ show (x',y',ready,v,dont)) $
let v' = filter (\(n, _) -> n `notElem` dont) v in
up (ns ++ v') acc ps
trace ( " FAILED " + + show ( , e ) ) $
up ns ((x',y',False,env',err',while,um) : acc) ps
up ns ((x',y', False, env',err', while, um) : acc) ps
updateNs ns (x, y, t, env, err, fc, fa)
= let (x', newx) = updateSolvedTerm' ns x
(y', newy) = updateSolvedTerm' ns y in
(x', y', newx || newy,
updateEnv ns env, updateError ns err, fc, fa)
orderUpdateSolved :: [(Name, Term)] -> ProofTerm -> (ProofTerm, [Name])
orderUpdateSolved ns tm = update [] ns tm
where
update done [] t = (t, done)
update done ((n, P _ n' _) : ns) t | n == n' = update done ns t
update done (n : ns) t = update (fst n : done)
(map (updateMatch n) ns)
(updateSolved [n] t)
updateMatch n (x, tm) = (x, updateSolvedTerm [n] tm)
matchProblems :: Bool -> ProofState -> [(Name, TT Name)] -> Fails
-> ([(Name, TT Name)], Fails)
matchProblems all ps updates probs = up updates probs where
hs = holes ps
inj = injective ps
ctxt = context ps
up ns [] = (ns, [])
up ns ((x, y, ready, env, err, while, um) : ps)
| all || um == Match =
let x' = updateSolvedTerm ns x
y' = updateSolvedTerm ns y
(lp, rp) = getProvenance err
err' = updateError ns err
env' = updateEnv ns env in
case match_unify ctxt env' (x', lp) (y', rp) inj hs while of
up (ns ++ v) ps
_ -> let (ns', ps') = up ns ps in
(ns', (x', y', True, env', err', while, um) : ps')
up ns (p : ps) = let (ns', ps') = up ns ps in
(ns', p : ps')
processTactic :: Tactic -> ProofState -> TC (ProofState, String)
processTactic QED ps = case holes ps of
(tm', ty', _) <- recheck (constraint_ns ps) (context ps) [] (forget tm) tm
return (ps { done = True, pterm = mkProofTerm tm' },
"Proof complete: " ++ showEnv [] tm')
_ -> fail "Still holes to fill."
processTactic ProofState ps = return (ps, showEnv [] (getProofTerm (pterm ps)))
processTactic Undo ps = case previous ps of
Nothing -> Error . Msg $ "Nothing to undo."
Just pold -> return (pold, "")
processTactic EndUnify ps
= let (h, ns_in) = unified ps
ns = dropGiven (dontunify ps) ns_in (holes ps)
ns' = map (\ (n, t) -> (n, updateSolvedTerm ns t)) ns
(ns'', probs') = updateProblems ps ns' (problems ps)
tm' = updateSolved ns'' (pterm ps) in
traceWhen (unifylog ps) ("(EndUnify) Dropping holes: " ++ show (map fst ns'')) $
return (ps { pterm = tm',
unified = (h, []),
problems = probs',
notunified = updateNotunified ns'' (notunified ps),
recents = recents ps ++ map fst ns'',
holes = holes ps \\ map fst ns'' }, "")
processTactic UnifyAll ps
= let tm' = updateSolved (notunified ps) (pterm ps) in
return (ps { pterm = tm',
notunified = [],
recents = recents ps ++ map fst (notunified ps),
holes = holes ps \\ map fst (notunified ps) }, "")
processTactic (Reorder n) ps
= do ps' <- execStateT (tactic (Just n) reorder_claims) ps
return (ps' { previous = Just ps, plog = "" }, plog ps')
processTactic (ComputeLet n) ps
= return (ps { pterm = mkProofTerm $
computeLet (context ps) n
(getProofTerm (pterm ps)) }, "")
processTactic UnifyProblems ps
= do let (ns', probs') = updateProblems ps [] (map setReady (problems ps))
(pterm', dropped) = orderUpdateSolved ns' (pterm ps)
traceWhen (unifylog ps) ("(UnifyProblems) Dropping holes: " ++ show dropped) $
return (ps { pterm = pterm', solved = Nothing, problems = probs',
previous = Just ps, plog = "",
notunified = updateNotunified ns' (notunified ps),
recents = recents ps ++ dropped,
dotted = filter (notIn ns') (dotted ps),
holes = holes ps \\ dropped }, plog ps)
where notIn ns (h, _) = h `notElem` map fst ns
processTactic (MatchProblems all) ps
= do let (ns', probs') = matchProblems all ps [] (map setReady (problems ps))
(ns'', probs'') = matchProblems all ps ns' probs'
(pterm', dropped) = orderUpdateSolved ns'' (resetProofTerm (pterm ps))
traceWhen (unifylog ps) ("(MatchProblems) Dropping holes: " ++ show dropped) $
return (ps { pterm = pterm', solved = Nothing, problems = probs'',
previous = Just ps, plog = "",
notunified = updateNotunified ns'' (notunified ps),
recents = recents ps ++ dropped,
holes = holes ps \\ dropped }, plog ps)
processTactic t ps
= case holes ps of
[] -> case t of
_ -> fail $ "Proof done, nothing to run tactic on: " ++ show t ++
"\n" ++ show (getProofTerm (pterm ps))
(h:_) -> do ps' <- execStateT (process t h) ps
let (ns_in, probs')
= case solved ps' of
Just s -> traceWhen (unifylog ps)
("SOLVED " ++ show s ++ " " ++ show (dontunify ps')) $
updateProblems ps' [s] (problems ps')
_ -> ([], problems ps')
let ns' = dropGiven (dontunify ps') ns_in (holes ps')
let pterm'' = updateSolved ns' (pterm ps')
traceWhen (unifylog ps)
("Updated problems after solve " ++ qshow probs' ++ "\n" ++
"(Toplevel) Dropping holes: " ++ show (map fst ns') ++ "\n" ++
"Holes were: " ++ show (holes ps')) $
return (ps' { pterm = pterm'',
solved = Nothing,
problems = probs',
notunified = updateNotunified ns' (notunified ps'),
previous = Just ps, plog = "",
recents = recents ps' ++ map fst ns',
holes = holes ps' \\ (map fst ns')
}, plog ps')
process :: Tactic -> Name -> StateT TState TC ()
process EndUnify _
= do ps <- get
let (h, _) = unified ps
tactic (Just h) solve_unified
process t h = tactic (Just h) (mktac t)
where mktac Attack = attack
mktac (Claim n r) = claim n r
mktac (ClaimFn n bn r) = claimFn n bn r
mktac (Exact r) = exact r
mktac (Fill r) = fill r
mktac (MatchFill r) = match_fill r
mktac (PrepFill n ns) = prep_fill n ns
mktac CompleteFill = complete_fill
mktac Solve = solve
mktac (StartUnify n) = start_unify n
mktac Compute = compute
mktac Simplify = Idris.Core.ProofState.simplify
mktac WHNF_Compute = whnf_compute
mktac WHNF_ComputeArgs = whnf_compute_args
mktac (Intro n) = intro n
mktac (IntroTy ty n) = introTy ty n
mktac (Forall n r i t) = forAll n r i t
mktac (LetBind n r t v) = letbind n r t v
mktac (ExpandLet n b) = expandLet n b
mktac (Rewrite t) = rewrite t
mktac (Equiv t) = equiv t
mktac (PatVar n) = patvar n
mktac (PatBind n rig) = patbind n rig
mktac (CheckIn r) = check_in r
mktac (EvalIn r) = eval_in r
mktac (Focus n) = focus n
mktac (Defer ns ls n) = defer ns ls n
mktac (DeferType n t a) = deferType n t a
mktac (Implementation n)= implementationArg n
mktac (AutoArg n) = autoArg n
mktac (SetInjective n) = setinj n
mktac (MoveLast n) = movelast n
mktac (UnifyGoal r) = unifyGoal r
mktac (UnifyTerms x y) = unifyTerms x y
|
38195c494de2d9ab7c99d8512d62cc2c574d1b879f566b0db28338938b827e77 | startalkIM/ejabberd | mod_http_api.erl | %%%----------------------------------------------------------------------
%%% File : mod_http_api.erl
Author : >
%%% Purpose : Implements REST API for ejabberd using JSON data
Created : 15 Sep 2014 by
%%%
%%%
ejabberd , Copyright ( C ) 2002 - 2016 ProcessOne
%%%
%%% This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License as
published by the Free Software Foundation ; either version 2 of the
%%% License, or (at your option) any later version.
%%%
%%% This program is distributed in the hope that it will be useful,
%%% but WITHOUT ANY WARRANTY; without even the implied warranty of
%%% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
%%% General Public License for more details.
%%%
You should have received a copy of the GNU General Public License along
with this program ; if not , write to the Free Software Foundation , Inc. ,
51 Franklin Street , Fifth Floor , Boston , USA .
%%%
%%%----------------------------------------------------------------------
%% Example config:
%%
%% in ejabberd_http listener
%% request_handlers:
%% "/api": mod_http_api
%%
%% To use a specific API version N, add a vN element in the URL path:
%% in ejabberd_http listener
%% request_handlers:
%% "/api/v2": mod_http_api
%%
%% Access rights are defined with:
commands_admin_access : configure
%% commands:
%% - add_commands: user
%%
%%
%% add_commands allow exporting a class of commands, from
%% open: methods is not risky and can be called by without any access check
restricted ( default ): the same , but will appear only in ejabberdctl list .
admin – auth is required with XMLRPC and HTTP API and checked for admin priviledges , works as usual in ejabberdctl .
user - can be used through XMLRPC and HTTP API , even by user . Only admin can use the commands for other users .
%%
%% Then to perform an action, send a POST request to the following URL:
%% :5280/api/<call_name>
%%
%% It's also possible to enable unrestricted access to some commands from group
of IP addresses by using option ` admin_ip_access ` by having fragment like
%% this in configuration file:
%% modules:
%% mod_http_api:
%% admin_ip_access: admin_ip_access_rule
%%...
%% access:
%% admin_ip_access_rule:
%% admin_ip_acl:
%% - command1
%% - command2
%% %% use `all` to give access to all commands
%%...
%% acl:
%% admin_ip_acl:
%% ip:
%% - "127.0.0.1/8"
-module(mod_http_api).
-author('').
-behaviour(gen_mod).
-export([start/2, stop/1, process/2, mod_opt_type/1, depends/2]).
-include("ejabberd.hrl").
-include("jlib.hrl").
-include("logger.hrl").
-include("ejabberd_http.hrl").
-define(DEFAULT_API_VERSION, 0).
-define(CT_PLAIN,
{<<"Content-Type">>, <<"text/plain">>}).
-define(CT_XML,
{<<"Content-Type">>, <<"text/xml; charset=utf-8">>}).
-define(CT_JSON,
{<<"Content-Type">>, <<"application/json">>}).
-define(AC_ALLOW_ORIGIN,
{<<"Access-Control-Allow-Origin">>, <<"*">>}).
-define(AC_ALLOW_METHODS,
{<<"Access-Control-Allow-Methods">>,
<<"GET, POST, OPTIONS">>}).
-define(AC_ALLOW_HEADERS,
{<<"Access-Control-Allow-Headers">>,
<<"Content-Type, Authorization, X-Admin">>}).
-define(AC_MAX_AGE,
{<<"Access-Control-Max-Age">>, <<"86400">>}).
-define(OPTIONS_HEADER,
[?CT_PLAIN, ?AC_ALLOW_ORIGIN, ?AC_ALLOW_METHODS,
?AC_ALLOW_HEADERS, ?AC_MAX_AGE]).
-define(HEADER(CType),
[CType, ?AC_ALLOW_ORIGIN, ?AC_ALLOW_HEADERS]).
%% -------------------
%% Module control
%% -------------------
start(_Host, _Opts) ->
ok.
stop(_Host) ->
ok.
depends(_Host, _Opts) ->
[].
%% ----------
%% basic auth
%% ----------
check_permissions(Request, Command) ->
case catch binary_to_existing_atom(Command, utf8) of
Call when is_atom(Call) ->
{ok, CommandPolicy, Scope} = ejabberd_commands:get_command_policy_and_scope(Call),
check_permissions2(Request, Call, CommandPolicy, Scope);
_ ->
json_error(404, 40, <<"Endpoint not found.">>)
end.
check_permissions2(#request{auth = HTTPAuth, headers = Headers}, Call, _, ScopeList)
when HTTPAuth /= undefined ->
Admin =
case lists:keysearch(<<"X-Admin">>, 1, Headers) of
{value, {_, <<"true">>}} -> true;
_ -> false
end,
Auth =
case HTTPAuth of
{SJID, Pass} ->
case jid:from_string(SJID) of
#jid{user = User, server = Server} ->
case ejabberd_auth:check_password(User, <<"">>, Server, Pass) of
true -> {ok, {User, Server, Pass, Admin}};
false -> false
end;
_ ->
false
end;
{oauth, Token, _} ->
case oauth_check_token(ScopeList, Token) of
{ok, user, {User, Server}} ->
{ok, {User, Server, {oauth, Token}, Admin}};
{false, Reason} ->
{false, Reason}
end;
_ ->
false
end,
case Auth of
{ok, A} -> {allowed, Call, A};
{false, no_matching_scope} -> outofscope_response();
_ -> unauthorized_response()
end;
check_permissions2(_Request, Call, open, _Scope) ->
{allowed, Call, noauth};
check_permissions2(#request{ip={IP, _Port}}, Call, _Policy, _Scope) ->
Access = gen_mod:get_module_opt(global, ?MODULE, admin_ip_access,
fun(V) -> V end,
none),
Res = acl:match_rule(global, Access, IP),
case Res of
all ->
{allowed, Call, admin};
[all] ->
{allowed, Call, admin};
allow ->
{allowed, Call, admin};
Commands when is_list(Commands) ->
case lists:member(Call, Commands) of
true -> {allowed, Call, admin};
_ -> outofscope_response()
end;
_E ->
{allowed, Call, noauth}
end;
check_permissions2(_Request, _Call, _Policy, _Scope) ->
unauthorized_response().
oauth_check_token(ScopeList, Token) when is_list(ScopeList) ->
ejabberd_oauth:check_token(ScopeList, Token).
%% ------------------
%% command processing
%% ------------------
%process(Call, Request) ->
? ~ n ~ p " , [ Call , Request ] ) , ok ;
process(_, #request{method = 'POST', data = <<>>}) ->
?DEBUG("Bad Request: no data", []),
badrequest_response(<<"Missing POST data">>);
process([Call], #request{method = 'POST', data = Data, ip = {IP, _} = IPPort} = Req) ->
Version = get_api_version(Req),
try
Args = extract_args(Data),
log(Call, Args, IPPort),
case check_permissions(Req, Call) of
{allowed, Cmd, Auth} ->
Result = handle(Cmd, Auth, Args, Version, IP),
json_format(Result);
Warning : check_permission direcly formats 401 reply if not authorized
ErrorResponse ->
ErrorResponse
end
catch
%% TODO We need to refactor to remove redundant error return formatting
throw:{error, unknown_command} ->
{404, 40, <<"Command not found.">>};
_:{error,{_,invalid_json}} = _Err ->
?DEBUG("Bad Request: ~p", [_Err]),
badrequest_response(<<"Invalid JSON input">>);
_:_Error ->
?DEBUG("Bad Request: ~p ~p", [_Error, erlang:get_stacktrace()]),
badrequest_response()
end;
process([Call], #request{method = 'GET', q = Data, ip = IP} = Req) ->
Version = get_api_version(Req),
try
Args = case Data of
[{nokey, <<>>}] -> [];
_ -> Data
end,
log(Call, Args, IP),
case check_permissions(Req, Call) of
{allowed, Cmd, Auth} ->
Result = handle(Cmd, Auth, Args, Version, IP),
json_format(Result);
Warning : check_permission direcly formats 401 reply if not authorized
ErrorResponse ->
ErrorResponse
end
catch
%% TODO We need to refactor to remove redundant error return formatting
throw:{error, unknown_command} ->
json_format({404, 44, <<"Command not found.">>});
_:_Error ->
?DEBUG("Bad Request: ~p ~p", [_Error, erlang:get_stacktrace()]),
badrequest_response()
end;
process([_Call], #request{method = 'OPTIONS', data = <<>>}) ->
{200, ?OPTIONS_HEADER, []};
process(_, #request{method = 'OPTIONS'}) ->
{400, ?OPTIONS_HEADER, []};
process(_Path, Request) ->
?DEBUG("Bad Request: no handler ~p", [Request]),
json_error(400, 40, <<"Missing command name.">>).
%% Be tolerant to make API more easily usable from command-line pipe.
extract_args(<<"\n">>) -> [];
extract_args(Data) ->
case jiffy:decode(Data) of
List when is_list(List) -> List;
{List} when is_list(List) -> List;
Other -> [Other]
end.
% get API version N from last "vN" element in URL path
get_api_version(#request{path = Path}) ->
get_api_version(lists:reverse(Path));
get_api_version([<<"v", String/binary>> | Tail]) ->
case catch jlib:binary_to_integer(String) of
N when is_integer(N) ->
N;
_ ->
get_api_version(Tail)
end;
get_api_version([_Head | Tail]) ->
get_api_version(Tail);
get_api_version([]) ->
?DEFAULT_API_VERSION.
%% ----------------
%% command handlers
%% ----------------
%% TODO Check accept types of request before decided format of reply.
% generic ejabberd command handler
handle(Call, Auth, Args, Version, IP) when is_atom(Call), is_list(Args) ->
case ejabberd_commands:get_command_format(Call, Auth, Version) of
{ArgsSpec, _} when is_list(ArgsSpec) ->
Args2 = [{jlib:binary_to_atom(Key), Value} || {Key, Value} <- Args],
Spec = lists:foldr(
fun ({Key, binary}, Acc) ->
[{Key, <<>>}|Acc];
({Key, string}, Acc) ->
[{Key, <<>>}|Acc];
({Key, integer}, Acc) ->
[{Key, 0}|Acc];
({Key, {list, _}}, Acc) ->
[{Key, []}|Acc];
({Key, atom}, Acc) ->
[{Key, undefined}|Acc]
end, [], ArgsSpec),
try
handle2(Call, Auth, match(Args2, Spec), Version, IP)
catch throw:not_found ->
{404, <<"not_found">>};
throw:{not_found, Why} when is_atom(Why) ->
{404, jlib:atom_to_binary(Why)};
throw:{not_found, Msg} ->
{404, iolist_to_binary(Msg)};
throw:not_allowed ->
{401, <<"not_allowed">>};
throw:{not_allowed, Why} when is_atom(Why) ->
{401, jlib:atom_to_binary(Why)};
throw:{not_allowed, Msg} ->
{401, iolist_to_binary(Msg)};
throw:{error, account_unprivileged} ->
{403, 31, <<"Command need to be run with admin priviledge.">>};
throw:{error, access_rules_unauthorized} ->
{403, 32, <<"AccessRules: Account associated to token does not have the right to perform the operation.">>};
throw:{invalid_parameter, Msg} ->
{400, iolist_to_binary(Msg)};
throw:{error, Why} when is_atom(Why) ->
{400, jlib:atom_to_binary(Why)};
throw:{error, Msg} ->
{400, iolist_to_binary(Msg)};
throw:Error when is_atom(Error) ->
{400, jlib:atom_to_binary(Error)};
throw:Msg when is_list(Msg); is_binary(Msg) ->
{400, iolist_to_binary(Msg)};
_Error ->
?ERROR_MSG("REST API Error: ~p ~p", [_Error, erlang:get_stacktrace()]),
{500, <<"internal_error">>}
end;
{error, Msg} ->
?ERROR_MSG("REST API Error: ~p", [Msg]),
{400, Msg};
_Error ->
?ERROR_MSG("REST API Error: ~p", [_Error]),
{400, <<"Error">>}
end.
handle2(Call, Auth, Args, Version, IP) when is_atom(Call), is_list(Args) ->
{ArgsF, _ResultF} = ejabberd_commands:get_command_format(Call, Auth, Version),
ArgsFormatted = format_args(Args, ArgsF),
ejabberd_command(Auth, Call, ArgsFormatted, Version, IP).
get_elem_delete(A, L) ->
case proplists:get_all_values(A, L) of
[Value] -> {Value, proplists:delete(A, L)};
[_, _ | _] ->
%% Crash reporting the error
exit({duplicated_attribute, A, L});
[] ->
%% Report the error and then force a crash
exit({attribute_not_found, A, L})
end.
format_args(Args, ArgsFormat) ->
{ArgsRemaining, R} = lists:foldl(fun ({ArgName,
ArgFormat},
{Args1, Res}) ->
{ArgValue, Args2} =
get_elem_delete(ArgName,
Args1),
Formatted = format_arg(ArgValue,
ArgFormat),
{Args2, Res ++ [Formatted]}
end,
{Args, []}, ArgsFormat),
case ArgsRemaining of
[] -> R;
L when is_list(L) -> exit({additional_unused_args, L})
end.
format_arg({Elements},
{list, {_ElementDefName, {tuple, [{_Tuple1N, Tuple1S}, {_Tuple2N, Tuple2S}]} = Tuple}})
when is_list(Elements) andalso
(Tuple1S == binary orelse Tuple1S == string) ->
lists:map(fun({F1, F2}) ->
{format_arg(F1, Tuple1S), format_arg(F2, Tuple2S)};
({Val}) when is_list(Val) ->
format_arg({Val}, Tuple)
end, Elements);
format_arg(Elements,
{list, {_ElementDefName, {list, _} = ElementDefFormat}})
when is_list(Elements) ->
[{format_arg(Element, ElementDefFormat)}
|| Element <- Elements];
format_arg(Elements,
{list, {_ElementDefName, ElementDefFormat}})
when is_list(Elements) ->
[format_arg(Element, ElementDefFormat)
|| Element <- Elements];
format_arg({[{Name, Value}]},
{tuple, [{_Tuple1N, Tuple1S}, {_Tuple2N, Tuple2S}]})
when Tuple1S == binary;
Tuple1S == string ->
{format_arg(Name, Tuple1S), format_arg(Value, Tuple2S)};
format_arg({Elements},
{tuple, ElementsDef})
when is_list(Elements) ->
F = lists:map(fun({TElName, TElDef}) ->
case lists:keyfind(atom_to_binary(TElName, latin1), 1, Elements) of
{_, Value} ->
format_arg(Value, TElDef);
_ when TElDef == binary; TElDef == string ->
<<"">>;
_ ->
?ERROR_MSG("missing field ~p in tuple ~p", [TElName, Elements]),
throw({invalid_parameter,
io_lib:format("Missing field ~w in tuple ~w", [TElName, Elements])})
end
end, ElementsDef),
list_to_tuple(F);
format_arg(Elements, {list, ElementsDef})
when is_list(Elements) and is_atom(ElementsDef) ->
[format_arg(Element, ElementsDef)
|| Element <- Elements];
format_arg(Arg, integer) when is_integer(Arg) -> Arg;
format_arg(Arg, binary) when is_list(Arg) -> process_unicode_codepoints(Arg);
format_arg(Arg, binary) when is_binary(Arg) -> Arg;
format_arg(Arg, string) when is_list(Arg) -> process_unicode_codepoints(Arg);
format_arg(Arg, string) when is_binary(Arg) -> Arg;
format_arg(undefined, binary) -> <<>>;
format_arg(undefined, string) -> <<>>;
format_arg(Arg, Format) ->
?ERROR_MSG("don't know how to format Arg ~p for format ~p", [Arg, Format]),
throw({invalid_parameter,
io_lib:format("Arg ~w is not in format ~w",
[Arg, Format])}).
process_unicode_codepoints(Str) ->
iolist_to_binary(lists:map(fun(X) when X > 255 -> unicode:characters_to_binary([X]);
(Y) -> Y
end, Str)).
%% ----------------
%% internal helpers
%% ----------------
match(Args, Spec) ->
[{Key, proplists:get_value(Key, Args, Default)} || {Key, Default} <- Spec].
ejabberd_command(Auth, Cmd, Args, Version, IP) ->
Access = case Auth of
admin -> [];
_ -> undefined
end,
case ejabberd_commands:execute_command(Access, Auth, Cmd, Args, Version, #{ip => IP}) of
{error, Error} ->
throw(Error);
Res ->
format_command_result(Cmd, Auth, Res, Version)
end.
format_command_result(Cmd, Auth, Result, Version) ->
{_, ResultFormat} = ejabberd_commands:get_command_format(Cmd, Auth, Version),
case {ResultFormat, Result} of
{{_, rescode}, V} when V == true; V == ok ->
{200, 0};
{{_, rescode}, _} ->
{200, 1};
{_, {error, ErrorAtom, Code, Msg}} ->
format_error_result(ErrorAtom, Code, Msg);
{{_, restuple}, {V, Text}} when V == true; V == ok ->
{200, iolist_to_binary(Text)};
{{_, restuple}, {ErrorAtom, Msg}} ->
format_error_result(ErrorAtom, 0, Msg);
{{_, {list, _}}, _V} ->
{_, L} = format_result(Result, ResultFormat),
{200, L};
{{_, {tuple, _}}, _V} ->
{_, T} = format_result(Result, ResultFormat),
{200, T};
_ ->
{200, {[format_result(Result, ResultFormat)]}}
end.
format_result(Atom, {Name, atom}) ->
{jlib:atom_to_binary(Name), jlib:atom_to_binary(Atom)};
format_result(Int, {Name, integer}) ->
{jlib:atom_to_binary(Name), Int};
format_result(String, {Name, string}) ->
{jlib:atom_to_binary(Name), iolist_to_binary(String)};
format_result(Code, {Name, rescode}) ->
{jlib:atom_to_binary(Name), Code == true orelse Code == ok};
format_result({Code, Text}, {Name, restuple}) ->
{jlib:atom_to_binary(Name),
{[{<<"res">>, Code == true orelse Code == ok},
{<<"text">>, iolist_to_binary(Text)}]}};
format_result(Code, {Name, restuple}) ->
{jlib:atom_to_binary(Name),
{[{<<"res">>, Code == true orelse Code == ok},
{<<"text">>, <<"">>}]}};
format_result(Els, {Name, {list, {_, {tuple, [{_, atom}, _]}} = Fmt}}) ->
{jlib:atom_to_binary(Name), {[format_result(El, Fmt) || El <- Els]}};
format_result(Els, {Name, {list, Def}}) ->
{jlib:atom_to_binary(Name), [element(2, format_result(El, Def)) || El <- Els]};
format_result(Tuple, {_Name, {tuple, [{_, atom}, ValFmt]}}) ->
{Name2, Val} = Tuple,
{_, Val2} = format_result(Val, ValFmt),
{jlib:atom_to_binary(Name2), Val2};
format_result(Tuple, {Name, {tuple, Def}}) ->
Els = lists:zip(tuple_to_list(Tuple), Def),
{jlib:atom_to_binary(Name), {[format_result(El, ElDef) || {El, ElDef} <- Els]}};
format_result(404, {_Name, _}) ->
"not_found".
format_error_result(conflict, Code, Msg) ->
{409, Code, iolist_to_binary(Msg)};
format_error_result(_ErrorAtom, Code, Msg) ->
{500, Code, iolist_to_binary(Msg)}.
unauthorized_response() ->
json_error(401, 10, <<"Oauth Token is invalid or expired.">>).
outofscope_response() ->
json_error(401, 11, <<"Token does not grant usage to command required scope.">>).
badrequest_response() ->
badrequest_response(<<"400 Bad Request">>).
badrequest_response(Body) ->
json_response(400, jiffy:encode(Body)).
json_format({Code, Result}) ->
json_response(Code, jiffy:encode(Result));
json_format({HTMLCode, JSONErrorCode, Message}) ->
json_error(HTMLCode, JSONErrorCode, Message).
json_response(Code, Body) when is_integer(Code) ->
{Code, ?HEADER(?CT_JSON), Body}.
HTTPCode , = integers
%% message is binary
json_error(HTTPCode, JSONCode, Message) ->
{HTTPCode, ?HEADER(?CT_JSON),
jiffy:encode({[{<<"status">>, <<"error">>},
{<<"code">>, JSONCode},
{<<"message">>, Message}]})
}.
log(Call, Args, {Addr, Port}) ->
AddrS = jlib:ip_to_list({Addr, Port}),
?INFO_MSG("API call ~s ~p from ~s:~p", [Call, Args, AddrS, Port]);
log(Call, Args, IP) ->
?INFO_MSG("API call ~s ~p (~p)", [Call, Args, IP]).
mod_opt_type(admin_ip_access) -> fun acl:access_rules_validator/1;
mod_opt_type(_) -> [admin_ip_access].
| null | https://raw.githubusercontent.com/startalkIM/ejabberd/718d86cd2f5681099fad14dab5f2541ddc612c8b/src/mod_http_api.erl | erlang | ----------------------------------------------------------------------
File : mod_http_api.erl
Purpose : Implements REST API for ejabberd using JSON data
This program is free software; you can redistribute it and/or
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
General Public License for more details.
----------------------------------------------------------------------
Example config:
in ejabberd_http listener
request_handlers:
"/api": mod_http_api
To use a specific API version N, add a vN element in the URL path:
in ejabberd_http listener
request_handlers:
"/api/v2": mod_http_api
Access rights are defined with:
commands:
- add_commands: user
add_commands allow exporting a class of commands, from
open: methods is not risky and can be called by without any access check
Then to perform an action, send a POST request to the following URL:
:5280/api/<call_name>
It's also possible to enable unrestricted access to some commands from group
this in configuration file:
modules:
mod_http_api:
admin_ip_access: admin_ip_access_rule
...
access:
admin_ip_access_rule:
admin_ip_acl:
- command1
- command2
%% use `all` to give access to all commands
...
acl:
admin_ip_acl:
ip:
- "127.0.0.1/8"
-------------------
Module control
-------------------
----------
basic auth
----------
------------------
command processing
------------------
process(Call, Request) ->
TODO We need to refactor to remove redundant error return formatting
TODO We need to refactor to remove redundant error return formatting
Be tolerant to make API more easily usable from command-line pipe.
get API version N from last "vN" element in URL path
----------------
command handlers
----------------
TODO Check accept types of request before decided format of reply.
generic ejabberd command handler
Crash reporting the error
Report the error and then force a crash
----------------
internal helpers
----------------
message is binary | Author : >
Created : 15 Sep 2014 by
ejabberd , Copyright ( C ) 2002 - 2016 ProcessOne
modify it under the terms of the GNU General Public License as
published by the Free Software Foundation ; either version 2 of the
You should have received a copy of the GNU General Public License along
with this program ; if not , write to the Free Software Foundation , Inc. ,
51 Franklin Street , Fifth Floor , Boston , USA .
commands_admin_access : configure
restricted ( default ): the same , but will appear only in ejabberdctl list .
admin – auth is required with XMLRPC and HTTP API and checked for admin priviledges , works as usual in ejabberdctl .
user - can be used through XMLRPC and HTTP API , even by user . Only admin can use the commands for other users .
of IP addresses by using option ` admin_ip_access ` by having fragment like
-module(mod_http_api).
-author('').
-behaviour(gen_mod).
-export([start/2, stop/1, process/2, mod_opt_type/1, depends/2]).
-include("ejabberd.hrl").
-include("jlib.hrl").
-include("logger.hrl").
-include("ejabberd_http.hrl").
-define(DEFAULT_API_VERSION, 0).
-define(CT_PLAIN,
{<<"Content-Type">>, <<"text/plain">>}).
-define(CT_XML,
{<<"Content-Type">>, <<"text/xml; charset=utf-8">>}).
-define(CT_JSON,
{<<"Content-Type">>, <<"application/json">>}).
-define(AC_ALLOW_ORIGIN,
{<<"Access-Control-Allow-Origin">>, <<"*">>}).
-define(AC_ALLOW_METHODS,
{<<"Access-Control-Allow-Methods">>,
<<"GET, POST, OPTIONS">>}).
-define(AC_ALLOW_HEADERS,
{<<"Access-Control-Allow-Headers">>,
<<"Content-Type, Authorization, X-Admin">>}).
-define(AC_MAX_AGE,
{<<"Access-Control-Max-Age">>, <<"86400">>}).
-define(OPTIONS_HEADER,
[?CT_PLAIN, ?AC_ALLOW_ORIGIN, ?AC_ALLOW_METHODS,
?AC_ALLOW_HEADERS, ?AC_MAX_AGE]).
-define(HEADER(CType),
[CType, ?AC_ALLOW_ORIGIN, ?AC_ALLOW_HEADERS]).
start(_Host, _Opts) ->
ok.
stop(_Host) ->
ok.
depends(_Host, _Opts) ->
[].
check_permissions(Request, Command) ->
case catch binary_to_existing_atom(Command, utf8) of
Call when is_atom(Call) ->
{ok, CommandPolicy, Scope} = ejabberd_commands:get_command_policy_and_scope(Call),
check_permissions2(Request, Call, CommandPolicy, Scope);
_ ->
json_error(404, 40, <<"Endpoint not found.">>)
end.
check_permissions2(#request{auth = HTTPAuth, headers = Headers}, Call, _, ScopeList)
when HTTPAuth /= undefined ->
Admin =
case lists:keysearch(<<"X-Admin">>, 1, Headers) of
{value, {_, <<"true">>}} -> true;
_ -> false
end,
Auth =
case HTTPAuth of
{SJID, Pass} ->
case jid:from_string(SJID) of
#jid{user = User, server = Server} ->
case ejabberd_auth:check_password(User, <<"">>, Server, Pass) of
true -> {ok, {User, Server, Pass, Admin}};
false -> false
end;
_ ->
false
end;
{oauth, Token, _} ->
case oauth_check_token(ScopeList, Token) of
{ok, user, {User, Server}} ->
{ok, {User, Server, {oauth, Token}, Admin}};
{false, Reason} ->
{false, Reason}
end;
_ ->
false
end,
case Auth of
{ok, A} -> {allowed, Call, A};
{false, no_matching_scope} -> outofscope_response();
_ -> unauthorized_response()
end;
check_permissions2(_Request, Call, open, _Scope) ->
{allowed, Call, noauth};
check_permissions2(#request{ip={IP, _Port}}, Call, _Policy, _Scope) ->
Access = gen_mod:get_module_opt(global, ?MODULE, admin_ip_access,
fun(V) -> V end,
none),
Res = acl:match_rule(global, Access, IP),
case Res of
all ->
{allowed, Call, admin};
[all] ->
{allowed, Call, admin};
allow ->
{allowed, Call, admin};
Commands when is_list(Commands) ->
case lists:member(Call, Commands) of
true -> {allowed, Call, admin};
_ -> outofscope_response()
end;
_E ->
{allowed, Call, noauth}
end;
check_permissions2(_Request, _Call, _Policy, _Scope) ->
unauthorized_response().
oauth_check_token(ScopeList, Token) when is_list(ScopeList) ->
ejabberd_oauth:check_token(ScopeList, Token).
? ~ n ~ p " , [ Call , Request ] ) , ok ;
process(_, #request{method = 'POST', data = <<>>}) ->
?DEBUG("Bad Request: no data", []),
badrequest_response(<<"Missing POST data">>);
process([Call], #request{method = 'POST', data = Data, ip = {IP, _} = IPPort} = Req) ->
Version = get_api_version(Req),
try
Args = extract_args(Data),
log(Call, Args, IPPort),
case check_permissions(Req, Call) of
{allowed, Cmd, Auth} ->
Result = handle(Cmd, Auth, Args, Version, IP),
json_format(Result);
Warning : check_permission direcly formats 401 reply if not authorized
ErrorResponse ->
ErrorResponse
end
catch
throw:{error, unknown_command} ->
{404, 40, <<"Command not found.">>};
_:{error,{_,invalid_json}} = _Err ->
?DEBUG("Bad Request: ~p", [_Err]),
badrequest_response(<<"Invalid JSON input">>);
_:_Error ->
?DEBUG("Bad Request: ~p ~p", [_Error, erlang:get_stacktrace()]),
badrequest_response()
end;
process([Call], #request{method = 'GET', q = Data, ip = IP} = Req) ->
Version = get_api_version(Req),
try
Args = case Data of
[{nokey, <<>>}] -> [];
_ -> Data
end,
log(Call, Args, IP),
case check_permissions(Req, Call) of
{allowed, Cmd, Auth} ->
Result = handle(Cmd, Auth, Args, Version, IP),
json_format(Result);
Warning : check_permission direcly formats 401 reply if not authorized
ErrorResponse ->
ErrorResponse
end
catch
throw:{error, unknown_command} ->
json_format({404, 44, <<"Command not found.">>});
_:_Error ->
?DEBUG("Bad Request: ~p ~p", [_Error, erlang:get_stacktrace()]),
badrequest_response()
end;
process([_Call], #request{method = 'OPTIONS', data = <<>>}) ->
{200, ?OPTIONS_HEADER, []};
process(_, #request{method = 'OPTIONS'}) ->
{400, ?OPTIONS_HEADER, []};
process(_Path, Request) ->
?DEBUG("Bad Request: no handler ~p", [Request]),
json_error(400, 40, <<"Missing command name.">>).
extract_args(<<"\n">>) -> [];
extract_args(Data) ->
case jiffy:decode(Data) of
List when is_list(List) -> List;
{List} when is_list(List) -> List;
Other -> [Other]
end.
get_api_version(#request{path = Path}) ->
get_api_version(lists:reverse(Path));
get_api_version([<<"v", String/binary>> | Tail]) ->
case catch jlib:binary_to_integer(String) of
N when is_integer(N) ->
N;
_ ->
get_api_version(Tail)
end;
get_api_version([_Head | Tail]) ->
get_api_version(Tail);
get_api_version([]) ->
?DEFAULT_API_VERSION.
handle(Call, Auth, Args, Version, IP) when is_atom(Call), is_list(Args) ->
case ejabberd_commands:get_command_format(Call, Auth, Version) of
{ArgsSpec, _} when is_list(ArgsSpec) ->
Args2 = [{jlib:binary_to_atom(Key), Value} || {Key, Value} <- Args],
Spec = lists:foldr(
fun ({Key, binary}, Acc) ->
[{Key, <<>>}|Acc];
({Key, string}, Acc) ->
[{Key, <<>>}|Acc];
({Key, integer}, Acc) ->
[{Key, 0}|Acc];
({Key, {list, _}}, Acc) ->
[{Key, []}|Acc];
({Key, atom}, Acc) ->
[{Key, undefined}|Acc]
end, [], ArgsSpec),
try
handle2(Call, Auth, match(Args2, Spec), Version, IP)
catch throw:not_found ->
{404, <<"not_found">>};
throw:{not_found, Why} when is_atom(Why) ->
{404, jlib:atom_to_binary(Why)};
throw:{not_found, Msg} ->
{404, iolist_to_binary(Msg)};
throw:not_allowed ->
{401, <<"not_allowed">>};
throw:{not_allowed, Why} when is_atom(Why) ->
{401, jlib:atom_to_binary(Why)};
throw:{not_allowed, Msg} ->
{401, iolist_to_binary(Msg)};
throw:{error, account_unprivileged} ->
{403, 31, <<"Command need to be run with admin priviledge.">>};
throw:{error, access_rules_unauthorized} ->
{403, 32, <<"AccessRules: Account associated to token does not have the right to perform the operation.">>};
throw:{invalid_parameter, Msg} ->
{400, iolist_to_binary(Msg)};
throw:{error, Why} when is_atom(Why) ->
{400, jlib:atom_to_binary(Why)};
throw:{error, Msg} ->
{400, iolist_to_binary(Msg)};
throw:Error when is_atom(Error) ->
{400, jlib:atom_to_binary(Error)};
throw:Msg when is_list(Msg); is_binary(Msg) ->
{400, iolist_to_binary(Msg)};
_Error ->
?ERROR_MSG("REST API Error: ~p ~p", [_Error, erlang:get_stacktrace()]),
{500, <<"internal_error">>}
end;
{error, Msg} ->
?ERROR_MSG("REST API Error: ~p", [Msg]),
{400, Msg};
_Error ->
?ERROR_MSG("REST API Error: ~p", [_Error]),
{400, <<"Error">>}
end.
handle2(Call, Auth, Args, Version, IP) when is_atom(Call), is_list(Args) ->
{ArgsF, _ResultF} = ejabberd_commands:get_command_format(Call, Auth, Version),
ArgsFormatted = format_args(Args, ArgsF),
ejabberd_command(Auth, Call, ArgsFormatted, Version, IP).
get_elem_delete(A, L) ->
case proplists:get_all_values(A, L) of
[Value] -> {Value, proplists:delete(A, L)};
[_, _ | _] ->
exit({duplicated_attribute, A, L});
[] ->
exit({attribute_not_found, A, L})
end.
format_args(Args, ArgsFormat) ->
{ArgsRemaining, R} = lists:foldl(fun ({ArgName,
ArgFormat},
{Args1, Res}) ->
{ArgValue, Args2} =
get_elem_delete(ArgName,
Args1),
Formatted = format_arg(ArgValue,
ArgFormat),
{Args2, Res ++ [Formatted]}
end,
{Args, []}, ArgsFormat),
case ArgsRemaining of
[] -> R;
L when is_list(L) -> exit({additional_unused_args, L})
end.
format_arg({Elements},
{list, {_ElementDefName, {tuple, [{_Tuple1N, Tuple1S}, {_Tuple2N, Tuple2S}]} = Tuple}})
when is_list(Elements) andalso
(Tuple1S == binary orelse Tuple1S == string) ->
lists:map(fun({F1, F2}) ->
{format_arg(F1, Tuple1S), format_arg(F2, Tuple2S)};
({Val}) when is_list(Val) ->
format_arg({Val}, Tuple)
end, Elements);
format_arg(Elements,
{list, {_ElementDefName, {list, _} = ElementDefFormat}})
when is_list(Elements) ->
[{format_arg(Element, ElementDefFormat)}
|| Element <- Elements];
format_arg(Elements,
{list, {_ElementDefName, ElementDefFormat}})
when is_list(Elements) ->
[format_arg(Element, ElementDefFormat)
|| Element <- Elements];
format_arg({[{Name, Value}]},
{tuple, [{_Tuple1N, Tuple1S}, {_Tuple2N, Tuple2S}]})
when Tuple1S == binary;
Tuple1S == string ->
{format_arg(Name, Tuple1S), format_arg(Value, Tuple2S)};
format_arg({Elements},
{tuple, ElementsDef})
when is_list(Elements) ->
F = lists:map(fun({TElName, TElDef}) ->
case lists:keyfind(atom_to_binary(TElName, latin1), 1, Elements) of
{_, Value} ->
format_arg(Value, TElDef);
_ when TElDef == binary; TElDef == string ->
<<"">>;
_ ->
?ERROR_MSG("missing field ~p in tuple ~p", [TElName, Elements]),
throw({invalid_parameter,
io_lib:format("Missing field ~w in tuple ~w", [TElName, Elements])})
end
end, ElementsDef),
list_to_tuple(F);
format_arg(Elements, {list, ElementsDef})
when is_list(Elements) and is_atom(ElementsDef) ->
[format_arg(Element, ElementsDef)
|| Element <- Elements];
format_arg(Arg, integer) when is_integer(Arg) -> Arg;
format_arg(Arg, binary) when is_list(Arg) -> process_unicode_codepoints(Arg);
format_arg(Arg, binary) when is_binary(Arg) -> Arg;
format_arg(Arg, string) when is_list(Arg) -> process_unicode_codepoints(Arg);
format_arg(Arg, string) when is_binary(Arg) -> Arg;
format_arg(undefined, binary) -> <<>>;
format_arg(undefined, string) -> <<>>;
format_arg(Arg, Format) ->
?ERROR_MSG("don't know how to format Arg ~p for format ~p", [Arg, Format]),
throw({invalid_parameter,
io_lib:format("Arg ~w is not in format ~w",
[Arg, Format])}).
process_unicode_codepoints(Str) ->
iolist_to_binary(lists:map(fun(X) when X > 255 -> unicode:characters_to_binary([X]);
(Y) -> Y
end, Str)).
match(Args, Spec) ->
[{Key, proplists:get_value(Key, Args, Default)} || {Key, Default} <- Spec].
ejabberd_command(Auth, Cmd, Args, Version, IP) ->
Access = case Auth of
admin -> [];
_ -> undefined
end,
case ejabberd_commands:execute_command(Access, Auth, Cmd, Args, Version, #{ip => IP}) of
{error, Error} ->
throw(Error);
Res ->
format_command_result(Cmd, Auth, Res, Version)
end.
format_command_result(Cmd, Auth, Result, Version) ->
{_, ResultFormat} = ejabberd_commands:get_command_format(Cmd, Auth, Version),
case {ResultFormat, Result} of
{{_, rescode}, V} when V == true; V == ok ->
{200, 0};
{{_, rescode}, _} ->
{200, 1};
{_, {error, ErrorAtom, Code, Msg}} ->
format_error_result(ErrorAtom, Code, Msg);
{{_, restuple}, {V, Text}} when V == true; V == ok ->
{200, iolist_to_binary(Text)};
{{_, restuple}, {ErrorAtom, Msg}} ->
format_error_result(ErrorAtom, 0, Msg);
{{_, {list, _}}, _V} ->
{_, L} = format_result(Result, ResultFormat),
{200, L};
{{_, {tuple, _}}, _V} ->
{_, T} = format_result(Result, ResultFormat),
{200, T};
_ ->
{200, {[format_result(Result, ResultFormat)]}}
end.
format_result(Atom, {Name, atom}) ->
{jlib:atom_to_binary(Name), jlib:atom_to_binary(Atom)};
format_result(Int, {Name, integer}) ->
{jlib:atom_to_binary(Name), Int};
format_result(String, {Name, string}) ->
{jlib:atom_to_binary(Name), iolist_to_binary(String)};
format_result(Code, {Name, rescode}) ->
{jlib:atom_to_binary(Name), Code == true orelse Code == ok};
format_result({Code, Text}, {Name, restuple}) ->
{jlib:atom_to_binary(Name),
{[{<<"res">>, Code == true orelse Code == ok},
{<<"text">>, iolist_to_binary(Text)}]}};
format_result(Code, {Name, restuple}) ->
{jlib:atom_to_binary(Name),
{[{<<"res">>, Code == true orelse Code == ok},
{<<"text">>, <<"">>}]}};
format_result(Els, {Name, {list, {_, {tuple, [{_, atom}, _]}} = Fmt}}) ->
{jlib:atom_to_binary(Name), {[format_result(El, Fmt) || El <- Els]}};
format_result(Els, {Name, {list, Def}}) ->
{jlib:atom_to_binary(Name), [element(2, format_result(El, Def)) || El <- Els]};
format_result(Tuple, {_Name, {tuple, [{_, atom}, ValFmt]}}) ->
{Name2, Val} = Tuple,
{_, Val2} = format_result(Val, ValFmt),
{jlib:atom_to_binary(Name2), Val2};
format_result(Tuple, {Name, {tuple, Def}}) ->
Els = lists:zip(tuple_to_list(Tuple), Def),
{jlib:atom_to_binary(Name), {[format_result(El, ElDef) || {El, ElDef} <- Els]}};
format_result(404, {_Name, _}) ->
"not_found".
format_error_result(conflict, Code, Msg) ->
{409, Code, iolist_to_binary(Msg)};
format_error_result(_ErrorAtom, Code, Msg) ->
{500, Code, iolist_to_binary(Msg)}.
unauthorized_response() ->
json_error(401, 10, <<"Oauth Token is invalid or expired.">>).
outofscope_response() ->
json_error(401, 11, <<"Token does not grant usage to command required scope.">>).
badrequest_response() ->
badrequest_response(<<"400 Bad Request">>).
badrequest_response(Body) ->
json_response(400, jiffy:encode(Body)).
json_format({Code, Result}) ->
json_response(Code, jiffy:encode(Result));
json_format({HTMLCode, JSONErrorCode, Message}) ->
json_error(HTMLCode, JSONErrorCode, Message).
json_response(Code, Body) when is_integer(Code) ->
{Code, ?HEADER(?CT_JSON), Body}.
HTTPCode , = integers
json_error(HTTPCode, JSONCode, Message) ->
{HTTPCode, ?HEADER(?CT_JSON),
jiffy:encode({[{<<"status">>, <<"error">>},
{<<"code">>, JSONCode},
{<<"message">>, Message}]})
}.
log(Call, Args, {Addr, Port}) ->
AddrS = jlib:ip_to_list({Addr, Port}),
?INFO_MSG("API call ~s ~p from ~s:~p", [Call, Args, AddrS, Port]);
log(Call, Args, IP) ->
?INFO_MSG("API call ~s ~p (~p)", [Call, Args, IP]).
mod_opt_type(admin_ip_access) -> fun acl:access_rules_validator/1;
mod_opt_type(_) -> [admin_ip_access].
|
79e01f56295871c33e643995900d1b8dc999a51609466157b812f36d1711df79 | larcenists/larceny | exceptions.sps | (import (tests r6rs exceptions)
(tests scheme test)
(scheme write))
(display "Running tests for (rnrs exceptions)\n")
(run-exceptions-tests)
(report-test-results)
| null | https://raw.githubusercontent.com/larcenists/larceny/fef550c7d3923deb7a5a1ccd5a628e54cf231c75/test/R7RS/Lib/tests/r6rs/run/exceptions.sps | scheme | (import (tests r6rs exceptions)
(tests scheme test)
(scheme write))
(display "Running tests for (rnrs exceptions)\n")
(run-exceptions-tests)
(report-test-results)
| |
8d2111cf0569e9f0d4e4e950ca5f6d390d2c602f45076fbacac9fe826eda7699 | AshleyYakeley/Truth | FreeVars.hs | module Pinafore.Language.Grammar.FreeVars
( syntaxExpressionFreeVariables
, syntaxPatternBindingVariables
) where
import Pinafore.Language.Grammar.Syntax
import Pinafore.Language.Name
import Shapes
syntaxExpressionFreeVariables :: SyntaxExpression -> [FullName]
syntaxExpressionFreeVariables expr = toList $ syntaxFreeVariables expr
syntaxPatternBindingVariables :: SyntaxPattern -> [FullName]
syntaxPatternBindingVariables pat = toList $ syntaxBindingVariables pat
class SyntaxFreeVariables t where
syntaxFreeVariables :: t -> FiniteSet FullName
instance SyntaxFreeVariables t => SyntaxFreeVariables [t] where
syntaxFreeVariables tt = mconcat $ fmap syntaxFreeVariables tt
instance SyntaxFreeVariables t => SyntaxFreeVariables (NonEmpty t) where
syntaxFreeVariables tt = syntaxFreeVariables $ toList tt
instance SyntaxFreeVariables t => SyntaxFreeVariables (FixedList n t) where
syntaxFreeVariables tt = syntaxFreeVariables $ toList tt
instance SyntaxFreeVariables st => SyntaxFreeVariables (WithSourcePos st) where
syntaxFreeVariables (MkWithSourcePos _ e) = syntaxFreeVariables e
instance SyntaxFreeVariables SyntaxCase where
syntaxFreeVariables (MkSyntaxCase pat expr) = difference (syntaxFreeVariables expr) (syntaxBindingVariables pat)
instance SyntaxFreeVariables (SyntaxMulticase n) where
syntaxFreeVariables (MkSyntaxMulticase pats expr) =
difference (syntaxFreeVariables expr) (syntaxBindingVariables pats)
instance SyntaxFreeVariables (Some SyntaxMulticase) where
syntaxFreeVariables (MkSome m) = syntaxFreeVariables m
instance SyntaxFreeVariables SyntaxMulticaseList where
syntaxFreeVariables (MkSyntaxMulticaseList _ l) = syntaxFreeVariables l
instance SyntaxFreeVariables SyntaxExpression' where
syntaxFreeVariables (SESubsume expr _) = syntaxFreeVariables expr
syntaxFreeVariables (SEConst _) = mempty
syntaxFreeVariables (SEVar ns name) = opoint $ namespaceConcatFullName ns name
syntaxFreeVariables (SESpecialForm _ _) = mempty
syntaxFreeVariables (SEApply f arg) = union (syntaxFreeVariables f) (syntaxFreeVariables arg)
syntaxFreeVariables (SEAbstract match) = syntaxFreeVariables match
syntaxFreeVariables (SEAbstracts match) = syntaxFreeVariables match
syntaxFreeVariables (SEMatch match) = syntaxFreeVariables match
syntaxFreeVariables (SEMatches match) = syntaxFreeVariables match
syntaxFreeVariables (SERef expr) = syntaxFreeVariables expr
syntaxFreeVariables (SEUnref expr) = syntaxFreeVariables expr
syntaxFreeVariables (SELet binds expr) =
difference (syntaxFreeVariables binds <> syntaxFreeVariables expr) (syntaxBindingVariables binds)
syntaxFreeVariables (SEList exprs) = syntaxFreeVariables exprs
instance SyntaxFreeVariables SyntaxBinding where
syntaxFreeVariables (MkSyntaxBinding _ expr) = syntaxFreeVariables expr
instance SyntaxFreeVariables t => SyntaxFreeVariables (SyntaxWithDoc t) where
syntaxFreeVariables (MkSyntaxWithDoc _ decl) = syntaxFreeVariables decl
instance SyntaxFreeVariables SyntaxRecursiveDeclaration' where
syntaxFreeVariables (BindingSyntaxDeclaration bind) = syntaxFreeVariables bind
syntaxFreeVariables _ = mempty
instance SyntaxFreeVariables SyntaxDeclaration' where
syntaxFreeVariables (DirectSyntaxDeclaration bind) = syntaxFreeVariables bind
syntaxFreeVariables (RecursiveSyntaxDeclaration decls) = syntaxFreeVariables decls
syntaxFreeVariables (NamespaceSyntaxDeclaration _ decls) = syntaxFreeVariables decls
syntaxFreeVariables _ = mempty
class SyntaxBindingVariables t where
syntaxBindingVariables :: t -> FiniteSet FullName
instance SyntaxBindingVariables t => SyntaxBindingVariables [t] where
syntaxBindingVariables tt = mconcat $ fmap syntaxBindingVariables tt
instance SyntaxBindingVariables t => SyntaxBindingVariables (NonEmpty t) where
syntaxBindingVariables tt = syntaxBindingVariables $ toList tt
instance SyntaxBindingVariables t => SyntaxBindingVariables (FixedList n t) where
syntaxBindingVariables tt = syntaxBindingVariables $ toList tt
instance SyntaxBindingVariables st => SyntaxBindingVariables (WithSourcePos st) where
syntaxBindingVariables (MkWithSourcePos _ pat) = syntaxBindingVariables pat
instance SyntaxBindingVariables SyntaxPattern' where
syntaxBindingVariables AnySyntaxPattern = mempty
syntaxBindingVariables (VarSyntaxPattern name) = singletonSet name
syntaxBindingVariables (BothSyntaxPattern pat1 pat2) =
union (syntaxBindingVariables pat1) (syntaxBindingVariables pat2)
syntaxBindingVariables (ConstructorSyntaxPattern _ _ pats) = syntaxBindingVariables pats
syntaxBindingVariables (TypedSyntaxPattern pat _) = syntaxBindingVariables pat
syntaxBindingVariables (DynamicTypedSyntaxPattern pat _) = syntaxBindingVariables pat
syntaxBindingVariables (NamespaceSyntaxPattern _ _) = mempty
instance SyntaxBindingVariables t => SyntaxBindingVariables (SyntaxWithDoc t) where
syntaxBindingVariables (MkSyntaxWithDoc _ decl) = syntaxBindingVariables decl
instance SyntaxBindingVariables SyntaxRecursiveDeclaration' where
syntaxBindingVariables (BindingSyntaxDeclaration bind) = syntaxBindingVariables bind
syntaxBindingVariables _ = mempty
instance SyntaxBindingVariables SyntaxDeclaration' where
syntaxBindingVariables (DirectSyntaxDeclaration bind) = syntaxBindingVariables bind
syntaxBindingVariables (RecursiveSyntaxDeclaration decls) = syntaxBindingVariables decls
syntaxBindingVariables _ = mempty
instance SyntaxBindingVariables SyntaxBinding where
syntaxBindingVariables (MkSyntaxBinding pat _) = syntaxBindingVariables pat
| null | https://raw.githubusercontent.com/AshleyYakeley/Truth/53900d89022f68bffb08d5c07b4e783ab0a0542e/Pinafore/pinafore-language/lib/Pinafore/Language/Grammar/FreeVars.hs | haskell | module Pinafore.Language.Grammar.FreeVars
( syntaxExpressionFreeVariables
, syntaxPatternBindingVariables
) where
import Pinafore.Language.Grammar.Syntax
import Pinafore.Language.Name
import Shapes
syntaxExpressionFreeVariables :: SyntaxExpression -> [FullName]
syntaxExpressionFreeVariables expr = toList $ syntaxFreeVariables expr
syntaxPatternBindingVariables :: SyntaxPattern -> [FullName]
syntaxPatternBindingVariables pat = toList $ syntaxBindingVariables pat
class SyntaxFreeVariables t where
syntaxFreeVariables :: t -> FiniteSet FullName
instance SyntaxFreeVariables t => SyntaxFreeVariables [t] where
syntaxFreeVariables tt = mconcat $ fmap syntaxFreeVariables tt
instance SyntaxFreeVariables t => SyntaxFreeVariables (NonEmpty t) where
syntaxFreeVariables tt = syntaxFreeVariables $ toList tt
instance SyntaxFreeVariables t => SyntaxFreeVariables (FixedList n t) where
syntaxFreeVariables tt = syntaxFreeVariables $ toList tt
instance SyntaxFreeVariables st => SyntaxFreeVariables (WithSourcePos st) where
syntaxFreeVariables (MkWithSourcePos _ e) = syntaxFreeVariables e
instance SyntaxFreeVariables SyntaxCase where
syntaxFreeVariables (MkSyntaxCase pat expr) = difference (syntaxFreeVariables expr) (syntaxBindingVariables pat)
instance SyntaxFreeVariables (SyntaxMulticase n) where
syntaxFreeVariables (MkSyntaxMulticase pats expr) =
difference (syntaxFreeVariables expr) (syntaxBindingVariables pats)
instance SyntaxFreeVariables (Some SyntaxMulticase) where
syntaxFreeVariables (MkSome m) = syntaxFreeVariables m
instance SyntaxFreeVariables SyntaxMulticaseList where
syntaxFreeVariables (MkSyntaxMulticaseList _ l) = syntaxFreeVariables l
instance SyntaxFreeVariables SyntaxExpression' where
syntaxFreeVariables (SESubsume expr _) = syntaxFreeVariables expr
syntaxFreeVariables (SEConst _) = mempty
syntaxFreeVariables (SEVar ns name) = opoint $ namespaceConcatFullName ns name
syntaxFreeVariables (SESpecialForm _ _) = mempty
syntaxFreeVariables (SEApply f arg) = union (syntaxFreeVariables f) (syntaxFreeVariables arg)
syntaxFreeVariables (SEAbstract match) = syntaxFreeVariables match
syntaxFreeVariables (SEAbstracts match) = syntaxFreeVariables match
syntaxFreeVariables (SEMatch match) = syntaxFreeVariables match
syntaxFreeVariables (SEMatches match) = syntaxFreeVariables match
syntaxFreeVariables (SERef expr) = syntaxFreeVariables expr
syntaxFreeVariables (SEUnref expr) = syntaxFreeVariables expr
syntaxFreeVariables (SELet binds expr) =
difference (syntaxFreeVariables binds <> syntaxFreeVariables expr) (syntaxBindingVariables binds)
syntaxFreeVariables (SEList exprs) = syntaxFreeVariables exprs
instance SyntaxFreeVariables SyntaxBinding where
syntaxFreeVariables (MkSyntaxBinding _ expr) = syntaxFreeVariables expr
instance SyntaxFreeVariables t => SyntaxFreeVariables (SyntaxWithDoc t) where
syntaxFreeVariables (MkSyntaxWithDoc _ decl) = syntaxFreeVariables decl
instance SyntaxFreeVariables SyntaxRecursiveDeclaration' where
syntaxFreeVariables (BindingSyntaxDeclaration bind) = syntaxFreeVariables bind
syntaxFreeVariables _ = mempty
instance SyntaxFreeVariables SyntaxDeclaration' where
syntaxFreeVariables (DirectSyntaxDeclaration bind) = syntaxFreeVariables bind
syntaxFreeVariables (RecursiveSyntaxDeclaration decls) = syntaxFreeVariables decls
syntaxFreeVariables (NamespaceSyntaxDeclaration _ decls) = syntaxFreeVariables decls
syntaxFreeVariables _ = mempty
class SyntaxBindingVariables t where
syntaxBindingVariables :: t -> FiniteSet FullName
instance SyntaxBindingVariables t => SyntaxBindingVariables [t] where
syntaxBindingVariables tt = mconcat $ fmap syntaxBindingVariables tt
instance SyntaxBindingVariables t => SyntaxBindingVariables (NonEmpty t) where
syntaxBindingVariables tt = syntaxBindingVariables $ toList tt
instance SyntaxBindingVariables t => SyntaxBindingVariables (FixedList n t) where
syntaxBindingVariables tt = syntaxBindingVariables $ toList tt
instance SyntaxBindingVariables st => SyntaxBindingVariables (WithSourcePos st) where
syntaxBindingVariables (MkWithSourcePos _ pat) = syntaxBindingVariables pat
instance SyntaxBindingVariables SyntaxPattern' where
syntaxBindingVariables AnySyntaxPattern = mempty
syntaxBindingVariables (VarSyntaxPattern name) = singletonSet name
syntaxBindingVariables (BothSyntaxPattern pat1 pat2) =
union (syntaxBindingVariables pat1) (syntaxBindingVariables pat2)
syntaxBindingVariables (ConstructorSyntaxPattern _ _ pats) = syntaxBindingVariables pats
syntaxBindingVariables (TypedSyntaxPattern pat _) = syntaxBindingVariables pat
syntaxBindingVariables (DynamicTypedSyntaxPattern pat _) = syntaxBindingVariables pat
syntaxBindingVariables (NamespaceSyntaxPattern _ _) = mempty
instance SyntaxBindingVariables t => SyntaxBindingVariables (SyntaxWithDoc t) where
syntaxBindingVariables (MkSyntaxWithDoc _ decl) = syntaxBindingVariables decl
instance SyntaxBindingVariables SyntaxRecursiveDeclaration' where
syntaxBindingVariables (BindingSyntaxDeclaration bind) = syntaxBindingVariables bind
syntaxBindingVariables _ = mempty
instance SyntaxBindingVariables SyntaxDeclaration' where
syntaxBindingVariables (DirectSyntaxDeclaration bind) = syntaxBindingVariables bind
syntaxBindingVariables (RecursiveSyntaxDeclaration decls) = syntaxBindingVariables decls
syntaxBindingVariables _ = mempty
instance SyntaxBindingVariables SyntaxBinding where
syntaxBindingVariables (MkSyntaxBinding pat _) = syntaxBindingVariables pat
| |
8b9832df3754b4ad828ed12ed99e6eca394b174921bb3cde9889b58fa6e6780b | hipsleek/hipsleek | golf.ml |
*
* Copyright ( c ) 2001 - 2002 ,
* < >
* All rights reserved .
*
* Redistribution and use in source and binary forms , with or without
* modification , are permitted provided that the following conditions are
* met :
*
* 1 . Redistributions of source code must retain the above copyright
* notice , this list of conditions and the following disclaimer .
*
* 2 . Redistributions in binary form must reproduce the above copyright
* notice , this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution .
*
* 3 . The names of the contributors may not be used to endorse or promote
* products derived from this software without specific prior written
* permission .
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS " AS
* IS " AND ANY EXPRESS OR IMPLIED WARRANTIES , INCLUDING , BUT NOT LIMITED
* TO , THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
* PARTICULAR PURPOSE ARE DISCLAIMED . IN NO EVENT SHALL THE COPYRIGHT OWNER
* OR FOR ANY DIRECT , INDIRECT , INCIDENTAL , SPECIAL ,
* EXEMPLARY , OR CONSEQUENTIAL DAMAGES ( INCLUDING , BUT NOT LIMITED TO ,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES ; LOSS OF USE , DATA , OR
* PROFITS ; OR BUSINESS INTERRUPTION ) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY , WHETHER IN CONTRACT , STRICT LIABILITY , OR TORT ( INCLUDING
* NEGLIGENCE OR OTHERWISE ) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE , EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE .
*
*
* Copyright (c) 2001-2002,
* John Kodumal <>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* 3. The names of the contributors may not be used to endorse or promote
* products derived from this software without specific prior written
* permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
* PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER
* OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*)
(***********************************************************************)
(* *)
(* Exceptions *)
(* *)
(***********************************************************************)
exception Inconsistent (* raised if constraint system is inconsistent *)
exception WellFormed (* raised if types are not well-formed *)
exception NoContents
exception APFound (* raised if an alias pair is found, a control
flow exception *)
module U = Uref
module S = Setp
module H = Hashtbl
module Q = Queue
(** Subtyping kinds *)
type polarity =
Pos
| Neg
| Sub
* Path kinds , for CFL reachability
type pkind =
Positive
| Negative
| Match
| Seed
(** Context kinds -- open or closed *)
type context =
Open
| Closed
A configuration is a context ( open or closed ) coupled with a pair
of stamps representing a state in the cartesian product DFA .
of stamps representing a state in the cartesian product DFA. *)
type configuration = context * int * int
module ConfigHash =
struct
type t = configuration
let equal t t' = t = t'
let hash t = Hashtbl.hash t
end
module CH = H.Make (ConfigHash)
type config_map = unit CH.t
(** Generic bounds *)
type 'a bound = {index : int; info : 'a U.uref}
(** For label paths. *)
type 'a path = {
kind : pkind;
reached_global : bool;
head : 'a U.uref;
tail : 'a U.uref
}
module Bound =
struct
type 'a t = 'a bound
let compare (x : 'a t) (y : 'a t) =
if U.equal (x.info, y.info) then x.index - y.index
else Pervasives.compare (U.deref x.info) (U.deref y.info)
end
module Path =
struct
type 'a t = 'a path
let compare (x : 'a t) (y : 'a t) =
if U.equal (x.head, y.head) then
begin
if U.equal (x.tail, y.tail) then
begin
if x.reached_global = y.reached_global then
Pervasives.compare x.kind y.kind
else Pervasives.compare x.reached_global y.reached_global
end
else Pervasives.compare (U.deref x.tail) (U.deref y.tail)
end
else Pervasives.compare (U.deref x.head) (U.deref y.head)
end
module B = S.Make (Bound)
module P = S.Make (Path)
type 'a boundset = 'a B.t
type 'a pathset = 'a P.t
(** Constants, which identify elements in points-to sets *)
* jk : I 'd prefer to make this an ' a constant and specialize it to varinfo
for use with the frontend , but for now , this will do
for use with the Cil frontend, but for now, this will do *)
type constant = int * string * Cil.varinfo
module Constant =
struct
type t = constant
let compare (xid, _, _) (yid, _, _) = xid - yid
end
module C = Set.Make (Constant)
* Sets of constants . Set union is used when two labels containing
constant sets are unified
constant sets are unified *)
type constantset = C.t
type lblinfo = {
mutable l_name: string;
(** either empty or a singleton, the initial location for this label *)
loc : constantset;
(** Name of this label *)
l_stamp : int;
(** Unique integer for this label *)
mutable l_global : bool;
(** True if this location is globally accessible *)
mutable aliases: constantset;
(** Set of constants (tags) for checking aliases *)
mutable p_lbounds: lblinfo boundset;
(** Set of umatched (p) lower bounds *)
mutable n_lbounds: lblinfo boundset;
(** Set of unmatched (n) lower bounds *)
mutable p_ubounds: lblinfo boundset;
(** Set of umatched (p) upper bounds *)
mutable n_ubounds: lblinfo boundset;
(** Set of unmatched (n) upper bounds *)
mutable m_lbounds: lblinfo boundset;
(** Set of matched (m) lower bounds *)
mutable m_ubounds: lblinfo boundset;
(** Set of matched (m) upper bounds *)
mutable m_upath: lblinfo pathset;
mutable m_lpath: lblinfo pathset;
mutable n_upath: lblinfo pathset;
mutable n_lpath: lblinfo pathset;
mutable p_upath: lblinfo pathset;
mutable p_lpath: lblinfo pathset;
mutable l_seeded : bool;
mutable l_ret : bool;
mutable l_param : bool;
}
(** Constructor labels *)
and label = lblinfo U.uref
* The type of lvalues .
type lvalue = {
l: label;
contents: tau
}
and vinfo = {
v_stamp : int;
v_name : string;
mutable v_hole : (int,unit) H.t;
mutable v_global : bool;
mutable v_mlbs : tinfo boundset;
mutable v_mubs : tinfo boundset;
mutable v_plbs : tinfo boundset;
mutable v_pubs : tinfo boundset;
mutable v_nlbs : tinfo boundset;
mutable v_nubs : tinfo boundset
}
and rinfo = {
r_stamp : int;
rl : label;
points_to : tau;
mutable r_global: bool;
}
and finfo = {
f_stamp : int;
fl : label;
ret : tau;
mutable args : tau list;
mutable f_global : bool;
}
and pinfo = {
p_stamp : int;
ptr : tau;
lam : tau;
mutable p_global : bool;
}
and tinfo = Var of vinfo
| Ref of rinfo
| Fun of finfo
| Pair of pinfo
and tau = tinfo U.uref
type tconstraint = Unification of tau * tau
| Leq of tau * (int * polarity) * tau
* Association lists , used for printing recursive types . The first element
is a type that has been visited . The second element is the string
representation of that type ( so far ) . If the string option is set , then
this type occurs within itself , and is associated with the recursive var
name stored in the option . When walking a type , add it to an association
list .
Example : suppose we have the constraint ' a = ref('a ) . The type is unified
via cyclic unification , and would loop infinitely if we attempted to print
it . What we want to do is print the type ref(rv ) . This is accomplished
in the following manner :
-- ref('a ) is visited . It is not in the association list , so it is added
and the string " ref ( " is stored in the second element . We recurse to print
the first argument of the constructor .
-- In the recursive call , we see that ' a ( or ref('a ) ) is already in the
association list , so the type is recursive . We check the string option ,
which is None , meaning that this is the first recurrence of the type . We
create a new recursive variable , rv and set the string option to ' rv . Next ,
we prepend to the string representation we have seen before , " ref ( " ,
and return " rv " as the string representation of this type .
-- The string so far is " u rv.ref ( " . The recursive call returns , and we
complete the type by printing the result of the call , " rv " , and " ) "
In a type where the recursive variable appears twice , e.g. ' a = pair('a,'a ) ,
the second time we hit ' a , the string option will be set , so we know to
reuse the same recursive variable name .
is a type that has been visited. The second element is the string
representation of that type (so far). If the string option is set, then
this type occurs within itself, and is associated with the recursive var
name stored in the option. When walking a type, add it to an association
list.
Example : suppose we have the constraint 'a = ref('a). The type is unified
via cyclic unification, and would loop infinitely if we attempted to print
it. What we want to do is print the type u rv. ref(rv). This is accomplished
in the following manner:
-- ref('a) is visited. It is not in the association list, so it is added
and the string "ref(" is stored in the second element. We recurse to print
the first argument of the constructor.
-- In the recursive call, we see that 'a (or ref('a)) is already in the
association list, so the type is recursive. We check the string option,
which is None, meaning that this is the first recurrence of the type. We
create a new recursive variable, rv and set the string option to 'rv. Next,
we prepend u rv. to the string representation we have seen before, "ref(",
and return "rv" as the string representation of this type.
-- The string so far is "u rv.ref(". The recursive call returns, and we
complete the type by printing the result of the call, "rv", and ")"
In a type where the recursive variable appears twice, e.g. 'a = pair('a,'a),
the second time we hit 'a, the string option will be set, so we know to
reuse the same recursive variable name.
*)
type association = tau * string ref * string option ref
module PathHash =
struct
type t = int list
let equal t t' = t = t'
let hash t = Hashtbl.hash t
end
module PH = H.Make (PathHash)
(***********************************************************************)
(* *)
(* Global Variables *)
(* *)
(***********************************************************************)
(** Print the instantiations constraints. *)
let print_constraints : bool ref = ref false
(** If true, print all constraints (including induced) and show
additional debug output. *)
let debug = ref false
(** Just debug all the constraints (including induced) *)
let debug_constraints = ref false
(** Debug smart alias queries *)
let debug_aliases = ref false
let smart_aliases = ref false
(** If true, make the flow step a no-op *)
let no_flow = ref false
(** If true, disable subtyping (unification at all levels) *)
let no_sub = ref false
(** If true, treat indexed edges as regular subtyping *)
let analyze_mono = ref true
(** A list of equality constraints. *)
let eq_worklist : tconstraint Q.t = Q.create ()
* A list of leq constraints .
let leq_worklist : tconstraint Q.t = Q.create ()
let path_worklist : (lblinfo path) Q.t = Q.create ()
let path_hash : (lblinfo path) PH.t = PH.create 32
(** A count of the constraints introduced from the AST. Used for debugging. *)
let toplev_count = ref 0
(** A hashtable containing stamp pairs of labels that must be aliased. *)
let cached_aliases : (int * int,unit) H.t = H.create 64
(** A hashtable mapping pairs of tau's to their join node. *)
let join_cache : (int * int, tau) H.t = H.create 64
(***********************************************************************)
(* *)
(* Utility Functions *)
(* *)
(***********************************************************************)
let find = U.deref
let die s =
Printf.printf "*******\nAssertion failed: %s\n*******\n" s;
assert false
let fresh_appsite : (unit -> int) =
let appsite_index = ref 0 in
fun () ->
incr appsite_index;
!appsite_index
(** Generate a unique integer. *)
let fresh_index : (unit -> int) =
let counter = ref 0 in
fun () ->
incr counter;
!counter
let fresh_stamp : (unit -> int) =
let stamp = ref 0 in
fun () ->
incr stamp;
!stamp
(** Return a unique integer representation of a tau *)
let get_stamp (t : tau) : int =
match find t with
Var v -> v.v_stamp
| Ref r -> r.r_stamp
| Pair p -> p.p_stamp
| Fun f -> f.f_stamp
(** Negate a polarity. *)
let negate (p : polarity) : polarity =
match p with
Pos -> Neg
| Neg -> Pos
| Sub -> die "negate"
(** Consistency checks for inferred types *)
let pair_or_var (t : tau) =
match find t with
Pair _ -> true
| Var _ -> true
| _ -> false
let ref_or_var (t : tau) =
match find t with
Ref _ -> true
| Var _ -> true
| _ -> false
let fun_or_var (t : tau) =
match find t with
Fun _ -> true
| Var _ -> true
| _ -> false
(** Apply [f] structurally down [t]. Guaranteed to terminate, even if [t]
is recursive *)
let iter_tau f t =
let visited : (int,tau) H.t = H.create 4 in
let rec iter_tau' t =
if H.mem visited (get_stamp t) then () else
begin
f t;
H.add visited (get_stamp t) t;
match U.deref t with
Pair p ->
iter_tau' p.ptr;
iter_tau' p.lam
| Fun f ->
List.iter iter_tau' (f.args);
iter_tau' f.ret
| Ref r -> iter_tau' r.points_to
| _ -> ()
end
in
iter_tau' t
(* Extract a label's bounds according to [positive] and [upper]. *)
let get_bounds (p :polarity ) (upper : bool) (l : label) : lblinfo boundset =
let li = find l in
match p with
Pos -> if upper then li.p_ubounds else li.p_lbounds
| Neg -> if upper then li.n_ubounds else li.n_lbounds
| Sub -> if upper then li.m_ubounds else li.m_lbounds
let equal_tau (t : tau) (t' : tau) =
get_stamp t = get_stamp t'
let get_label_stamp (l : label) : int =
(find l).l_stamp
* Return true if [ t ] is global ( treated )
let get_global (t : tau) : bool =
match find t with
Var v -> v.v_global
| Ref r -> r.r_global
| Pair p -> p.p_global
| Fun f -> f.f_global
let is_ret_label l = (find l).l_ret || (find l).l_global (* todo - check *)
let is_param_label l = (find l).l_param || (find l).l_global
let is_global_label l = (find l).l_global
let is_seeded_label l = (find l).l_seeded
let set_global_label (l : label) (b : bool) : unit =
assert ((not (is_global_label l)) || b);
(U.deref l).l_global <- b
(** Aliases for set_global *)
let global_tau = get_global
* Get_global for
let global_lvalue lv = get_global lv.contents
(***********************************************************************)
(* *)
(* Printing Functions *)
(* *)
(***********************************************************************)
let string_of_configuration (c, i, i') =
let context = match c with
Open -> "O"
| Closed -> "C"
in
Printf.sprintf "(%s,%d,%d)" context i i'
let string_of_polarity p =
match p with
Pos -> "+"
| Neg -> "-"
| Sub -> "M"
(** Convert a label to a string, short representation *)
let string_of_label (l : label) : string =
"\"" ^ (find l).l_name ^ "\""
(** Return true if the element [e] is present in the association list,
according to uref equality *)
let rec assoc_list_mem (e : tau) (l : association list) =
match l with
| [] -> None
| (h, s, so) :: t ->
if U.equal (h,e) then Some (s, so) else assoc_list_mem e t
(** Given a tau, create a unique recursive variable name. This should always
return the same name for a given tau *)
let fresh_recvar_name (t : tau) : string =
match find t with
Pair p -> "rvp" ^ string_of_int p.p_stamp
| Ref r -> "rvr" ^ string_of_int r.r_stamp
| Fun f -> "rvf" ^ string_of_int f.f_stamp
| _ -> die "fresh_recvar_name"
(** Return a string representation of a tau, using association lists. *)
let string_of_tau (t : tau) : string =
let tau_map : association list ref = ref [] in
let rec string_of_tau' t =
match assoc_list_mem t !tau_map with
Some (s, so) -> (* recursive type. see if a var name has been set *)
begin
match !so with
None ->
let rv = fresh_recvar_name t in
s := "u " ^ rv ^ "." ^ !s;
so := Some rv;
rv
| Some rv -> rv
end
| None -> (* type's not recursive. Add it to the assoc list and cont. *)
let s = ref ""
and so : string option ref = ref None in
tau_map := (t, s, so) :: !tau_map;
begin
match find t with
Var v -> s := v.v_name;
| Pair p ->
assert (ref_or_var p.ptr);
assert (fun_or_var p.lam);
s := "{";
s := !s ^ string_of_tau' p.ptr;
s := !s ^ ",";
s := !s ^ string_of_tau' p.lam;
s := !s ^"}"
| Ref r ->
assert (pair_or_var r.points_to);
s := "ref(|";
s := !s ^ string_of_label r.rl;
s := !s ^ "|,";
s := !s ^ string_of_tau' r.points_to;
s := !s ^ ")"
| Fun f ->
assert (pair_or_var f.ret);
let rec string_of_args = function
h :: [] ->
assert (pair_or_var h);
s := !s ^ string_of_tau' h
| h :: t ->
assert (pair_or_var h);
s := !s ^ string_of_tau' h ^ ",";
string_of_args t
| [] -> ()
in
s := "fun(|";
s := !s ^ string_of_label f.fl;
s := !s ^ "|,";
s := !s ^ "<";
if List.length f.args > 0 then string_of_args f.args
else s := !s ^ "void";
s := !s ^">,";
s := !s ^ string_of_tau' f.ret;
s := !s ^ ")"
end;
tau_map := List.tl !tau_map;
!s
in
string_of_tau' t
(** Convert an lvalue to a string *)
let rec string_of_lvalue (lv : lvalue) : string =
let contents = string_of_tau lv.contents
and l = string_of_label lv.l in
assert (pair_or_var lv.contents); (* do a consistency check *)
Printf.sprintf "[%s]^(%s)" contents l
let print_path (p : lblinfo path) : unit =
let string_of_pkind = function
Positive -> "p"
| Negative -> "n"
| Match -> "m"
| Seed -> "s"
in
Printf.printf
"%s --%s--> %s (%d) : "
(string_of_label p.head)
(string_of_pkind p.kind)
(string_of_label p.tail)
(PathHash.hash p)
(** Print a list of tau elements, comma separated *)
let rec print_tau_list (l : tau list) : unit =
let rec print_t_strings = function
h :: [] -> print_endline h
| h :: t ->
print_string h;
print_string ", ";
print_t_strings t
| [] -> ()
in
print_t_strings (Util.list_map string_of_tau l)
let print_constraint (c : tconstraint) =
match c with
Unification (t, t') ->
let lhs = string_of_tau t
and rhs = string_of_tau t' in
Printf.printf "%s == %s\n" lhs rhs
| Leq (t, (i, p), t') ->
let lhs = string_of_tau t
and rhs = string_of_tau t' in
Printf.printf "%s <={%d,%s} %s\n" lhs i (string_of_polarity p) rhs
(***********************************************************************)
(* *)
(* Type Operations -- these do not create any constraints *)
(* *)
(***********************************************************************)
(** Create an lvalue with label [lbl] and tau contents [t]. *)
let make_lval (lbl, t : label * tau) : lvalue =
{l = lbl; contents = t}
let make_label_int (is_global : bool) (name :string) (vio : Cil.varinfo option) : label =
let locc =
match vio with
Some vi -> C.add (fresh_index (), name, vi) C.empty
| None -> C.empty
in
U.uref {
l_name = name;
l_global = is_global;
l_stamp = fresh_stamp ();
loc = locc;
aliases = locc;
p_ubounds = B.empty;
p_lbounds = B.empty;
n_ubounds = B.empty;
n_lbounds = B.empty;
m_ubounds = B.empty;
m_lbounds = B.empty;
m_upath = P.empty;
m_lpath = P.empty;
n_upath = P.empty;
n_lpath = P.empty;
p_upath = P.empty;
p_lpath = P.empty;
l_seeded = false;
l_ret = false;
l_param = false
}
(** Create a new label with name [name]. Also adds a fresh constant
with name [name] to this label's aliases set. *)
let make_label (is_global : bool) (name : string) (vio : Cil.varinfo option) : label =
make_label_int is_global name vio
(** Create a new label with an unspecified name and an empty alias set. *)
let fresh_label (is_global : bool) : label =
let index = fresh_index () in
make_label_int is_global ("l_" ^ string_of_int index) None
(** Create a fresh bound (edge in the constraint graph). *)
let make_bound (i, a : int * label) : lblinfo bound =
{index = i; info = a}
let make_tau_bound (i, a : int * tau) : tinfo bound =
{index = i; info = a}
(** Create a fresh named variable with name '[name]. *)
let make_var (b: bool) (name : string) : tau =
U.uref (Var {v_name = ("'" ^ name);
v_hole = H.create 8;
v_stamp = fresh_index ();
v_global = b;
v_mlbs = B.empty;
v_mubs = B.empty;
v_plbs = B.empty;
v_pubs = B.empty;
v_nlbs = B.empty;
v_nubs = B.empty})
(** Create a fresh unnamed variable (name will be 'fv). *)
let fresh_var (is_global : bool) : tau =
make_var is_global ("fv" ^ string_of_int (fresh_index ()))
(** Create a fresh unnamed variable (name will be 'fi). *)
let fresh_var_i (is_global : bool) : tau =
make_var is_global ("fi" ^ string_of_int (fresh_index()))
(** Create a Fun constructor. *)
let make_fun (lbl, a, r : label * (tau list) * tau) : tau =
U.uref (Fun {fl = lbl;
f_stamp = fresh_index ();
f_global = false;
args = a;
ret = r })
* Create a Ref constructor .
let make_ref (lbl,pt : label * tau) : tau =
U.uref (Ref {rl = lbl;
r_stamp = fresh_index ();
r_global = false;
points_to = pt})
(** Create a Pair constructor. *)
let make_pair (p,f : tau * tau) : tau =
U.uref (Pair {ptr = p;
p_stamp = fresh_index ();
p_global = false;
lam = f})
(** Copy the toplevel constructor of [t], putting fresh variables in each
argement of the constructor. *)
let copy_toplevel (t : tau) : tau =
match find t with
Pair _ -> make_pair (fresh_var_i false, fresh_var_i false)
| Ref _ -> make_ref (fresh_label false, fresh_var_i false)
| Fun f ->
let fresh_fn = fun _ -> fresh_var_i false in
make_fun (fresh_label false,
Util.list_map fresh_fn f.args, fresh_var_i false)
| _ -> die "copy_toplevel"
let has_same_structure (t : tau) (t' : tau) =
match find t, find t' with
Pair _, Pair _ -> true
| Ref _, Ref _ -> true
| Fun _, Fun _ -> true
| Var _, Var _ -> true
| _ -> false
let pad_args (f, f' : finfo * finfo) : unit =
let padding = ref ((List.length f.args) - (List.length f'.args))
in
if !padding == 0 then ()
else
let to_pad =
if !padding > 0 then f' else (padding := -(!padding); f)
in
for i = 1 to !padding do
to_pad.args <- to_pad.args @ [fresh_var false]
done
let pad_args2 (fi, tlr : finfo * tau list ref) : unit =
let padding = ref (List.length fi.args - List.length !tlr)
in
if !padding == 0 then ()
else
if !padding > 0 then
for i = 1 to !padding do
tlr := !tlr @ [fresh_var false]
done
else
begin
padding := -(!padding);
for i = 1 to !padding do
fi.args <- fi.args @ [fresh_var false]
done
end
(***********************************************************************)
(* *)
(* Constraint Generation/ Resolution *)
(* *)
(***********************************************************************)
(** Make the type a global type *)
let set_global (t : tau) (b : bool) : unit =
let set_global_down t =
match find t with
Var v -> v.v_global <- true
| Ref r -> set_global_label r.rl true
| Fun f -> set_global_label f.fl true
| _ -> ()
in
if !debug && b then Printf.printf "Set global: %s\n" (string_of_tau t);
assert ((not (get_global t)) || b);
if b then iter_tau set_global_down t;
match find t with
Var v -> v.v_global <- b
| Ref r -> r.r_global <- b
| Pair p -> p.p_global <- b
| Fun f -> f.f_global <- b
let rec unify_int (t, t' : tau * tau) : unit =
if equal_tau t t' then ()
else
let ti, ti' = find t, find t' in
U.unify combine (t, t');
match ti, ti' with
Var v, Var v' ->
set_global t' (v.v_global || get_global t');
merge_vholes (v, v');
merge_vlbs (v, v');
merge_vubs (v, v')
| Var v, _ ->
set_global t' (v.v_global || get_global t');
trigger_vhole v t';
notify_vlbs t v;
notify_vubs t v
| _, Var v ->
set_global t (v.v_global || get_global t);
trigger_vhole v t;
notify_vlbs t' v;
notify_vubs t' v
| Ref r, Ref r' ->
set_global t (r.r_global || r'.r_global);
unify_ref (r, r')
| Fun f, Fun f' ->
set_global t (f.f_global || f'.f_global);
unify_fun (f, f')
| Pair p, Pair p' -> ()
| _ -> raise Inconsistent
and notify_vlbs (t : tau) (vi : vinfo) : unit =
let notify p bounds =
List.iter
(fun b ->
add_constraint (Unification (b.info,copy_toplevel t));
add_constraint (Leq (b.info, (b.index, p), t)))
bounds
in
notify Sub (B.elements vi.v_mlbs);
notify Pos (B.elements vi.v_plbs);
notify Neg (B.elements vi.v_nlbs)
and notify_vubs (t : tau) (vi : vinfo) : unit =
let notify p bounds =
List.iter
(fun b ->
add_constraint (Unification (b.info,copy_toplevel t));
add_constraint (Leq (t, (b.index, p), b.info)))
bounds
in
notify Sub (B.elements vi.v_mubs);
notify Pos (B.elements vi.v_pubs);
notify Neg (B.elements vi.v_nubs)
and unify_ref (ri,ri' : rinfo * rinfo) : unit =
add_constraint (Unification (ri.points_to, ri'.points_to))
and unify_fun (fi, fi' : finfo * finfo) : unit =
let rec union_args = function
_, [] -> false
| [], _ -> true
| h :: t, h' :: t' ->
add_constraint (Unification (h, h'));
union_args(t, t')
in
unify_label(fi.fl, fi'.fl);
add_constraint (Unification (fi.ret, fi'.ret));
if union_args (fi.args, fi'.args) then fi.args <- fi'.args;
and unify_label (l, l' : label * label) : unit =
let pick_name (li, li' : lblinfo * lblinfo) =
if String.length li.l_name > 1 && String.sub (li.l_name) 0 2 = "l_" then
li.l_name <- li'.l_name
else ()
in
let combine_label (li, li' : lblinfo *lblinfo) : lblinfo =
let rm_self b = not (li.l_stamp = get_label_stamp b.info)
in
pick_name (li, li');
li.l_global <- li.l_global || li'.l_global;
li.aliases <- C.union li.aliases li'.aliases;
li.p_ubounds <- B.union li.p_ubounds li'.p_ubounds;
li.p_lbounds <- B.union li.p_lbounds li'.p_lbounds;
li.n_ubounds <- B.union li.n_ubounds li'.n_ubounds;
li.n_lbounds <- B.union li.n_lbounds li'.n_lbounds;
li.m_ubounds <- B.union li.m_ubounds (B.filter rm_self li'.m_ubounds);
li.m_lbounds <- B.union li.m_lbounds (B.filter rm_self li'.m_lbounds);
li.m_upath <- P.union li.m_upath li'.m_upath;
li.m_lpath<- P.union li.m_lpath li'.m_lpath;
li.n_upath <- P.union li.n_upath li'.n_upath;
li.n_lpath <- P.union li.n_lpath li'.n_lpath;
li.p_upath <- P.union li.p_upath li'.p_upath;
li.p_lpath <- P.union li.p_lpath li'.p_lpath;
li.l_seeded <- li.l_seeded || li'.l_seeded;
li.l_ret <- li.l_ret || li'.l_ret;
li.l_param <- li.l_param || li'.l_param;
li
in
if !debug_constraints then
Printf.printf "%s == %s\n" (string_of_label l) (string_of_label l');
U.unify combine_label (l, l')
and merge_vholes (vi, vi' : vinfo * vinfo) : unit =
H.iter
(fun i -> fun _ -> H.replace vi'.v_hole i ())
vi.v_hole
and merge_vlbs (vi, vi' : vinfo * vinfo) : unit =
vi'.v_mlbs <- B.union vi.v_mlbs vi'.v_mlbs;
vi'.v_plbs <- B.union vi.v_plbs vi'.v_plbs;
vi'.v_nlbs <- B.union vi.v_nlbs vi'.v_nlbs
and merge_vubs (vi, vi' : vinfo * vinfo) : unit =
vi'.v_mubs <- B.union vi.v_mubs vi'.v_mubs;
vi'.v_pubs <- B.union vi.v_pubs vi'.v_pubs;
vi'.v_nubs <- B.union vi.v_nubs vi'.v_nubs
and trigger_vhole (vi : vinfo) (t : tau) =
let add_self_loops (t : tau) : unit =
match find t with
Var v ->
H.iter
(fun i -> fun _ -> H.replace v.v_hole i ())
vi.v_hole
| Ref r ->
H.iter
(fun i -> fun _ ->
leq_label (r.rl, (i, Pos), r.rl);
leq_label (r.rl, (i, Neg), r.rl))
vi.v_hole
| Fun f ->
H.iter
(fun i -> fun _ ->
leq_label (f.fl, (i, Pos), f.fl);
leq_label (f.fl, (i, Neg), f.fl))
vi.v_hole
| _ -> ()
in
iter_tau add_self_loops t
* Pick the representative info for two tinfo 's . This function prefers the
first argument when both arguments are the same structure , but when
one type is a structure and the other is a var , it picks the structure .
All other actions ( e.g. , updating the info ) is done in unify_int
first argument when both arguments are the same structure, but when
one type is a structure and the other is a var, it picks the structure.
All other actions (e.g., updating the info) is done in unify_int *)
and combine (ti, ti' : tinfo * tinfo) : tinfo =
match ti, ti' with
Var _, _ -> ti'
| _, _ -> ti
and leq_int (t, (i, p), t') : unit =
if equal_tau t t' then ()
else
let ti, ti' = find t, find t' in
match ti, ti' with
Var v, Var v' ->
begin
match p with
Pos ->
v.v_pubs <- B.add (make_tau_bound (i, t')) v.v_pubs;
v'.v_plbs <- B.add (make_tau_bound (i, t)) v'.v_plbs
| Neg ->
v.v_nubs <- B.add (make_tau_bound (i, t')) v.v_nubs;
v'.v_nlbs <- B.add (make_tau_bound (i, t)) v'.v_nlbs
| Sub ->
v.v_mubs <- B.add (make_tau_bound (i, t')) v.v_mubs;
v'.v_mlbs <- B.add (make_tau_bound (i, t)) v'.v_mlbs
end
| Var v, _ ->
add_constraint (Unification (t, copy_toplevel t'));
add_constraint (Leq (t, (i, p), t'))
| _, Var v ->
add_constraint (Unification (t', copy_toplevel t));
add_constraint (Leq (t, (i, p), t'))
| Ref r, Ref r' -> leq_ref (r, (i, p), r')
| Fun f, Fun f' -> add_constraint (Unification (t, t'))
| Pair pr, Pair pr' ->
add_constraint (Leq (pr.ptr, (i, p), pr'.ptr));
add_constraint (Leq (pr.lam, (i, p), pr'.lam))
| _ -> raise Inconsistent
and leq_ref (ri, (i, p), ri') : unit =
let add_self_loops (t : tau) : unit =
match find t with
Var v -> H.replace v.v_hole i ()
| Ref r ->
leq_label (r.rl, (i, Pos), r.rl);
leq_label (r.rl, (i, Neg), r.rl)
| Fun f ->
leq_label (f.fl, (i, Pos), f.fl);
leq_label (f.fl, (i, Neg), f.fl)
| _ -> ()
in
iter_tau add_self_loops ri.points_to;
add_constraint (Unification (ri.points_to, ri'.points_to));
leq_label(ri.rl, (i, p), ri'.rl)
and leq_label (l,(i, p), l') : unit =
if !debug_constraints then
Printf.printf
"%s <={%d,%s} %s\n"
(string_of_label l) i (string_of_polarity p) (string_of_label l');
let li, li' = find l, find l' in
match p with
Pos ->
li.l_ret <- true;
li.p_ubounds <- B.add (make_bound (i, l')) li.p_ubounds;
li'.p_lbounds <- B.add (make_bound (i, l)) li'.p_lbounds
| Neg ->
li'.l_param <- true;
li.n_ubounds <- B.add (make_bound (i, l')) li.n_ubounds;
li'.n_lbounds <- B.add (make_bound (i, l)) li'.n_lbounds
| Sub ->
if U.equal (l, l') then ()
else
begin
li.m_ubounds <- B.add (make_bound(0, l')) li.m_ubounds;
li'.m_lbounds <- B.add (make_bound(0, l)) li'.m_lbounds
end
and add_constraint_int (c : tconstraint) (toplev : bool) =
if !debug_constraints && toplev then
begin
Printf.printf "%d:>" !toplev_count;
print_constraint c;
incr toplev_count
end
else
if !debug_constraints then print_constraint c else ();
begin
match c with
Unification _ -> Q.add c eq_worklist
| Leq _ -> Q.add c leq_worklist
end;
solve_constraints ()
and add_constraint (c : tconstraint) =
add_constraint_int c false
and add_toplev_constraint (c : tconstraint) =
if !print_constraints && not !debug_constraints then
begin
Printf.printf "%d:>" !toplev_count;
incr toplev_count;
print_constraint c
end
else ();
add_constraint_int c true
and fetch_constraint () : tconstraint option =
try Some (Q.take eq_worklist)
with Q.Empty -> (try Some (Q.take leq_worklist)
with Q.Empty -> None)
(** The main solver loop. *)
and solve_constraints () : unit =
match fetch_constraint () with
Some c ->
begin
match c with
Unification (t, t') -> unify_int (t, t')
| Leq (t, (i, p), t') ->
if !no_sub then unify_int (t, t')
else
if !analyze_mono then leq_int (t, (0, Sub), t')
else leq_int (t, (i, p), t')
end;
solve_constraints ()
| None -> ()
(***********************************************************************)
(* *)
(* Interface Functions *)
(* *)
(***********************************************************************)
(** Return the contents of the lvalue. *)
let rvalue (lv : lvalue) : tau =
lv.contents
(** Dereference the rvalue. If it does not have enough structure to support
the operation, then the correct structure is added via new unification
constraints. *)
let rec deref (t : tau) : lvalue =
match U.deref t with
Pair p ->
begin
match U.deref p.ptr with
Var _ ->
let is_global = global_tau p.ptr in
let points_to = fresh_var is_global in
let l = fresh_label is_global in
let r = make_ref (l, points_to)
in
add_toplev_constraint (Unification (p.ptr, r));
make_lval (l, points_to)
| Ref r -> make_lval (r.rl, r.points_to)
| _ -> raise WellFormed
end
| Var v ->
let is_global = global_tau t in
add_toplev_constraint
(Unification (t, make_pair (fresh_var is_global,
fresh_var is_global)));
deref t
| _ -> raise WellFormed
(** Form the union of [t] and [t'], if it doesn't exist already. *)
let join (t : tau) (t' : tau) : tau =
try H.find join_cache (get_stamp t, get_stamp t')
with Not_found ->
let t'' = fresh_var false in
add_toplev_constraint (Leq (t, (0, Sub), t''));
add_toplev_constraint (Leq (t', (0, Sub), t''));
H.add join_cache (get_stamp t, get_stamp t') t'';
t''
(** Form the union of a list [tl], expected to be the initializers of some
structure or array type. *)
let join_inits (tl : tau list) : tau =
let t' = fresh_var false in
List.iter
(fun t -> add_toplev_constraint (Leq (t, (0, Sub), t')))
tl;
t'
(** Take the address of an lvalue. Does not add constraints. *)
let address (lv : lvalue) : tau =
make_pair (make_ref (lv.l, lv.contents), fresh_var false)
(** For this version of golf, instantiation is handled at [apply] *)
let instantiate (lv : lvalue) (i : int) : lvalue =
lv
(** Constraint generated from assigning [t] to [lv]. *)
let assign (lv : lvalue) (t : tau) : unit =
add_toplev_constraint (Leq (t, (0, Sub), lv.contents))
let assign_ret (i : int) (lv : lvalue) (t : tau) : unit =
add_toplev_constraint (Leq (t, (i, Pos), lv.contents))
* Project out the first ( ref ) component or a pair . If the argument [ t ] has
no discovered structure , raise NoContents .
no discovered structure, raise NoContents. *)
let proj_ref (t : tau) : tau =
match U.deref t with
Pair p -> p.ptr
| Var v -> raise NoContents
| _ -> raise WellFormed
Project out the second ( fun ) component of a pair . If the argument [ t ] has
no discovered structure , create it on the fly by adding constraints .
no discovered structure, create it on the fly by adding constraints. *)
let proj_fun (t : tau) : tau =
match U.deref t with
Pair p -> p.lam
| Var v ->
let p, f = fresh_var false, fresh_var false in
add_toplev_constraint (Unification (t, make_pair(p, f)));
f
| _ -> raise WellFormed
let get_args (t : tau) : tau list =
match U.deref t with
Fun f -> f.args
| _ -> raise WellFormed
let get_finfo (t : tau) : finfo =
match U.deref t with
Fun f -> f
| _ -> raise WellFormed
* Function type [ t ] is applied to the arguments [ actuals ] . the
actuals with the formals of [ t ] . If no functions have been discovered for
[ t ] yet , create a fresh one and unify it with t. The result is the return
value of the function plus the index of this application site .
actuals with the formals of [t]. If no functions have been discovered for
[t] yet, create a fresh one and unify it with t. The result is the return
value of the function plus the index of this application site. *)
let apply (t : tau) (al : tau list) : (tau * int) =
let i = fresh_appsite () in
let f = proj_fun t in
let actuals = ref al in
let fi,ret =
match U.deref f with
Fun fi -> fi, fi.ret
| Var v ->
let new_l, new_ret, new_args =
fresh_label false, fresh_var false,
Util.list_map (function _ -> fresh_var false) !actuals
in
let new_fun = make_fun (new_l, new_args, new_ret) in
add_toplev_constraint (Unification (new_fun, f));
(get_finfo new_fun, new_ret)
| _ -> raise WellFormed
in
pad_args2 (fi, actuals);
List.iter2
(fun actual -> fun formal ->
add_toplev_constraint (Leq (actual,(i, Neg), formal)))
!actuals fi.args;
(ret, i)
* Create a new function type with name [ name ] , list of formal arguments
[ formals ] , and return value [ ret ] . Adds no constraints .
[formals], and return value [ret]. Adds no constraints. *)
let make_function (name : string) (formals : lvalue list) (ret : tau) : tau =
let f = make_fun (make_label false name None,
Util.list_map (fun x -> rvalue x) formals,
ret)
in
make_pair (fresh_var false, f)
(** Create an lvalue. If [is_global] is true, the lvalue will be treated
monomorphically. *)
let make_lvalue (is_global : bool) (name : string) (vio : Cil.varinfo option) : lvalue =
if !debug && is_global then
Printf.printf "Making global lvalue : %s\n" name
else ();
make_lval (make_label is_global name vio, make_var is_global name)
(** Create a fresh non-global named variable. *)
let make_fresh (name : string) : tau =
make_var false name
(** The default type for constants. *)
let bottom () : tau =
make_var false "bottom"
(** Unify the result of a function with its return value. *)
let return (t : tau) (t' : tau) =
add_toplev_constraint (Leq (t', (0, Sub), t))
(***********************************************************************)
(* *)
(* Query/Extract Solutions *)
(* *)
(***********************************************************************)
let make_summary = leq_label
let path_signature k l l' b : int list =
let ksig =
match k with
Positive -> 1
| Negative -> 2
| _ -> 3
in
[ksig;
get_label_stamp l;
get_label_stamp l';
if b then 1 else 0]
let make_path (k, l, l', b) =
let psig = path_signature k l l' b in
if PH.mem path_hash psig then ()
else
let new_path = {kind = k; head = l; tail = l'; reached_global = b}
and li, li' = find l, find l' in
PH.add path_hash psig new_path;
Q.add new_path path_worklist;
begin
match k with
Positive ->
li.p_upath <- P.add new_path li.p_upath;
li'.p_lpath <- P.add new_path li'.p_lpath
| Negative ->
li.n_upath <- P.add new_path li.n_upath;
li'.n_lpath <- P.add new_path li'.n_lpath
| _ ->
li.m_upath <- P.add new_path li.m_upath;
li'.m_lpath <- P.add new_path li'.m_lpath
end;
if !debug then
begin
print_string "Discovered path : ";
print_path new_path;
print_newline ()
end
let backwards_tabulate (l : label) : unit =
let rec loop () =
let rule1 p =
if !debug then print_endline "rule1";
B.iter
(fun lb ->
make_path (Match, lb.info, p.tail,
p.reached_global || is_global_label p.head))
(find p.head).m_lbounds
and rule2 p =
if !debug then print_endline "rule2";
B.iter
(fun lb ->
make_path (Negative, lb.info, p.tail,
p.reached_global || is_global_label p.head))
(find p.head).n_lbounds
and rule2m p =
if !debug then print_endline "rule2m";
B.iter
(fun lb ->
make_path (Match, lb.info, p.tail,
p.reached_global || is_global_label p.head))
(find p.head).n_lbounds
and rule3 p =
if !debug then print_endline "rule3";
B.iter
(fun lb ->
make_path (Positive, lb.info, p.tail,
p.reached_global || is_global_label p.head))
(find p.head).p_lbounds
and rule4 p =
if !debug then print_endline "rule4";
B.iter
(fun lb ->
make_path(Negative, lb.info, p.tail,
p.reached_global || is_global_label p.head))
(find p.head).m_lbounds
and rule5 p =
if !debug then print_endline "rule5";
B.iter
(fun lb ->
make_path (Positive, lb.info, p.tail,
p.reached_global || is_global_label p.head))
(find p.head).m_lbounds
and rule6 p =
if !debug then print_endline "rule6";
B.iter
(fun lb ->
if is_seeded_label lb.info then ()
else
begin
(find lb.info).l_seeded <- true; (* set seeded *)
make_path (Seed, lb.info, lb.info,
is_global_label lb.info)
end)
(find p.head).p_lbounds
and rule7 p =
if !debug then print_endline "rule7";
if not (is_ret_label p.tail && is_param_label p.head) then ()
else
B.iter
(fun lb ->
B.iter
(fun ub ->
if lb.index = ub.index then
begin
if !debug then
Printf.printf "New summary : %s %s\n"
(string_of_label lb.info)
(string_of_label ub.info);
make_summary (lb.info, (0, Sub), ub.info);
rules 1 , 4 , and 5
P.iter
rule 1
make_path (Match, lb.info, ubp.tail,
ubp.reached_global))
(find ub.info).m_upath;
P.iter
rule 4
make_path (Negative, lb.info, ubp.tail,
ubp.reached_global))
(find ub.info).n_upath;
P.iter
rule 5
make_path (Positive, lb.info, ubp.tail,
ubp.reached_global))
(find ub.info).p_upath
end)
(find p.tail).p_ubounds)
(find p.head).n_lbounds
in
let matched_backward_rules p =
rule1 p;
if p.reached_global then rule2m p else rule2 p;
rule3 p;
rule6 p;
rule7 p
and negative_backward_rules p =
rule2 p;
rule3 p;
rule4 p;
rule6 p;
rule7 p
and positive_backward_rules p =
rule3 p;
rule5 p;
rule6 p;
rule7 p
in (* loop *)
if Q.is_empty path_worklist then ()
else
let p = Q.take path_worklist in
if !debug then
begin
print_string "Processing path: ";
print_path p;
print_newline ()
end;
begin
match p.kind with
Positive ->
if is_global_label p.tail then matched_backward_rules p
else positive_backward_rules p
| Negative -> negative_backward_rules p
| _ -> matched_backward_rules p
end;
loop ()
in (* backwards_tabulate *)
if !debug then
begin
Printf.printf "Tabulating for %s..." (string_of_label l);
if is_global_label l then print_string "(global)";
print_newline ()
end;
make_path (Seed, l, l, is_global_label l);
loop ()
let collect_ptsets (l : label) : constantset = (* todo -- cache aliases *)
let li = find l
and collect init s =
P.fold (fun x a -> C.union a (find x.head).aliases) s init
in
backwards_tabulate l;
collect (collect (collect li.aliases li.m_lpath) li.n_lpath) li.p_lpath
let extract_ptlabel (lv : lvalue) : label option =
try
match find (proj_ref lv.contents) with
Var v -> None
| Ref r -> Some r.rl;
| _ -> raise WellFormed
with NoContents -> None
let points_to_aux (t : tau) : constant list =
try
match find (proj_ref t) with
Var v -> []
| Ref r -> C.elements (collect_ptsets r.rl)
| _ -> raise WellFormed
with NoContents -> []
let points_to_names (lv : lvalue) : string list =
Util.list_map (fun (_, str, _) -> str) (points_to_aux lv.contents)
let points_to (lv : lvalue) : Cil.varinfo list =
let rec get_vinfos l : Cil.varinfo list = match l with
| (_, _, h) :: t -> h :: get_vinfos t
| [] -> []
in
get_vinfos (points_to_aux lv.contents)
let epoints_to (t : tau) : Cil.varinfo list =
let rec get_vinfos l : Cil.varinfo list = match l with
| (_, _, h) :: t -> h :: get_vinfos t
| [] -> []
in
get_vinfos (points_to_aux t)
let smart_alias_query (l : label) (l' : label) : bool =
(* Set of dead configurations *)
let dead_configs : config_map = CH.create 16 in
(* the set of discovered configurations *)
let discovered : config_map = CH.create 16 in
let rec filter_match (i : int) =
B.filter (fun (b : lblinfo bound) -> i = b.index)
in
let rec simulate c l l' =
let config = (c, get_label_stamp l, get_label_stamp l') in
if U.equal (l, l') then
begin
if !debug then
Printf.printf
"%s and %s are aliased\n"
(string_of_label l)
(string_of_label l');
raise APFound
end
else if CH.mem discovered config then ()
else
begin
if !debug_aliases then
Printf.printf
"Exploring configuration %s\n"
(string_of_configuration config);
CH.add discovered config ();
B.iter
(fun lb -> simulate c lb.info l')
(get_bounds Sub false l); (* epsilon closure of l *)
B.iter
(fun lb -> simulate c l lb.info)
(get_bounds Sub false l'); (* epsilon closure of l' *)
B.iter
(fun lb ->
let matching =
filter_match lb.index (get_bounds Pos false l')
in
B.iter
(fun b -> simulate Closed lb.info b.info)
matching;
if is_global_label l' then (* positive self-loops on l' *)
simulate Closed lb.info l')
(get_bounds Pos false l); (* positive transitions on l *)
if is_global_label l then
B.iter
(fun lb -> simulate Closed l lb.info)
(get_bounds Pos false l'); (* positive self-loops on l *)
begin
match c with (* negative transitions on l, only if Open *)
Open ->
B.iter
(fun lb ->
let matching =
filter_match lb.index (get_bounds Neg false l')
in
B.iter
(fun b -> simulate Open lb.info b.info)
matching ;
if is_global_label l' then (* neg self-loops on l' *)
simulate Open lb.info l')
(get_bounds Neg false l);
if is_global_label l then
B.iter
(fun lb -> simulate Open l lb.info)
(get_bounds Neg false l') (* negative self-loops on l *)
| _ -> ()
end;
(* if we got this far, then the configuration was not used *)
CH.add dead_configs config ();
end
in
try
begin
if H.mem cached_aliases (get_label_stamp l, get_label_stamp l') then
true
else
begin
simulate Open l l';
if !debug then
Printf.printf
"%s and %s are NOT aliased\n"
(string_of_label l)
(string_of_label l');
false
end
end
with APFound ->
CH.iter
(fun config -> fun _ ->
if not (CH.mem dead_configs config) then
H.add
cached_aliases
(get_label_stamp l, get_label_stamp l')
())
discovered;
true
(** todo : uses naive alias query for now *)
let may_alias (t1 : tau) (t2 : tau) : bool =
try
let l1 =
match find (proj_ref t1) with
Ref r -> r.rl
| Var v -> raise NoContents
| _ -> raise WellFormed
and l2 =
match find (proj_ref t2) with
Ref r -> r.rl
| Var v -> raise NoContents
| _ -> raise WellFormed
in
not (C.is_empty (C.inter (collect_ptsets l1) (collect_ptsets l2)))
with NoContents -> false
let alias_query (b : bool) (lvl : lvalue list) : int * int =
let naive_count = ref 0 in
let smart_count = ref 0 in
let lbls = Util.list_map extract_ptlabel lvl in (* label option list *)
let ptsets =
Util.list_map
(function
Some l -> collect_ptsets l
| None -> C.empty)
lbls in
let record_alias s lo s' lo' =
match lo, lo' with
Some l, Some l' ->
if !debug_aliases then
Printf.printf
"Checking whether %s and %s are aliased...\n"
(string_of_label l)
(string_of_label l');
if C.is_empty (C.inter s s') then ()
else
begin
incr naive_count;
if !smart_aliases && smart_alias_query l l' then
incr smart_count
end
| _ -> ()
in
let rec check_alias sets labels =
match sets,labels with
s :: st, l :: lt ->
List.iter2 (record_alias s l) ptsets lbls;
check_alias st lt
| [], [] -> ()
| _ -> die "check_alias"
in
check_alias ptsets lbls;
(!naive_count, !smart_count)
let alias_frequency (lvl : (lvalue * bool) list) : int * int =
let extract_lbl (lv, b : lvalue * bool) = (lv.l, b) in
let naive_count = ref 0 in
let smart_count = ref 0 in
let lbls = Util.list_map extract_lbl lvl in
let ptsets =
Util.list_map
(fun (lbl, b) ->
if b then (find lbl).loc (* symbol access *)
else collect_ptsets lbl)
lbls in
let record_alias s (l, b) s' (l', b') =
if !debug_aliases then
Printf.printf
"Checking whether %s and %s are aliased...\n"
(string_of_label l)
(string_of_label l');
if C.is_empty (C.inter s s') then ()
else
begin
if !debug_aliases then
Printf.printf
"%s and %s are aliased naively...\n"
(string_of_label l)
(string_of_label l');
incr naive_count;
if !smart_aliases then
if b || b' || smart_alias_query l l' then incr smart_count
else
Printf.printf
"%s and %s are not aliased by smart queries...\n"
(string_of_label l)
(string_of_label l');
end
in
let rec check_alias sets labels =
match sets, labels with
s :: st, l :: lt ->
List.iter2 (record_alias s l) ptsets lbls;
check_alias st lt
| [], [] -> ()
| _ -> die "check_alias"
in
check_alias ptsets lbls;
(!naive_count, !smart_count)
(** an interface for extracting abstract locations from this analysis *)
type absloc = label
let absloc_of_lvalue (l : lvalue) : absloc = l.l
let absloc_eq (a1, a2) = smart_alias_query a1 a2
let absloc_print_name = ref true
let d_absloc () (p : absloc) =
let a = find p in
if !absloc_print_name then Pretty.dprintf "%s" a.l_name
else Pretty.dprintf "%d" a.l_stamp
let phonyAddrOf (lv : lvalue) : lvalue =
make_lval (fresh_label true, address lv)
(* transitive closure of points to, starting from l *)
let rec tauPointsTo (l : tau) : absloc list =
match find l with
Var _ -> []
| Ref r -> r.rl :: tauPointsTo r.points_to
| _ -> []
let rec absloc_points_to (l : lvalue) : absloc list =
tauPointsTo l.contents
(** The following definitions are only introduced for the
compatability with Olf. *)
exception UnknownLocation
let finished_constraints () = ()
let apply_undefined (_ : tau list) = (fresh_var true, 0)
let assign_undefined (_ : lvalue) = ()
let absloc_epoints_to = tauPointsTo
| null | https://raw.githubusercontent.com/hipsleek/hipsleek/596f7fa7f67444c8309da2ca86ba4c47d376618c/cil/src/ext/pta/golf.ml | ocaml | *********************************************************************
Exceptions
*********************************************************************
raised if constraint system is inconsistent
raised if types are not well-formed
raised if an alias pair is found, a control
flow exception
* Subtyping kinds
* Context kinds -- open or closed
* Generic bounds
* For label paths.
* Constants, which identify elements in points-to sets
* either empty or a singleton, the initial location for this label
* Name of this label
* Unique integer for this label
* True if this location is globally accessible
* Set of constants (tags) for checking aliases
* Set of umatched (p) lower bounds
* Set of unmatched (n) lower bounds
* Set of umatched (p) upper bounds
* Set of unmatched (n) upper bounds
* Set of matched (m) lower bounds
* Set of matched (m) upper bounds
* Constructor labels
*********************************************************************
Global Variables
*********************************************************************
* Print the instantiations constraints.
* If true, print all constraints (including induced) and show
additional debug output.
* Just debug all the constraints (including induced)
* Debug smart alias queries
* If true, make the flow step a no-op
* If true, disable subtyping (unification at all levels)
* If true, treat indexed edges as regular subtyping
* A list of equality constraints.
* A count of the constraints introduced from the AST. Used for debugging.
* A hashtable containing stamp pairs of labels that must be aliased.
* A hashtable mapping pairs of tau's to their join node.
*********************************************************************
Utility Functions
*********************************************************************
* Generate a unique integer.
* Return a unique integer representation of a tau
* Negate a polarity.
* Consistency checks for inferred types
* Apply [f] structurally down [t]. Guaranteed to terminate, even if [t]
is recursive
Extract a label's bounds according to [positive] and [upper].
todo - check
* Aliases for set_global
*********************************************************************
Printing Functions
*********************************************************************
* Convert a label to a string, short representation
* Return true if the element [e] is present in the association list,
according to uref equality
* Given a tau, create a unique recursive variable name. This should always
return the same name for a given tau
* Return a string representation of a tau, using association lists.
recursive type. see if a var name has been set
type's not recursive. Add it to the assoc list and cont.
* Convert an lvalue to a string
do a consistency check
* Print a list of tau elements, comma separated
*********************************************************************
Type Operations -- these do not create any constraints
*********************************************************************
* Create an lvalue with label [lbl] and tau contents [t].
* Create a new label with name [name]. Also adds a fresh constant
with name [name] to this label's aliases set.
* Create a new label with an unspecified name and an empty alias set.
* Create a fresh bound (edge in the constraint graph).
* Create a fresh named variable with name '[name].
* Create a fresh unnamed variable (name will be 'fv).
* Create a fresh unnamed variable (name will be 'fi).
* Create a Fun constructor.
* Create a Pair constructor.
* Copy the toplevel constructor of [t], putting fresh variables in each
argement of the constructor.
*********************************************************************
Constraint Generation/ Resolution
*********************************************************************
* Make the type a global type
* The main solver loop.
*********************************************************************
Interface Functions
*********************************************************************
* Return the contents of the lvalue.
* Dereference the rvalue. If it does not have enough structure to support
the operation, then the correct structure is added via new unification
constraints.
* Form the union of [t] and [t'], if it doesn't exist already.
* Form the union of a list [tl], expected to be the initializers of some
structure or array type.
* Take the address of an lvalue. Does not add constraints.
* For this version of golf, instantiation is handled at [apply]
* Constraint generated from assigning [t] to [lv].
* Create an lvalue. If [is_global] is true, the lvalue will be treated
monomorphically.
* Create a fresh non-global named variable.
* The default type for constants.
* Unify the result of a function with its return value.
*********************************************************************
Query/Extract Solutions
*********************************************************************
set seeded
loop
backwards_tabulate
todo -- cache aliases
Set of dead configurations
the set of discovered configurations
epsilon closure of l
epsilon closure of l'
positive self-loops on l'
positive transitions on l
positive self-loops on l
negative transitions on l, only if Open
neg self-loops on l'
negative self-loops on l
if we got this far, then the configuration was not used
* todo : uses naive alias query for now
label option list
symbol access
* an interface for extracting abstract locations from this analysis
transitive closure of points to, starting from l
* The following definitions are only introduced for the
compatability with Olf. |
*
* Copyright ( c ) 2001 - 2002 ,
* < >
* All rights reserved .
*
* Redistribution and use in source and binary forms , with or without
* modification , are permitted provided that the following conditions are
* met :
*
* 1 . Redistributions of source code must retain the above copyright
* notice , this list of conditions and the following disclaimer .
*
* 2 . Redistributions in binary form must reproduce the above copyright
* notice , this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution .
*
* 3 . The names of the contributors may not be used to endorse or promote
* products derived from this software without specific prior written
* permission .
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS " AS
* IS " AND ANY EXPRESS OR IMPLIED WARRANTIES , INCLUDING , BUT NOT LIMITED
* TO , THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
* PARTICULAR PURPOSE ARE DISCLAIMED . IN NO EVENT SHALL THE COPYRIGHT OWNER
* OR FOR ANY DIRECT , INDIRECT , INCIDENTAL , SPECIAL ,
* EXEMPLARY , OR CONSEQUENTIAL DAMAGES ( INCLUDING , BUT NOT LIMITED TO ,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES ; LOSS OF USE , DATA , OR
* PROFITS ; OR BUSINESS INTERRUPTION ) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY , WHETHER IN CONTRACT , STRICT LIABILITY , OR TORT ( INCLUDING
* NEGLIGENCE OR OTHERWISE ) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE , EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE .
*
*
* Copyright (c) 2001-2002,
* John Kodumal <>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* 3. The names of the contributors may not be used to endorse or promote
* products derived from this software without specific prior written
* permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
* PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER
* OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*)
exception NoContents
module U = Uref
module S = Setp
module H = Hashtbl
module Q = Queue
type polarity =
Pos
| Neg
| Sub
* Path kinds , for CFL reachability
type pkind =
Positive
| Negative
| Match
| Seed
type context =
Open
| Closed
A configuration is a context ( open or closed ) coupled with a pair
of stamps representing a state in the cartesian product DFA .
of stamps representing a state in the cartesian product DFA. *)
type configuration = context * int * int
module ConfigHash =
struct
type t = configuration
let equal t t' = t = t'
let hash t = Hashtbl.hash t
end
module CH = H.Make (ConfigHash)
type config_map = unit CH.t
type 'a bound = {index : int; info : 'a U.uref}
type 'a path = {
kind : pkind;
reached_global : bool;
head : 'a U.uref;
tail : 'a U.uref
}
module Bound =
struct
type 'a t = 'a bound
let compare (x : 'a t) (y : 'a t) =
if U.equal (x.info, y.info) then x.index - y.index
else Pervasives.compare (U.deref x.info) (U.deref y.info)
end
module Path =
struct
type 'a t = 'a path
let compare (x : 'a t) (y : 'a t) =
if U.equal (x.head, y.head) then
begin
if U.equal (x.tail, y.tail) then
begin
if x.reached_global = y.reached_global then
Pervasives.compare x.kind y.kind
else Pervasives.compare x.reached_global y.reached_global
end
else Pervasives.compare (U.deref x.tail) (U.deref y.tail)
end
else Pervasives.compare (U.deref x.head) (U.deref y.head)
end
module B = S.Make (Bound)
module P = S.Make (Path)
type 'a boundset = 'a B.t
type 'a pathset = 'a P.t
* jk : I 'd prefer to make this an ' a constant and specialize it to varinfo
for use with the frontend , but for now , this will do
for use with the Cil frontend, but for now, this will do *)
type constant = int * string * Cil.varinfo
module Constant =
struct
type t = constant
let compare (xid, _, _) (yid, _, _) = xid - yid
end
module C = Set.Make (Constant)
* Sets of constants . Set union is used when two labels containing
constant sets are unified
constant sets are unified *)
type constantset = C.t
type lblinfo = {
mutable l_name: string;
loc : constantset;
l_stamp : int;
mutable l_global : bool;
mutable aliases: constantset;
mutable p_lbounds: lblinfo boundset;
mutable n_lbounds: lblinfo boundset;
mutable p_ubounds: lblinfo boundset;
mutable n_ubounds: lblinfo boundset;
mutable m_lbounds: lblinfo boundset;
mutable m_ubounds: lblinfo boundset;
mutable m_upath: lblinfo pathset;
mutable m_lpath: lblinfo pathset;
mutable n_upath: lblinfo pathset;
mutable n_lpath: lblinfo pathset;
mutable p_upath: lblinfo pathset;
mutable p_lpath: lblinfo pathset;
mutable l_seeded : bool;
mutable l_ret : bool;
mutable l_param : bool;
}
and label = lblinfo U.uref
* The type of lvalues .
type lvalue = {
l: label;
contents: tau
}
and vinfo = {
v_stamp : int;
v_name : string;
mutable v_hole : (int,unit) H.t;
mutable v_global : bool;
mutable v_mlbs : tinfo boundset;
mutable v_mubs : tinfo boundset;
mutable v_plbs : tinfo boundset;
mutable v_pubs : tinfo boundset;
mutable v_nlbs : tinfo boundset;
mutable v_nubs : tinfo boundset
}
and rinfo = {
r_stamp : int;
rl : label;
points_to : tau;
mutable r_global: bool;
}
and finfo = {
f_stamp : int;
fl : label;
ret : tau;
mutable args : tau list;
mutable f_global : bool;
}
and pinfo = {
p_stamp : int;
ptr : tau;
lam : tau;
mutable p_global : bool;
}
and tinfo = Var of vinfo
| Ref of rinfo
| Fun of finfo
| Pair of pinfo
and tau = tinfo U.uref
type tconstraint = Unification of tau * tau
| Leq of tau * (int * polarity) * tau
* Association lists , used for printing recursive types . The first element
is a type that has been visited . The second element is the string
representation of that type ( so far ) . If the string option is set , then
this type occurs within itself , and is associated with the recursive var
name stored in the option . When walking a type , add it to an association
list .
Example : suppose we have the constraint ' a = ref('a ) . The type is unified
via cyclic unification , and would loop infinitely if we attempted to print
it . What we want to do is print the type ref(rv ) . This is accomplished
in the following manner :
-- ref('a ) is visited . It is not in the association list , so it is added
and the string " ref ( " is stored in the second element . We recurse to print
the first argument of the constructor .
-- In the recursive call , we see that ' a ( or ref('a ) ) is already in the
association list , so the type is recursive . We check the string option ,
which is None , meaning that this is the first recurrence of the type . We
create a new recursive variable , rv and set the string option to ' rv . Next ,
we prepend to the string representation we have seen before , " ref ( " ,
and return " rv " as the string representation of this type .
-- The string so far is " u rv.ref ( " . The recursive call returns , and we
complete the type by printing the result of the call , " rv " , and " ) "
In a type where the recursive variable appears twice , e.g. ' a = pair('a,'a ) ,
the second time we hit ' a , the string option will be set , so we know to
reuse the same recursive variable name .
is a type that has been visited. The second element is the string
representation of that type (so far). If the string option is set, then
this type occurs within itself, and is associated with the recursive var
name stored in the option. When walking a type, add it to an association
list.
Example : suppose we have the constraint 'a = ref('a). The type is unified
via cyclic unification, and would loop infinitely if we attempted to print
it. What we want to do is print the type u rv. ref(rv). This is accomplished
in the following manner:
-- ref('a) is visited. It is not in the association list, so it is added
and the string "ref(" is stored in the second element. We recurse to print
the first argument of the constructor.
-- In the recursive call, we see that 'a (or ref('a)) is already in the
association list, so the type is recursive. We check the string option,
which is None, meaning that this is the first recurrence of the type. We
create a new recursive variable, rv and set the string option to 'rv. Next,
we prepend u rv. to the string representation we have seen before, "ref(",
and return "rv" as the string representation of this type.
-- The string so far is "u rv.ref(". The recursive call returns, and we
complete the type by printing the result of the call, "rv", and ")"
In a type where the recursive variable appears twice, e.g. 'a = pair('a,'a),
the second time we hit 'a, the string option will be set, so we know to
reuse the same recursive variable name.
*)
type association = tau * string ref * string option ref
module PathHash =
struct
type t = int list
let equal t t' = t = t'
let hash t = Hashtbl.hash t
end
module PH = H.Make (PathHash)
let print_constraints : bool ref = ref false
let debug = ref false
let debug_constraints = ref false
let debug_aliases = ref false
let smart_aliases = ref false
let no_flow = ref false
let no_sub = ref false
let analyze_mono = ref true
let eq_worklist : tconstraint Q.t = Q.create ()
* A list of leq constraints .
let leq_worklist : tconstraint Q.t = Q.create ()
let path_worklist : (lblinfo path) Q.t = Q.create ()
let path_hash : (lblinfo path) PH.t = PH.create 32
let toplev_count = ref 0
let cached_aliases : (int * int,unit) H.t = H.create 64
let join_cache : (int * int, tau) H.t = H.create 64
let find = U.deref
let die s =
Printf.printf "*******\nAssertion failed: %s\n*******\n" s;
assert false
let fresh_appsite : (unit -> int) =
let appsite_index = ref 0 in
fun () ->
incr appsite_index;
!appsite_index
let fresh_index : (unit -> int) =
let counter = ref 0 in
fun () ->
incr counter;
!counter
let fresh_stamp : (unit -> int) =
let stamp = ref 0 in
fun () ->
incr stamp;
!stamp
let get_stamp (t : tau) : int =
match find t with
Var v -> v.v_stamp
| Ref r -> r.r_stamp
| Pair p -> p.p_stamp
| Fun f -> f.f_stamp
let negate (p : polarity) : polarity =
match p with
Pos -> Neg
| Neg -> Pos
| Sub -> die "negate"
let pair_or_var (t : tau) =
match find t with
Pair _ -> true
| Var _ -> true
| _ -> false
let ref_or_var (t : tau) =
match find t with
Ref _ -> true
| Var _ -> true
| _ -> false
let fun_or_var (t : tau) =
match find t with
Fun _ -> true
| Var _ -> true
| _ -> false
let iter_tau f t =
let visited : (int,tau) H.t = H.create 4 in
let rec iter_tau' t =
if H.mem visited (get_stamp t) then () else
begin
f t;
H.add visited (get_stamp t) t;
match U.deref t with
Pair p ->
iter_tau' p.ptr;
iter_tau' p.lam
| Fun f ->
List.iter iter_tau' (f.args);
iter_tau' f.ret
| Ref r -> iter_tau' r.points_to
| _ -> ()
end
in
iter_tau' t
let get_bounds (p :polarity ) (upper : bool) (l : label) : lblinfo boundset =
let li = find l in
match p with
Pos -> if upper then li.p_ubounds else li.p_lbounds
| Neg -> if upper then li.n_ubounds else li.n_lbounds
| Sub -> if upper then li.m_ubounds else li.m_lbounds
let equal_tau (t : tau) (t' : tau) =
get_stamp t = get_stamp t'
let get_label_stamp (l : label) : int =
(find l).l_stamp
* Return true if [ t ] is global ( treated )
let get_global (t : tau) : bool =
match find t with
Var v -> v.v_global
| Ref r -> r.r_global
| Pair p -> p.p_global
| Fun f -> f.f_global
let is_param_label l = (find l).l_param || (find l).l_global
let is_global_label l = (find l).l_global
let is_seeded_label l = (find l).l_seeded
let set_global_label (l : label) (b : bool) : unit =
assert ((not (is_global_label l)) || b);
(U.deref l).l_global <- b
let global_tau = get_global
* Get_global for
let global_lvalue lv = get_global lv.contents
let string_of_configuration (c, i, i') =
let context = match c with
Open -> "O"
| Closed -> "C"
in
Printf.sprintf "(%s,%d,%d)" context i i'
let string_of_polarity p =
match p with
Pos -> "+"
| Neg -> "-"
| Sub -> "M"
let string_of_label (l : label) : string =
"\"" ^ (find l).l_name ^ "\""
let rec assoc_list_mem (e : tau) (l : association list) =
match l with
| [] -> None
| (h, s, so) :: t ->
if U.equal (h,e) then Some (s, so) else assoc_list_mem e t
let fresh_recvar_name (t : tau) : string =
match find t with
Pair p -> "rvp" ^ string_of_int p.p_stamp
| Ref r -> "rvr" ^ string_of_int r.r_stamp
| Fun f -> "rvf" ^ string_of_int f.f_stamp
| _ -> die "fresh_recvar_name"
let string_of_tau (t : tau) : string =
let tau_map : association list ref = ref [] in
let rec string_of_tau' t =
match assoc_list_mem t !tau_map with
begin
match !so with
None ->
let rv = fresh_recvar_name t in
s := "u " ^ rv ^ "." ^ !s;
so := Some rv;
rv
| Some rv -> rv
end
let s = ref ""
and so : string option ref = ref None in
tau_map := (t, s, so) :: !tau_map;
begin
match find t with
Var v -> s := v.v_name;
| Pair p ->
assert (ref_or_var p.ptr);
assert (fun_or_var p.lam);
s := "{";
s := !s ^ string_of_tau' p.ptr;
s := !s ^ ",";
s := !s ^ string_of_tau' p.lam;
s := !s ^"}"
| Ref r ->
assert (pair_or_var r.points_to);
s := "ref(|";
s := !s ^ string_of_label r.rl;
s := !s ^ "|,";
s := !s ^ string_of_tau' r.points_to;
s := !s ^ ")"
| Fun f ->
assert (pair_or_var f.ret);
let rec string_of_args = function
h :: [] ->
assert (pair_or_var h);
s := !s ^ string_of_tau' h
| h :: t ->
assert (pair_or_var h);
s := !s ^ string_of_tau' h ^ ",";
string_of_args t
| [] -> ()
in
s := "fun(|";
s := !s ^ string_of_label f.fl;
s := !s ^ "|,";
s := !s ^ "<";
if List.length f.args > 0 then string_of_args f.args
else s := !s ^ "void";
s := !s ^">,";
s := !s ^ string_of_tau' f.ret;
s := !s ^ ")"
end;
tau_map := List.tl !tau_map;
!s
in
string_of_tau' t
let rec string_of_lvalue (lv : lvalue) : string =
let contents = string_of_tau lv.contents
and l = string_of_label lv.l in
Printf.sprintf "[%s]^(%s)" contents l
let print_path (p : lblinfo path) : unit =
let string_of_pkind = function
Positive -> "p"
| Negative -> "n"
| Match -> "m"
| Seed -> "s"
in
Printf.printf
"%s --%s--> %s (%d) : "
(string_of_label p.head)
(string_of_pkind p.kind)
(string_of_label p.tail)
(PathHash.hash p)
let rec print_tau_list (l : tau list) : unit =
let rec print_t_strings = function
h :: [] -> print_endline h
| h :: t ->
print_string h;
print_string ", ";
print_t_strings t
| [] -> ()
in
print_t_strings (Util.list_map string_of_tau l)
let print_constraint (c : tconstraint) =
match c with
Unification (t, t') ->
let lhs = string_of_tau t
and rhs = string_of_tau t' in
Printf.printf "%s == %s\n" lhs rhs
| Leq (t, (i, p), t') ->
let lhs = string_of_tau t
and rhs = string_of_tau t' in
Printf.printf "%s <={%d,%s} %s\n" lhs i (string_of_polarity p) rhs
let make_lval (lbl, t : label * tau) : lvalue =
{l = lbl; contents = t}
let make_label_int (is_global : bool) (name :string) (vio : Cil.varinfo option) : label =
let locc =
match vio with
Some vi -> C.add (fresh_index (), name, vi) C.empty
| None -> C.empty
in
U.uref {
l_name = name;
l_global = is_global;
l_stamp = fresh_stamp ();
loc = locc;
aliases = locc;
p_ubounds = B.empty;
p_lbounds = B.empty;
n_ubounds = B.empty;
n_lbounds = B.empty;
m_ubounds = B.empty;
m_lbounds = B.empty;
m_upath = P.empty;
m_lpath = P.empty;
n_upath = P.empty;
n_lpath = P.empty;
p_upath = P.empty;
p_lpath = P.empty;
l_seeded = false;
l_ret = false;
l_param = false
}
let make_label (is_global : bool) (name : string) (vio : Cil.varinfo option) : label =
make_label_int is_global name vio
let fresh_label (is_global : bool) : label =
let index = fresh_index () in
make_label_int is_global ("l_" ^ string_of_int index) None
let make_bound (i, a : int * label) : lblinfo bound =
{index = i; info = a}
let make_tau_bound (i, a : int * tau) : tinfo bound =
{index = i; info = a}
let make_var (b: bool) (name : string) : tau =
U.uref (Var {v_name = ("'" ^ name);
v_hole = H.create 8;
v_stamp = fresh_index ();
v_global = b;
v_mlbs = B.empty;
v_mubs = B.empty;
v_plbs = B.empty;
v_pubs = B.empty;
v_nlbs = B.empty;
v_nubs = B.empty})
let fresh_var (is_global : bool) : tau =
make_var is_global ("fv" ^ string_of_int (fresh_index ()))
let fresh_var_i (is_global : bool) : tau =
make_var is_global ("fi" ^ string_of_int (fresh_index()))
let make_fun (lbl, a, r : label * (tau list) * tau) : tau =
U.uref (Fun {fl = lbl;
f_stamp = fresh_index ();
f_global = false;
args = a;
ret = r })
* Create a Ref constructor .
let make_ref (lbl,pt : label * tau) : tau =
U.uref (Ref {rl = lbl;
r_stamp = fresh_index ();
r_global = false;
points_to = pt})
let make_pair (p,f : tau * tau) : tau =
U.uref (Pair {ptr = p;
p_stamp = fresh_index ();
p_global = false;
lam = f})
let copy_toplevel (t : tau) : tau =
match find t with
Pair _ -> make_pair (fresh_var_i false, fresh_var_i false)
| Ref _ -> make_ref (fresh_label false, fresh_var_i false)
| Fun f ->
let fresh_fn = fun _ -> fresh_var_i false in
make_fun (fresh_label false,
Util.list_map fresh_fn f.args, fresh_var_i false)
| _ -> die "copy_toplevel"
let has_same_structure (t : tau) (t' : tau) =
match find t, find t' with
Pair _, Pair _ -> true
| Ref _, Ref _ -> true
| Fun _, Fun _ -> true
| Var _, Var _ -> true
| _ -> false
let pad_args (f, f' : finfo * finfo) : unit =
let padding = ref ((List.length f.args) - (List.length f'.args))
in
if !padding == 0 then ()
else
let to_pad =
if !padding > 0 then f' else (padding := -(!padding); f)
in
for i = 1 to !padding do
to_pad.args <- to_pad.args @ [fresh_var false]
done
let pad_args2 (fi, tlr : finfo * tau list ref) : unit =
let padding = ref (List.length fi.args - List.length !tlr)
in
if !padding == 0 then ()
else
if !padding > 0 then
for i = 1 to !padding do
tlr := !tlr @ [fresh_var false]
done
else
begin
padding := -(!padding);
for i = 1 to !padding do
fi.args <- fi.args @ [fresh_var false]
done
end
let set_global (t : tau) (b : bool) : unit =
let set_global_down t =
match find t with
Var v -> v.v_global <- true
| Ref r -> set_global_label r.rl true
| Fun f -> set_global_label f.fl true
| _ -> ()
in
if !debug && b then Printf.printf "Set global: %s\n" (string_of_tau t);
assert ((not (get_global t)) || b);
if b then iter_tau set_global_down t;
match find t with
Var v -> v.v_global <- b
| Ref r -> r.r_global <- b
| Pair p -> p.p_global <- b
| Fun f -> f.f_global <- b
let rec unify_int (t, t' : tau * tau) : unit =
if equal_tau t t' then ()
else
let ti, ti' = find t, find t' in
U.unify combine (t, t');
match ti, ti' with
Var v, Var v' ->
set_global t' (v.v_global || get_global t');
merge_vholes (v, v');
merge_vlbs (v, v');
merge_vubs (v, v')
| Var v, _ ->
set_global t' (v.v_global || get_global t');
trigger_vhole v t';
notify_vlbs t v;
notify_vubs t v
| _, Var v ->
set_global t (v.v_global || get_global t);
trigger_vhole v t;
notify_vlbs t' v;
notify_vubs t' v
| Ref r, Ref r' ->
set_global t (r.r_global || r'.r_global);
unify_ref (r, r')
| Fun f, Fun f' ->
set_global t (f.f_global || f'.f_global);
unify_fun (f, f')
| Pair p, Pair p' -> ()
| _ -> raise Inconsistent
and notify_vlbs (t : tau) (vi : vinfo) : unit =
let notify p bounds =
List.iter
(fun b ->
add_constraint (Unification (b.info,copy_toplevel t));
add_constraint (Leq (b.info, (b.index, p), t)))
bounds
in
notify Sub (B.elements vi.v_mlbs);
notify Pos (B.elements vi.v_plbs);
notify Neg (B.elements vi.v_nlbs)
and notify_vubs (t : tau) (vi : vinfo) : unit =
let notify p bounds =
List.iter
(fun b ->
add_constraint (Unification (b.info,copy_toplevel t));
add_constraint (Leq (t, (b.index, p), b.info)))
bounds
in
notify Sub (B.elements vi.v_mubs);
notify Pos (B.elements vi.v_pubs);
notify Neg (B.elements vi.v_nubs)
and unify_ref (ri,ri' : rinfo * rinfo) : unit =
add_constraint (Unification (ri.points_to, ri'.points_to))
and unify_fun (fi, fi' : finfo * finfo) : unit =
let rec union_args = function
_, [] -> false
| [], _ -> true
| h :: t, h' :: t' ->
add_constraint (Unification (h, h'));
union_args(t, t')
in
unify_label(fi.fl, fi'.fl);
add_constraint (Unification (fi.ret, fi'.ret));
if union_args (fi.args, fi'.args) then fi.args <- fi'.args;
and unify_label (l, l' : label * label) : unit =
let pick_name (li, li' : lblinfo * lblinfo) =
if String.length li.l_name > 1 && String.sub (li.l_name) 0 2 = "l_" then
li.l_name <- li'.l_name
else ()
in
let combine_label (li, li' : lblinfo *lblinfo) : lblinfo =
let rm_self b = not (li.l_stamp = get_label_stamp b.info)
in
pick_name (li, li');
li.l_global <- li.l_global || li'.l_global;
li.aliases <- C.union li.aliases li'.aliases;
li.p_ubounds <- B.union li.p_ubounds li'.p_ubounds;
li.p_lbounds <- B.union li.p_lbounds li'.p_lbounds;
li.n_ubounds <- B.union li.n_ubounds li'.n_ubounds;
li.n_lbounds <- B.union li.n_lbounds li'.n_lbounds;
li.m_ubounds <- B.union li.m_ubounds (B.filter rm_self li'.m_ubounds);
li.m_lbounds <- B.union li.m_lbounds (B.filter rm_self li'.m_lbounds);
li.m_upath <- P.union li.m_upath li'.m_upath;
li.m_lpath<- P.union li.m_lpath li'.m_lpath;
li.n_upath <- P.union li.n_upath li'.n_upath;
li.n_lpath <- P.union li.n_lpath li'.n_lpath;
li.p_upath <- P.union li.p_upath li'.p_upath;
li.p_lpath <- P.union li.p_lpath li'.p_lpath;
li.l_seeded <- li.l_seeded || li'.l_seeded;
li.l_ret <- li.l_ret || li'.l_ret;
li.l_param <- li.l_param || li'.l_param;
li
in
if !debug_constraints then
Printf.printf "%s == %s\n" (string_of_label l) (string_of_label l');
U.unify combine_label (l, l')
and merge_vholes (vi, vi' : vinfo * vinfo) : unit =
H.iter
(fun i -> fun _ -> H.replace vi'.v_hole i ())
vi.v_hole
and merge_vlbs (vi, vi' : vinfo * vinfo) : unit =
vi'.v_mlbs <- B.union vi.v_mlbs vi'.v_mlbs;
vi'.v_plbs <- B.union vi.v_plbs vi'.v_plbs;
vi'.v_nlbs <- B.union vi.v_nlbs vi'.v_nlbs
and merge_vubs (vi, vi' : vinfo * vinfo) : unit =
vi'.v_mubs <- B.union vi.v_mubs vi'.v_mubs;
vi'.v_pubs <- B.union vi.v_pubs vi'.v_pubs;
vi'.v_nubs <- B.union vi.v_nubs vi'.v_nubs
and trigger_vhole (vi : vinfo) (t : tau) =
let add_self_loops (t : tau) : unit =
match find t with
Var v ->
H.iter
(fun i -> fun _ -> H.replace v.v_hole i ())
vi.v_hole
| Ref r ->
H.iter
(fun i -> fun _ ->
leq_label (r.rl, (i, Pos), r.rl);
leq_label (r.rl, (i, Neg), r.rl))
vi.v_hole
| Fun f ->
H.iter
(fun i -> fun _ ->
leq_label (f.fl, (i, Pos), f.fl);
leq_label (f.fl, (i, Neg), f.fl))
vi.v_hole
| _ -> ()
in
iter_tau add_self_loops t
* Pick the representative info for two tinfo 's . This function prefers the
first argument when both arguments are the same structure , but when
one type is a structure and the other is a var , it picks the structure .
All other actions ( e.g. , updating the info ) is done in unify_int
first argument when both arguments are the same structure, but when
one type is a structure and the other is a var, it picks the structure.
All other actions (e.g., updating the info) is done in unify_int *)
and combine (ti, ti' : tinfo * tinfo) : tinfo =
match ti, ti' with
Var _, _ -> ti'
| _, _ -> ti
and leq_int (t, (i, p), t') : unit =
if equal_tau t t' then ()
else
let ti, ti' = find t, find t' in
match ti, ti' with
Var v, Var v' ->
begin
match p with
Pos ->
v.v_pubs <- B.add (make_tau_bound (i, t')) v.v_pubs;
v'.v_plbs <- B.add (make_tau_bound (i, t)) v'.v_plbs
| Neg ->
v.v_nubs <- B.add (make_tau_bound (i, t')) v.v_nubs;
v'.v_nlbs <- B.add (make_tau_bound (i, t)) v'.v_nlbs
| Sub ->
v.v_mubs <- B.add (make_tau_bound (i, t')) v.v_mubs;
v'.v_mlbs <- B.add (make_tau_bound (i, t)) v'.v_mlbs
end
| Var v, _ ->
add_constraint (Unification (t, copy_toplevel t'));
add_constraint (Leq (t, (i, p), t'))
| _, Var v ->
add_constraint (Unification (t', copy_toplevel t));
add_constraint (Leq (t, (i, p), t'))
| Ref r, Ref r' -> leq_ref (r, (i, p), r')
| Fun f, Fun f' -> add_constraint (Unification (t, t'))
| Pair pr, Pair pr' ->
add_constraint (Leq (pr.ptr, (i, p), pr'.ptr));
add_constraint (Leq (pr.lam, (i, p), pr'.lam))
| _ -> raise Inconsistent
and leq_ref (ri, (i, p), ri') : unit =
let add_self_loops (t : tau) : unit =
match find t with
Var v -> H.replace v.v_hole i ()
| Ref r ->
leq_label (r.rl, (i, Pos), r.rl);
leq_label (r.rl, (i, Neg), r.rl)
| Fun f ->
leq_label (f.fl, (i, Pos), f.fl);
leq_label (f.fl, (i, Neg), f.fl)
| _ -> ()
in
iter_tau add_self_loops ri.points_to;
add_constraint (Unification (ri.points_to, ri'.points_to));
leq_label(ri.rl, (i, p), ri'.rl)
and leq_label (l,(i, p), l') : unit =
if !debug_constraints then
Printf.printf
"%s <={%d,%s} %s\n"
(string_of_label l) i (string_of_polarity p) (string_of_label l');
let li, li' = find l, find l' in
match p with
Pos ->
li.l_ret <- true;
li.p_ubounds <- B.add (make_bound (i, l')) li.p_ubounds;
li'.p_lbounds <- B.add (make_bound (i, l)) li'.p_lbounds
| Neg ->
li'.l_param <- true;
li.n_ubounds <- B.add (make_bound (i, l')) li.n_ubounds;
li'.n_lbounds <- B.add (make_bound (i, l)) li'.n_lbounds
| Sub ->
if U.equal (l, l') then ()
else
begin
li.m_ubounds <- B.add (make_bound(0, l')) li.m_ubounds;
li'.m_lbounds <- B.add (make_bound(0, l)) li'.m_lbounds
end
and add_constraint_int (c : tconstraint) (toplev : bool) =
if !debug_constraints && toplev then
begin
Printf.printf "%d:>" !toplev_count;
print_constraint c;
incr toplev_count
end
else
if !debug_constraints then print_constraint c else ();
begin
match c with
Unification _ -> Q.add c eq_worklist
| Leq _ -> Q.add c leq_worklist
end;
solve_constraints ()
and add_constraint (c : tconstraint) =
add_constraint_int c false
and add_toplev_constraint (c : tconstraint) =
if !print_constraints && not !debug_constraints then
begin
Printf.printf "%d:>" !toplev_count;
incr toplev_count;
print_constraint c
end
else ();
add_constraint_int c true
and fetch_constraint () : tconstraint option =
try Some (Q.take eq_worklist)
with Q.Empty -> (try Some (Q.take leq_worklist)
with Q.Empty -> None)
and solve_constraints () : unit =
match fetch_constraint () with
Some c ->
begin
match c with
Unification (t, t') -> unify_int (t, t')
| Leq (t, (i, p), t') ->
if !no_sub then unify_int (t, t')
else
if !analyze_mono then leq_int (t, (0, Sub), t')
else leq_int (t, (i, p), t')
end;
solve_constraints ()
| None -> ()
let rvalue (lv : lvalue) : tau =
lv.contents
let rec deref (t : tau) : lvalue =
match U.deref t with
Pair p ->
begin
match U.deref p.ptr with
Var _ ->
let is_global = global_tau p.ptr in
let points_to = fresh_var is_global in
let l = fresh_label is_global in
let r = make_ref (l, points_to)
in
add_toplev_constraint (Unification (p.ptr, r));
make_lval (l, points_to)
| Ref r -> make_lval (r.rl, r.points_to)
| _ -> raise WellFormed
end
| Var v ->
let is_global = global_tau t in
add_toplev_constraint
(Unification (t, make_pair (fresh_var is_global,
fresh_var is_global)));
deref t
| _ -> raise WellFormed
let join (t : tau) (t' : tau) : tau =
try H.find join_cache (get_stamp t, get_stamp t')
with Not_found ->
let t'' = fresh_var false in
add_toplev_constraint (Leq (t, (0, Sub), t''));
add_toplev_constraint (Leq (t', (0, Sub), t''));
H.add join_cache (get_stamp t, get_stamp t') t'';
t''
let join_inits (tl : tau list) : tau =
let t' = fresh_var false in
List.iter
(fun t -> add_toplev_constraint (Leq (t, (0, Sub), t')))
tl;
t'
let address (lv : lvalue) : tau =
make_pair (make_ref (lv.l, lv.contents), fresh_var false)
let instantiate (lv : lvalue) (i : int) : lvalue =
lv
let assign (lv : lvalue) (t : tau) : unit =
add_toplev_constraint (Leq (t, (0, Sub), lv.contents))
let assign_ret (i : int) (lv : lvalue) (t : tau) : unit =
add_toplev_constraint (Leq (t, (i, Pos), lv.contents))
* Project out the first ( ref ) component or a pair . If the argument [ t ] has
no discovered structure , raise NoContents .
no discovered structure, raise NoContents. *)
let proj_ref (t : tau) : tau =
match U.deref t with
Pair p -> p.ptr
| Var v -> raise NoContents
| _ -> raise WellFormed
Project out the second ( fun ) component of a pair . If the argument [ t ] has
no discovered structure , create it on the fly by adding constraints .
no discovered structure, create it on the fly by adding constraints. *)
let proj_fun (t : tau) : tau =
match U.deref t with
Pair p -> p.lam
| Var v ->
let p, f = fresh_var false, fresh_var false in
add_toplev_constraint (Unification (t, make_pair(p, f)));
f
| _ -> raise WellFormed
let get_args (t : tau) : tau list =
match U.deref t with
Fun f -> f.args
| _ -> raise WellFormed
let get_finfo (t : tau) : finfo =
match U.deref t with
Fun f -> f
| _ -> raise WellFormed
* Function type [ t ] is applied to the arguments [ actuals ] . the
actuals with the formals of [ t ] . If no functions have been discovered for
[ t ] yet , create a fresh one and unify it with t. The result is the return
value of the function plus the index of this application site .
actuals with the formals of [t]. If no functions have been discovered for
[t] yet, create a fresh one and unify it with t. The result is the return
value of the function plus the index of this application site. *)
let apply (t : tau) (al : tau list) : (tau * int) =
let i = fresh_appsite () in
let f = proj_fun t in
let actuals = ref al in
let fi,ret =
match U.deref f with
Fun fi -> fi, fi.ret
| Var v ->
let new_l, new_ret, new_args =
fresh_label false, fresh_var false,
Util.list_map (function _ -> fresh_var false) !actuals
in
let new_fun = make_fun (new_l, new_args, new_ret) in
add_toplev_constraint (Unification (new_fun, f));
(get_finfo new_fun, new_ret)
| _ -> raise WellFormed
in
pad_args2 (fi, actuals);
List.iter2
(fun actual -> fun formal ->
add_toplev_constraint (Leq (actual,(i, Neg), formal)))
!actuals fi.args;
(ret, i)
* Create a new function type with name [ name ] , list of formal arguments
[ formals ] , and return value [ ret ] . Adds no constraints .
[formals], and return value [ret]. Adds no constraints. *)
let make_function (name : string) (formals : lvalue list) (ret : tau) : tau =
let f = make_fun (make_label false name None,
Util.list_map (fun x -> rvalue x) formals,
ret)
in
make_pair (fresh_var false, f)
let make_lvalue (is_global : bool) (name : string) (vio : Cil.varinfo option) : lvalue =
if !debug && is_global then
Printf.printf "Making global lvalue : %s\n" name
else ();
make_lval (make_label is_global name vio, make_var is_global name)
let make_fresh (name : string) : tau =
make_var false name
let bottom () : tau =
make_var false "bottom"
let return (t : tau) (t' : tau) =
add_toplev_constraint (Leq (t', (0, Sub), t))
let make_summary = leq_label
let path_signature k l l' b : int list =
let ksig =
match k with
Positive -> 1
| Negative -> 2
| _ -> 3
in
[ksig;
get_label_stamp l;
get_label_stamp l';
if b then 1 else 0]
let make_path (k, l, l', b) =
let psig = path_signature k l l' b in
if PH.mem path_hash psig then ()
else
let new_path = {kind = k; head = l; tail = l'; reached_global = b}
and li, li' = find l, find l' in
PH.add path_hash psig new_path;
Q.add new_path path_worklist;
begin
match k with
Positive ->
li.p_upath <- P.add new_path li.p_upath;
li'.p_lpath <- P.add new_path li'.p_lpath
| Negative ->
li.n_upath <- P.add new_path li.n_upath;
li'.n_lpath <- P.add new_path li'.n_lpath
| _ ->
li.m_upath <- P.add new_path li.m_upath;
li'.m_lpath <- P.add new_path li'.m_lpath
end;
if !debug then
begin
print_string "Discovered path : ";
print_path new_path;
print_newline ()
end
let backwards_tabulate (l : label) : unit =
let rec loop () =
let rule1 p =
if !debug then print_endline "rule1";
B.iter
(fun lb ->
make_path (Match, lb.info, p.tail,
p.reached_global || is_global_label p.head))
(find p.head).m_lbounds
and rule2 p =
if !debug then print_endline "rule2";
B.iter
(fun lb ->
make_path (Negative, lb.info, p.tail,
p.reached_global || is_global_label p.head))
(find p.head).n_lbounds
and rule2m p =
if !debug then print_endline "rule2m";
B.iter
(fun lb ->
make_path (Match, lb.info, p.tail,
p.reached_global || is_global_label p.head))
(find p.head).n_lbounds
and rule3 p =
if !debug then print_endline "rule3";
B.iter
(fun lb ->
make_path (Positive, lb.info, p.tail,
p.reached_global || is_global_label p.head))
(find p.head).p_lbounds
and rule4 p =
if !debug then print_endline "rule4";
B.iter
(fun lb ->
make_path(Negative, lb.info, p.tail,
p.reached_global || is_global_label p.head))
(find p.head).m_lbounds
and rule5 p =
if !debug then print_endline "rule5";
B.iter
(fun lb ->
make_path (Positive, lb.info, p.tail,
p.reached_global || is_global_label p.head))
(find p.head).m_lbounds
and rule6 p =
if !debug then print_endline "rule6";
B.iter
(fun lb ->
if is_seeded_label lb.info then ()
else
begin
make_path (Seed, lb.info, lb.info,
is_global_label lb.info)
end)
(find p.head).p_lbounds
and rule7 p =
if !debug then print_endline "rule7";
if not (is_ret_label p.tail && is_param_label p.head) then ()
else
B.iter
(fun lb ->
B.iter
(fun ub ->
if lb.index = ub.index then
begin
if !debug then
Printf.printf "New summary : %s %s\n"
(string_of_label lb.info)
(string_of_label ub.info);
make_summary (lb.info, (0, Sub), ub.info);
rules 1 , 4 , and 5
P.iter
rule 1
make_path (Match, lb.info, ubp.tail,
ubp.reached_global))
(find ub.info).m_upath;
P.iter
rule 4
make_path (Negative, lb.info, ubp.tail,
ubp.reached_global))
(find ub.info).n_upath;
P.iter
rule 5
make_path (Positive, lb.info, ubp.tail,
ubp.reached_global))
(find ub.info).p_upath
end)
(find p.tail).p_ubounds)
(find p.head).n_lbounds
in
let matched_backward_rules p =
rule1 p;
if p.reached_global then rule2m p else rule2 p;
rule3 p;
rule6 p;
rule7 p
and negative_backward_rules p =
rule2 p;
rule3 p;
rule4 p;
rule6 p;
rule7 p
and positive_backward_rules p =
rule3 p;
rule5 p;
rule6 p;
rule7 p
if Q.is_empty path_worklist then ()
else
let p = Q.take path_worklist in
if !debug then
begin
print_string "Processing path: ";
print_path p;
print_newline ()
end;
begin
match p.kind with
Positive ->
if is_global_label p.tail then matched_backward_rules p
else positive_backward_rules p
| Negative -> negative_backward_rules p
| _ -> matched_backward_rules p
end;
loop ()
if !debug then
begin
Printf.printf "Tabulating for %s..." (string_of_label l);
if is_global_label l then print_string "(global)";
print_newline ()
end;
make_path (Seed, l, l, is_global_label l);
loop ()
let li = find l
and collect init s =
P.fold (fun x a -> C.union a (find x.head).aliases) s init
in
backwards_tabulate l;
collect (collect (collect li.aliases li.m_lpath) li.n_lpath) li.p_lpath
let extract_ptlabel (lv : lvalue) : label option =
try
match find (proj_ref lv.contents) with
Var v -> None
| Ref r -> Some r.rl;
| _ -> raise WellFormed
with NoContents -> None
let points_to_aux (t : tau) : constant list =
try
match find (proj_ref t) with
Var v -> []
| Ref r -> C.elements (collect_ptsets r.rl)
| _ -> raise WellFormed
with NoContents -> []
let points_to_names (lv : lvalue) : string list =
Util.list_map (fun (_, str, _) -> str) (points_to_aux lv.contents)
let points_to (lv : lvalue) : Cil.varinfo list =
let rec get_vinfos l : Cil.varinfo list = match l with
| (_, _, h) :: t -> h :: get_vinfos t
| [] -> []
in
get_vinfos (points_to_aux lv.contents)
let epoints_to (t : tau) : Cil.varinfo list =
let rec get_vinfos l : Cil.varinfo list = match l with
| (_, _, h) :: t -> h :: get_vinfos t
| [] -> []
in
get_vinfos (points_to_aux t)
let smart_alias_query (l : label) (l' : label) : bool =
let dead_configs : config_map = CH.create 16 in
let discovered : config_map = CH.create 16 in
let rec filter_match (i : int) =
B.filter (fun (b : lblinfo bound) -> i = b.index)
in
let rec simulate c l l' =
let config = (c, get_label_stamp l, get_label_stamp l') in
if U.equal (l, l') then
begin
if !debug then
Printf.printf
"%s and %s are aliased\n"
(string_of_label l)
(string_of_label l');
raise APFound
end
else if CH.mem discovered config then ()
else
begin
if !debug_aliases then
Printf.printf
"Exploring configuration %s\n"
(string_of_configuration config);
CH.add discovered config ();
B.iter
(fun lb -> simulate c lb.info l')
B.iter
(fun lb -> simulate c l lb.info)
B.iter
(fun lb ->
let matching =
filter_match lb.index (get_bounds Pos false l')
in
B.iter
(fun b -> simulate Closed lb.info b.info)
matching;
simulate Closed lb.info l')
if is_global_label l then
B.iter
(fun lb -> simulate Closed l lb.info)
begin
Open ->
B.iter
(fun lb ->
let matching =
filter_match lb.index (get_bounds Neg false l')
in
B.iter
(fun b -> simulate Open lb.info b.info)
matching ;
simulate Open lb.info l')
(get_bounds Neg false l);
if is_global_label l then
B.iter
(fun lb -> simulate Open l lb.info)
| _ -> ()
end;
CH.add dead_configs config ();
end
in
try
begin
if H.mem cached_aliases (get_label_stamp l, get_label_stamp l') then
true
else
begin
simulate Open l l';
if !debug then
Printf.printf
"%s and %s are NOT aliased\n"
(string_of_label l)
(string_of_label l');
false
end
end
with APFound ->
CH.iter
(fun config -> fun _ ->
if not (CH.mem dead_configs config) then
H.add
cached_aliases
(get_label_stamp l, get_label_stamp l')
())
discovered;
true
let may_alias (t1 : tau) (t2 : tau) : bool =
try
let l1 =
match find (proj_ref t1) with
Ref r -> r.rl
| Var v -> raise NoContents
| _ -> raise WellFormed
and l2 =
match find (proj_ref t2) with
Ref r -> r.rl
| Var v -> raise NoContents
| _ -> raise WellFormed
in
not (C.is_empty (C.inter (collect_ptsets l1) (collect_ptsets l2)))
with NoContents -> false
let alias_query (b : bool) (lvl : lvalue list) : int * int =
let naive_count = ref 0 in
let smart_count = ref 0 in
let ptsets =
Util.list_map
(function
Some l -> collect_ptsets l
| None -> C.empty)
lbls in
let record_alias s lo s' lo' =
match lo, lo' with
Some l, Some l' ->
if !debug_aliases then
Printf.printf
"Checking whether %s and %s are aliased...\n"
(string_of_label l)
(string_of_label l');
if C.is_empty (C.inter s s') then ()
else
begin
incr naive_count;
if !smart_aliases && smart_alias_query l l' then
incr smart_count
end
| _ -> ()
in
let rec check_alias sets labels =
match sets,labels with
s :: st, l :: lt ->
List.iter2 (record_alias s l) ptsets lbls;
check_alias st lt
| [], [] -> ()
| _ -> die "check_alias"
in
check_alias ptsets lbls;
(!naive_count, !smart_count)
let alias_frequency (lvl : (lvalue * bool) list) : int * int =
let extract_lbl (lv, b : lvalue * bool) = (lv.l, b) in
let naive_count = ref 0 in
let smart_count = ref 0 in
let lbls = Util.list_map extract_lbl lvl in
let ptsets =
Util.list_map
(fun (lbl, b) ->
else collect_ptsets lbl)
lbls in
let record_alias s (l, b) s' (l', b') =
if !debug_aliases then
Printf.printf
"Checking whether %s and %s are aliased...\n"
(string_of_label l)
(string_of_label l');
if C.is_empty (C.inter s s') then ()
else
begin
if !debug_aliases then
Printf.printf
"%s and %s are aliased naively...\n"
(string_of_label l)
(string_of_label l');
incr naive_count;
if !smart_aliases then
if b || b' || smart_alias_query l l' then incr smart_count
else
Printf.printf
"%s and %s are not aliased by smart queries...\n"
(string_of_label l)
(string_of_label l');
end
in
let rec check_alias sets labels =
match sets, labels with
s :: st, l :: lt ->
List.iter2 (record_alias s l) ptsets lbls;
check_alias st lt
| [], [] -> ()
| _ -> die "check_alias"
in
check_alias ptsets lbls;
(!naive_count, !smart_count)
type absloc = label
let absloc_of_lvalue (l : lvalue) : absloc = l.l
let absloc_eq (a1, a2) = smart_alias_query a1 a2
let absloc_print_name = ref true
let d_absloc () (p : absloc) =
let a = find p in
if !absloc_print_name then Pretty.dprintf "%s" a.l_name
else Pretty.dprintf "%d" a.l_stamp
let phonyAddrOf (lv : lvalue) : lvalue =
make_lval (fresh_label true, address lv)
let rec tauPointsTo (l : tau) : absloc list =
match find l with
Var _ -> []
| Ref r -> r.rl :: tauPointsTo r.points_to
| _ -> []
let rec absloc_points_to (l : lvalue) : absloc list =
tauPointsTo l.contents
exception UnknownLocation
let finished_constraints () = ()
let apply_undefined (_ : tau list) = (fresh_var true, 0)
let assign_undefined (_ : lvalue) = ()
let absloc_epoints_to = tauPointsTo
|
6530bdd0e08bbcd11264e9cd2b968da6f831df2ad49eccac2a0a82ae2d9cec08 | TyOverby/bonsai-wall | minimal.ml | open Tsdl
open Wall
let load_font name =
let ic = open_in_bin name in
let dim = in_channel_length ic in
let fd = Unix.descr_of_in_channel ic in
let buffer =
Unix.map_file fd Bigarray.int8_unsigned Bigarray.c_layout false [|dim|]
|> Bigarray.array1_of_genarray
in
let offset = List.hd (Stb_truetype.enum buffer) in
match Stb_truetype.init buffer offset with
| None -> assert false
| Some font -> font
let font_sans = lazy (load_font "Roboto-Regular.ttf")
let normalize (dx, dy) =
let d = sqrt (dx *. dx +. dy *. dy) in
if d > 1.0 then
(dx /. d, dy /. d)
else
(dx, dy)
let w = 1000
let h = 600
let f = try float_of_string Sys.argv.(1) with _ -> 1.0
let fw = int_of_float (f *. float w)
let fh = int_of_float (f *. float h)
let b2 x y w h = Gg.Box2.v (Gg.P2.v x y) (Gg.Size2.v w h)
let draw_arrow ~x ~y ~size color =
Image.paint (Paint.color color)
(Image.fill_path @@ fun t ->
Path.move_to t x y;
Path.line_to t (x-.size) (y+.size);
Path.line_to t (x-.size) (y-.size);
Path.close t;
)
let draw_arrow' ~x ~y ~size color =
Image.paint (Paint.color color)
(Image.fill_path @@ fun t ->
Path.move_to t x y;
Path.line_to t (x-.size) (y-.size);
Path.line_to t (x-.size/.2.0) y;
Path.line_to t (x-.size) (y+.size);
Path.close t;
)
let text_arrow ?(size=16.0) ~x ~y () =
Image.alpha 0.5 (draw_arrow ~x ~y ~size Color.blue)
let text_arrow' ?(size=16.0) ~x ~y () =
Image.alpha 0.5 (draw_arrow' ~x ~y ~size Color.blue)
let render context sw sh t =
let lw = float w in
let lh = float h in
let pw = lw *. f *. sw in
let ph = lh *. f *. sh in
Renderer.render context ~width:pw ~height:ph
(Image.paint Paint.black @@
Image.seq [
(*text_arrow ~x:400.0 ~y:300.0 ~size:200.0 ();*)
text_arrow' ~x:300.0 ~y:300.0 ~size:200.0 ();
Image.transform ( Transform.translate 10.0 10.0 ( Transform.scale 5.0 5.0 ) ) (
Image.seq [
( * text_arrow ~x:50.0 ~y:50.0 ( ) ;
text_arrow ' ~x:50.0 ~y:60.0 ( ) ;
Image.seq [
(*text_arrow ~x:50.0 ~y:50.0 ();
text_arrow' ~x:50.0 ~y:60.0 ();*)
Image.stroke_path (Outline.make ~join:`MITER ~cap:`BUTT (*~cap:`ROUND*) ~width:(15.0) ()) @@ fun p ->
Path.move_to p 300.0 (18.0 +. 100.0 *. sin t);
Path.line_to p 0.0 0.0;
Path.line_to p 300.0 0.0;
Path.line_to p 300.0 (18.0 +. 100.0 *. sin t);
Path.close p;
]
)*)
])
open Tgles2
let ignore_r here = function
| Ok () -> ()
| Error (`Msg s) -> Sdl.log "%s %s" (Base.Source_code_position.to_string here) s
let main () =
Printexc.record_backtrace true;
match Sdl.init Sdl.Init.video with
| Error (`Msg e) -> Sdl.log "Init error: %s" e; exit 1
| Ok () ->
ignore (Sdl.gl_set_attribute Sdl.Gl.depth_size 24 : _ result);
ignore (Sdl.gl_set_attribute Sdl.Gl.stencil_size 8 : _ result);
match
Sdl.create_window ~w:fw ~h:fh "SDL OpenGL"
Sdl.Window.(opengl + allow_highdpi)
with
| Error (`Msg e) -> Sdl.log "Create window error: %s" e; exit 1
| Ok w ->
Sdl.gl_set_attribute Sdl . Gl.context_profile_mask . ;
Sdl.gl_set_attribute Sdl . Gl.context_major_version 2 ;
Sdl.gl_set_attribute . Gl.context_minor_version 1 ;
Sdl.gl_set_attribute Sdl.Gl.context_major_version 2;
Sdl.gl_set_attribute Sdl.Gl.context_minor_version 1;*)
ignore (Sdl.gl_set_swap_interval (-1));
let ow, oh = Sdl.gl_get_drawable_size w in
Sdl.log "window size: %d,%d\topengl drawable size: %d,%d" fw fh ow oh;
let sw = float ow /. float fw and sh = float oh /. float fh in
ignore (Sdl.gl_set_attribute Sdl.Gl.stencil_size 1);
match Sdl.gl_create_context w with
| Error (`Msg e) -> Sdl.log "Create context error: %s" e; exit 1
| Ok ctx ->
let context = Renderer.create ~antialias:true () in
let quit = ref false in
let event = Sdl.Event.create () in
while not !quit do
while Sdl.poll_event (Some event) do
match Sdl.Event.enum (Sdl.Event.get event Sdl.Event.typ) with
| `Quit -> quit := true
| _ -> ()
done;
Gl.viewport 0 0 ow oh;
Gl.clear_color 0.3 0.3 0.32 1.0;
Gl.(clear (color_buffer_bit lor depth_buffer_bit lor stencil_buffer_bit));
Gl.enable Gl.blend;
Gl.blend_func_separate Gl.one Gl.src_alpha Gl.one Gl.one_minus_src_alpha;
Gl.enable Gl.cull_face_enum;
Gl.disable Gl.depth_test;
render context sw sh (Int32.to_float (Sdl.get_ticks ()) /. 1000.0);
Sdl.gl_swap_window w;
done;
Sdl.gl_delete_context ctx;
Sdl.destroy_window w;
Sdl.quit ();
exit 0
let () = main ()
| null | https://raw.githubusercontent.com/TyOverby/bonsai-wall/1c633c40eb836b7b1d639fcfca4f3ccf3b1902ad/example/minimal.ml | ocaml | text_arrow ~x:400.0 ~y:300.0 ~size:200.0 ();
text_arrow ~x:50.0 ~y:50.0 ();
text_arrow' ~x:50.0 ~y:60.0 ();
~cap:`ROUND | open Tsdl
open Wall
let load_font name =
let ic = open_in_bin name in
let dim = in_channel_length ic in
let fd = Unix.descr_of_in_channel ic in
let buffer =
Unix.map_file fd Bigarray.int8_unsigned Bigarray.c_layout false [|dim|]
|> Bigarray.array1_of_genarray
in
let offset = List.hd (Stb_truetype.enum buffer) in
match Stb_truetype.init buffer offset with
| None -> assert false
| Some font -> font
let font_sans = lazy (load_font "Roboto-Regular.ttf")
let normalize (dx, dy) =
let d = sqrt (dx *. dx +. dy *. dy) in
if d > 1.0 then
(dx /. d, dy /. d)
else
(dx, dy)
let w = 1000
let h = 600
let f = try float_of_string Sys.argv.(1) with _ -> 1.0
let fw = int_of_float (f *. float w)
let fh = int_of_float (f *. float h)
let b2 x y w h = Gg.Box2.v (Gg.P2.v x y) (Gg.Size2.v w h)
let draw_arrow ~x ~y ~size color =
Image.paint (Paint.color color)
(Image.fill_path @@ fun t ->
Path.move_to t x y;
Path.line_to t (x-.size) (y+.size);
Path.line_to t (x-.size) (y-.size);
Path.close t;
)
let draw_arrow' ~x ~y ~size color =
Image.paint (Paint.color color)
(Image.fill_path @@ fun t ->
Path.move_to t x y;
Path.line_to t (x-.size) (y-.size);
Path.line_to t (x-.size/.2.0) y;
Path.line_to t (x-.size) (y+.size);
Path.close t;
)
let text_arrow ?(size=16.0) ~x ~y () =
Image.alpha 0.5 (draw_arrow ~x ~y ~size Color.blue)
let text_arrow' ?(size=16.0) ~x ~y () =
Image.alpha 0.5 (draw_arrow' ~x ~y ~size Color.blue)
let render context sw sh t =
let lw = float w in
let lh = float h in
let pw = lw *. f *. sw in
let ph = lh *. f *. sh in
Renderer.render context ~width:pw ~height:ph
(Image.paint Paint.black @@
Image.seq [
text_arrow' ~x:300.0 ~y:300.0 ~size:200.0 ();
Image.transform ( Transform.translate 10.0 10.0 ( Transform.scale 5.0 5.0 ) ) (
Image.seq [
( * text_arrow ~x:50.0 ~y:50.0 ( ) ;
text_arrow ' ~x:50.0 ~y:60.0 ( ) ;
Image.seq [
Path.move_to p 300.0 (18.0 +. 100.0 *. sin t);
Path.line_to p 0.0 0.0;
Path.line_to p 300.0 0.0;
Path.line_to p 300.0 (18.0 +. 100.0 *. sin t);
Path.close p;
]
)*)
])
open Tgles2
let ignore_r here = function
| Ok () -> ()
| Error (`Msg s) -> Sdl.log "%s %s" (Base.Source_code_position.to_string here) s
let main () =
Printexc.record_backtrace true;
match Sdl.init Sdl.Init.video with
| Error (`Msg e) -> Sdl.log "Init error: %s" e; exit 1
| Ok () ->
ignore (Sdl.gl_set_attribute Sdl.Gl.depth_size 24 : _ result);
ignore (Sdl.gl_set_attribute Sdl.Gl.stencil_size 8 : _ result);
match
Sdl.create_window ~w:fw ~h:fh "SDL OpenGL"
Sdl.Window.(opengl + allow_highdpi)
with
| Error (`Msg e) -> Sdl.log "Create window error: %s" e; exit 1
| Ok w ->
Sdl.gl_set_attribute Sdl . Gl.context_profile_mask . ;
Sdl.gl_set_attribute Sdl . Gl.context_major_version 2 ;
Sdl.gl_set_attribute . Gl.context_minor_version 1 ;
Sdl.gl_set_attribute Sdl.Gl.context_major_version 2;
Sdl.gl_set_attribute Sdl.Gl.context_minor_version 1;*)
ignore (Sdl.gl_set_swap_interval (-1));
let ow, oh = Sdl.gl_get_drawable_size w in
Sdl.log "window size: %d,%d\topengl drawable size: %d,%d" fw fh ow oh;
let sw = float ow /. float fw and sh = float oh /. float fh in
ignore (Sdl.gl_set_attribute Sdl.Gl.stencil_size 1);
match Sdl.gl_create_context w with
| Error (`Msg e) -> Sdl.log "Create context error: %s" e; exit 1
| Ok ctx ->
let context = Renderer.create ~antialias:true () in
let quit = ref false in
let event = Sdl.Event.create () in
while not !quit do
while Sdl.poll_event (Some event) do
match Sdl.Event.enum (Sdl.Event.get event Sdl.Event.typ) with
| `Quit -> quit := true
| _ -> ()
done;
Gl.viewport 0 0 ow oh;
Gl.clear_color 0.3 0.3 0.32 1.0;
Gl.(clear (color_buffer_bit lor depth_buffer_bit lor stencil_buffer_bit));
Gl.enable Gl.blend;
Gl.blend_func_separate Gl.one Gl.src_alpha Gl.one Gl.one_minus_src_alpha;
Gl.enable Gl.cull_face_enum;
Gl.disable Gl.depth_test;
render context sw sh (Int32.to_float (Sdl.get_ticks ()) /. 1000.0);
Sdl.gl_swap_window w;
done;
Sdl.gl_delete_context ctx;
Sdl.destroy_window w;
Sdl.quit ();
exit 0
let () = main ()
|
cc3773ed0c04ebaf4e2f9540fa59b18c0dc53fcf0ea8276e95f7694b7f9f00d0 | lwhjp/racket-asm | mode.rkt | #lang racket/base
(require racket/contract)
(provide (all-defined-out))
(define default-assembler-bits
(let ([word-size (system-type 'word)])
(if (memv word-size '(16 32 64))
word-size
64)))
(define/contract current-assembler-bits
(parameter/c (or/c 16 32 64))
(make-parameter default-assembler-bits))
| null | https://raw.githubusercontent.com/lwhjp/racket-asm/57abd235fcb8c7505990f8e9731c01c716324ee5/x86/private/mode.rkt | racket | #lang racket/base
(require racket/contract)
(provide (all-defined-out))
(define default-assembler-bits
(let ([word-size (system-type 'word)])
(if (memv word-size '(16 32 64))
word-size
64)))
(define/contract current-assembler-bits
(parameter/c (or/c 16 32 64))
(make-parameter default-assembler-bits))
| |
bdbd0c65f0a146819932d808b5686287cc5ddb844b4dde394482aa0abb4056ec | eskimor/servant-purescript | WebAPI.hs | # LANGUAGE AutoDeriveTypeable #
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveGeneric #-}
# LANGUAGE FlexibleInstances #
# LANGUAGE MultiParamTypeClasses #
# LANGUAGE OverloadedStrings #
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TypeOperators #-}
module Counter.WebAPI where
import Control.Applicative
import Control.Lens
import Data.Aeson
import Data.Proxy
import qualified Data.Set as Set
import Data.Text (Text)
import qualified Data.Text.Encoding as T
import qualified Data.Text.IO as T
import Data.Typeable
import GHC.Generics (Generic)
import Language.PureScript.Bridge
import Language.PureScript.Bridge.PSTypes
import Network.HTTP.Types.URI (urlDecode)
import Servant.API
import Servant.PureScript (jsonParseUrlPiece, jsonParseHeader)
import Servant.Subscriber.Subscribable
import Web.HttpApiData
data Hello = Hello {
_message :: Text
} deriving Generic
instance FromJSON Hello
instance ToJSON Hello
data AuthToken = VerySecret Text deriving (Generic, Show, Eq, Ord, Read)
instance FromJSON AuthToken
instance FromHttpApiData AuthToken where
parseUrlPiece = jsonParseUrlPiece
parseHeader = jsonParseHeader
data CounterAction = CounterAdd Int | CounterSet Int deriving (Generic, Show, Eq, Ord)
instance FromJSON CounterAction
type FullAPI = AppAPI :<|> Raw
type AppAPI = Header "AuthToken" AuthToken :> "counter" :> CounterAPI
type CounterAPI = Subscribable :> Get '[JSON] Int
:<|> ReqBody '[JSON] CounterAction :> Put '[JSON] Int
fullAPI :: Proxy FullAPI
fullAPI = Proxy
appAPI :: Proxy AppAPI
appAPI = Proxy
| null | https://raw.githubusercontent.com/eskimor/servant-purescript/6454d5bcb9aa2a5d6e3a3dc935423b67b6f3993c/examples/central-counter/src/Counter/WebAPI.hs | haskell | # LANGUAGE DataKinds #
# LANGUAGE DeriveGeneric #
# LANGUAGE ScopedTypeVariables #
# LANGUAGE TypeOperators # | # LANGUAGE AutoDeriveTypeable #
# LANGUAGE FlexibleInstances #
# LANGUAGE MultiParamTypeClasses #
# LANGUAGE OverloadedStrings #
module Counter.WebAPI where
import Control.Applicative
import Control.Lens
import Data.Aeson
import Data.Proxy
import qualified Data.Set as Set
import Data.Text (Text)
import qualified Data.Text.Encoding as T
import qualified Data.Text.IO as T
import Data.Typeable
import GHC.Generics (Generic)
import Language.PureScript.Bridge
import Language.PureScript.Bridge.PSTypes
import Network.HTTP.Types.URI (urlDecode)
import Servant.API
import Servant.PureScript (jsonParseUrlPiece, jsonParseHeader)
import Servant.Subscriber.Subscribable
import Web.HttpApiData
data Hello = Hello {
_message :: Text
} deriving Generic
instance FromJSON Hello
instance ToJSON Hello
data AuthToken = VerySecret Text deriving (Generic, Show, Eq, Ord, Read)
instance FromJSON AuthToken
instance FromHttpApiData AuthToken where
parseUrlPiece = jsonParseUrlPiece
parseHeader = jsonParseHeader
data CounterAction = CounterAdd Int | CounterSet Int deriving (Generic, Show, Eq, Ord)
instance FromJSON CounterAction
type FullAPI = AppAPI :<|> Raw
type AppAPI = Header "AuthToken" AuthToken :> "counter" :> CounterAPI
type CounterAPI = Subscribable :> Get '[JSON] Int
:<|> ReqBody '[JSON] CounterAction :> Put '[JSON] Int
fullAPI :: Proxy FullAPI
fullAPI = Proxy
appAPI :: Proxy AppAPI
appAPI = Proxy
|
66bb47d3862940c438cb144c97feab2dc6e4c451ba9b683d3e0f3052e98051ec | agda/agda | Fail.hs | | A pure MonadFail .
module Agda.Utils.Fail where
Control . Monad . Fail import is redundant since GHC 8.8.1
import Control.Monad.Fail
newtype Fail a = Fail { runFail :: Either String a }
deriving (Functor, Applicative, Monad)
instance MonadFail Fail where
fail = Fail . Left
runFail_ :: Fail a -> a
runFail_ = either error id . runFail
| null | https://raw.githubusercontent.com/agda/agda/f50c14d3a4e92ed695783e26dbe11ad1ad7b73f7/src/full/Agda/Utils/Fail.hs | haskell | | A pure MonadFail .
module Agda.Utils.Fail where
Control . Monad . Fail import is redundant since GHC 8.8.1
import Control.Monad.Fail
newtype Fail a = Fail { runFail :: Either String a }
deriving (Functor, Applicative, Monad)
instance MonadFail Fail where
fail = Fail . Left
runFail_ :: Fail a -> a
runFail_ = either error id . runFail
| |
f88725ba029cf9536cff321e0a2575a448e555ce6146ffdaf336907a9d1482be | cbaggers/varjo | and-or.lisp | (in-package :vari.cl)
(in-readtable fn:fn-reader)
;;------------------------------------------------------------
;; And
(v-defspecial and (&rest forms)
:args-valid t
:return
(let* ((objs (mapcar (lambda (x) (compile-form x env)) forms))
(flow-id (flow-id!))
(type-set (make-type-set (type-spec->type :bool flow-id))))
(unless (loop for o in objs always (v-primary-type-eq o (first objs)))
(error "all forms of an 'AND' form must resolve to the same type"))
(if (v-typep (primary-type (first objs)) :bool)
(values (merge-compiled objs
:type-set type-set
:current-line (gen-bool-and-string objs))
env) ;; pretty sure this env is wrong, what if side effects in
;; forms?
(values (last1 objs) env))))
;;------------------------------------------------------------
;; Or
;; pretty sure env is wrong in 'or and 'and, what if there are side effects in
;; forms?
;; In fact function calls in general should at least propagate the flow ids
;; down the arg compiles..could even the env be passed? may just work
(v-defspecial or (&rest forms)
:args-valid t
:return
(let* ((objs (mapcar (lambda (x) (compile-form x env)) forms))
(flow-id (flow-id!))
(type-set (make-type-set (type-spec->type :bool flow-id))))
(unless (loop for o in objs always (v-primary-type-eq o (first objs)))
(error "all forms of an 'OR' form must resolve to the same type"))
(if (v-typep (primary-type (first objs)) :bool)
(values (merge-compiled
objs
:type-set type-set
:current-line (gen-bool-or-string objs))
env)
(values (first objs) env))))
;;------------------------------------------------------------
| null | https://raw.githubusercontent.com/cbaggers/varjo/9e77f30220053155d2ef8870ceba157f75e538d4/src/vari.cl/special-operators/and-or.lisp | lisp | ------------------------------------------------------------
And
pretty sure this env is wrong, what if side effects in
forms?
------------------------------------------------------------
Or
pretty sure env is wrong in 'or and 'and, what if there are side effects in
forms?
In fact function calls in general should at least propagate the flow ids
down the arg compiles..could even the env be passed? may just work
------------------------------------------------------------ | (in-package :vari.cl)
(in-readtable fn:fn-reader)
(v-defspecial and (&rest forms)
:args-valid t
:return
(let* ((objs (mapcar (lambda (x) (compile-form x env)) forms))
(flow-id (flow-id!))
(type-set (make-type-set (type-spec->type :bool flow-id))))
(unless (loop for o in objs always (v-primary-type-eq o (first objs)))
(error "all forms of an 'AND' form must resolve to the same type"))
(if (v-typep (primary-type (first objs)) :bool)
(values (merge-compiled objs
:type-set type-set
:current-line (gen-bool-and-string objs))
(values (last1 objs) env))))
(v-defspecial or (&rest forms)
:args-valid t
:return
(let* ((objs (mapcar (lambda (x) (compile-form x env)) forms))
(flow-id (flow-id!))
(type-set (make-type-set (type-spec->type :bool flow-id))))
(unless (loop for o in objs always (v-primary-type-eq o (first objs)))
(error "all forms of an 'OR' form must resolve to the same type"))
(if (v-typep (primary-type (first objs)) :bool)
(values (merge-compiled
objs
:type-set type-set
:current-line (gen-bool-or-string objs))
env)
(values (first objs) env))))
|
be25fe27050f7698f5c2abfc5f3961d02621a8772596c130212b58876aaba348 | robert-strandh/CLIMatis | clx-framebuffer.lisp | (in-package #:clim3-clx-framebuffer)
(defparameter *hpos* nil)
(defparameter *vpos* nil)
(defparameter *hstart* nil)
(defparameter *vstart* nil)
(defparameter *hend* nil)
(defparameter *vend* nil)
(defparameter *pixel-array* nil)
(defclass clx-framebuffer-port (clim3:port)
((%display :accessor display)
(%screen :accessor screen)
(%root :accessor root)
(%white :accessor white)
(%black :accessor black)
(%shift-state :initform nil :accessor shift-state)
(%zone-entries :initform '() :accessor zone-entries)
;; A vector of interpretations. Each interpretation is a
;; short vector of keysyms
(%keyboard-mapping :initform nil :accessor keyboard-mapping)
(%meter :initform (benchmark:make-timer) :reader meter)))
(defmethod clim3-ext:call-with-zone ((port clx-framebuffer-port) thunk zone)
(let ((zone-hpos (clim3:hpos zone))
(zone-vpos (clim3:vpos zone))
(zone-width (clim3:width zone))
(zone-height (clim3:height zone)))
(let ((new-hpos (+ *hpos* zone-hpos))
(new-vpos (+ *vpos* zone-vpos)))
(let ((new-hstart (max *hstart* new-hpos))
(new-vstart (max *vstart* new-vpos))
(new-hend (min *hend* (+ new-hpos zone-width)))
(new-vend (min *vend* (+ new-vpos zone-height))))
(when (and (< new-hstart new-hend)
(< new-vstart new-vend))
(let ((*vpos* new-vpos)
(*hpos* new-hpos)
(*hstart* new-hstart)
(*vstart* new-vstart)
(*hend* new-hend)
(*vend* new-vend))
(funcall thunk)))))))
(defmethod clim3-ext:call-with-area
((port clx-framebuffer-port) function hpos vpos width height)
(let ((new-hpos (+ *hpos* hpos))
(new-vpos (+ *vpos* vpos)))
(let ((new-hstart (max *hstart* new-hpos))
(new-vstart (max *vstart* new-vpos))
(new-hend (min *hend* (+ new-hpos width)))
(new-vend (min *vend* (+ new-vpos height))))
(when (and (< new-hstart new-hend)
(< new-vstart new-vend))
(let ((*vpos* new-vpos)
(*hpos* new-hpos)
(*hstart* new-hstart)
(*vstart* new-vstart)
(*hend* new-hend)
(*vend* new-vend))
(funcall function))))))
;;; Do not change the clipping region, just the
;;; origin of the coordinate system.
(defmethod clim3-ext:call-with-position
((port clx-framebuffer-port) function hpos vpos)
(let ((*hpos* (+ *hpos* hpos))
(*vpos* (+ *vpos* vpos)))
(funcall function)))
(defmethod clim3:make-port ((display-server (eql :clx-framebuffer)))
(let ((port (make-instance 'clx-framebuffer-port)))
(setf (display port) (xlib:open-default-display))
(setf (xlib:display-after-function (display port))
#'xlib:display-finish-output)
(setf (screen port) (car (xlib:display-roots (display port))))
(setf (white port) (xlib:screen-white-pixel (screen port)))
(setf (black port) (xlib:screen-black-pixel (screen port)))
(setf (root port) (xlib:screen-root (screen port)))
(setf (keyboard-mapping port)
(let* ((temp (xlib:keyboard-mapping (display port)))
(result (make-array (array-dimension temp 0))))
(loop for row from 0 below (array-dimension temp 0)
do (let ((interpretations (make-array (array-dimension temp 1))))
(loop for col from 0 below (array-dimension temp 1)
do (setf (aref interpretations col)
(aref temp row col)))
(setf (aref result row) interpretations)))
result))
port))
(defclass zone-entry ()
((%port :initarg :port :reader port)
(%zone :initarg :zone :accessor zone)
(%gcontext :accessor gcontext)
(%window :accessor window)
(%pixel-array :accessor pixel-array)
(%image :accessor image)
(%motion-zones :initform '() :accessor motion-zones)
(%zone-containing-pointer :initform nil :accessor zone-containing-pointer)
(%prev-pointer-hpos :initform 0 :accessor prev-pointer-hpos)
(%prev-pointer-vpos :initform 0 :accessor prev-pointer-vpos)))
(defmethod clim3-ext:notify-child-hsprawl-changed
(zone (port clx-framebuffer-port))
nil)
(defmethod clim3-ext:notify-child-vsprawl-changed
(zone (port clx-framebuffer-port))
nil)
;;; Later, we might try to do something more fancy here, such as
;;; attempting to move the window on the screen.
(defmethod clim3-ext:notify-child-position-changed
(zone (port clx-framebuffer-port))
nil)
(defmethod clim3-ext:notify-child-depth-changed
(zone (port clx-framebuffer-port))
nil)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Handle pointer position
(defmethod (setf clim3-ext:client) :after
((new-client clx-framebuffer-port) (zone clim3:motion))
;; Find the root zone of the zone.
(let ((root zone))
(loop while (clim3:zone-p (clim3-ext:parent root))
do (setf root (clim3-ext:parent root)))
;; Find the zone entry with that root zone.
(let ((zone-entry (find root
(zone-entries new-client)
:key #'zone
:test #'eq)))
(assert (not (null zone-entry)))
;; Add the motion zone to the list of motion zones.
(push zone (motion-zones zone-entry)))))
(defun handle-motion-zones (zone-entry)
(multiple-value-bind (hpos vpos same-screen-p)
(xlib:pointer-position (window zone-entry))
;; FIXME: Figure out what to do with same-screen-p
(declare (ignore same-screen-p))
;; Only alert if the pointer is at a different position.
;; This optimization is valuable if many consecutive events
;; are non-pointer events such as key-press and key-release.
(unless (and (= hpos (prev-pointer-hpos zone-entry))
(= vpos (prev-pointer-vpos zone-entry)))
(setf (prev-pointer-hpos zone-entry) hpos)
(setf (prev-pointer-vpos zone-entry) vpos)
;; If any of the zones on the list has a client other than
;; the port of this zone-entry, then remove it.
(setf (motion-zones zone-entry)
(remove (port zone-entry)
(motion-zones zone-entry)
:key #'clim3-ext:client
:test-not #'eq))
;; For the remaining ones, call the handler.
(loop for zone in (motion-zones zone-entry)
do (let ((absolute-hpos 0)
(absolute-vpos 0)
(parent zone))
;; Find the absolute position of the zone.
(loop while (clim3:zone-p parent)
do (incf absolute-hpos (clim3:hpos parent))
(incf absolute-vpos (clim3:vpos parent))
(setf parent (clim3-ext:parent parent)))
(funcall (clim3:handler zone)
zone
(- hpos absolute-hpos)
(- vpos absolute-vpos)))))))
(defun handle-visit (zone-entry)
(let ((prev (zone-containing-pointer zone-entry)))
(multiple-value-bind (hpos vpos same-screen-p)
(xlib:pointer-position (window zone-entry))
;; FIXME: Figure out what to do with same-screen-p
(declare (ignore same-screen-p))
(let ((zone
(block found
(labels ((traverse (zone hpos vpos)
(unless (or (< hpos 0)
(< vpos 0)
(> hpos (clim3:width zone))
(> vpos (clim3:height zone)))
(if (and (typep zone 'clim3:visit)
(funcall (clim3:inside-p zone)
hpos vpos))
(return-from found zone)
(progn
(clim3-ext:map-over-children-top-to-bottom
(lambda (child)
(traverse child
(- hpos (clim3:hpos child))
(- vpos (clim3:vpos child))))
zone)
nil)))))
(traverse (zone zone-entry) hpos vpos)))))
(unless (eq zone prev)
(unless (null prev)
(clim3:leave prev))
(unless (null zone)
(clim3:enter zone))
(setf (zone-containing-pointer zone-entry) zone))))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Experiment: build a skeleton zone hierarchy.
(defclass skeleton ()
((%zone :initarg :zone :reader zone)
(%hpos :initarg :hpos :reader hpos)
(%vpos :initarg :vpos :reader vpos)
(%width :initarg :width :reader width)
(%height :initarg :height :reader height)
(%children :initform '() :initarg :children :accessor children)))
(defmethod print-object ((object skeleton) stream)
(print-unreadable-object (object stream :type t :identity t)
(format stream
"zone: ~s hpos: ~s :vpos ~s :width ~s :height ~s"
(zone object)
(hpos object)
(vpos object)
(width object)
(height object))))
;;; The purpose of this function is to build a skeletal version of the
;;; visible zone hierarchy, so that this hierarchy can be compared to
;;; what was there last time around the event loop.
;;;
The parameters HMIN , VMIN , HMAX , and VMAX are in the coordinate
system of ZONE , and they are inside ZONE . In other words , HMIN
and VMIN are non - negative , HMAX is less than or equal to the width
of ZONE , and VMAX is less than or equal to the height of ZONE .
(defun build-visible-hierarchy (zone hmin vmin hmax vmax)
(let ((children '()))
(clim3-ext:map-over-children-top-to-bottom
(lambda (child)
(let ((chpos (clim3:hpos child))
(cvpos (clim3:vpos child))
(cwidth (clim3:width child))
(cheight (clim3:height child)))
(when (and (< chpos hmax)
(< cvpos vmax)
(> (+ chpos cwidth) hmin)
(> (+ cvpos cheight) vmin))
;; The child is at least partially inside the area.
(let ((new-hmin (max 0 (- hmin chpos)))
(new-vmin (max 0 (- vmin cvpos)))
(new-hmax (min cwidth (- hmax chpos)))
(new-vmax (min cheight (- vmax cvpos))))
(push (build-visible-hierarchy
child new-hmin new-vmin new-hmax new-vmax)
children)))))
zone)
(make-instance 'skeleton
:zone zone
:hpos (clim3:hpos zone)
:vpos (clim3:vpos zone)
:width (clim3:width zone)
:height (clim3:height zone)
:children (nreverse children))))
(defparameter *hierarchy* nil)
(defun build-top-level-hierarchy (zone)
(setf *hierarchy*
(let ((width (clim3:width zone))
(height (clim3:height zone)))
(build-visible-hierarchy zone 0 0 width height))))
;;; The purpose of this function is to scan the visible zone hierarchy
;;; and compare it to what was painted last time around the event
;;; loop. This information is then used to determine whether we need
;;; to paint anything at all.
;;;
(defun visible-hierarchy-unchanged-p (hierarchy zone hmin vmin hmax vmax)
(and (eq (zone hierarchy) zone)
(= (hpos hierarchy) (clim3:hpos zone))
(= (vpos hierarchy) (clim3:vpos zone))
(= (width hierarchy) (clim3:width zone))
(= (height hierarchy) (clim3:height zone))
(let ((children (children hierarchy)))
(clim3-ext:map-over-children-top-to-bottom
(lambda (child)
(if (or (null children)
(not (eq (zone (car children)) child))
(let ((chpos (clim3:hpos child))
(cvpos (clim3:vpos child))
(cwidth (clim3:width child))
(cheight (clim3:height child)))
(when (and (< chpos hmax)
(< cvpos vmax)
(> (+ chpos cwidth) hmin)
(> (+ cvpos cheight) vmin))
;; The child is at least partially inside the
;; area.
(let ((new-hmin (max 0 (- hmin chpos)))
(new-vmin (max 0 (- vmin cvpos)))
(new-hmax (min cwidth (- hmax chpos)))
(new-vmax (min cheight (- vmax cvpos))))
(not (visible-hierarchy-unchanged-p
(car children) child
new-hmin new-vmin new-hmax new-vmax))))))
(return-from visible-hierarchy-unchanged-p nil)
(pop children)))
zone)
;; If there are any children left in the hierarchy, then
;; something has changed.
(null children))))
(defun top-level-hierarchy-unchanged-p (zone)
(and (not (null *hierarchy*))
(let ((width (clim3:width zone))
(height (clim3:height zone)))
(visible-hierarchy-unchanged-p
*hierarchy* zone 0 0 width height))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Update zones.
(defun layout-visible-zones (zone width height)
(labels ((aux (zone)
(when (typep zone 'clim3-ext:compound-mixin)
(clim3-ext:impose-child-layouts zone)
(clim3-ext:map-over-children
(lambda (child)
(clim3:with-zone child
(aux child)))
zone))))
(let ((*hpos* 0)
(*vpos* 0)
(*hstart* 0)
(*vstart* 0)
(*hend* width)
(*vend* height))
(aux zone))))
(defun paint-visible-area (zone width height pixel-array)
(let ((*hpos* 0)
(*vpos* 0)
(*hstart* 0)
(*vstart* 0)
(*hend* width)
(*vend* height)
(*pixel-array* pixel-array))
(clim3-ext:paint zone)))
(defun draw-default-background (pixel-array)
(let* ((size (array-total-size pixel-array))
(v (make-array size
:element-type '(unsigned-byte 32)
:displaced-to pixel-array)))
(fill v #xffffffff)))
(defun update (zone-entry)
(with-accessors ((zone zone)
(gcontext gcontext)
(window window)
(pixel-array pixel-array)
(image image))
zone-entry
(let ((width (xlib:drawable-width window))
(height (xlib:drawable-height window)))
(clim3-ext:impose-size zone width height)
;; Make sure the pixmap and the image object have the same
;; dimensions as the window.
(when (or (/= width (array-dimension pixel-array 1))
(/= height (array-dimension pixel-array 0)))
(setf *hierarchy* nil)
(setf pixel-array
(make-array (list height width)
:element-type '(unsigned-byte 32)))
(setf image
(xlib:create-image :bits-per-pixel 32
:data pixel-array
:depth 24
:width width :height height
:format :z-pixmap)))
(layout-visible-zones zone width height)
(unless (top-level-hierarchy-unchanged-p zone)
(build-top-level-hierarchy zone)
(draw-default-background pixel-array)
(paint-visible-area zone width height pixel-array))
;; Transfer the image.
(xlib::put-image window
gcontext
image
:x 0 :y 0
:width width :height height))))
(defmethod clim3-ext:repaint ((port clx-framebuffer-port))
(loop for zone-entry in (zone-entries port)
do (update zone-entry)))
(defmethod clim3:connect ((zone clim3:zone)
(port clx-framebuffer-port))
(let ((zone-entry (make-instance 'zone-entry :port port :zone zone))
(clim3:*port* port))
Register this zone entry . We need to do this right away , because
;; it has to exist when we set the parent of the zone.
(push zone-entry (zone-entries port))
(setf (clim3-ext:parent zone) port)
(clim3-ext:ensure-hsprawl-valid zone)
(clim3-ext:ensure-vsprawl-valid zone)
;; Ask for a window that has the natural size of the zone. We may
;; not get it, though.
;;
;; FIXME: take into account the position of the zone
(setf (window zone-entry)
(multiple-value-bind (width height) (clim3:natural-size zone)
(xlib:create-window :parent (root port)
:x 0 :y 0 :width width :height height
:class :input-output
:visual :copy
:background (white port)
:bit-gravity :north-west
:event-mask
'(:key-press :key-release
:button-motion :button-press :button-release
:enter-window :leave-window
:exposure
:structure-notify
:pointer-motion))))
(xlib:map-window (window zone-entry))
;; Create an adequate gcontext for this window.
(setf (gcontext zone-entry)
(xlib:create-gcontext :drawable (window zone-entry)
:background (white port)
:foreground (black port)))
;; Make the array of the pixels. The dimensions don't matter,
;; because we reallocate it if necessary every time we need to
;; draw, so as to reflect the current size of the window.
(setf (pixel-array zone-entry)
(make-array '(0 0)
:element-type '(unsigned-byte 32)))
;; Make the image object. Again, the size is of no importance,
;; but we must remember to change it later.
(setf (image zone-entry)
(xlib:create-image :bits-per-pixel 32
:data (pixel-array zone-entry)
:depth 24
:width 0 :height 0
:format :z-pixmap))
(setf *hierarchy* nil)
;; Make sure the window has the right contents.
(update zone-entry)))
(defmethod clim3:disconnect (zone (port clx-framebuffer-port))
(let ((zone-entry (find zone (zone-entries port) :key #'zone)))
(xlib:free-gcontext (gcontext zone-entry))
(xlib:destroy-window (window zone-entry))
(setf (zone-entries port) (remove zone-entry (zone-entries port)))
(when (null (zone-entries port))
(xlib:close-display (display port)))
(setf (clim3-ext:parent zone) nil)))
(defmethod clim3:text-style-ascent ((port clx-framebuffer-port)
text-style)
(clim3-fonts:ascent (clim3-fonts:text-style-to-font text-style)))
(defmethod clim3:text-style-descent ((port clx-framebuffer-port)
text-style)
(clim3-fonts:descent (clim3-fonts:text-style-to-font text-style)))
;;; These are not used for now.
;; (defmethod clim3:text-ascent ((port clx-framebuffer-port)
;; text-style
;; string)
;; (let ((font (font port)))
;; (reduce #'min string
;; :key (lambda (char)
;; (camfer:y-offset (camfer:find-glyph font char))))))
;; (defmethod clim3:text-descent ((port clx-framebuffer-port)
;; text-style
;; string)
;; (let ((font (font port)))
;; (reduce #'max string
;; :key (lambda (char)
;; (+ (array-dimension (camfer:mask (camfer:find-glyph font char)) 0)
;; (camfer:y-offset (camfer:find-glyph font char)))))))
(defmethod clim3:text-width
((port clx-framebuffer-port) text-style string)
(clim3-fonts:text-width (clim3-fonts:text-style-to-font text-style) string))
(defmethod clim3:text-prefix-length
((port clx-framebuffer-port) text-style string width)
(clim3-fonts:text-prefix-length (clim3-fonts:text-style-to-font text-style) string width))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
Keycodes , keysyms , etc .
(defparameter *modifier-names*
#(:shift :lock :control :meta :hyper :super :modifier-4 :modifier-5))
(defparameter +shift-mask+ #b00000001)
(defparameter +lock-mask+ #b00000010)
(defparameter +control-mask+ #b00000100)
(defparameter +meta-mask+ #b00001000)
(defparameter +hyper-mask+ #b00010000)
(defparameter +super-mask+ #b00100000)
(defparameter +modifier-4-mask+ #b01000000)
(defparameter +modifier-5-mask+ #b10000000)
(defun modifier-names (mask)
(loop for i from 0 below 8
when (plusp (logand (ash 1 i) mask))
collect (aref *modifier-names* i)))
(defun keycode-is-modifier-p (port keycode)
(some (lambda (modifiers)
(member keycode modifiers))
(multiple-value-list (xlib:modifier-mapping (display port)))))
(defmethod clim3-ext:standard-key-decoder
((port clx-framebuffer-port) keycode modifiers)
(if (keycode-is-modifier-p port keycode)
nil
(let ((keysyms (vector (xlib:keycode->keysym (display port) keycode 0)
(xlib:keycode->keysym (display port) keycode 1)
(xlib:keycode->keysym (display port) keycode 2)
(xlib:keycode->keysym (display port) keycode 3))))
(cond ((= (aref keysyms 0) (aref keysyms 1))
;; FIXME: do this better
(if (= (aref keysyms 0) 65293)
(cons #\Return
(modifier-names modifiers))
(cons (code-char (aref keysyms 0))
(modifier-names modifiers))))
((plusp (logand +shift-mask+ modifiers))
(cons (code-char (aref keysyms 1))
(modifier-names
(logandc2 modifiers +shift-mask+))))
(t
(cons (code-char (aref keysyms 0))
(modifier-names modifiers)))))))
(defmethod clim3-ext:standard-button-decoder
((port clx-framebuffer-port) button-code modifiers)
(cons (ecase button-code
(1 :button-1)
(2 :button-2)
(3 :button-3)
(4 :button-4)
(5 :button-5))
(modifier-names modifiers)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Handling events.
(defmethod clim3:event-loop ((port clx-framebuffer-port))
(let ((clim3:*port* port))
(loop do (let ((event (xlib:event-case ((display port))
(:key-press
(window code state)
`(:key-press ,window ,code ,state))
(:key-release
(window code state)
`(:key-release ,window ,code ,state))
(:button-press
(window code state)
`(:button-press ,window ,code ,state))
(:button-release
(window code state)
`(:button-release ,window ,code ,state))
(:exposure
(window)
`(:exposure ,window))
(:enter-notify
(window)
`(:enter-notify ,window))
(:leave-notify
(window)
`(:leave-notify ,window))
(:motion-notify
(window display)
`(:motion-notify ,display ,window))
(t
()
`(:other)))))
(cond ((eq (car event) :other)
(loop for zone-entry in (zone-entries port)
do (handle-motion-zones zone-entry)
(handle-visit zone-entry)
(update zone-entry)))
((eq (car event) :motion-notify)
(let ((display (cadr event)))
(when (null (xlib:event-listen display))
(let ((entry (find (caddr event) (zone-entries port)
:test #'eq :key #'window)))
(unless (null entry)
(handle-motion-zones entry)
(handle-visit entry)
(update entry))))))
(t
(let ((entry (find (cadr event) (zone-entries port)
:test #'eq :key #'window)))
(unless (null entry)
(handle-motion-zones entry)
(handle-visit entry)
(ecase (car event)
(:key-press
(destructuring-bind (code state) (cddr event)
(clim3:handle-key-press
clim3:*key-handler* code state)))
(:key-release
(destructuring-bind (code state) (cddr event)
(clim3:handle-key-release
clim3:*key-handler* code state)))
(:button-press
(destructuring-bind (code state) (cddr event)
(clim3:handle-button-press
clim3:*button-handler* code state)))
(:button-release
(destructuring-bind (code state) (cddr event)
(clim3:handle-button-release
clim3:*button-handler* code state)))
((:exposure :enter-notify :leave-notify)
nil))
(update entry)))))))))
| null | https://raw.githubusercontent.com/robert-strandh/CLIMatis/4949ddcc46d3f81596f956d12f64035e04589b29/Backends/CLX-Framebuffer/clx-framebuffer.lisp | lisp | A vector of interpretations. Each interpretation is a
short vector of keysyms
Do not change the clipping region, just the
origin of the coordinate system.
Later, we might try to do something more fancy here, such as
attempting to move the window on the screen.
Handle pointer position
Find the root zone of the zone.
Find the zone entry with that root zone.
Add the motion zone to the list of motion zones.
FIXME: Figure out what to do with same-screen-p
Only alert if the pointer is at a different position.
This optimization is valuable if many consecutive events
are non-pointer events such as key-press and key-release.
If any of the zones on the list has a client other than
the port of this zone-entry, then remove it.
For the remaining ones, call the handler.
Find the absolute position of the zone.
FIXME: Figure out what to do with same-screen-p
Experiment: build a skeleton zone hierarchy.
The purpose of this function is to build a skeletal version of the
visible zone hierarchy, so that this hierarchy can be compared to
what was there last time around the event loop.
The child is at least partially inside the area.
The purpose of this function is to scan the visible zone hierarchy
and compare it to what was painted last time around the event
loop. This information is then used to determine whether we need
to paint anything at all.
The child is at least partially inside the
area.
If there are any children left in the hierarchy, then
something has changed.
Update zones.
Make sure the pixmap and the image object have the same
dimensions as the window.
Transfer the image.
it has to exist when we set the parent of the zone.
Ask for a window that has the natural size of the zone. We may
not get it, though.
FIXME: take into account the position of the zone
Create an adequate gcontext for this window.
Make the array of the pixels. The dimensions don't matter,
because we reallocate it if necessary every time we need to
draw, so as to reflect the current size of the window.
Make the image object. Again, the size is of no importance,
but we must remember to change it later.
Make sure the window has the right contents.
These are not used for now.
(defmethod clim3:text-ascent ((port clx-framebuffer-port)
text-style
string)
(let ((font (font port)))
(reduce #'min string
:key (lambda (char)
(camfer:y-offset (camfer:find-glyph font char))))))
(defmethod clim3:text-descent ((port clx-framebuffer-port)
text-style
string)
(let ((font (font port)))
(reduce #'max string
:key (lambda (char)
(+ (array-dimension (camfer:mask (camfer:find-glyph font char)) 0)
(camfer:y-offset (camfer:find-glyph font char)))))))
FIXME: do this better
Handling events. | (in-package #:clim3-clx-framebuffer)
(defparameter *hpos* nil)
(defparameter *vpos* nil)
(defparameter *hstart* nil)
(defparameter *vstart* nil)
(defparameter *hend* nil)
(defparameter *vend* nil)
(defparameter *pixel-array* nil)
(defclass clx-framebuffer-port (clim3:port)
((%display :accessor display)
(%screen :accessor screen)
(%root :accessor root)
(%white :accessor white)
(%black :accessor black)
(%shift-state :initform nil :accessor shift-state)
(%zone-entries :initform '() :accessor zone-entries)
(%keyboard-mapping :initform nil :accessor keyboard-mapping)
(%meter :initform (benchmark:make-timer) :reader meter)))
(defmethod clim3-ext:call-with-zone ((port clx-framebuffer-port) thunk zone)
(let ((zone-hpos (clim3:hpos zone))
(zone-vpos (clim3:vpos zone))
(zone-width (clim3:width zone))
(zone-height (clim3:height zone)))
(let ((new-hpos (+ *hpos* zone-hpos))
(new-vpos (+ *vpos* zone-vpos)))
(let ((new-hstart (max *hstart* new-hpos))
(new-vstart (max *vstart* new-vpos))
(new-hend (min *hend* (+ new-hpos zone-width)))
(new-vend (min *vend* (+ new-vpos zone-height))))
(when (and (< new-hstart new-hend)
(< new-vstart new-vend))
(let ((*vpos* new-vpos)
(*hpos* new-hpos)
(*hstart* new-hstart)
(*vstart* new-vstart)
(*hend* new-hend)
(*vend* new-vend))
(funcall thunk)))))))
(defmethod clim3-ext:call-with-area
((port clx-framebuffer-port) function hpos vpos width height)
(let ((new-hpos (+ *hpos* hpos))
(new-vpos (+ *vpos* vpos)))
(let ((new-hstart (max *hstart* new-hpos))
(new-vstart (max *vstart* new-vpos))
(new-hend (min *hend* (+ new-hpos width)))
(new-vend (min *vend* (+ new-vpos height))))
(when (and (< new-hstart new-hend)
(< new-vstart new-vend))
(let ((*vpos* new-vpos)
(*hpos* new-hpos)
(*hstart* new-hstart)
(*vstart* new-vstart)
(*hend* new-hend)
(*vend* new-vend))
(funcall function))))))
(defmethod clim3-ext:call-with-position
((port clx-framebuffer-port) function hpos vpos)
(let ((*hpos* (+ *hpos* hpos))
(*vpos* (+ *vpos* vpos)))
(funcall function)))
(defmethod clim3:make-port ((display-server (eql :clx-framebuffer)))
(let ((port (make-instance 'clx-framebuffer-port)))
(setf (display port) (xlib:open-default-display))
(setf (xlib:display-after-function (display port))
#'xlib:display-finish-output)
(setf (screen port) (car (xlib:display-roots (display port))))
(setf (white port) (xlib:screen-white-pixel (screen port)))
(setf (black port) (xlib:screen-black-pixel (screen port)))
(setf (root port) (xlib:screen-root (screen port)))
(setf (keyboard-mapping port)
(let* ((temp (xlib:keyboard-mapping (display port)))
(result (make-array (array-dimension temp 0))))
(loop for row from 0 below (array-dimension temp 0)
do (let ((interpretations (make-array (array-dimension temp 1))))
(loop for col from 0 below (array-dimension temp 1)
do (setf (aref interpretations col)
(aref temp row col)))
(setf (aref result row) interpretations)))
result))
port))
(defclass zone-entry ()
((%port :initarg :port :reader port)
(%zone :initarg :zone :accessor zone)
(%gcontext :accessor gcontext)
(%window :accessor window)
(%pixel-array :accessor pixel-array)
(%image :accessor image)
(%motion-zones :initform '() :accessor motion-zones)
(%zone-containing-pointer :initform nil :accessor zone-containing-pointer)
(%prev-pointer-hpos :initform 0 :accessor prev-pointer-hpos)
(%prev-pointer-vpos :initform 0 :accessor prev-pointer-vpos)))
(defmethod clim3-ext:notify-child-hsprawl-changed
(zone (port clx-framebuffer-port))
nil)
(defmethod clim3-ext:notify-child-vsprawl-changed
(zone (port clx-framebuffer-port))
nil)
(defmethod clim3-ext:notify-child-position-changed
(zone (port clx-framebuffer-port))
nil)
(defmethod clim3-ext:notify-child-depth-changed
(zone (port clx-framebuffer-port))
nil)
(defmethod (setf clim3-ext:client) :after
((new-client clx-framebuffer-port) (zone clim3:motion))
(let ((root zone))
(loop while (clim3:zone-p (clim3-ext:parent root))
do (setf root (clim3-ext:parent root)))
(let ((zone-entry (find root
(zone-entries new-client)
:key #'zone
:test #'eq)))
(assert (not (null zone-entry)))
(push zone (motion-zones zone-entry)))))
(defun handle-motion-zones (zone-entry)
(multiple-value-bind (hpos vpos same-screen-p)
(xlib:pointer-position (window zone-entry))
(declare (ignore same-screen-p))
(unless (and (= hpos (prev-pointer-hpos zone-entry))
(= vpos (prev-pointer-vpos zone-entry)))
(setf (prev-pointer-hpos zone-entry) hpos)
(setf (prev-pointer-vpos zone-entry) vpos)
(setf (motion-zones zone-entry)
(remove (port zone-entry)
(motion-zones zone-entry)
:key #'clim3-ext:client
:test-not #'eq))
(loop for zone in (motion-zones zone-entry)
do (let ((absolute-hpos 0)
(absolute-vpos 0)
(parent zone))
(loop while (clim3:zone-p parent)
do (incf absolute-hpos (clim3:hpos parent))
(incf absolute-vpos (clim3:vpos parent))
(setf parent (clim3-ext:parent parent)))
(funcall (clim3:handler zone)
zone
(- hpos absolute-hpos)
(- vpos absolute-vpos)))))))
(defun handle-visit (zone-entry)
(let ((prev (zone-containing-pointer zone-entry)))
(multiple-value-bind (hpos vpos same-screen-p)
(xlib:pointer-position (window zone-entry))
(declare (ignore same-screen-p))
(let ((zone
(block found
(labels ((traverse (zone hpos vpos)
(unless (or (< hpos 0)
(< vpos 0)
(> hpos (clim3:width zone))
(> vpos (clim3:height zone)))
(if (and (typep zone 'clim3:visit)
(funcall (clim3:inside-p zone)
hpos vpos))
(return-from found zone)
(progn
(clim3-ext:map-over-children-top-to-bottom
(lambda (child)
(traverse child
(- hpos (clim3:hpos child))
(- vpos (clim3:vpos child))))
zone)
nil)))))
(traverse (zone zone-entry) hpos vpos)))))
(unless (eq zone prev)
(unless (null prev)
(clim3:leave prev))
(unless (null zone)
(clim3:enter zone))
(setf (zone-containing-pointer zone-entry) zone))))))
(defclass skeleton ()
((%zone :initarg :zone :reader zone)
(%hpos :initarg :hpos :reader hpos)
(%vpos :initarg :vpos :reader vpos)
(%width :initarg :width :reader width)
(%height :initarg :height :reader height)
(%children :initform '() :initarg :children :accessor children)))
(defmethod print-object ((object skeleton) stream)
(print-unreadable-object (object stream :type t :identity t)
(format stream
"zone: ~s hpos: ~s :vpos ~s :width ~s :height ~s"
(zone object)
(hpos object)
(vpos object)
(width object)
(height object))))
The parameters HMIN , VMIN , HMAX , and VMAX are in the coordinate
system of ZONE , and they are inside ZONE . In other words , HMIN
and VMIN are non - negative , HMAX is less than or equal to the width
of ZONE , and VMAX is less than or equal to the height of ZONE .
(defun build-visible-hierarchy (zone hmin vmin hmax vmax)
(let ((children '()))
(clim3-ext:map-over-children-top-to-bottom
(lambda (child)
(let ((chpos (clim3:hpos child))
(cvpos (clim3:vpos child))
(cwidth (clim3:width child))
(cheight (clim3:height child)))
(when (and (< chpos hmax)
(< cvpos vmax)
(> (+ chpos cwidth) hmin)
(> (+ cvpos cheight) vmin))
(let ((new-hmin (max 0 (- hmin chpos)))
(new-vmin (max 0 (- vmin cvpos)))
(new-hmax (min cwidth (- hmax chpos)))
(new-vmax (min cheight (- vmax cvpos))))
(push (build-visible-hierarchy
child new-hmin new-vmin new-hmax new-vmax)
children)))))
zone)
(make-instance 'skeleton
:zone zone
:hpos (clim3:hpos zone)
:vpos (clim3:vpos zone)
:width (clim3:width zone)
:height (clim3:height zone)
:children (nreverse children))))
(defparameter *hierarchy* nil)
(defun build-top-level-hierarchy (zone)
(setf *hierarchy*
(let ((width (clim3:width zone))
(height (clim3:height zone)))
(build-visible-hierarchy zone 0 0 width height))))
(defun visible-hierarchy-unchanged-p (hierarchy zone hmin vmin hmax vmax)
(and (eq (zone hierarchy) zone)
(= (hpos hierarchy) (clim3:hpos zone))
(= (vpos hierarchy) (clim3:vpos zone))
(= (width hierarchy) (clim3:width zone))
(= (height hierarchy) (clim3:height zone))
(let ((children (children hierarchy)))
(clim3-ext:map-over-children-top-to-bottom
(lambda (child)
(if (or (null children)
(not (eq (zone (car children)) child))
(let ((chpos (clim3:hpos child))
(cvpos (clim3:vpos child))
(cwidth (clim3:width child))
(cheight (clim3:height child)))
(when (and (< chpos hmax)
(< cvpos vmax)
(> (+ chpos cwidth) hmin)
(> (+ cvpos cheight) vmin))
(let ((new-hmin (max 0 (- hmin chpos)))
(new-vmin (max 0 (- vmin cvpos)))
(new-hmax (min cwidth (- hmax chpos)))
(new-vmax (min cheight (- vmax cvpos))))
(not (visible-hierarchy-unchanged-p
(car children) child
new-hmin new-vmin new-hmax new-vmax))))))
(return-from visible-hierarchy-unchanged-p nil)
(pop children)))
zone)
(null children))))
(defun top-level-hierarchy-unchanged-p (zone)
(and (not (null *hierarchy*))
(let ((width (clim3:width zone))
(height (clim3:height zone)))
(visible-hierarchy-unchanged-p
*hierarchy* zone 0 0 width height))))
(defun layout-visible-zones (zone width height)
(labels ((aux (zone)
(when (typep zone 'clim3-ext:compound-mixin)
(clim3-ext:impose-child-layouts zone)
(clim3-ext:map-over-children
(lambda (child)
(clim3:with-zone child
(aux child)))
zone))))
(let ((*hpos* 0)
(*vpos* 0)
(*hstart* 0)
(*vstart* 0)
(*hend* width)
(*vend* height))
(aux zone))))
(defun paint-visible-area (zone width height pixel-array)
(let ((*hpos* 0)
(*vpos* 0)
(*hstart* 0)
(*vstart* 0)
(*hend* width)
(*vend* height)
(*pixel-array* pixel-array))
(clim3-ext:paint zone)))
(defun draw-default-background (pixel-array)
(let* ((size (array-total-size pixel-array))
(v (make-array size
:element-type '(unsigned-byte 32)
:displaced-to pixel-array)))
(fill v #xffffffff)))
(defun update (zone-entry)
(with-accessors ((zone zone)
(gcontext gcontext)
(window window)
(pixel-array pixel-array)
(image image))
zone-entry
(let ((width (xlib:drawable-width window))
(height (xlib:drawable-height window)))
(clim3-ext:impose-size zone width height)
(when (or (/= width (array-dimension pixel-array 1))
(/= height (array-dimension pixel-array 0)))
(setf *hierarchy* nil)
(setf pixel-array
(make-array (list height width)
:element-type '(unsigned-byte 32)))
(setf image
(xlib:create-image :bits-per-pixel 32
:data pixel-array
:depth 24
:width width :height height
:format :z-pixmap)))
(layout-visible-zones zone width height)
(unless (top-level-hierarchy-unchanged-p zone)
(build-top-level-hierarchy zone)
(draw-default-background pixel-array)
(paint-visible-area zone width height pixel-array))
(xlib::put-image window
gcontext
image
:x 0 :y 0
:width width :height height))))
(defmethod clim3-ext:repaint ((port clx-framebuffer-port))
(loop for zone-entry in (zone-entries port)
do (update zone-entry)))
(defmethod clim3:connect ((zone clim3:zone)
(port clx-framebuffer-port))
(let ((zone-entry (make-instance 'zone-entry :port port :zone zone))
(clim3:*port* port))
Register this zone entry . We need to do this right away , because
(push zone-entry (zone-entries port))
(setf (clim3-ext:parent zone) port)
(clim3-ext:ensure-hsprawl-valid zone)
(clim3-ext:ensure-vsprawl-valid zone)
(setf (window zone-entry)
(multiple-value-bind (width height) (clim3:natural-size zone)
(xlib:create-window :parent (root port)
:x 0 :y 0 :width width :height height
:class :input-output
:visual :copy
:background (white port)
:bit-gravity :north-west
:event-mask
'(:key-press :key-release
:button-motion :button-press :button-release
:enter-window :leave-window
:exposure
:structure-notify
:pointer-motion))))
(xlib:map-window (window zone-entry))
(setf (gcontext zone-entry)
(xlib:create-gcontext :drawable (window zone-entry)
:background (white port)
:foreground (black port)))
(setf (pixel-array zone-entry)
(make-array '(0 0)
:element-type '(unsigned-byte 32)))
(setf (image zone-entry)
(xlib:create-image :bits-per-pixel 32
:data (pixel-array zone-entry)
:depth 24
:width 0 :height 0
:format :z-pixmap))
(setf *hierarchy* nil)
(update zone-entry)))
(defmethod clim3:disconnect (zone (port clx-framebuffer-port))
(let ((zone-entry (find zone (zone-entries port) :key #'zone)))
(xlib:free-gcontext (gcontext zone-entry))
(xlib:destroy-window (window zone-entry))
(setf (zone-entries port) (remove zone-entry (zone-entries port)))
(when (null (zone-entries port))
(xlib:close-display (display port)))
(setf (clim3-ext:parent zone) nil)))
(defmethod clim3:text-style-ascent ((port clx-framebuffer-port)
text-style)
(clim3-fonts:ascent (clim3-fonts:text-style-to-font text-style)))
(defmethod clim3:text-style-descent ((port clx-framebuffer-port)
text-style)
(clim3-fonts:descent (clim3-fonts:text-style-to-font text-style)))
(defmethod clim3:text-width
((port clx-framebuffer-port) text-style string)
(clim3-fonts:text-width (clim3-fonts:text-style-to-font text-style) string))
(defmethod clim3:text-prefix-length
((port clx-framebuffer-port) text-style string width)
(clim3-fonts:text-prefix-length (clim3-fonts:text-style-to-font text-style) string width))
Keycodes , keysyms , etc .
(defparameter *modifier-names*
#(:shift :lock :control :meta :hyper :super :modifier-4 :modifier-5))
(defparameter +shift-mask+ #b00000001)
(defparameter +lock-mask+ #b00000010)
(defparameter +control-mask+ #b00000100)
(defparameter +meta-mask+ #b00001000)
(defparameter +hyper-mask+ #b00010000)
(defparameter +super-mask+ #b00100000)
(defparameter +modifier-4-mask+ #b01000000)
(defparameter +modifier-5-mask+ #b10000000)
(defun modifier-names (mask)
(loop for i from 0 below 8
when (plusp (logand (ash 1 i) mask))
collect (aref *modifier-names* i)))
(defun keycode-is-modifier-p (port keycode)
(some (lambda (modifiers)
(member keycode modifiers))
(multiple-value-list (xlib:modifier-mapping (display port)))))
(defmethod clim3-ext:standard-key-decoder
((port clx-framebuffer-port) keycode modifiers)
(if (keycode-is-modifier-p port keycode)
nil
(let ((keysyms (vector (xlib:keycode->keysym (display port) keycode 0)
(xlib:keycode->keysym (display port) keycode 1)
(xlib:keycode->keysym (display port) keycode 2)
(xlib:keycode->keysym (display port) keycode 3))))
(cond ((= (aref keysyms 0) (aref keysyms 1))
(if (= (aref keysyms 0) 65293)
(cons #\Return
(modifier-names modifiers))
(cons (code-char (aref keysyms 0))
(modifier-names modifiers))))
((plusp (logand +shift-mask+ modifiers))
(cons (code-char (aref keysyms 1))
(modifier-names
(logandc2 modifiers +shift-mask+))))
(t
(cons (code-char (aref keysyms 0))
(modifier-names modifiers)))))))
(defmethod clim3-ext:standard-button-decoder
((port clx-framebuffer-port) button-code modifiers)
(cons (ecase button-code
(1 :button-1)
(2 :button-2)
(3 :button-3)
(4 :button-4)
(5 :button-5))
(modifier-names modifiers)))
(defmethod clim3:event-loop ((port clx-framebuffer-port))
(let ((clim3:*port* port))
(loop do (let ((event (xlib:event-case ((display port))
(:key-press
(window code state)
`(:key-press ,window ,code ,state))
(:key-release
(window code state)
`(:key-release ,window ,code ,state))
(:button-press
(window code state)
`(:button-press ,window ,code ,state))
(:button-release
(window code state)
`(:button-release ,window ,code ,state))
(:exposure
(window)
`(:exposure ,window))
(:enter-notify
(window)
`(:enter-notify ,window))
(:leave-notify
(window)
`(:leave-notify ,window))
(:motion-notify
(window display)
`(:motion-notify ,display ,window))
(t
()
`(:other)))))
(cond ((eq (car event) :other)
(loop for zone-entry in (zone-entries port)
do (handle-motion-zones zone-entry)
(handle-visit zone-entry)
(update zone-entry)))
((eq (car event) :motion-notify)
(let ((display (cadr event)))
(when (null (xlib:event-listen display))
(let ((entry (find (caddr event) (zone-entries port)
:test #'eq :key #'window)))
(unless (null entry)
(handle-motion-zones entry)
(handle-visit entry)
(update entry))))))
(t
(let ((entry (find (cadr event) (zone-entries port)
:test #'eq :key #'window)))
(unless (null entry)
(handle-motion-zones entry)
(handle-visit entry)
(ecase (car event)
(:key-press
(destructuring-bind (code state) (cddr event)
(clim3:handle-key-press
clim3:*key-handler* code state)))
(:key-release
(destructuring-bind (code state) (cddr event)
(clim3:handle-key-release
clim3:*key-handler* code state)))
(:button-press
(destructuring-bind (code state) (cddr event)
(clim3:handle-button-press
clim3:*button-handler* code state)))
(:button-release
(destructuring-bind (code state) (cddr event)
(clim3:handle-button-release
clim3:*button-handler* code state)))
((:exposure :enter-notify :leave-notify)
nil))
(update entry)))))))))
|
b8e2fd632095c73659d9ea29d61c57d240f5629000f24569cc5918f3017b684f | igorhvr/bedlam | differ.scm | " differ.scm " ) Sequence Comparison Algorithm .
Copyright ( C ) 2001 , 2002 , 2003 , 2004 , 2007
;
;Permission to copy this software, to modify it, to redistribute it,
;to distribute modified versions, and to use it for any purpose is
;granted, subject to the following restrictions and understandings.
;
1 . Any copy made of this software must include this copyright notice
;in full.
;
2 . I have made no warranty or representation that the operation of
;this software will be error-free, and I am under no obligation to
;provide any services, by way of maintenance, update, or otherwise.
;
3 . In conjunction with products arising from the use of this
;material, there shall be no use of my name in any advertising,
;promotional, or sales literature without prior written consent in
;each case.
;;@noindent
;;@code{diff:edit-length} implements the algorithm:
;;
@ifinfo
;;@example
, , , and ,
;; "An O(NP) Sequence Comparison Algorithm,"
Information Processing Letters 35 , 6 ( 1990 ) , 317 - 323 .
;; @url{}
;;@end example
;;@end ifinfo
;;@ifset html
, < A HREF=" / people / gene / vita.html " >
E. Myers,</A > U. Manber , and ,
< A HREF=" / people / gene / PAPERS / np_diff.ps " >
;;"An O(NP) Sequence Comparison Algorithm"</A>,
Information Processing Letters 35 , 6 ( 1990 ) , 317 - 323 .
;;@end ifset
;;
;;@noindent
;;The values returned by @code{diff:edit-length} can be used to gauge
the degree of match between two sequences .
;;
;;@noindent
;;@code{diff:edits} and @code{diff:longest-common-subsequence} combine
;;the algorithm with the divide-and-conquer method outlined in:
;;
@ifinfo
;;@example
and ,
;; "Optimal alignments in linear space",
Computer Application in the Biosciences ( CABIOS ) , 4(1):11 - 17 , 1988 .
;; @url{}
;;@end example
;;@end ifinfo
;;@ifset html
< A HREF=" / people / gene / vita.html " >
E. Myers,</A > and ,
< A HREF=" / people / gene / PAPERS / linear.ps " >
;;"Optimal alignments in linear space"</A>,
Computer Application in the Biosciences ( CABIOS ) , 4(1):11 - 17 , 1988 .
;;@end ifset
;;
;;@noindent
;;If the items being sequenced are text lines, then the computed
;;edit-list is equivalent to the output of the @dfn{diff} utility
;;program. If the items being sequenced are words, then it is like the
;;lesser known @dfn{spiff} program.
(require 'array)
p - lim is half the number of gratuitous edits for strings of given
;;; lengths.
When passed # f CC , fp : compare returns edit - distance if successful ;
# f otherwise ( p > ) . When passed CC , fp : compare returns # f.
(define (fp:compare fp fpoff CC A M B N p-lim)
(define Delta (- N M))
;;(if (negative? Delta) (slib:error 'fp:compare (fp:subarray A 0 M) '> (fp:subarray B 0 N)))
( set ! compares ( + 1 compares ) ) ; ( print ' fp : compare M N p - lim )
(let loop ((p 0))
(do ((k (- p) (+ 1 k)))
((>= k Delta))
(fp:run fp fpoff k A M B N CC p))
(do ((k (+ Delta p) (+ -1 k)))
((<= k Delta))
(fp:run fp fpoff k A M B N CC p))
(let ((fpval (fp:run fp fpoff Delta A M B N CC p)))
At this point , the cost to ( fpval - Delta , fpval ) is Delta + 2*p
(cond ((and (not CC) (<= N fpval)) (+ Delta (* 2 p)))
((and (not (negative? p-lim)) (>= p p-lim)) #f)
(else (loop (+ 1 p)))))))
;;; Traces runs of matches until they end; then set fp[k]=y.
If CC is supplied , set each CC[y ] = min(CC[y ] , cost ) for run .
;;; Returns furthest y reached.
(define (fp:run fp fpoff k A M B N CC p)
(define cost (+ k p p))
(let snloop ((y (max (+ (array-ref fp (+ -1 k fpoff)) 1)
(array-ref fp (+ 1 k fpoff)))))
(define x (- y k))
(and CC (<= y N)
(let ((xcst (- M x)))
(cond ((negative? xcst))
(else (array-set! CC
(min (+ xcst cost) (array-ref CC y))
y)))))
;;(set! tick (+ 1 tick))
(cond ((and (< x M) (< y N)
(eqv? (array-ref A x) (array-ref B y)))
(snloop (+ 1 y)))
(else (array-set! fp y (+ fpoff k))
y))))
Check that only 1 and -1 steps between adjacent CC entries .
;;(define (fp:step-check A M B N CC)
;; (do ((cdx (+ -1 N) (+ -1 cdx)))
;; ((negative? cdx))
;; (case (- (array-ref CC cdx) (array-ref CC (+ 1 cdx)))
;; ((1 -1) #t)
( else ( cond ( ( > 30 ( car ( array - dimensions CC ) ) )
;; (display "A: ") (print A)
;; (display "B: ") (print B)))
;; (slib:warn
" CC " ( append ( list ( max 0 ( + -5 cdx ) ) ' : ( min ( + 1 N ) ( + 5 cdx ) )
;; 'of)
( array - dimensions CC ) )
( fp : subarray CC ( max 0 ( + -5 cdx ) ) ( min ( + 1 N ) ( + 5 cdx ) ) ) ) ) ) ) )
;;; Correct cost jumps left by fp:compare [which visits only a few (x,y)].
( define ( smooth - costs CC N )
;; (do ((cdx (+ -1 N) (+ -1 cdx))) ; smooth from end
;; ((negative? cdx))
;; (array-set! CC (min (array-ref CC cdx) (+ 1 (array-ref CC (+ 1 cdx))))
;; cdx))
;; (do ((cdx 1 (+ 1 cdx))) ; smooth toward end
;; ((> cdx N))
;; (array-set! CC (min (array-ref CC cdx) (+ 1 (array-ref CC (+ -1 cdx))))
;; cdx))
;; CC)
(define (diff:mid-split N RR CC cost)
RR is not longer than CC . So do for each element of RR .
(let loop ((cdx (+ 1 (quotient N 2)))
(rdx (quotient N 2)))
( if ( negative ? rdx ) ( slib : error ' negative ? ' rdx ) )
(cond ((eqv? cost (+ (array-ref CC rdx) (array-ref RR (- N rdx)))) rdx)
((eqv? cost (+ (array-ref CC cdx) (array-ref RR (- N cdx)))) cdx)
(else (loop (+ 1 cdx) (+ -1 rdx))))))
;;; Return 0-based shared array.
;;; Reverse RA if END < START.
(define (fp:subarray RA start end)
(define n-len (abs (- end start)))
(if (< end start)
(make-shared-array RA (lambda (idx) (list (+ -1 (- start idx)))) n-len)
(make-shared-array RA (lambda (idx) (list (+ start idx))) n-len)))
(define (fp:init! fp fpoff fill mindx maxdx)
(define mlim (+ fpoff mindx))
(do ((idx (+ fpoff maxdx) (+ -1 idx)))
((< idx mlim))
(array-set! fp fill idx)))
;;; Split A[start-a..end-a] (shorter array) into smaller and smaller chunks.
EDX is index into EDITS .
;;; EPO is insert/delete polarity (+1 or -1)
(define (diff:divide-and-conquer fp fpoff CCRR A start-a end-a B start-b end-b edits edx epo p-lim)
(define mid-a (quotient (+ start-a end-a) 2))
(define len-b (- end-b start-b))
(define len-a (- end-a start-a))
(let ((tcst (+ p-lim p-lim (- len-b len-a))))
(define CC (fp:subarray CCRR 0 (+ len-b 1)))
(define RR (fp:subarray CCRR (+ len-b 1) (* 2 (+ len-b 1))))
(define M2 (- end-a mid-a))
(define M1 (- mid-a start-a))
(fp:init! CC 0 (+ len-a len-b) 0 len-b)
(fp:init! fp fpoff -1 (- (+ 1 p-lim)) (+ 1 p-lim (- len-b M1)))
(fp:compare fp fpoff CC
(fp:subarray A start-a mid-a) M1
(fp:subarray B start-b end-b) len-b
(min p-lim len-a))
(fp:init! RR 0 (+ len-a len-b) 0 len-b)
(fp:init! fp fpoff -1 (- (+ 1 p-lim)) (+ 1 p-lim (- len-b M2)))
(fp:compare fp fpoff RR
(fp:subarray A end-a mid-a) M2
(fp:subarray B end-b start-b) len-b
(min p-lim len-a))
( smooth - costs ) ( smooth - costs )
(let ((b-splt (diff:mid-split len-b RR CC tcst)))
(define est-c (array-ref CC b-splt))
(define est-r (array-ref RR (- len-b b-splt)))
;;(display "A: ") (array-for-each display (fp:subarray A start-a mid-a)) (display " + ") (array-for-each display (fp:subarray A mid-a end-a)) (newline)
;;(display "B: ") (array-for-each display (fp:subarray B start-b end-b)) (newline)
( print ' cc cc ) ( print ' rr ( fp : subarray RR ( + 1 len - b ) 0 ) )
( print ( make - string ( + 12 ( * 2 b - splt ) ) # \- ) ' ^ ( list b - splt ) )
(check-cost! 'CC est-c
(diff2et fp fpoff CCRR
A start-a mid-a
B start-b (+ start-b b-splt)
edits edx epo
(quotient (- est-c (- b-splt (- mid-a start-a)))
2)))
(check-cost! 'RR est-r
(diff2et fp fpoff CCRR
A mid-a end-a
B (+ start-b b-splt) end-b
edits (+ est-c edx) epo
(quotient (- est-r (- (- len-b b-splt)
(- end-a mid-a)))
2)))
(+ est-c est-r))))
;;; Trim; then diff sub-arrays; either one longer. Returns edit-length
(define (diff2et fp fpoff CCRR A start-a end-a B start-b end-b edits edx epo p-lim)
( if ( < ( - end - a start - a ) p - lim ) ( slib : warn ' diff2et ' len - a ( - end - a start - a ) ' len - b ( - end - b start - b ) ' p - lim p - lim ) )
(do ((bdx (+ -1 end-b) (+ -1 bdx))
(adx (+ -1 end-a) (+ -1 adx)))
((not (and (<= start-b bdx)
(<= start-a adx)
(eqv? (array-ref A adx) (array-ref B bdx))))
(do ((bsx start-b (+ 1 bsx))
(asx start-a (+ 1 asx)))
((not (and (< bsx bdx)
(< asx adx)
(eqv? (array-ref A asx) (array-ref B bsx))))
;;(print 'trim-et (- asx start-a) '+ (- end-a adx))
(let ((delta (- (- bdx bsx) (- adx asx))))
(if (negative? delta)
(diff2ez fp fpoff CCRR B bsx (+ 1 bdx) A asx (+ 1 adx)
edits edx (- epo) (+ delta p-lim))
(diff2ez fp fpoff CCRR A asx (+ 1 adx) B bsx (+ 1 bdx)
edits edx epo p-lim))))
;;(set! tick (+ 1 tick))
))
;;(set! tick (+ 1 tick))
))
Diff sub - arrays , A not longer than B. Returns edit - length
(define (diff2ez fp fpoff CCRR A start-a end-a B start-b end-b edits edx epo p-lim)
(define len-a (- end-a start-a))
(define len-b (- end-b start-b))
( if ( > len - a len - b ) ( slib : error ' > len - b ) )
(cond ((zero? p-lim) ; B inserts only
(if (= len-b len-a)
0 ; A = B; no edits
(let loop ((adx start-a)
(bdx start-b)
(edx edx))
(cond ((>= bdx end-b) (- len-b len-a))
((>= adx end-a)
(do ((idx bdx (+ 1 idx))
(edx edx (+ 1 edx)))
((>= idx end-b) (- len-b len-a))
(array-set! edits (* epo (+ 1 idx)) edx)))
((eqv? (array-ref A adx) (array-ref B bdx))
;;(set! tick (+ 1 tick))
(loop (+ 1 adx) (+ 1 bdx) edx))
(else (array-set! edits (* epo (+ 1 bdx)) edx)
;;(set! tick (+ 1 tick))
(loop adx (+ 1 bdx) (+ 1 edx)))))))
((<= len-a p-lim) ; delete all A; insert all B
( if ( p - lim ) ( slib : error ' p - lim p - lim ) )
(do ((idx start-a (+ 1 idx))
(jdx start-b (+ 1 jdx)))
((and (>= idx end-a) (>= jdx end-b)) (+ len-a len-b))
(cond ((< jdx end-b)
(array-set! edits (* epo (+ 1 jdx)) edx)
(set! edx (+ 1 edx))))
(cond ((< idx end-a)
(array-set! edits (* epo (- -1 idx)) edx)
(set! edx (+ 1 edx))))))
(else (diff:divide-and-conquer
fp fpoff CCRR A start-a end-a B start-b end-b
edits edx epo p-lim))))
(define (check-cost! name est cost)
(if (not (eqv? est cost))
(slib:warn name "cost check failed" est '!= cost)))
;;;; Routines interfacing API layer to algorithms.
(define (diff:invert-edits! edits)
(define cost (car (array-dimensions edits)))
(do ((idx (+ -1 cost) (+ -1 idx)))
((negative? idx))
(array-set! edits (- (array-ref edits idx)) idx)))
;;; len-a < len-b
(define (edits2lcs! lcs edits A)
(define cost (car (array-dimensions edits)))
(define len-a (car (array-dimensions A)))
(let loop ((edx 0)
(sdx 0)
(adx 0))
(let ((edit (if (< edx cost) (array-ref edits edx) 0)))
(cond ((>= adx len-a))
((positive? edit)
(loop (+ 1 edx) sdx adx))
((zero? edit)
(array-set! lcs (array-ref A adx) sdx)
(loop edx (+ 1 sdx) (+ 1 adx)))
((>= adx (- -1 edit))
(loop (+ 1 edx) sdx (+ 1 adx)))
(else
(array-set! lcs (array-ref A adx) sdx)
(loop edx (+ 1 sdx) (+ 1 adx)))))))
;; A not longer than B (M <= N)
(define (diff2edits! edits fp CCRR A B)
(define N (car (array-dimensions B)))
(define M (car (array-dimensions A)))
(define est (car (array-dimensions edits)))
(let ((p-lim (quotient (- est (- N M)) 2)))
(check-cost! 'diff2edits!
est
(diff2et fp (+ 1 p-lim)
CCRR A 0 M B 0 N edits 0 1 p-lim))))
;; A not longer than B (M <= N)
(define (diff2editlen fp A B p-lim)
(define N (car (array-dimensions B)))
(define M (car (array-dimensions A)))
(let ((maxdx (if (negative? p-lim) (+ 1 N) (+ 1 p-lim (- N M))))
(mindx (if (negative? p-lim) (- (+ 1 M)) (- (+ 1 p-lim)))))
(fp:init! fp (- mindx) -1 mindx maxdx)
(fp:compare fp (- mindx) #f A M B N p-lim)))
;;;; API
@args
@args array1 array2
@1 and @2 are one - dimensional arrays .
;;
;;The non-negative integer @3, if provided, is maximum number of
deletions of the shorter sequence to allow . @0 will return @code{#f }
;;if more deletions would be necessary.
;;
@0 returns a one - dimensional array of length @code{(quotient ( - ( +
len1 len2 ) ( diff : edit - length @1 @2 ) ) 2 ) } holding the longest sequence
common to both @var{array}s .
(define (diff:longest-common-subsequence A B . p-lim)
(define M (car (array-dimensions A)))
(define N (car (array-dimensions B)))
(set! p-lim (if (null? p-lim) -1 (car p-lim)))
(let ((edits (if (< N M)
(diff:edits B A p-lim)
(diff:edits A B p-lim))))
(and edits
(let* ((cost (car (array-dimensions edits)))
(lcs (make-array A (/ (- (+ N M) cost) 2))))
(edits2lcs! lcs edits (if (< N M) B A))
lcs))))
@args
@args array1 array2
@1 and @2 are one - dimensional arrays .
;;
;;The non-negative integer @3, if provided, is maximum number of
deletions of the shorter sequence to allow . @0 will return @code{#f }
;;if more deletions would be necessary.
;;
@0 returns a vector of length @code{(diff : edit - length @1 @2 ) } composed
of a shortest sequence of edits transformaing @1 to @2 .
;;
;;Each edit is an integer:
@table @asis
@item @var{k } > 0
Inserts @code{(array - ref @1 ( + -1 } ) ) } into the sequence .
@item @var{k } < 0
;;Deletes @code{(array-ref @2 (- -1 @var{k}))} from the sequence.
;;@end table
(define (diff:edits A B . p-lim)
(define M (car (array-dimensions A)))
(define N (car (array-dimensions B)))
(define est (diff:edit-length A B (if (null? p-lim) -1 (car p-lim))))
(and est
(let ((CCRR (make-array (A:fixZ32b) (* 2 (+ (max M N) 1))))
(edits (make-array (A:fixZ32b) est)))
(define fp (make-array (A:fixZ32b)
(+ (max (- N (quotient M 2))
(- M (quotient N 2)))
2 * p - lim
3)))
(cond ((< N M)
(diff2edits! edits fp CCRR B A)
(diff:invert-edits! edits))
(else
(diff2edits! edits fp CCRR A B)))
;;(diff:order-edits! edits est)
edits)))
@args
@args array1 array2
@1 and @2 are one - dimensional arrays .
;;
;;The non-negative integer @3, if provided, is maximum number of
deletions of the shorter sequence to allow . @0 will return @code{#f }
;;if more deletions would be necessary.
;;
@0 returns the length of the shortest sequence of edits transformaing
@1 to @2 .
(define (diff:edit-length A B . p-lim)
(define M (car (array-dimensions A)))
(define N (car (array-dimensions B)))
(set! p-lim (if (null? p-lim) -1 (car p-lim)))
(let ((fp (make-array (A:fixZ32b) (if (negative? p-lim)
(+ 3 M N)
(+ 3 (abs (- N M)) p-lim p-lim)))))
(if (< N M)
(diff2editlen fp B A p-lim)
(diff2editlen fp A B p-lim))))
;;@example
( diff : longest - common - subsequence " " " fgehijkpqrlm " )
@result { } " "
;;
( diff : edit - length " " " fgehijkpqrlm " )
@result { } 6
;;
( diff : edits " " " fgehijkpqrlm " )
;;@result{} #A:fixZ32b(3 -5 -7 8 9 10)
; e c h p q r
;;@end example
( trace - all " /home / jaffer / slib / differ.scm")(set ! * qp - width * 999)(untrace fp : run ) ; fp : subarray
| null | https://raw.githubusercontent.com/igorhvr/bedlam/b62e0d047105bb0473bdb47c58b23f6ca0f79a4e/iasylum/slib/3b2/differ.scm | scheme |
Permission to copy this software, to modify it, to redistribute it,
to distribute modified versions, and to use it for any purpose is
granted, subject to the following restrictions and understandings.
in full.
this software will be error-free, and I am under no obligation to
provide any services, by way of maintenance, update, or otherwise.
material, there shall be no use of my name in any advertising,
promotional, or sales literature without prior written consent in
each case.
@noindent
@code{diff:edit-length} implements the algorithm:
@example
"An O(NP) Sequence Comparison Algorithm,"
@url{}
@end example
@end ifinfo
@ifset html
"An O(NP) Sequence Comparison Algorithm"</A>,
@end ifset
@noindent
The values returned by @code{diff:edit-length} can be used to gauge
@noindent
@code{diff:edits} and @code{diff:longest-common-subsequence} combine
the algorithm with the divide-and-conquer method outlined in:
@example
"Optimal alignments in linear space",
@url{}
@end example
@end ifinfo
@ifset html
"Optimal alignments in linear space"</A>,
@end ifset
@noindent
If the items being sequenced are text lines, then the computed
edit-list is equivalent to the output of the @dfn{diff} utility
program. If the items being sequenced are words, then it is like the
lesser known @dfn{spiff} program.
lengths.
(if (negative? Delta) (slib:error 'fp:compare (fp:subarray A 0 M) '> (fp:subarray B 0 N)))
( print ' fp : compare M N p - lim )
Traces runs of matches until they end; then set fp[k]=y.
Returns furthest y reached.
(set! tick (+ 1 tick))
(define (fp:step-check A M B N CC)
(do ((cdx (+ -1 N) (+ -1 cdx)))
((negative? cdx))
(case (- (array-ref CC cdx) (array-ref CC (+ 1 cdx)))
((1 -1) #t)
(display "A: ") (print A)
(display "B: ") (print B)))
(slib:warn
'of)
Correct cost jumps left by fp:compare [which visits only a few (x,y)].
(do ((cdx (+ -1 N) (+ -1 cdx))) ; smooth from end
((negative? cdx))
(array-set! CC (min (array-ref CC cdx) (+ 1 (array-ref CC (+ 1 cdx))))
cdx))
(do ((cdx 1 (+ 1 cdx))) ; smooth toward end
((> cdx N))
(array-set! CC (min (array-ref CC cdx) (+ 1 (array-ref CC (+ -1 cdx))))
cdx))
CC)
Return 0-based shared array.
Reverse RA if END < START.
Split A[start-a..end-a] (shorter array) into smaller and smaller chunks.
EPO is insert/delete polarity (+1 or -1)
(display "A: ") (array-for-each display (fp:subarray A start-a mid-a)) (display " + ") (array-for-each display (fp:subarray A mid-a end-a)) (newline)
(display "B: ") (array-for-each display (fp:subarray B start-b end-b)) (newline)
Trim; then diff sub-arrays; either one longer. Returns edit-length
(print 'trim-et (- asx start-a) '+ (- end-a adx))
(set! tick (+ 1 tick))
(set! tick (+ 1 tick))
B inserts only
A = B; no edits
(set! tick (+ 1 tick))
(set! tick (+ 1 tick))
delete all A; insert all B
Routines interfacing API layer to algorithms.
len-a < len-b
A not longer than B (M <= N)
A not longer than B (M <= N)
API
The non-negative integer @3, if provided, is maximum number of
if more deletions would be necessary.
The non-negative integer @3, if provided, is maximum number of
if more deletions would be necessary.
Each edit is an integer:
Deletes @code{(array-ref @2 (- -1 @var{k}))} from the sequence.
@end table
(diff:order-edits! edits est)
The non-negative integer @3, if provided, is maximum number of
if more deletions would be necessary.
@example
@result{} #A:fixZ32b(3 -5 -7 8 9 10)
e c h p q r
@end example
fp : subarray | " differ.scm " ) Sequence Comparison Algorithm .
Copyright ( C ) 2001 , 2002 , 2003 , 2004 , 2007
1 . Any copy made of this software must include this copyright notice
2 . I have made no warranty or representation that the operation of
3 . In conjunction with products arising from the use of this
@ifinfo
, , , and ,
Information Processing Letters 35 , 6 ( 1990 ) , 317 - 323 .
, < A HREF=" / people / gene / vita.html " >
E. Myers,</A > U. Manber , and ,
< A HREF=" / people / gene / PAPERS / np_diff.ps " >
Information Processing Letters 35 , 6 ( 1990 ) , 317 - 323 .
the degree of match between two sequences .
@ifinfo
and ,
Computer Application in the Biosciences ( CABIOS ) , 4(1):11 - 17 , 1988 .
< A HREF=" / people / gene / vita.html " >
E. Myers,</A > and ,
< A HREF=" / people / gene / PAPERS / linear.ps " >
Computer Application in the Biosciences ( CABIOS ) , 4(1):11 - 17 , 1988 .
(require 'array)
p - lim is half the number of gratuitous edits for strings of given
# f otherwise ( p > ) . When passed CC , fp : compare returns # f.
(define (fp:compare fp fpoff CC A M B N p-lim)
(define Delta (- N M))
(let loop ((p 0))
(do ((k (- p) (+ 1 k)))
((>= k Delta))
(fp:run fp fpoff k A M B N CC p))
(do ((k (+ Delta p) (+ -1 k)))
((<= k Delta))
(fp:run fp fpoff k A M B N CC p))
(let ((fpval (fp:run fp fpoff Delta A M B N CC p)))
At this point , the cost to ( fpval - Delta , fpval ) is Delta + 2*p
(cond ((and (not CC) (<= N fpval)) (+ Delta (* 2 p)))
((and (not (negative? p-lim)) (>= p p-lim)) #f)
(else (loop (+ 1 p)))))))
If CC is supplied , set each CC[y ] = min(CC[y ] , cost ) for run .
(define (fp:run fp fpoff k A M B N CC p)
(define cost (+ k p p))
(let snloop ((y (max (+ (array-ref fp (+ -1 k fpoff)) 1)
(array-ref fp (+ 1 k fpoff)))))
(define x (- y k))
(and CC (<= y N)
(let ((xcst (- M x)))
(cond ((negative? xcst))
(else (array-set! CC
(min (+ xcst cost) (array-ref CC y))
y)))))
(cond ((and (< x M) (< y N)
(eqv? (array-ref A x) (array-ref B y)))
(snloop (+ 1 y)))
(else (array-set! fp y (+ fpoff k))
y))))
Check that only 1 and -1 steps between adjacent CC entries .
( else ( cond ( ( > 30 ( car ( array - dimensions CC ) ) )
" CC " ( append ( list ( max 0 ( + -5 cdx ) ) ' : ( min ( + 1 N ) ( + 5 cdx ) )
( array - dimensions CC ) )
( fp : subarray CC ( max 0 ( + -5 cdx ) ) ( min ( + 1 N ) ( + 5 cdx ) ) ) ) ) ) ) )
( define ( smooth - costs CC N )
(define (diff:mid-split N RR CC cost)
RR is not longer than CC . So do for each element of RR .
(let loop ((cdx (+ 1 (quotient N 2)))
(rdx (quotient N 2)))
( if ( negative ? rdx ) ( slib : error ' negative ? ' rdx ) )
(cond ((eqv? cost (+ (array-ref CC rdx) (array-ref RR (- N rdx)))) rdx)
((eqv? cost (+ (array-ref CC cdx) (array-ref RR (- N cdx)))) cdx)
(else (loop (+ 1 cdx) (+ -1 rdx))))))
(define (fp:subarray RA start end)
(define n-len (abs (- end start)))
(if (< end start)
(make-shared-array RA (lambda (idx) (list (+ -1 (- start idx)))) n-len)
(make-shared-array RA (lambda (idx) (list (+ start idx))) n-len)))
(define (fp:init! fp fpoff fill mindx maxdx)
(define mlim (+ fpoff mindx))
(do ((idx (+ fpoff maxdx) (+ -1 idx)))
((< idx mlim))
(array-set! fp fill idx)))
EDX is index into EDITS .
(define (diff:divide-and-conquer fp fpoff CCRR A start-a end-a B start-b end-b edits edx epo p-lim)
(define mid-a (quotient (+ start-a end-a) 2))
(define len-b (- end-b start-b))
(define len-a (- end-a start-a))
(let ((tcst (+ p-lim p-lim (- len-b len-a))))
(define CC (fp:subarray CCRR 0 (+ len-b 1)))
(define RR (fp:subarray CCRR (+ len-b 1) (* 2 (+ len-b 1))))
(define M2 (- end-a mid-a))
(define M1 (- mid-a start-a))
(fp:init! CC 0 (+ len-a len-b) 0 len-b)
(fp:init! fp fpoff -1 (- (+ 1 p-lim)) (+ 1 p-lim (- len-b M1)))
(fp:compare fp fpoff CC
(fp:subarray A start-a mid-a) M1
(fp:subarray B start-b end-b) len-b
(min p-lim len-a))
(fp:init! RR 0 (+ len-a len-b) 0 len-b)
(fp:init! fp fpoff -1 (- (+ 1 p-lim)) (+ 1 p-lim (- len-b M2)))
(fp:compare fp fpoff RR
(fp:subarray A end-a mid-a) M2
(fp:subarray B end-b start-b) len-b
(min p-lim len-a))
( smooth - costs ) ( smooth - costs )
(let ((b-splt (diff:mid-split len-b RR CC tcst)))
(define est-c (array-ref CC b-splt))
(define est-r (array-ref RR (- len-b b-splt)))
( print ' cc cc ) ( print ' rr ( fp : subarray RR ( + 1 len - b ) 0 ) )
( print ( make - string ( + 12 ( * 2 b - splt ) ) # \- ) ' ^ ( list b - splt ) )
(check-cost! 'CC est-c
(diff2et fp fpoff CCRR
A start-a mid-a
B start-b (+ start-b b-splt)
edits edx epo
(quotient (- est-c (- b-splt (- mid-a start-a)))
2)))
(check-cost! 'RR est-r
(diff2et fp fpoff CCRR
A mid-a end-a
B (+ start-b b-splt) end-b
edits (+ est-c edx) epo
(quotient (- est-r (- (- len-b b-splt)
(- end-a mid-a)))
2)))
(+ est-c est-r))))
(define (diff2et fp fpoff CCRR A start-a end-a B start-b end-b edits edx epo p-lim)
( if ( < ( - end - a start - a ) p - lim ) ( slib : warn ' diff2et ' len - a ( - end - a start - a ) ' len - b ( - end - b start - b ) ' p - lim p - lim ) )
(do ((bdx (+ -1 end-b) (+ -1 bdx))
(adx (+ -1 end-a) (+ -1 adx)))
((not (and (<= start-b bdx)
(<= start-a adx)
(eqv? (array-ref A adx) (array-ref B bdx))))
(do ((bsx start-b (+ 1 bsx))
(asx start-a (+ 1 asx)))
((not (and (< bsx bdx)
(< asx adx)
(eqv? (array-ref A asx) (array-ref B bsx))))
(let ((delta (- (- bdx bsx) (- adx asx))))
(if (negative? delta)
(diff2ez fp fpoff CCRR B bsx (+ 1 bdx) A asx (+ 1 adx)
edits edx (- epo) (+ delta p-lim))
(diff2ez fp fpoff CCRR A asx (+ 1 adx) B bsx (+ 1 bdx)
edits edx epo p-lim))))
))
))
Diff sub - arrays , A not longer than B. Returns edit - length
(define (diff2ez fp fpoff CCRR A start-a end-a B start-b end-b edits edx epo p-lim)
(define len-a (- end-a start-a))
(define len-b (- end-b start-b))
( if ( > len - a len - b ) ( slib : error ' > len - b ) )
(if (= len-b len-a)
(let loop ((adx start-a)
(bdx start-b)
(edx edx))
(cond ((>= bdx end-b) (- len-b len-a))
((>= adx end-a)
(do ((idx bdx (+ 1 idx))
(edx edx (+ 1 edx)))
((>= idx end-b) (- len-b len-a))
(array-set! edits (* epo (+ 1 idx)) edx)))
((eqv? (array-ref A adx) (array-ref B bdx))
(loop (+ 1 adx) (+ 1 bdx) edx))
(else (array-set! edits (* epo (+ 1 bdx)) edx)
(loop adx (+ 1 bdx) (+ 1 edx)))))))
( if ( p - lim ) ( slib : error ' p - lim p - lim ) )
(do ((idx start-a (+ 1 idx))
(jdx start-b (+ 1 jdx)))
((and (>= idx end-a) (>= jdx end-b)) (+ len-a len-b))
(cond ((< jdx end-b)
(array-set! edits (* epo (+ 1 jdx)) edx)
(set! edx (+ 1 edx))))
(cond ((< idx end-a)
(array-set! edits (* epo (- -1 idx)) edx)
(set! edx (+ 1 edx))))))
(else (diff:divide-and-conquer
fp fpoff CCRR A start-a end-a B start-b end-b
edits edx epo p-lim))))
(define (check-cost! name est cost)
(if (not (eqv? est cost))
(slib:warn name "cost check failed" est '!= cost)))
(define (diff:invert-edits! edits)
(define cost (car (array-dimensions edits)))
(do ((idx (+ -1 cost) (+ -1 idx)))
((negative? idx))
(array-set! edits (- (array-ref edits idx)) idx)))
(define (edits2lcs! lcs edits A)
(define cost (car (array-dimensions edits)))
(define len-a (car (array-dimensions A)))
(let loop ((edx 0)
(sdx 0)
(adx 0))
(let ((edit (if (< edx cost) (array-ref edits edx) 0)))
(cond ((>= adx len-a))
((positive? edit)
(loop (+ 1 edx) sdx adx))
((zero? edit)
(array-set! lcs (array-ref A adx) sdx)
(loop edx (+ 1 sdx) (+ 1 adx)))
((>= adx (- -1 edit))
(loop (+ 1 edx) sdx (+ 1 adx)))
(else
(array-set! lcs (array-ref A adx) sdx)
(loop edx (+ 1 sdx) (+ 1 adx)))))))
(define (diff2edits! edits fp CCRR A B)
(define N (car (array-dimensions B)))
(define M (car (array-dimensions A)))
(define est (car (array-dimensions edits)))
(let ((p-lim (quotient (- est (- N M)) 2)))
(check-cost! 'diff2edits!
est
(diff2et fp (+ 1 p-lim)
CCRR A 0 M B 0 N edits 0 1 p-lim))))
(define (diff2editlen fp A B p-lim)
(define N (car (array-dimensions B)))
(define M (car (array-dimensions A)))
(let ((maxdx (if (negative? p-lim) (+ 1 N) (+ 1 p-lim (- N M))))
(mindx (if (negative? p-lim) (- (+ 1 M)) (- (+ 1 p-lim)))))
(fp:init! fp (- mindx) -1 mindx maxdx)
(fp:compare fp (- mindx) #f A M B N p-lim)))
@args
@args array1 array2
@1 and @2 are one - dimensional arrays .
deletions of the shorter sequence to allow . @0 will return @code{#f }
@0 returns a one - dimensional array of length @code{(quotient ( - ( +
len1 len2 ) ( diff : edit - length @1 @2 ) ) 2 ) } holding the longest sequence
common to both @var{array}s .
(define (diff:longest-common-subsequence A B . p-lim)
(define M (car (array-dimensions A)))
(define N (car (array-dimensions B)))
(set! p-lim (if (null? p-lim) -1 (car p-lim)))
(let ((edits (if (< N M)
(diff:edits B A p-lim)
(diff:edits A B p-lim))))
(and edits
(let* ((cost (car (array-dimensions edits)))
(lcs (make-array A (/ (- (+ N M) cost) 2))))
(edits2lcs! lcs edits (if (< N M) B A))
lcs))))
@args
@args array1 array2
@1 and @2 are one - dimensional arrays .
deletions of the shorter sequence to allow . @0 will return @code{#f }
@0 returns a vector of length @code{(diff : edit - length @1 @2 ) } composed
of a shortest sequence of edits transformaing @1 to @2 .
@table @asis
@item @var{k } > 0
Inserts @code{(array - ref @1 ( + -1 } ) ) } into the sequence .
@item @var{k } < 0
(define (diff:edits A B . p-lim)
(define M (car (array-dimensions A)))
(define N (car (array-dimensions B)))
(define est (diff:edit-length A B (if (null? p-lim) -1 (car p-lim))))
(and est
(let ((CCRR (make-array (A:fixZ32b) (* 2 (+ (max M N) 1))))
(edits (make-array (A:fixZ32b) est)))
(define fp (make-array (A:fixZ32b)
(+ (max (- N (quotient M 2))
(- M (quotient N 2)))
2 * p - lim
3)))
(cond ((< N M)
(diff2edits! edits fp CCRR B A)
(diff:invert-edits! edits))
(else
(diff2edits! edits fp CCRR A B)))
edits)))
@args
@args array1 array2
@1 and @2 are one - dimensional arrays .
deletions of the shorter sequence to allow . @0 will return @code{#f }
@0 returns the length of the shortest sequence of edits transformaing
@1 to @2 .
(define (diff:edit-length A B . p-lim)
(define M (car (array-dimensions A)))
(define N (car (array-dimensions B)))
(set! p-lim (if (null? p-lim) -1 (car p-lim)))
(let ((fp (make-array (A:fixZ32b) (if (negative? p-lim)
(+ 3 M N)
(+ 3 (abs (- N M)) p-lim p-lim)))))
(if (< N M)
(diff2editlen fp B A p-lim)
(diff2editlen fp A B p-lim))))
( diff : longest - common - subsequence " " " fgehijkpqrlm " )
@result { } " "
( diff : edit - length " " " fgehijkpqrlm " )
@result { } 6
( diff : edits " " " fgehijkpqrlm " )
|
441dbe69774c5689d18f27043e8d5e44f31fe6df5be643306573334d4a4cee4a | theurere/berkeley_cs61a_spring-2011_archive | explorin.scm | Library files for Exploring Computer Science with Scheme
Revised April 2002 by
Version 2.02.0 2002/04/26 02:22:06
;
; Contents
; truncate (redefined to give exact number)
; round (redefined to give exact number)
first , second , third , fourth , fifth , rest
subseq
; position, remove, count (all use equal? for comparison)
; atom?
; find-if, find-if-not, count-if, count-if-not, remove-if, keep-if
; rassoc (uses equal? for comparison)
; every, any, some
; accumulate, accumulate-tail, reduce, reduce-tail
; intersection, union, set-difference, subset?, adjoin
random , init - random ( now using )
; Removed redefinitions of define/set!
;
;; Tells us which file's (simply or explorin) definitions take precedence
;; if they conflict
(define (explorinOrSimply)
"explorin")
; Assumptions - function error exists
; Add the following code if error does not exist in your version of LISP
; (define error-setup 'init)
;
; (call-with-current-continuation
; (lambda (stop)
; (set! error-setup stop)))
;
; Print an error message made up of the arguments to the function.
; (define error
( let ( ( newline newline ) ( display display ) ( car car ) ( )
; (for-each for-each) (error-setup error-setup))
; (lambda vals
; (newline)
; (display "Error: ")
; (display (car vals))
( for - each ( lambda ( ) ( display " " ) ( display ) ) ( cdr vals ) )
; (error-setup '.))))
; Redefine truncate to return an exact integer.
(set! truncate
(let ((truncate truncate) (inexact->exact inexact->exact))
(lambda (number)
(inexact->exact (truncate number)))))
; Redefine round to return an exact integer.
(set! round
(let ((round round) (inexact->exact inexact->exact))
(lambda (number)
(inexact->exact (round number)))))
Return the first element of a list .
(define first car)
Return the second element of a list .
(define second cadr)
Return the third element of a list .
(define third caddr)
Return the fourth element of a list .
(define fourth cadddr)
Return the fifth element of a list .
(define fifth
(let ((car car) (cddddr cddddr))
(lambda (lst)
(car (cddddr lst)))))
; Return the rest of a list.
(define rest cdr)
Returns list without last num elements ( like butlast in Common LISP ) .
(define list-head
(let ((>= >=) (length length) (= =) (cons cons) (car car) (cdr cdr))
(lambda (lst num)
(cond ((>= num (length lst)) '())
((= num 0) lst)
(else (cons (car lst) (list-head (cdr lst) num)))))))
Returns subsection of lst from positions start to end-1 .
(define subseq
(let ((length length) (null? null?) (not not) (<= <=)
(error error) (list-head list-head) (list-tail list-tail))
(lambda (lst start . args)
(let* ((len (length lst))
(end (if (null? args) len (car args))))
(cond ((not (<= 0 start len))
(error "Improper start value for subseq:" start))
((not (<= 0 start end len))
(error "Improper end value for subseq:" end))
(else
(list-head (list-tail lst start) (- len end))))))))
Returns the position ( base 0 ) of the first occurrence of elt in lst .
(define position-helper
(let ((null? null?) (equal? equal?) (car car) (cdr cdr) (+ +))
(lambda (elt lst num)
(cond ((null? lst) #f)
((equal? elt (car lst)) num)
(else (position-helper elt (cdr lst) (+ num 1)))))))
(define position
(let ((position-helper position-helper))
(lambda (elt lst)
(position-helper elt lst 0))))
; Returns new list with all occurrences of elt removed.
(define remove
(let ((null? null?) (equal? equal?) (car car) (cdr cdr) (cons cons))
(lambda (elt lst)
(cond ((null? lst) '())
((equal? elt (car lst)) (remove elt (cdr lst)))
(else (cons (car lst) (remove elt (cdr lst))))))))
Returns the number of times elt occurs in lst .
(define count
(let ((null? null?) (equal? equal?) (car car) (cdr cdr) (+ +))
(lambda (elt lst)
(cond ((null? lst) 0)
((equal? elt (car lst)) (+ 1 (count elt (cdr lst))))
(else (count elt (cdr lst)))))))
; Returns #t if item is a symbol or a number, #f otherwise.
(define atom?
(let ((symbol? symbol?) (number? number?))
(lambda (item)
(or (symbol? item) (number? item)))))
Returns the first element in lst that satisfies func , # f if no elements
; satisfy func.
(define find-if
(let ((null? null?) (car car) (cdr cdr))
(lambda (func lst)
(cond ((null? lst) #f)
((func (car lst)) (car lst))
(else (find-if func (cdr lst)))))))
Returns the first element in lst that does not satisfy func , # f if all
; elements satisfy func.
(define find-if-not
(let ((null? null?) (not not) (car car) (cdr cdr))
(lambda (func lst)
(cond ((null? lst) #f)
((not (func (car lst))) (car lst))
(else (find-if-not func (cdr lst)))))))
Returns the number of elements in lst that satisfy func .
(define count-if
(let ((null? null?) (car car) (cdr cdr) (+ +))
(lambda (func lst)
(cond ((null? lst) 0)
((func (car lst)) (+ 1 (count-if func (cdr lst))))
(else (count-if func (cdr lst)))))))
Returns the number of elements in lst that do not satisfy func .
(define count-if-not
(let ((null? null?) (not not) (car car) (cdr cdr) (+ +))
(lambda (func lst)
(cond ((null? lst) 0)
((not (func (car lst))) (+ 1 (count-if-not func (cdr lst))))
(else (count-if-not func (cdr lst)))))))
; Returns new list with all elements satisfying func removed.
(define remove-if
(let ((null? null?) (car car) (cdr cdr) (cons cons))
(lambda (func lst)
(cond ((null? lst) '())
((func (car lst))
(remove-if func (cdr lst)))
(else
(cons (car lst) (remove-if func (cdr lst))))))))
; Returns new list with all elements satisfying func.
(define keep-if
(let ((null? null?) (not not) (car car) (cdr cdr) (cons cons))
(lambda (func lst)
(cond ((null? lst) '())
((not (func (car lst)))
(keep-if func (cdr lst)))
(else
(cons (car lst) (keep-if func (cdr lst))))))))
Like assoc but returns the first pair whose cdr matches elt .
; 2.0: Uses equal? for comparison, by analogy with assoc.
(define rassoc
(let ((find-if find-if) (equal? equal?) (cdr cdr))
(lambda (elt assoc-list)
(find-if (lambda (dotted-pair)
(equal? (cdr dotted-pair) elt))
assoc-list))))
; every and any each take a variable number of lists as arguments and
; apply the function to those N lists using apply and map. To make the
; recursive call, apply is used to convert a list of argument lists into
; separate arguments.
; Returns #t if all successive elements in lists satisfy func, #f otherwise.
(define every
(let ((null? null?) (car car) (cdr cdr) (apply apply) (map map) (cons cons)
(member member))
(lambda (func . lists)
(cond ((member #t (map null? lists)) #t)
((member #t (map (lambda (lst) (null? (cdr lst))) lists))
(apply func (map car lists)))
(else
(and (apply func (map car lists))
(apply every (cons func (map cdr lists)))))))))
Return the first true value from applying func to successive
; elements in lists, or #f if no elements satisfy func.
;
; 2.0: some is another name for any.
(define any
(let ((null? null?) (car car) (cdr cdr) (apply apply) (map map) (cons cons)
(member member))
(lambda (func . lists)
(if (member #t (map null? lists))
#f
(or (apply func (map first lists))
(apply any (cons func (map rest lists))))))))
(define some any)
Returns result of applying func to elements of lst in the following manner :
func is applied to the first two elements of lst then to that result and the
third element , then to that result and the fourth element , and so on until
; all elements have been applied.
;
; 2.0: accumulate-tail is a helper function for accumulate. reduce and
; reduce-tail are the old-school COMMON LISP names for these functions.
(define accumulate-tail
(let ((null? null?) (car car) (cdr cdr))
(lambda (func lst answer)
(if (null? lst)
answer
(accumulate-tail func (cdr lst) (func answer (car lst)))))))
(define reduce-tail accumulate-tail)
(define accumulate
(let ((null? null?) (car car) (cdr cdr) (accumulate-tail accumulate-tail))
(lambda (func lst)
(if (null? lst)
(func)
(accumulate-tail func (cdr lst) (car lst))))))
(define reduce accumulate)
Returns the elements that set1 and set2 have in common .
(define intersection
(let ((null? null?) (member member) (car car) (cdr cdr) (cons cons))
(lambda (set1 set2)
(cond ((or (null? set1) (null? set2))
'())
((member (car set1) set2)
(cons (car set1) (intersection (cdr set1) set2)))
(else
(intersection (cdr set1) set2))))))
Returns the elements that exist in either set1 or set2 .
(define union
(let ((null? null?) (member member) (car car) (cdr cdr) (cons cons))
(lambda (set1 set2)
(cond ((null? set1)
set2)
((member (car set1) set2)
(union (cdr set1) set2))
(else
(cons (car set1) (union (cdr set1) set2)))))))
Returns the elements that exist in set1 but not in set2 .
(define set-difference
(let ((null? null?) (member member) (car car) (cdr cdr) (cons cons))
(lambda (set1 set2)
(cond ((null? set2)
set1)
((null? set1)
'())
((member (car set1) set2)
(set-difference (cdr set1) set2))
(else
(cons (car set1) (set-difference (cdr set1) set2)))))))
Returns # t if all the elements in set1 exist in set2 .
(define subset?
(let ((null? null?) (member member) (car car) (cdr cdr))
(lambda (set1 set2)
(cond ((null? set1)
#t)
((null? set2)
#f)
(else
(and (member (car set1) set2)
(subset? (cdr set1) set2)))))))
; Returns a new set of item and the elements in set if item does not exist
; in set, otherwise returns set.
(define adjoin
(let ((member member) (cons cons))
(lambda (item set)
(if (member item set)
set
(cons item set)))))
2.0 : has random built in . It takes a single argument .
; (random N) returns a pseudorandom number between 0 and N-1 inclusive.
; It needs a little initialization in order to give interesting numbers:
(require "posix")
(set-random-seed! (posix-time))
2.0 : has init - random built in , but under a different name .
(define (init-random seed)
(set-random-seed! seed))
(define remove!
(let ((null? null?)
(cdr cdr)
(eq? eq?)
(set-cdr! set-cdr!)
(car car))
(lambda (thing lst)
(define (r! prev)
(cond ((null? (cdr prev)) lst)
((eq? thing (car (cdr prev)))
(set-cdr! prev (cdr (cdr prev)))
lst)
(else (r! (cdr prev)))))
(cond ((null? lst) lst)
((eq? thing (car lst)) (cdr lst))
(else (r! lst))))))
(provide "explorin")
| null | https://raw.githubusercontent.com/theurere/berkeley_cs61a_spring-2011_archive/1d90036a0a76c62933753ad71f8dcccbbbd37ae4/code/src/ucb/bscheme/explorin.scm | scheme |
Contents
truncate (redefined to give exact number)
round (redefined to give exact number)
position, remove, count (all use equal? for comparison)
atom?
find-if, find-if-not, count-if, count-if-not, remove-if, keep-if
rassoc (uses equal? for comparison)
every, any, some
accumulate, accumulate-tail, reduce, reduce-tail
intersection, union, set-difference, subset?, adjoin
Removed redefinitions of define/set!
Tells us which file's (simply or explorin) definitions take precedence
if they conflict
Assumptions - function error exists
Add the following code if error does not exist in your version of LISP
(define error-setup 'init)
(call-with-current-continuation
(lambda (stop)
(set! error-setup stop)))
Print an error message made up of the arguments to the function.
(define error
(for-each for-each) (error-setup error-setup))
(lambda vals
(newline)
(display "Error: ")
(display (car vals))
(error-setup '.))))
Redefine truncate to return an exact integer.
Redefine round to return an exact integer.
Return the rest of a list.
Returns new list with all occurrences of elt removed.
Returns #t if item is a symbol or a number, #f otherwise.
satisfy func.
elements satisfy func.
Returns new list with all elements satisfying func removed.
Returns new list with all elements satisfying func.
2.0: Uses equal? for comparison, by analogy with assoc.
every and any each take a variable number of lists as arguments and
apply the function to those N lists using apply and map. To make the
recursive call, apply is used to convert a list of argument lists into
separate arguments.
Returns #t if all successive elements in lists satisfy func, #f otherwise.
elements in lists, or #f if no elements satisfy func.
2.0: some is another name for any.
all elements have been applied.
2.0: accumulate-tail is a helper function for accumulate. reduce and
reduce-tail are the old-school COMMON LISP names for these functions.
Returns a new set of item and the elements in set if item does not exist
in set, otherwise returns set.
(random N) returns a pseudorandom number between 0 and N-1 inclusive.
It needs a little initialization in order to give interesting numbers: | Library files for Exploring Computer Science with Scheme
Revised April 2002 by
Version 2.02.0 2002/04/26 02:22:06
first , second , third , fourth , fifth , rest
subseq
random , init - random ( now using )
(define (explorinOrSimply)
"explorin")
( let ( ( newline newline ) ( display display ) ( car car ) ( )
( for - each ( lambda ( ) ( display " " ) ( display ) ) ( cdr vals ) )
(set! truncate
(let ((truncate truncate) (inexact->exact inexact->exact))
(lambda (number)
(inexact->exact (truncate number)))))
(set! round
(let ((round round) (inexact->exact inexact->exact))
(lambda (number)
(inexact->exact (round number)))))
Return the first element of a list .
(define first car)
Return the second element of a list .
(define second cadr)
Return the third element of a list .
(define third caddr)
Return the fourth element of a list .
(define fourth cadddr)
Return the fifth element of a list .
(define fifth
(let ((car car) (cddddr cddddr))
(lambda (lst)
(car (cddddr lst)))))
(define rest cdr)
Returns list without last num elements ( like butlast in Common LISP ) .
(define list-head
(let ((>= >=) (length length) (= =) (cons cons) (car car) (cdr cdr))
(lambda (lst num)
(cond ((>= num (length lst)) '())
((= num 0) lst)
(else (cons (car lst) (list-head (cdr lst) num)))))))
Returns subsection of lst from positions start to end-1 .
(define subseq
(let ((length length) (null? null?) (not not) (<= <=)
(error error) (list-head list-head) (list-tail list-tail))
(lambda (lst start . args)
(let* ((len (length lst))
(end (if (null? args) len (car args))))
(cond ((not (<= 0 start len))
(error "Improper start value for subseq:" start))
((not (<= 0 start end len))
(error "Improper end value for subseq:" end))
(else
(list-head (list-tail lst start) (- len end))))))))
Returns the position ( base 0 ) of the first occurrence of elt in lst .
(define position-helper
(let ((null? null?) (equal? equal?) (car car) (cdr cdr) (+ +))
(lambda (elt lst num)
(cond ((null? lst) #f)
((equal? elt (car lst)) num)
(else (position-helper elt (cdr lst) (+ num 1)))))))
(define position
(let ((position-helper position-helper))
(lambda (elt lst)
(position-helper elt lst 0))))
(define remove
(let ((null? null?) (equal? equal?) (car car) (cdr cdr) (cons cons))
(lambda (elt lst)
(cond ((null? lst) '())
((equal? elt (car lst)) (remove elt (cdr lst)))
(else (cons (car lst) (remove elt (cdr lst))))))))
Returns the number of times elt occurs in lst .
(define count
(let ((null? null?) (equal? equal?) (car car) (cdr cdr) (+ +))
(lambda (elt lst)
(cond ((null? lst) 0)
((equal? elt (car lst)) (+ 1 (count elt (cdr lst))))
(else (count elt (cdr lst)))))))
(define atom?
(let ((symbol? symbol?) (number? number?))
(lambda (item)
(or (symbol? item) (number? item)))))
Returns the first element in lst that satisfies func , # f if no elements
(define find-if
(let ((null? null?) (car car) (cdr cdr))
(lambda (func lst)
(cond ((null? lst) #f)
((func (car lst)) (car lst))
(else (find-if func (cdr lst)))))))
Returns the first element in lst that does not satisfy func , # f if all
(define find-if-not
(let ((null? null?) (not not) (car car) (cdr cdr))
(lambda (func lst)
(cond ((null? lst) #f)
((not (func (car lst))) (car lst))
(else (find-if-not func (cdr lst)))))))
Returns the number of elements in lst that satisfy func .
(define count-if
(let ((null? null?) (car car) (cdr cdr) (+ +))
(lambda (func lst)
(cond ((null? lst) 0)
((func (car lst)) (+ 1 (count-if func (cdr lst))))
(else (count-if func (cdr lst)))))))
Returns the number of elements in lst that do not satisfy func .
(define count-if-not
(let ((null? null?) (not not) (car car) (cdr cdr) (+ +))
(lambda (func lst)
(cond ((null? lst) 0)
((not (func (car lst))) (+ 1 (count-if-not func (cdr lst))))
(else (count-if-not func (cdr lst)))))))
(define remove-if
(let ((null? null?) (car car) (cdr cdr) (cons cons))
(lambda (func lst)
(cond ((null? lst) '())
((func (car lst))
(remove-if func (cdr lst)))
(else
(cons (car lst) (remove-if func (cdr lst))))))))
(define keep-if
(let ((null? null?) (not not) (car car) (cdr cdr) (cons cons))
(lambda (func lst)
(cond ((null? lst) '())
((not (func (car lst)))
(keep-if func (cdr lst)))
(else
(cons (car lst) (keep-if func (cdr lst))))))))
Like assoc but returns the first pair whose cdr matches elt .
(define rassoc
(let ((find-if find-if) (equal? equal?) (cdr cdr))
(lambda (elt assoc-list)
(find-if (lambda (dotted-pair)
(equal? (cdr dotted-pair) elt))
assoc-list))))
(define every
(let ((null? null?) (car car) (cdr cdr) (apply apply) (map map) (cons cons)
(member member))
(lambda (func . lists)
(cond ((member #t (map null? lists)) #t)
((member #t (map (lambda (lst) (null? (cdr lst))) lists))
(apply func (map car lists)))
(else
(and (apply func (map car lists))
(apply every (cons func (map cdr lists)))))))))
Return the first true value from applying func to successive
(define any
(let ((null? null?) (car car) (cdr cdr) (apply apply) (map map) (cons cons)
(member member))
(lambda (func . lists)
(if (member #t (map null? lists))
#f
(or (apply func (map first lists))
(apply any (cons func (map rest lists))))))))
(define some any)
Returns result of applying func to elements of lst in the following manner :
func is applied to the first two elements of lst then to that result and the
third element , then to that result and the fourth element , and so on until
(define accumulate-tail
(let ((null? null?) (car car) (cdr cdr))
(lambda (func lst answer)
(if (null? lst)
answer
(accumulate-tail func (cdr lst) (func answer (car lst)))))))
(define reduce-tail accumulate-tail)
(define accumulate
(let ((null? null?) (car car) (cdr cdr) (accumulate-tail accumulate-tail))
(lambda (func lst)
(if (null? lst)
(func)
(accumulate-tail func (cdr lst) (car lst))))))
(define reduce accumulate)
Returns the elements that set1 and set2 have in common .
(define intersection
(let ((null? null?) (member member) (car car) (cdr cdr) (cons cons))
(lambda (set1 set2)
(cond ((or (null? set1) (null? set2))
'())
((member (car set1) set2)
(cons (car set1) (intersection (cdr set1) set2)))
(else
(intersection (cdr set1) set2))))))
Returns the elements that exist in either set1 or set2 .
(define union
(let ((null? null?) (member member) (car car) (cdr cdr) (cons cons))
(lambda (set1 set2)
(cond ((null? set1)
set2)
((member (car set1) set2)
(union (cdr set1) set2))
(else
(cons (car set1) (union (cdr set1) set2)))))))
Returns the elements that exist in set1 but not in set2 .
(define set-difference
(let ((null? null?) (member member) (car car) (cdr cdr) (cons cons))
(lambda (set1 set2)
(cond ((null? set2)
set1)
((null? set1)
'())
((member (car set1) set2)
(set-difference (cdr set1) set2))
(else
(cons (car set1) (set-difference (cdr set1) set2)))))))
Returns # t if all the elements in set1 exist in set2 .
(define subset?
(let ((null? null?) (member member) (car car) (cdr cdr))
(lambda (set1 set2)
(cond ((null? set1)
#t)
((null? set2)
#f)
(else
(and (member (car set1) set2)
(subset? (cdr set1) set2)))))))
(define adjoin
(let ((member member) (cons cons))
(lambda (item set)
(if (member item set)
set
(cons item set)))))
2.0 : has random built in . It takes a single argument .
(require "posix")
(set-random-seed! (posix-time))
2.0 : has init - random built in , but under a different name .
(define (init-random seed)
(set-random-seed! seed))
(define remove!
(let ((null? null?)
(cdr cdr)
(eq? eq?)
(set-cdr! set-cdr!)
(car car))
(lambda (thing lst)
(define (r! prev)
(cond ((null? (cdr prev)) lst)
((eq? thing (car (cdr prev)))
(set-cdr! prev (cdr (cdr prev)))
lst)
(else (r! (cdr prev)))))
(cond ((null? lst) lst)
((eq? thing (car lst)) (cdr lst))
(else (r! lst))))))
(provide "explorin")
|
e66acc1f5b38f12b5ee97319ef9c22ce06c028b238c8806147b1b63e4ec3fee6 | eeng/shevek | profile_test.clj | (ns shevek.acceptance.profile-test
(:require [clojure.test :refer [deftest use-fixtures is]]
[shevek.acceptance.test-helper :refer [wrap-acceptance-tests it login click click-text visit fill has-css? has-text? click-tid select clear-preferences]]
[etaoin.keys :as k]))
(use-fixtures :once wrap-acceptance-tests)
(use-fixtures :once {:after clear-preferences})
(deftest ^:acceptance profile-tests
(it "changing the app language"
(login)
(click-tid "sidebar-profile")
(select {:data-tid "lang"} "Español")
(click-text "Save")
(is (has-css? "#notification" :text "Preferences saved!"))
(is (has-text? "Preferencias")))
(it "the current password mast match"
(login {:username "max" :fullname "Max" :password "secret999"})
(click-tid "sidebar-profile")
(is (has-css? ".page-title" :text "Max"))
(click-text "Change Password")
(fill {:name "current-password"} "nop" k/enter)
(is (has-css? ".red.label" :text "is incorrect"))
(is (has-css? ".page-title" :text "Max")))
(it "changing the fullname"
(login {:username "max" :fullname "Max" :password "secret999"})
(click-tid "sidebar-profile")
(click-text "Change Password")
(fill {:name "fullname"} (k/with-shift k/home) k/delete "Mex")
(fill {:name "current-password"} "secret999" k/enter)
(is (has-css? "#notification" :text "Your account has been saved"))
(is (has-css? ".page-title" :text "Mex"))))
| null | https://raw.githubusercontent.com/eeng/shevek/7783b8037303b8dd5f320f35edee3bfbb2b41c02/test/clj/shevek/acceptance/profile_test.clj | clojure | (ns shevek.acceptance.profile-test
(:require [clojure.test :refer [deftest use-fixtures is]]
[shevek.acceptance.test-helper :refer [wrap-acceptance-tests it login click click-text visit fill has-css? has-text? click-tid select clear-preferences]]
[etaoin.keys :as k]))
(use-fixtures :once wrap-acceptance-tests)
(use-fixtures :once {:after clear-preferences})
(deftest ^:acceptance profile-tests
(it "changing the app language"
(login)
(click-tid "sidebar-profile")
(select {:data-tid "lang"} "Español")
(click-text "Save")
(is (has-css? "#notification" :text "Preferences saved!"))
(is (has-text? "Preferencias")))
(it "the current password mast match"
(login {:username "max" :fullname "Max" :password "secret999"})
(click-tid "sidebar-profile")
(is (has-css? ".page-title" :text "Max"))
(click-text "Change Password")
(fill {:name "current-password"} "nop" k/enter)
(is (has-css? ".red.label" :text "is incorrect"))
(is (has-css? ".page-title" :text "Max")))
(it "changing the fullname"
(login {:username "max" :fullname "Max" :password "secret999"})
(click-tid "sidebar-profile")
(click-text "Change Password")
(fill {:name "fullname"} (k/with-shift k/home) k/delete "Mex")
(fill {:name "current-password"} "secret999" k/enter)
(is (has-css? "#notification" :text "Your account has been saved"))
(is (has-css? ".page-title" :text "Mex"))))
| |
7e85fd2c96962ddd323299c512852af5a7dbb4f96304cb0b255c8a6133c74a74 | janestreet/username_kernel | username.ml | open! Core
include
String_id.Make
(struct
let module_name = "Username_kernel.Username"
end)
()
| null | https://raw.githubusercontent.com/janestreet/username_kernel/3ee803e1b422d261d31bc45fa65ae9a28634557d/src/username.ml | ocaml | open! Core
include
String_id.Make
(struct
let module_name = "Username_kernel.Username"
end)
()
| |
b8c150cd264b54ca04264d11c5356133374b07d0f2ad78b768ba914d8a0bb936 | thoughtstem/minetest | items.rkt | #lang racket
(provide define-item)
(require 2htdp/image)
(require "core.rkt")
(require (for-syntax racket/syntax))
;(struct item-struct asset-struct (image) #:transparent)
;Was a struct... not anymore...
(define (item-struct id desc img m)
(asset-struct id desc (make-immutable-hash
(list
(cons 'inventory_image
(compileable-image m id img))
))
m))
(define-syntax (define-item stx)
(syntax-case stx ()
[(_ id desc image)
(with-syntax* ([item-id (format-id stx "~a" #'id)]
[name (symbol->string (format-symbol "~a" #'id))])
#`(begin
(define id (item-struct name desc image my-mod))
(set-my-mod! (add-item my-mod id)))
)]))
i d desc
;;Makes a stub -- e.g. for default:stone
(define (default-item id)
(item-struct (++ "" id)
(++ "The default " id)
(circle 0 "solid" "transparent")
default-mod))
(define-syntax (define-default-item stx)
(syntax-case stx ()
[(_ x )
(with-syntax* ([name (symbol->string (format-symbol "default:~a" #'x))])
#`(begin
(define x (default-item name) )
(provide x)
) ) ]))
(define-syntax (define-default-items stx)
(syntax-case stx ()
[(_ x ... )
#`(begin
(define-default-item x ) ...
) ]))
(define-default-items
stick
paper
book
book_written
skeleton_key
coal_lump
iron_lump
copper_lump
tin_lump
mese_crystal
gold_lump
diamond
clay_lump
steel_ingot
copper_ingot
tin_ingot
bronze_ingot
gold_ingot
mese_crystal_fragment
clay_brick
obsidian_shard
flint
pick_wood
pick_stone
pick_steel
pick_bronze
pick_mese
pick_diamond
shovel_wood
shovel_stone
shovel_steel
shovel_bronze
shovel_mese
shovel_diamond
axe_wood
axe_stone
axe_steel
axe_bronze
axe_mese
axe_diamond
sword_wood
sword_stone
sword_steel
sword_bronze
sword_mese
sword_diamond
key)
| null | https://raw.githubusercontent.com/thoughtstem/minetest/74ba2d02511e96bfc477ab6db4937d1732bd1e2b/items.rkt | racket | (struct item-struct asset-struct (image) #:transparent)
Was a struct... not anymore...
Makes a stub -- e.g. for default:stone | #lang racket
(provide define-item)
(require 2htdp/image)
(require "core.rkt")
(require (for-syntax racket/syntax))
(define (item-struct id desc img m)
(asset-struct id desc (make-immutable-hash
(list
(cons 'inventory_image
(compileable-image m id img))
))
m))
(define-syntax (define-item stx)
(syntax-case stx ()
[(_ id desc image)
(with-syntax* ([item-id (format-id stx "~a" #'id)]
[name (symbol->string (format-symbol "~a" #'id))])
#`(begin
(define id (item-struct name desc image my-mod))
(set-my-mod! (add-item my-mod id)))
)]))
i d desc
(define (default-item id)
(item-struct (++ "" id)
(++ "The default " id)
(circle 0 "solid" "transparent")
default-mod))
(define-syntax (define-default-item stx)
(syntax-case stx ()
[(_ x )
(with-syntax* ([name (symbol->string (format-symbol "default:~a" #'x))])
#`(begin
(define x (default-item name) )
(provide x)
) ) ]))
(define-syntax (define-default-items stx)
(syntax-case stx ()
[(_ x ... )
#`(begin
(define-default-item x ) ...
) ]))
(define-default-items
stick
paper
book
book_written
skeleton_key
coal_lump
iron_lump
copper_lump
tin_lump
mese_crystal
gold_lump
diamond
clay_lump
steel_ingot
copper_ingot
tin_ingot
bronze_ingot
gold_ingot
mese_crystal_fragment
clay_brick
obsidian_shard
flint
pick_wood
pick_stone
pick_steel
pick_bronze
pick_mese
pick_diamond
shovel_wood
shovel_stone
shovel_steel
shovel_bronze
shovel_mese
shovel_diamond
axe_wood
axe_stone
axe_steel
axe_bronze
axe_mese
axe_diamond
sword_wood
sword_stone
sword_steel
sword_bronze
sword_mese
sword_diamond
key)
|
e6b05c416714a94a1c75d718e8f310ca5e0aff590b0463f0d25d68e58bbe11f8 | RefactoringTools/HaRe | tokens.hs |
import TestUtils
import SrcLoc
import Panic
import Lexer
main = do
(t,toks) <- parsedFileGhc "./test/testdata/MoveDef/Md1.hs"
let s = showRichTokenStream' toks
putStrLn s
putStrLn "----------------------------------------"
putStrLn (show $ filter (\(_,s) -> s == "") toks)
Based on version from GHC source
-- | Take a rich token stream such as produced from 'getRichTokenStream' and
-- return source code almost identical to the original code (except for
-- insignificant whitespace.)
showRichTokenStream' :: [(Located Token, String)] -> String
showRichTokenStream' ts = go startLoc ts ""
where sourceFile = getFile $ map (getLoc . fst) ts
getFile [] = panic "showRichTokenStream: No source file found"
getFile (UnhelpfulSpan _ : xs) = getFile xs
getFile (RealSrcSpan s : _) = srcSpanFile s
startLoc = mkRealSrcLoc sourceFile 1 1
go _ [] = id
go loc ((L span tok, str'):ts)
= case span of
UnhelpfulSpan _ -> go loc ts
RealSrcSpan s
| locLine == tokLine -> ((replicate (tokCol - locCol) ' ') ++)
. (str ++)
. go tokEnd ts
| otherwise -> ((replicate (tokLine - locLine) '\n') ++)
. ((replicate tokCol ' ') ++)
. (str ++)
. go tokEnd ts
where (locLine, locCol) = (srcLocLine loc, srcLocCol loc)
(tokLine, tokCol) = (srcSpanStartLine s, srcSpanStartCol s)
tokEnd = realSrcSpanEnd s
-- mark the position of the hidden tokens
str = case str' of
"" -> case tok of
ITvocurly -> "*{*"
ITsemi -> "*;*"
ITvccurly -> "*}*"
_ -> "{|}"
_ -> str'
| null | https://raw.githubusercontent.com/RefactoringTools/HaRe/ef5dee64c38fb104e6e5676095946279fbce381c/test/tokens.hs | haskell | | Take a rich token stream such as produced from 'getRichTokenStream' and
return source code almost identical to the original code (except for
insignificant whitespace.)
mark the position of the hidden tokens |
import TestUtils
import SrcLoc
import Panic
import Lexer
main = do
(t,toks) <- parsedFileGhc "./test/testdata/MoveDef/Md1.hs"
let s = showRichTokenStream' toks
putStrLn s
putStrLn "----------------------------------------"
putStrLn (show $ filter (\(_,s) -> s == "") toks)
Based on version from GHC source
showRichTokenStream' :: [(Located Token, String)] -> String
showRichTokenStream' ts = go startLoc ts ""
where sourceFile = getFile $ map (getLoc . fst) ts
getFile [] = panic "showRichTokenStream: No source file found"
getFile (UnhelpfulSpan _ : xs) = getFile xs
getFile (RealSrcSpan s : _) = srcSpanFile s
startLoc = mkRealSrcLoc sourceFile 1 1
go _ [] = id
go loc ((L span tok, str'):ts)
= case span of
UnhelpfulSpan _ -> go loc ts
RealSrcSpan s
| locLine == tokLine -> ((replicate (tokCol - locCol) ' ') ++)
. (str ++)
. go tokEnd ts
| otherwise -> ((replicate (tokLine - locLine) '\n') ++)
. ((replicate tokCol ' ') ++)
. (str ++)
. go tokEnd ts
where (locLine, locCol) = (srcLocLine loc, srcLocCol loc)
(tokLine, tokCol) = (srcSpanStartLine s, srcSpanStartCol s)
tokEnd = realSrcSpanEnd s
str = case str' of
"" -> case tok of
ITvocurly -> "*{*"
ITsemi -> "*;*"
ITvccurly -> "*}*"
_ -> "{|}"
_ -> str'
|
90e80a5b0ae9ca4dae92f59c3705a9069e05fb798ef550816b8768287d686c37 | JacquesCarette/Drasil | Main.hs | module Main (main) where
import GHC.IO.Encoding
import Language.Drasil.Generate (gen, typeCheckSI, genCode, genDot, genLog, DocSpec(DocSpec), DocType(SRS), Format(..), docChoices)
import Drasil.NoPCM.Body (srs, printSetting, fullSI)
import Drasil.NoPCM.Choices (choices, code)
main :: IO ()
main = do
setLocaleEncoding utf8
typeCheckSI fullSI
gen (DocSpec (docChoices SRS [HTML, TeX, JSON]) "NoPCM_SRS") srs printSetting
genCode choices code
genDot fullSI
genLog fullSI printSetting
| null | https://raw.githubusercontent.com/JacquesCarette/Drasil/98c6e2e81bc1479010ce71b22960ab214a891159/code/drasil-example/nopcm/app/Main.hs | haskell | module Main (main) where
import GHC.IO.Encoding
import Language.Drasil.Generate (gen, typeCheckSI, genCode, genDot, genLog, DocSpec(DocSpec), DocType(SRS), Format(..), docChoices)
import Drasil.NoPCM.Body (srs, printSetting, fullSI)
import Drasil.NoPCM.Choices (choices, code)
main :: IO ()
main = do
setLocaleEncoding utf8
typeCheckSI fullSI
gen (DocSpec (docChoices SRS [HTML, TeX, JSON]) "NoPCM_SRS") srs printSetting
genCode choices code
genDot fullSI
genLog fullSI printSetting
| |
f194d661059c84f78f7173384b784d63fa4364208ebd94c494c8a92a744bb411 | ProjectMAC/propagators | load.scm | ;;; ----------------------------------------------------------------------
Copyright 2010 and
;;; ----------------------------------------------------------------------
This file is part of Propagator Network Prototype .
;;;
Propagator Network Prototype is free software ; you can
;;; redistribute it and/or modify it under the terms of the GNU
General Public License as published by the Free Software
Foundation , either version 3 of the License , or ( at your option )
;;; any later version.
;;;
Propagator Network Prototype is distributed in the hope that it
;;; will be useful, but WITHOUT ANY WARRANTY; without even the implied
;;; warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
;;; See the GNU General Public License for more details.
;;;
You should have received a copy of the GNU General Public License
along with Propagator Network Prototype . If not , see
;;; </>.
;;; ----------------------------------------------------------------------
(define (self-relatively thunk)
(let ((place (ignore-errors current-load-pathname)))
(if (pathname? place)
(with-working-directory-pathname
(directory-namestring place)
thunk)
(thunk))))
(define (load-relative filename)
(self-relatively (lambda () (load filename))))
(load-relative "../../extensions/load.scm")
(for-each load-relative-compiled
'("infrastructure"
"layered"
"parts"
"slices"
"examples"))
(maybe-warn-low-memory)
(initialize-scheduler)
| null | https://raw.githubusercontent.com/ProjectMAC/propagators/add671f009e62441e77735a88980b6b21fad7a79/explorations/circuits/load.scm | scheme | ----------------------------------------------------------------------
----------------------------------------------------------------------
you can
redistribute it and/or modify it under the terms of the GNU
any later version.
will be useful, but WITHOUT ANY WARRANTY; without even the implied
warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the GNU General Public License for more details.
</>.
---------------------------------------------------------------------- | Copyright 2010 and
This file is part of Propagator Network Prototype .
General Public License as published by the Free Software
Foundation , either version 3 of the License , or ( at your option )
Propagator Network Prototype is distributed in the hope that it
You should have received a copy of the GNU General Public License
along with Propagator Network Prototype . If not , see
(define (self-relatively thunk)
(let ((place (ignore-errors current-load-pathname)))
(if (pathname? place)
(with-working-directory-pathname
(directory-namestring place)
thunk)
(thunk))))
(define (load-relative filename)
(self-relatively (lambda () (load filename))))
(load-relative "../../extensions/load.scm")
(for-each load-relative-compiled
'("infrastructure"
"layered"
"parts"
"slices"
"examples"))
(maybe-warn-low-memory)
(initialize-scheduler)
|
5d88a14f67c78cde1b508bd90418ca7e16a13c542ec67b45e7ca665d29632565 | EveryTian/Haskell-Codewars | tongues.hs |
module Codewars.Exercise.Tongues where
import Data.Char (toUpper)
import Data.Maybe (fromMaybe)
swapTable :: [(Char, Char)]
-- abcdefghijklmnopqrstuvwxyz
swapTable = let table = "eplragfsoxvcwtibzdhnykmjuq"
in zip (['a'..'z'] ++ ['A'..'Z']) (table ++ map toUpper table)
swapChar :: Char -> Char
-- swapChar c = case lookup c swapTable of
-- Nothing -> c
-- Just c' -> c'
swapChar c = fromMaybe c $ lookup c swapTable
tongues :: String -> String
tongues = map swapChar
| null | https://raw.githubusercontent.com/EveryTian/Haskell-Codewars/dc48d95c676ce1a59f697d07672acb6d4722893b/5kyu/tongues.hs | haskell | abcdefghijklmnopqrstuvwxyz
swapChar c = case lookup c swapTable of
Nothing -> c
Just c' -> c' |
module Codewars.Exercise.Tongues where
import Data.Char (toUpper)
import Data.Maybe (fromMaybe)
swapTable :: [(Char, Char)]
swapTable = let table = "eplragfsoxvcwtibzdhnykmjuq"
in zip (['a'..'z'] ++ ['A'..'Z']) (table ++ map toUpper table)
swapChar :: Char -> Char
swapChar c = fromMaybe c $ lookup c swapTable
tongues :: String -> String
tongues = map swapChar
|
dff95064d5511c3b901a85a001931a9520db166cee1f7599f9778e5e0d15c60b | mcorbin/tour-of-clojure | thread_macro.clj | (ns tourofclojure.pages.thread-macro
(:require [hiccup.element :refer [link-to]]
[clojure.java.io :as io]
[tourofclojure.pages.util :refer [navigation-block]]))
(def code
(slurp (io/resource "public/pages/code/thread_macro.clj")))
(defn desc
[previous next lang]
(condp = lang
"fr" [:div
[:h2 "Threading macros"]
[:p "En Clojure, on se retrouve facilement à imbriquer les expressions."
" A force, Cela peut nuire à la lisibilité. Prenons l'exemple suivant:"]
[:pre [:code "(reduce + (map inc (filter even? (range 10))))"]]
[:p "On voit 4 expressions imbriquées dans ce code. Voyons comment"
" rendre cela plus lisible."]
[:h3 "Thread-last: ->>"]
[:p "Le code précédent est équivalent au code suivant:"]
[:pre [:code "(->> (range 5)
(filter even?)
(map inc)
(reduce +))"]]
[:p "Le symbole " [:b "->>"] ", aussi appelé thread-last, est une"
" macro qui agira sur ses paramètres comme suit:"]
[:ul
[:li "le résultat de " [:b "(range 5)"] " est calculé, ce qui"
" donne " [:b "(0 1 2 3 4)"] "."
]
[:li "Ce résultat est placé à la fin de l'expression suivante, qui"
" vaudra maintenant donc " [:b "(filter even? '(0 1 2 3 4))"] "."
" Le résultat de cette expression est calculé, et vaut " [:b "(0 2 4)"]
"."]
[:li "De la même manière, le résultat précédent est placé à la fin de "
"l'expression suivante, qui vaudra " [:b "(map inc '(0 2 4))"]
" et donnera comme résultat " [:b "(1 3 5)"]]
[:li "Encore une fois, le résultat est passé à l'expression suivante"
" qui vaudra " [:b "(reduce + '(1 3 5))"] ". Le résultat final sera"
" 9."]
]
[:h3 "Thread-first: ->"]
[:p "La macro précédente permettait de placer les résultats intermédiaires"
" des opérations à la fin de l'expression suivante. La macro " [:b "->"]
", aussi appelée thread-first, fonctionne de la même façon sauf qu'ici"
" le résultat est passé comme premier paramètre de l'expression."]
[:p "Le code suivant:"]
[:pre [:code "(/ (:foo {:foo 1}) 100)"]]
[:p "qui a comme résultat 0.01 (ou 1/100 si vous êtes sur la JVM) peut"
" être écrit de la manière suivante avec la macro " [:b "->"] ":"]
[:pre [:code "(-> {:foo 1}
:foo
(/ 100))"]]
[:p "Ce code peut être déroulé comme suit:"]
[:ul
[:li [:b "{:foo 1}"] " est passé comme paramètre au keyword " [:b ":foo"]
", ce qui donne 1"]
[:li "Ce résultat intermédiaire est passé à " [:b "(/ 100)"] ", ce qui"
" donne " [:b "(/ 1 100)"] " qui est le résultat final"]]
[:h3 "Conclusion"]
[:p "Les deux macros présentées ici sont celles que l'on rencontre le plus"
" souvent. Il en existe d'autres, qui sont présentées dans cet "
(link-to "" "excellent guide")
"."]
[:p "Ces macros améliorent grandement la lisibilité du code, vous les"
" rencontrerez donc très souvent."]
(navigation-block previous next)]
[:h2 "Language not supported."]))
(defn page
[previous next lang]
[(desc previous next lang)
code])
| null | https://raw.githubusercontent.com/mcorbin/tour-of-clojure/57f97b68ca1a8c96904bfb960f515217eeda24a6/src/tourofclojure/pages/thread_macro.clj | clojure | (ns tourofclojure.pages.thread-macro
(:require [hiccup.element :refer [link-to]]
[clojure.java.io :as io]
[tourofclojure.pages.util :refer [navigation-block]]))
(def code
(slurp (io/resource "public/pages/code/thread_macro.clj")))
(defn desc
[previous next lang]
(condp = lang
"fr" [:div
[:h2 "Threading macros"]
[:p "En Clojure, on se retrouve facilement à imbriquer les expressions."
" A force, Cela peut nuire à la lisibilité. Prenons l'exemple suivant:"]
[:pre [:code "(reduce + (map inc (filter even? (range 10))))"]]
[:p "On voit 4 expressions imbriquées dans ce code. Voyons comment"
" rendre cela plus lisible."]
[:h3 "Thread-last: ->>"]
[:p "Le code précédent est équivalent au code suivant:"]
[:pre [:code "(->> (range 5)
(filter even?)
(map inc)
(reduce +))"]]
[:p "Le symbole " [:b "->>"] ", aussi appelé thread-last, est une"
" macro qui agira sur ses paramètres comme suit:"]
[:ul
[:li "le résultat de " [:b "(range 5)"] " est calculé, ce qui"
" donne " [:b "(0 1 2 3 4)"] "."
]
[:li "Ce résultat est placé à la fin de l'expression suivante, qui"
" vaudra maintenant donc " [:b "(filter even? '(0 1 2 3 4))"] "."
" Le résultat de cette expression est calculé, et vaut " [:b "(0 2 4)"]
"."]
[:li "De la même manière, le résultat précédent est placé à la fin de "
"l'expression suivante, qui vaudra " [:b "(map inc '(0 2 4))"]
" et donnera comme résultat " [:b "(1 3 5)"]]
[:li "Encore une fois, le résultat est passé à l'expression suivante"
" qui vaudra " [:b "(reduce + '(1 3 5))"] ". Le résultat final sera"
" 9."]
]
[:h3 "Thread-first: ->"]
[:p "La macro précédente permettait de placer les résultats intermédiaires"
" des opérations à la fin de l'expression suivante. La macro " [:b "->"]
", aussi appelée thread-first, fonctionne de la même façon sauf qu'ici"
" le résultat est passé comme premier paramètre de l'expression."]
[:p "Le code suivant:"]
[:pre [:code "(/ (:foo {:foo 1}) 100)"]]
[:p "qui a comme résultat 0.01 (ou 1/100 si vous êtes sur la JVM) peut"
" être écrit de la manière suivante avec la macro " [:b "->"] ":"]
[:pre [:code "(-> {:foo 1}
:foo
(/ 100))"]]
[:p "Ce code peut être déroulé comme suit:"]
[:ul
[:li [:b "{:foo 1}"] " est passé comme paramètre au keyword " [:b ":foo"]
", ce qui donne 1"]
[:li "Ce résultat intermédiaire est passé à " [:b "(/ 100)"] ", ce qui"
" donne " [:b "(/ 1 100)"] " qui est le résultat final"]]
[:h3 "Conclusion"]
[:p "Les deux macros présentées ici sont celles que l'on rencontre le plus"
" souvent. Il en existe d'autres, qui sont présentées dans cet "
(link-to "" "excellent guide")
"."]
[:p "Ces macros améliorent grandement la lisibilité du code, vous les"
" rencontrerez donc très souvent."]
(navigation-block previous next)]
[:h2 "Language not supported."]))
(defn page
[previous next lang]
[(desc previous next lang)
code])
| |
1db553cc23bd4afb2756184e57399cc65cf4112ca8f7db3cae48b7ccb0151d2a | zadean/xqerl | prod_ContextItemDecl_SUITE.erl | -module('prod_ContextItemDecl_SUITE').
-include_lib("common_test/include/ct.hrl").
-export([
all/0,
groups/0,
suite/0
]).
-export([
init_per_suite/1,
init_per_group/2,
end_per_group/2,
end_per_suite/1
]).
-export(['contextDecl-014'/1]).
-export(['contextDecl-015'/1]).
-export(['contextDecl-016'/1]).
-export(['contextDecl-017'/1]).
-export(['contextDecl-018'/1]).
-export(['contextDecl-019'/1]).
-export(['contextDecl-020'/1]).
-export(['contextDecl-021'/1]).
-export(['contextDecl-022'/1]).
-export(['contextDecl-023'/1]).
-export(['contextDecl-028'/1]).
-export(['contextDecl-029'/1]).
-export(['contextDecl-030'/1]).
-export(['contextDecl-031'/1]).
-export(['contextDecl-032'/1]).
-export(['contextDecl-033'/1]).
-export(['contextDecl-034'/1]).
-export(['contextDecl-035'/1]).
-export(['contextDecl-036'/1]).
-export(['contextDecl-037'/1]).
-export(['contextDecl-038'/1]).
-export(['contextDecl-039'/1]).
-export(['contextDecl-040'/1]).
-export(['contextDecl-041'/1]).
-export(['contextDecl-042'/1]).
-export(['contextDecl-043'/1]).
-export(['contextDecl-044'/1]).
-export(['contextDecl-045'/1]).
-export(['contextDecl-046'/1]).
-export(['contextDecl-047'/1]).
-export(['contextDecl-048'/1]).
-export(['contextDecl-049'/1]).
-export(['contextDecl-050'/1]).
-export(['contextDecl-051'/1]).
-export(['contextDecl-052'/1]).
-export(['contextDecl-053'/1]).
-export(['contextDecl-054'/1]).
-export(['contextDecl-055'/1]).
-export(['contextDecl-056'/1]).
-export(['contextDecl-057'/1]).
-export(['contextDecl-058'/1]).
suite() -> [{timetrap, {seconds, 180}}].
init_per_group(_, Config) -> Config.
end_per_group(_, _Config) ->
xqerl_code_server:unload(all).
end_per_suite(_Config) ->
ct:timetrap({seconds, 60}),
xqerl_code_server:unload(all).
init_per_suite(Config) ->
{ok, _} = application:ensure_all_started(xqerl),
DD = filename:dirname(filename:dirname(filename:dirname(?config(data_dir, Config)))),
TD = filename:join(DD, "QT3-test-suite"),
__BaseDir = filename:join(TD, "prod"),
[{base_dir, __BaseDir} | Config].
all() ->
[
{group, group_0}
].
groups() ->
[
{group_0, [], [
'contextDecl-014',
'contextDecl-015',
'contextDecl-016',
'contextDecl-017',
'contextDecl-018',
'contextDecl-019',
'contextDecl-020',
'contextDecl-021',
'contextDecl-022',
'contextDecl-023',
'contextDecl-028',
'contextDecl-029',
'contextDecl-030',
'contextDecl-031',
'contextDecl-032',
'contextDecl-033',
'contextDecl-034',
'contextDecl-035',
'contextDecl-036',
'contextDecl-037',
'contextDecl-038',
'contextDecl-039',
'contextDecl-040',
'contextDecl-041',
'contextDecl-042',
'contextDecl-043',
'contextDecl-044',
'contextDecl-045',
'contextDecl-046',
'contextDecl-047',
'contextDecl-048',
'contextDecl-049',
'contextDecl-050',
'contextDecl-051',
'contextDecl-052',
'contextDecl-053',
'contextDecl-054',
'contextDecl-055',
'contextDecl-056',
'contextDecl-057',
'contextDecl-058'
]}
].
environment('empty', __BaseDir) ->
[
{'decimal-formats', []},
{sources, []},
{collections, []},
{'static-base-uri', []},
{params, []},
{vars, []},
{namespaces, []},
{schemas, []},
{resources, []},
{modules, []}
];
environment('works-mod', __BaseDir) ->
[
{'decimal-formats', []},
{sources, [{filename:join(__BaseDir, "../docs/works-mod.xml"), ".", []}]},
{collections, []},
{'static-base-uri', []},
{params, []},
{vars, []},
{namespaces, []},
{schemas, []},
{resources, []},
{modules, []}
].
'contextDecl-014'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry =
"\n"
" declare variable $x := . + 5;\n"
" declare context item := 17;\n"
" $x\n"
" ",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(filename:join(__BaseDir, "contextDecl-014.xq"), Qry1),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_eq(Res, "22") of
true -> {comment, "Equal"};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'contextDecl-015'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry =
"\n"
" declare variable $y := /works/employee;\n"
" declare context item := $y[9];\n"
" declare variable $x external := if (./*) then fn:position() else 0;\n"
" ($x, $y)\n"
" ",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(filename:join(__BaseDir, "contextDecl-015.xq"), Qry1),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case
lists:any(
fun
({comment, _}) -> true;
(_) -> false
end,
[
case xqerl_test:assert_error(Res, "XPDY0002") of
true -> {comment, "Correct error"};
{true, F} -> {comment, "WE: XPDY0002 " ++ binary_to_list(F)};
{false, F} -> F
end,
case xqerl_test:assert_error(Res, "XQDY0054") of
true -> {comment, "Correct error"};
{true, F} -> {comment, "WE: XQDY0054 " ++ binary_to_list(F)};
{false, F} -> F
end
]
)
of
true -> {comment, "any-of"};
_ -> false
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'contextDecl-016'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry =
"\n"
" declare variable $y := (<a>1</a>,<a>2</a>,<a>3</a>,<a>4</a>,<a>5</a>,<a>6</a>,<a>7</a>,<a>8</a>,<a>9</a>,<a>10</a>);\n"
" declare context item := $y[3];\n"
" declare variable $x external := fn:position();\n"
" $x\n"
" ",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(filename:join(__BaseDir, "contextDecl-016.xq"), Qry1),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_eq(Res, "1") of
true -> {comment, "Equal"};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'contextDecl-017'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry =
"\n"
" declare variable $y := <root><a>1</a>,<a>2</a>,<a>3</a>,<a>4</a>,<a>5</a>,<a>6</a>,<a>7</a>,<a>8</a>,<a>9</a>,<a>10</a></root>;\n"
" declare context item := $y;\n"
" declare variable $x external := fn:last();\n"
" $x\n"
" ",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(filename:join(__BaseDir, "contextDecl-017.xq"), Qry1),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_eq(Res, "1") of
true -> {comment, "Equal"};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'contextDecl-018'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry = " declare context item := last() + 1; .",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(filename:join(__BaseDir, "contextDecl-018.xq"), Qry1),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case
lists:any(
fun
({comment, _}) -> true;
(_) -> false
end,
[
case xqerl_test:assert_eq(Res, "2") of
true -> {comment, "Equal"};
{false, F} -> F
end,
case xqerl_test:assert_error(Res, "XPDY0002") of
true -> {comment, "Correct error"};
{true, F} -> {comment, "WE: XPDY0002 " ++ binary_to_list(F)};
{false, F} -> F
end,
case xqerl_test:assert_error(Res, "XQDY0054") of
true -> {comment, "Correct error"};
{true, F} -> {comment, "WE: XQDY0054 " ++ binary_to_list(F)};
{false, F} -> F
end
]
)
of
true -> {comment, "any-of"};
_ -> false
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'contextDecl-019'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry = " declare context item := position() + 1; .",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(filename:join(__BaseDir, "contextDecl-019.xq"), Qry1),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case
lists:any(
fun
({comment, _}) -> true;
(_) -> false
end,
[
case xqerl_test:assert_eq(Res, "2") of
true -> {comment, "Equal"};
{false, F} -> F
end,
case xqerl_test:assert_error(Res, "XPDY0002") of
true -> {comment, "Correct error"};
{true, F} -> {comment, "WE: XPDY0002 " ++ binary_to_list(F)};
{false, F} -> F
end,
case xqerl_test:assert_error(Res, "XQDY0054") of
true -> {comment, "Correct error"};
{true, F} -> {comment, "WE: XQDY0054 " ++ binary_to_list(F)};
{false, F} -> F
end
]
)
of
true -> {comment, "any-of"};
_ -> false
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'contextDecl-020'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry = " declare context item as xs:integer external; . ",
{Env, Opts} = xqerl_test:handle_environment([
{'decimal-formats', []},
{sources, []},
{collections, []},
{'static-base-uri', []},
{'context-item', ["'London'"]},
{vars, []},
{params, []},
{namespaces, []},
{schemas, []},
{resources, []},
{modules, []}
]),
Qry1 = lists:flatten(Env ++ Qry),
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(filename:join(__BaseDir, "contextDecl-020.xq"), Qry1),
xqerl:run(Mod, Opts)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_error(Res, "XPTY0004") of
true -> {comment, "Correct error"};
{true, F} -> {comment, "WE: XPTY0004 " ++ binary_to_list(F)};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'contextDecl-021'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry = " declare context item as xs:integer := 'London'; . ",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(filename:join(__BaseDir, "contextDecl-021.xq"), Qry1),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_error(Res, "XPTY0004") of
true -> {comment, "Correct error"};
{true, F} -> {comment, "WE: XPTY0004 " ++ binary_to_list(F)};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'contextDecl-022'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry = " declare context item as xs:string := 2; . ",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(filename:join(__BaseDir, "contextDecl-022.xq"), Qry1),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case
lists:any(
fun
({comment, _}) -> true;
(_) -> false
end,
[
case xqerl_test:assert_error(Res, "XPTY0004") of
true -> {comment, "Correct error"};
{true, F} -> {comment, "WE: XPTY0004 " ++ binary_to_list(F)};
{false, F} -> F
end
]
)
of
true -> {comment, "any-of"};
_ -> false
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'contextDecl-023'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry =
"\n"
" declare context item as xs:integer+ := (1 to 17)[position() = 5];\n"
" .\n"
" ",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(filename:join(__BaseDir, "contextDecl-023.xq"), Qry1),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_error(Res, "XPST0003") of
true -> {comment, "Correct error"};
{true, F} -> {comment, "WE: XPST0003 " ++ binary_to_list(F)};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'contextDecl-028'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry = " declare context item := 3; . + 4 ",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(filename:join(__BaseDir, "contextDecl-028.xq"), Qry1),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_eq(Res, "7") of
true -> {comment, "Equal"};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'contextDecl-029'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry =
"\n"
" declare context item := <a>bananas</a>;\n"
" string-length()\n"
" ",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(filename:join(__BaseDir, "contextDecl-029.xq"), Qry1),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_eq(Res, "7") of
true -> {comment, "Equal"};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'contextDecl-030'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry =
"\n"
" declare context item := <a id=\"qwerty\">bananas</a>;\n"
" string-length(@id)\n"
" ",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(filename:join(__BaseDir, "contextDecl-030.xq"), Qry1),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_eq(Res, "6") of
true -> {comment, "Equal"};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'contextDecl-031'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry =
"\n"
" declare context item := contains(?, \"e\");\n"
" .(\"raspberry\")\n"
" ",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(filename:join(__BaseDir, "contextDecl-031.xq"), Qry1),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_true(Res) of
true -> {comment, "Empty"};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'contextDecl-032'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry = "declare context item := (1 to 17)[20]; .",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(filename:join(__BaseDir, "contextDecl-032.xq"), Qry1),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_error(Res, "XPTY0004") of
true -> {comment, "Correct error"};
{true, F} -> {comment, "WE: XPTY0004 " ++ binary_to_list(F)};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'contextDecl-033'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry = "declare context item := (1 to 17)[position() gt 5]; .",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(filename:join(__BaseDir, "contextDecl-033.xq"), Qry1),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_error(Res, "XPTY0004") of
true -> {comment, "Correct error"};
{true, F} -> {comment, "WE: XPTY0004 " ++ binary_to_list(F)};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'contextDecl-034'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry = "declare context item as xs:integer := (1 to 17)[position() = 5]; .",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(filename:join(__BaseDir, "contextDecl-034.xq"), Qry1),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_eq(Res, "5") of
true -> {comment, "Equal"};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'contextDecl-035'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry =
"\n"
" declare context item as xs:integer := (1 to 17)[position() = 5];\n"
" .\n"
" ",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(filename:join(__BaseDir, "contextDecl-035.xq"), Qry1),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_eq(Res, "5") of
true -> {comment, "Equal"};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'contextDecl-036'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry =
"\n"
" declare context item as xs:integer := current-date();\n"
" .\n"
" ",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(filename:join(__BaseDir, "contextDecl-036.xq"), Qry1),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_error(Res, "XPTY0004") of
true -> {comment, "Correct error"};
{true, F} -> {comment, "WE: XPTY0004 " ++ binary_to_list(F)};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'contextDecl-037'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry =
"\n"
" declare context item as xs:integer := <a>23</a>;\n"
" .\n"
" ",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(filename:join(__BaseDir, "contextDecl-037.xq"), Qry1),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_error(Res, "XPTY0004") of
true -> {comment, "Correct error"};
{true, F} -> {comment, "WE: XPTY0004 " ++ binary_to_list(F)};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'contextDecl-038'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry =
"\n"
" declare context item as xs:anyURI := \"/\";\n"
" .\n"
" ",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(filename:join(__BaseDir, "contextDecl-038.xq"), Qry1),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_error(Res, "XPTY0004") of
true -> {comment, "Correct error"};
{true, F} -> {comment, "WE: XPTY0004 " ++ binary_to_list(F)};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'contextDecl-039'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry =
"\n"
" declare context item as xs:double := 1.234;\n"
" .\n"
" ",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(filename:join(__BaseDir, "contextDecl-039.xq"), Qry1),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_error(Res, "XPTY0004") of
true -> {comment, "Correct error"};
{true, F} -> {comment, "WE: XPTY0004 " ++ binary_to_list(F)};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'contextDecl-040'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry =
"\n"
" declare context item external;\n"
" . instance of document-node()\n"
" ",
{Env, Opts} = xqerl_test:handle_environment(environment('works-mod', __BaseDir)),
Qry1 = lists:flatten(Env ++ Qry),
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(filename:join(__BaseDir, "contextDecl-040.xq"), Qry1),
xqerl:run(Mod, Opts)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_true(Res) of
true -> {comment, "Empty"};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'contextDecl-041'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry =
"\n"
" declare context item as document-node() external;\n"
" name(/*)\n"
" ",
{Env, Opts} = xqerl_test:handle_environment(environment('works-mod', __BaseDir)),
Qry1 = lists:flatten(Env ++ Qry),
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(filename:join(__BaseDir, "contextDecl-041.xq"), Qry1),
xqerl:run(Mod, Opts)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_eq(Res, "\"works\"") of
true -> {comment, "Equal"};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'contextDecl-042'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry =
"\n"
" declare context item external := 17;\n"
" . = 17\n"
" ",
{Env, Opts} = xqerl_test:handle_environment(environment('empty', __BaseDir)),
Qry1 = lists:flatten(Env ++ Qry),
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(filename:join(__BaseDir, "contextDecl-042.xq"), Qry1),
xqerl:run(Mod, Opts)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_true(Res) of
true -> {comment, "Empty"};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'contextDecl-043'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry =
"\n"
" declare context item as xs:integer external := 17;\n"
" . = 17\n"
" ",
{Env, Opts} = xqerl_test:handle_environment(environment('empty', __BaseDir)),
Qry1 = lists:flatten(Env ++ Qry),
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(filename:join(__BaseDir, "contextDecl-043.xq"), Qry1),
xqerl:run(Mod, Opts)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_true(Res) of
true -> {comment, "Empty"};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'contextDecl-044'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry = " declare context item as xs:double external := 17; . = 17",
{Env, Opts} = xqerl_test:handle_environment(environment('empty', __BaseDir)),
Qry1 = lists:flatten(Env ++ Qry),
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(filename:join(__BaseDir, "contextDecl-044.xq"), Qry1),
xqerl:run(Mod, Opts)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_error(Res, "XPTY0004") of
true -> {comment, "Correct error"};
{true, F} -> {comment, "WE: XPTY0004 " ++ binary_to_list(F)};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'contextDecl-045'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry = " declare context item as xs:double external; . = 17",
{Env, Opts} = xqerl_test:handle_environment(environment('empty', __BaseDir)),
Qry1 = lists:flatten(Env ++ Qry),
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(filename:join(__BaseDir, "contextDecl-045.xq"), Qry1),
xqerl:run(Mod, Opts)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_error(Res, "XPDY0002") of
true -> {comment, "Correct error"};
{true, F} -> {comment, "WE: XPDY0002 " ++ binary_to_list(F)};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'contextDecl-046'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry =
"\n"
" declare context item as xs:double external;\n"
" declare context item as xs:integer := 15;\n"
" . = 17\n"
" ",
{Env, Opts} = xqerl_test:handle_environment(environment('works-mod', __BaseDir)),
Qry1 = lists:flatten(Env ++ Qry),
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(filename:join(__BaseDir, "contextDecl-046.xq"), Qry1),
xqerl:run(Mod, Opts)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_error(Res, "XQST0099") of
true -> {comment, "Correct error"};
{true, F} -> {comment, "WE: XQST0099 " ++ binary_to_list(F)};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'contextDecl-047'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry =
"\n"
" import module namespace m=\"\"; \n"
" . gt xs:date('1900-01-01')\n"
" ",
{Env, Opts} = xqerl_test:handle_environment([
{'decimal-formats', []},
{sources, []},
{collections, []},
{'static-base-uri', []},
{'context-item', ["current-date()"]},
{vars, []},
{params, []},
{namespaces, []},
{schemas, []},
{resources, []},
{modules, [
{filename:join(__BaseDir, "ContextItemDecl/libmodule-2.xq"),
""}
]}
]),
Qry1 = lists:flatten(Env ++ Qry),
io:format("Qry1: ~p~n", [Qry1]),
Hints = [
{filename:join(__BaseDir, "ContextItemDecl/libmodule-2.xq"),
<<"Q{}">>}
],
LibList = xqerl_code_server:compile_files(Hints),
Res =
try
Mod = xqerl_code_server:compile(filename:join(__BaseDir, "contextDecl-047.xq"), Qry1),
xqerl:run(Mod, Opts)
of
Etup when is_tuple(Etup), element(1, Etup) == xqError ->
xqerl_test:combined_error(Etup, LibList);
D ->
D
catch
_:E -> xqerl_test:combined_error(E, LibList)
end,
Out =
case xqerl_test:assert_true(Res) of
true -> {comment, "Empty"};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'contextDecl-048'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry =
"\n"
" import module namespace m=\"\"; \n"
" . = 17\n"
" ",
{Env, Opts} = xqerl_test:handle_environment(environment('empty', __BaseDir)),
Qry1 = lists:flatten(Env ++ Qry),
io:format("Qry1: ~p~n", [Qry1]),
Hints = [
{filename:join(__BaseDir, "ContextItemDecl/libmodule-1.xq"),
<<"Q{}">>}
],
LibList = xqerl_code_server:compile_files(Hints),
Res =
try
Mod = xqerl_code_server:compile(filename:join(__BaseDir, "contextDecl-048.xq"), Qry1),
xqerl:run(Mod, Opts)
of
Etup when is_tuple(Etup), element(1, Etup) == xqError ->
xqerl_test:combined_error(Etup, LibList);
D ->
D
catch
_:E -> xqerl_test:combined_error(E, LibList)
end,
Out =
case xqerl_test:assert_error(Res, "XQST0113") of
true -> {comment, "Correct error"};
{true, F} -> {comment, "WE: XQST0113 " ++ binary_to_list(F)};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'contextDecl-049'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry =
"\n"
" import module namespace m=\"\"; \n"
" declare context item as xs:date := current-date();\n"
" . gt xs:date('1900-01-01')\n"
" ",
{Env, Opts} = xqerl_test:handle_environment(environment('empty', __BaseDir)),
Qry1 = lists:flatten(Env ++ Qry),
io:format("Qry1: ~p~n", [Qry1]),
Hints = [
{filename:join(__BaseDir, "ContextItemDecl/libmodule-2.xq"),
<<"Q{}">>}
],
LibList = xqerl_code_server:compile_files(Hints),
Res =
try
Mod = xqerl_code_server:compile(filename:join(__BaseDir, "contextDecl-049.xq"), Qry1),
xqerl:run(Mod, Opts)
of
Etup when is_tuple(Etup), element(1, Etup) == xqError ->
xqerl_test:combined_error(Etup, LibList);
D ->
D
catch
_:E -> xqerl_test:combined_error(E, LibList)
end,
Out =
case xqerl_test:assert_true(Res) of
true -> {comment, "Empty"};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'contextDecl-050'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry =
"\n"
" import module namespace m=\"\"; \n"
" declare context item as xs:integer := 23;\n"
" . eq 23\n"
" ",
{Env, Opts} = xqerl_test:handle_environment(environment('empty', __BaseDir)),
Qry1 = lists:flatten(Env ++ Qry),
io:format("Qry1: ~p~n", [Qry1]),
Hints = [
{filename:join(__BaseDir, "ContextItemDecl/libmodule-2.xq"),
<<"Q{}">>}
],
LibList = xqerl_code_server:compile_files(Hints),
Res =
try
Mod = xqerl_code_server:compile(filename:join(__BaseDir, "contextDecl-050.xq"), Qry1),
xqerl:run(Mod, Opts)
of
Etup when is_tuple(Etup), element(1, Etup) == xqError ->
xqerl_test:combined_error(Etup, LibList);
D ->
D
catch
_:E -> xqerl_test:combined_error(E, LibList)
end,
Out =
case xqerl_test:assert_error(Res, "XPTY0004") of
true -> {comment, "Correct error"};
{true, F} -> {comment, "WE: XPTY0004 " ++ binary_to_list(F)};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'contextDecl-051'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry =
"\n"
" import module namespace m=\"\"; \n"
" declare context item as node() external;\n"
" . instance of element()\n"
" ",
{Env, Opts} = xqerl_test:handle_environment(environment('works-mod', __BaseDir)),
Qry1 = lists:flatten(Env ++ Qry),
io:format("Qry1: ~p~n", [Qry1]),
Hints = [
{filename:join(__BaseDir, "ContextItemDecl/libmodule-2.xq"),
<<"Q{}">>}
],
LibList = xqerl_code_server:compile_files(Hints),
Res =
try
Mod = xqerl_code_server:compile(filename:join(__BaseDir, "contextDecl-051.xq"), Qry1),
xqerl:run(Mod, Opts)
of
Etup when is_tuple(Etup), element(1, Etup) == xqError ->
xqerl_test:combined_error(Etup, LibList);
D ->
D
catch
_:E -> xqerl_test:combined_error(E, LibList)
end,
Out =
case xqerl_test:assert_error(Res, "XPTY0004") of
true -> {comment, "Correct error"};
{true, F} -> {comment, "WE: XPTY0004 " ++ binary_to_list(F)};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'contextDecl-052'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry =
"\n"
" import module namespace m=\"\"; \n"
" . eq 23\n"
" ",
{Env, Opts} = xqerl_test:handle_environment(environment('empty', __BaseDir)),
Qry1 = lists:flatten(Env ++ Qry),
io:format("Qry1: ~p~n", [Qry1]),
Hints = [
{filename:join(__BaseDir, "ContextItemDecl/libmodule-3.xq"),
<<"Q{}">>}
],
LibList = xqerl_code_server:compile_files(Hints),
Res =
try
Mod = xqerl_code_server:compile(filename:join(__BaseDir, "contextDecl-052.xq"), Qry1),
xqerl:run(Mod, Opts)
of
Etup when is_tuple(Etup), element(1, Etup) == xqError ->
xqerl_test:combined_error(Etup, LibList);
D ->
D
catch
_:E -> xqerl_test:combined_error(E, LibList)
end,
Out =
case xqerl_test:assert_error(Res, "XQST0113") of
true -> {comment, "Correct error"};
{true, F} -> {comment, "WE: XQST0113 " ++ binary_to_list(F)};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'contextDecl-053'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry =
"\n"
" declare variable $p := \"base-uri\";\n"
" declare variable $f := function-lookup(xs:QName(\"fn:\"||$p), 0);\n"
" declare context item := $f();\n"
" .\n"
" ",
{Env, Opts} = xqerl_test:handle_environment(environment('empty', __BaseDir)),
Qry1 = lists:flatten(Env ++ Qry),
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(filename:join(__BaseDir, "contextDecl-053.xq"), Qry1),
xqerl:run(Mod, Opts)
of
D -> D
catch
_:E -> E
end,
Out =
case
lists:any(
fun
({comment, _}) -> true;
(_) -> false
end,
[
case xqerl_test:assert_error(Res, "XPDY0002") of
true -> {comment, "Correct error"};
{true, F} -> {comment, "WE: XPDY0002 " ++ binary_to_list(F)};
{false, F} -> F
end,
case xqerl_test:assert_error(Res, "XQDY0054") of
true -> {comment, "Correct error"};
{true, F} -> {comment, "WE: XQDY0054 " ++ binary_to_list(F)};
{false, F} -> F
end
]
)
of
true -> {comment, "any-of"};
_ -> false
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'contextDecl-054'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry =
"\n"
" import module namespace m=\"\"; \n"
" xs:date(.) gt xs:date('1900-01-01')\n"
" ",
{Env, Opts} = xqerl_test:handle_environment([
{'decimal-formats', []},
{sources, []},
{collections, []},
{'static-base-uri', []},
{'context-item', ["current-dateTime()"]},
{vars, []},
{params, []},
{namespaces, []},
{schemas, []},
{resources, []},
{modules, [
{filename:join(__BaseDir, "ContextItemDecl/libmodule-2.xq"),
""}
]}
]),
Qry1 = lists:flatten(Env ++ Qry),
io:format("Qry1: ~p~n", [Qry1]),
Hints = [
{filename:join(__BaseDir, "ContextItemDecl/libmodule-2.xq"),
<<"Q{}">>}
],
LibList = xqerl_code_server:compile_files(Hints),
Res =
try
Mod = xqerl_code_server:compile(filename:join(__BaseDir, "contextDecl-054.xq"), Qry1),
xqerl:run(Mod, Opts)
of
Etup when is_tuple(Etup), element(1, Etup) == xqError ->
xqerl_test:combined_error(Etup, LibList);
D ->
D
catch
_:E -> xqerl_test:combined_error(E, LibList)
end,
Out =
case xqerl_test:assert_error(Res, "XPTY0004") of
true -> {comment, "Correct error"};
{true, F} -> {comment, "WE: XPTY0004 " ++ binary_to_list(F)};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'contextDecl-055'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry =
"\n"
" declare variable $f := function-lookup(xs:QName(\"fn:\"||$p), 0);\n"
" declare context item := <e/>;\n"
" declare variable $p := \"local-name\";\n"
" $f()\n"
" ",
{Env, Opts} = xqerl_test:handle_environment(environment('empty', __BaseDir)),
Qry1 = lists:flatten(Env ++ Qry),
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(filename:join(__BaseDir, "contextDecl-055.xq"), Qry1),
xqerl:run(Mod, Opts)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_eq(Res, "\"e\"") of
true -> {comment, "Equal"};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'contextDecl-056'(Config) ->
__BaseDir = ?config(base_dir, Config),
{skip, "feature:schemaImport"}.
'contextDecl-057'(Config) ->
__BaseDir = ?config(base_dir, Config),
{skip, "feature:schemaImport"}.
'contextDecl-058'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry =
"\n"
" import module namespace m=\"\";\n"
" declare context item as array(xs:string) external;\n"
" $m:v eq 'green'\n"
" ",
{Env, Opts} = xqerl_test:handle_environment([
{'decimal-formats', []},
{sources, []},
{collections, []},
{'static-base-uri', []},
{'context-item', ["['blue', 'green']"]},
{vars, []},
{params, []},
{namespaces, []},
{schemas, []},
{resources, []},
{modules, [
{filename:join(__BaseDir, "ContextItemDecl/libmodule-5.xq"),
""}
]}
]),
Qry1 = lists:flatten(Env ++ Qry),
io:format("Qry1: ~p~n", [Qry1]),
Hints = [
{filename:join(__BaseDir, "ContextItemDecl/libmodule-5.xq"),
<<"Q{}">>}
],
LibList = xqerl_code_server:compile_files(Hints),
Res =
try
Mod = xqerl_code_server:compile(filename:join(__BaseDir, "contextDecl-058.xq"), Qry1),
xqerl:run(Mod, Opts)
of
Etup when is_tuple(Etup), element(1, Etup) == xqError ->
xqerl_test:combined_error(Etup, LibList);
D ->
D
catch
_:E -> xqerl_test:combined_error(E, LibList)
end,
Out =
case xqerl_test:assert_true(Res) of
true -> {comment, "Empty"};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
| null | https://raw.githubusercontent.com/zadean/xqerl/1a94833e996435495922346010ce918b4b0717f2/test/prod/prod_ContextItemDecl_SUITE.erl | erlang | -module('prod_ContextItemDecl_SUITE').
-include_lib("common_test/include/ct.hrl").
-export([
all/0,
groups/0,
suite/0
]).
-export([
init_per_suite/1,
init_per_group/2,
end_per_group/2,
end_per_suite/1
]).
-export(['contextDecl-014'/1]).
-export(['contextDecl-015'/1]).
-export(['contextDecl-016'/1]).
-export(['contextDecl-017'/1]).
-export(['contextDecl-018'/1]).
-export(['contextDecl-019'/1]).
-export(['contextDecl-020'/1]).
-export(['contextDecl-021'/1]).
-export(['contextDecl-022'/1]).
-export(['contextDecl-023'/1]).
-export(['contextDecl-028'/1]).
-export(['contextDecl-029'/1]).
-export(['contextDecl-030'/1]).
-export(['contextDecl-031'/1]).
-export(['contextDecl-032'/1]).
-export(['contextDecl-033'/1]).
-export(['contextDecl-034'/1]).
-export(['contextDecl-035'/1]).
-export(['contextDecl-036'/1]).
-export(['contextDecl-037'/1]).
-export(['contextDecl-038'/1]).
-export(['contextDecl-039'/1]).
-export(['contextDecl-040'/1]).
-export(['contextDecl-041'/1]).
-export(['contextDecl-042'/1]).
-export(['contextDecl-043'/1]).
-export(['contextDecl-044'/1]).
-export(['contextDecl-045'/1]).
-export(['contextDecl-046'/1]).
-export(['contextDecl-047'/1]).
-export(['contextDecl-048'/1]).
-export(['contextDecl-049'/1]).
-export(['contextDecl-050'/1]).
-export(['contextDecl-051'/1]).
-export(['contextDecl-052'/1]).
-export(['contextDecl-053'/1]).
-export(['contextDecl-054'/1]).
-export(['contextDecl-055'/1]).
-export(['contextDecl-056'/1]).
-export(['contextDecl-057'/1]).
-export(['contextDecl-058'/1]).
suite() -> [{timetrap, {seconds, 180}}].
init_per_group(_, Config) -> Config.
end_per_group(_, _Config) ->
xqerl_code_server:unload(all).
end_per_suite(_Config) ->
ct:timetrap({seconds, 60}),
xqerl_code_server:unload(all).
init_per_suite(Config) ->
{ok, _} = application:ensure_all_started(xqerl),
DD = filename:dirname(filename:dirname(filename:dirname(?config(data_dir, Config)))),
TD = filename:join(DD, "QT3-test-suite"),
__BaseDir = filename:join(TD, "prod"),
[{base_dir, __BaseDir} | Config].
all() ->
[
{group, group_0}
].
groups() ->
[
{group_0, [], [
'contextDecl-014',
'contextDecl-015',
'contextDecl-016',
'contextDecl-017',
'contextDecl-018',
'contextDecl-019',
'contextDecl-020',
'contextDecl-021',
'contextDecl-022',
'contextDecl-023',
'contextDecl-028',
'contextDecl-029',
'contextDecl-030',
'contextDecl-031',
'contextDecl-032',
'contextDecl-033',
'contextDecl-034',
'contextDecl-035',
'contextDecl-036',
'contextDecl-037',
'contextDecl-038',
'contextDecl-039',
'contextDecl-040',
'contextDecl-041',
'contextDecl-042',
'contextDecl-043',
'contextDecl-044',
'contextDecl-045',
'contextDecl-046',
'contextDecl-047',
'contextDecl-048',
'contextDecl-049',
'contextDecl-050',
'contextDecl-051',
'contextDecl-052',
'contextDecl-053',
'contextDecl-054',
'contextDecl-055',
'contextDecl-056',
'contextDecl-057',
'contextDecl-058'
]}
].
environment('empty', __BaseDir) ->
[
{'decimal-formats', []},
{sources, []},
{collections, []},
{'static-base-uri', []},
{params, []},
{vars, []},
{namespaces, []},
{schemas, []},
{resources, []},
{modules, []}
];
environment('works-mod', __BaseDir) ->
[
{'decimal-formats', []},
{sources, [{filename:join(__BaseDir, "../docs/works-mod.xml"), ".", []}]},
{collections, []},
{'static-base-uri', []},
{params, []},
{vars, []},
{namespaces, []},
{schemas, []},
{resources, []},
{modules, []}
].
'contextDecl-014'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry =
"\n"
" declare variable $x := . + 5;\n"
" declare context item := 17;\n"
" $x\n"
" ",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(filename:join(__BaseDir, "contextDecl-014.xq"), Qry1),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_eq(Res, "22") of
true -> {comment, "Equal"};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'contextDecl-015'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry =
"\n"
" declare variable $y := /works/employee;\n"
" declare context item := $y[9];\n"
" declare variable $x external := if (./*) then fn:position() else 0;\n"
" ($x, $y)\n"
" ",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(filename:join(__BaseDir, "contextDecl-015.xq"), Qry1),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case
lists:any(
fun
({comment, _}) -> true;
(_) -> false
end,
[
case xqerl_test:assert_error(Res, "XPDY0002") of
true -> {comment, "Correct error"};
{true, F} -> {comment, "WE: XPDY0002 " ++ binary_to_list(F)};
{false, F} -> F
end,
case xqerl_test:assert_error(Res, "XQDY0054") of
true -> {comment, "Correct error"};
{true, F} -> {comment, "WE: XQDY0054 " ++ binary_to_list(F)};
{false, F} -> F
end
]
)
of
true -> {comment, "any-of"};
_ -> false
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'contextDecl-016'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry =
"\n"
" declare variable $y := (<a>1</a>,<a>2</a>,<a>3</a>,<a>4</a>,<a>5</a>,<a>6</a>,<a>7</a>,<a>8</a>,<a>9</a>,<a>10</a>);\n"
" declare context item := $y[3];\n"
" declare variable $x external := fn:position();\n"
" $x\n"
" ",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(filename:join(__BaseDir, "contextDecl-016.xq"), Qry1),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_eq(Res, "1") of
true -> {comment, "Equal"};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'contextDecl-017'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry =
"\n"
" declare variable $y := <root><a>1</a>,<a>2</a>,<a>3</a>,<a>4</a>,<a>5</a>,<a>6</a>,<a>7</a>,<a>8</a>,<a>9</a>,<a>10</a></root>;\n"
" declare context item := $y;\n"
" declare variable $x external := fn:last();\n"
" $x\n"
" ",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(filename:join(__BaseDir, "contextDecl-017.xq"), Qry1),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_eq(Res, "1") of
true -> {comment, "Equal"};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'contextDecl-018'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry = " declare context item := last() + 1; .",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(filename:join(__BaseDir, "contextDecl-018.xq"), Qry1),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case
lists:any(
fun
({comment, _}) -> true;
(_) -> false
end,
[
case xqerl_test:assert_eq(Res, "2") of
true -> {comment, "Equal"};
{false, F} -> F
end,
case xqerl_test:assert_error(Res, "XPDY0002") of
true -> {comment, "Correct error"};
{true, F} -> {comment, "WE: XPDY0002 " ++ binary_to_list(F)};
{false, F} -> F
end,
case xqerl_test:assert_error(Res, "XQDY0054") of
true -> {comment, "Correct error"};
{true, F} -> {comment, "WE: XQDY0054 " ++ binary_to_list(F)};
{false, F} -> F
end
]
)
of
true -> {comment, "any-of"};
_ -> false
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'contextDecl-019'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry = " declare context item := position() + 1; .",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(filename:join(__BaseDir, "contextDecl-019.xq"), Qry1),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case
lists:any(
fun
({comment, _}) -> true;
(_) -> false
end,
[
case xqerl_test:assert_eq(Res, "2") of
true -> {comment, "Equal"};
{false, F} -> F
end,
case xqerl_test:assert_error(Res, "XPDY0002") of
true -> {comment, "Correct error"};
{true, F} -> {comment, "WE: XPDY0002 " ++ binary_to_list(F)};
{false, F} -> F
end,
case xqerl_test:assert_error(Res, "XQDY0054") of
true -> {comment, "Correct error"};
{true, F} -> {comment, "WE: XQDY0054 " ++ binary_to_list(F)};
{false, F} -> F
end
]
)
of
true -> {comment, "any-of"};
_ -> false
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'contextDecl-020'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry = " declare context item as xs:integer external; . ",
{Env, Opts} = xqerl_test:handle_environment([
{'decimal-formats', []},
{sources, []},
{collections, []},
{'static-base-uri', []},
{'context-item', ["'London'"]},
{vars, []},
{params, []},
{namespaces, []},
{schemas, []},
{resources, []},
{modules, []}
]),
Qry1 = lists:flatten(Env ++ Qry),
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(filename:join(__BaseDir, "contextDecl-020.xq"), Qry1),
xqerl:run(Mod, Opts)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_error(Res, "XPTY0004") of
true -> {comment, "Correct error"};
{true, F} -> {comment, "WE: XPTY0004 " ++ binary_to_list(F)};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'contextDecl-021'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry = " declare context item as xs:integer := 'London'; . ",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(filename:join(__BaseDir, "contextDecl-021.xq"), Qry1),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_error(Res, "XPTY0004") of
true -> {comment, "Correct error"};
{true, F} -> {comment, "WE: XPTY0004 " ++ binary_to_list(F)};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'contextDecl-022'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry = " declare context item as xs:string := 2; . ",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(filename:join(__BaseDir, "contextDecl-022.xq"), Qry1),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case
lists:any(
fun
({comment, _}) -> true;
(_) -> false
end,
[
case xqerl_test:assert_error(Res, "XPTY0004") of
true -> {comment, "Correct error"};
{true, F} -> {comment, "WE: XPTY0004 " ++ binary_to_list(F)};
{false, F} -> F
end
]
)
of
true -> {comment, "any-of"};
_ -> false
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'contextDecl-023'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry =
"\n"
" declare context item as xs:integer+ := (1 to 17)[position() = 5];\n"
" .\n"
" ",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(filename:join(__BaseDir, "contextDecl-023.xq"), Qry1),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_error(Res, "XPST0003") of
true -> {comment, "Correct error"};
{true, F} -> {comment, "WE: XPST0003 " ++ binary_to_list(F)};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'contextDecl-028'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry = " declare context item := 3; . + 4 ",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(filename:join(__BaseDir, "contextDecl-028.xq"), Qry1),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_eq(Res, "7") of
true -> {comment, "Equal"};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'contextDecl-029'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry =
"\n"
" declare context item := <a>bananas</a>;\n"
" string-length()\n"
" ",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(filename:join(__BaseDir, "contextDecl-029.xq"), Qry1),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_eq(Res, "7") of
true -> {comment, "Equal"};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'contextDecl-030'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry =
"\n"
" declare context item := <a id=\"qwerty\">bananas</a>;\n"
" string-length(@id)\n"
" ",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(filename:join(__BaseDir, "contextDecl-030.xq"), Qry1),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_eq(Res, "6") of
true -> {comment, "Equal"};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'contextDecl-031'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry =
"\n"
" declare context item := contains(?, \"e\");\n"
" .(\"raspberry\")\n"
" ",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(filename:join(__BaseDir, "contextDecl-031.xq"), Qry1),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_true(Res) of
true -> {comment, "Empty"};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'contextDecl-032'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry = "declare context item := (1 to 17)[20]; .",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(filename:join(__BaseDir, "contextDecl-032.xq"), Qry1),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_error(Res, "XPTY0004") of
true -> {comment, "Correct error"};
{true, F} -> {comment, "WE: XPTY0004 " ++ binary_to_list(F)};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'contextDecl-033'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry = "declare context item := (1 to 17)[position() gt 5]; .",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(filename:join(__BaseDir, "contextDecl-033.xq"), Qry1),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_error(Res, "XPTY0004") of
true -> {comment, "Correct error"};
{true, F} -> {comment, "WE: XPTY0004 " ++ binary_to_list(F)};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'contextDecl-034'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry = "declare context item as xs:integer := (1 to 17)[position() = 5]; .",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(filename:join(__BaseDir, "contextDecl-034.xq"), Qry1),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_eq(Res, "5") of
true -> {comment, "Equal"};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'contextDecl-035'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry =
"\n"
" declare context item as xs:integer := (1 to 17)[position() = 5];\n"
" .\n"
" ",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(filename:join(__BaseDir, "contextDecl-035.xq"), Qry1),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_eq(Res, "5") of
true -> {comment, "Equal"};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'contextDecl-036'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry =
"\n"
" declare context item as xs:integer := current-date();\n"
" .\n"
" ",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(filename:join(__BaseDir, "contextDecl-036.xq"), Qry1),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_error(Res, "XPTY0004") of
true -> {comment, "Correct error"};
{true, F} -> {comment, "WE: XPTY0004 " ++ binary_to_list(F)};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'contextDecl-037'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry =
"\n"
" declare context item as xs:integer := <a>23</a>;\n"
" .\n"
" ",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(filename:join(__BaseDir, "contextDecl-037.xq"), Qry1),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_error(Res, "XPTY0004") of
true -> {comment, "Correct error"};
{true, F} -> {comment, "WE: XPTY0004 " ++ binary_to_list(F)};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'contextDecl-038'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry =
"\n"
" declare context item as xs:anyURI := \"/\";\n"
" .\n"
" ",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(filename:join(__BaseDir, "contextDecl-038.xq"), Qry1),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_error(Res, "XPTY0004") of
true -> {comment, "Correct error"};
{true, F} -> {comment, "WE: XPTY0004 " ++ binary_to_list(F)};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'contextDecl-039'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry =
"\n"
" declare context item as xs:double := 1.234;\n"
" .\n"
" ",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(filename:join(__BaseDir, "contextDecl-039.xq"), Qry1),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_error(Res, "XPTY0004") of
true -> {comment, "Correct error"};
{true, F} -> {comment, "WE: XPTY0004 " ++ binary_to_list(F)};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'contextDecl-040'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry =
"\n"
" declare context item external;\n"
" . instance of document-node()\n"
" ",
{Env, Opts} = xqerl_test:handle_environment(environment('works-mod', __BaseDir)),
Qry1 = lists:flatten(Env ++ Qry),
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(filename:join(__BaseDir, "contextDecl-040.xq"), Qry1),
xqerl:run(Mod, Opts)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_true(Res) of
true -> {comment, "Empty"};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'contextDecl-041'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry =
"\n"
" declare context item as document-node() external;\n"
" name(/*)\n"
" ",
{Env, Opts} = xqerl_test:handle_environment(environment('works-mod', __BaseDir)),
Qry1 = lists:flatten(Env ++ Qry),
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(filename:join(__BaseDir, "contextDecl-041.xq"), Qry1),
xqerl:run(Mod, Opts)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_eq(Res, "\"works\"") of
true -> {comment, "Equal"};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'contextDecl-042'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry =
"\n"
" declare context item external := 17;\n"
" . = 17\n"
" ",
{Env, Opts} = xqerl_test:handle_environment(environment('empty', __BaseDir)),
Qry1 = lists:flatten(Env ++ Qry),
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(filename:join(__BaseDir, "contextDecl-042.xq"), Qry1),
xqerl:run(Mod, Opts)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_true(Res) of
true -> {comment, "Empty"};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'contextDecl-043'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry =
"\n"
" declare context item as xs:integer external := 17;\n"
" . = 17\n"
" ",
{Env, Opts} = xqerl_test:handle_environment(environment('empty', __BaseDir)),
Qry1 = lists:flatten(Env ++ Qry),
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(filename:join(__BaseDir, "contextDecl-043.xq"), Qry1),
xqerl:run(Mod, Opts)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_true(Res) of
true -> {comment, "Empty"};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'contextDecl-044'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry = " declare context item as xs:double external := 17; . = 17",
{Env, Opts} = xqerl_test:handle_environment(environment('empty', __BaseDir)),
Qry1 = lists:flatten(Env ++ Qry),
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(filename:join(__BaseDir, "contextDecl-044.xq"), Qry1),
xqerl:run(Mod, Opts)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_error(Res, "XPTY0004") of
true -> {comment, "Correct error"};
{true, F} -> {comment, "WE: XPTY0004 " ++ binary_to_list(F)};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'contextDecl-045'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry = " declare context item as xs:double external; . = 17",
{Env, Opts} = xqerl_test:handle_environment(environment('empty', __BaseDir)),
Qry1 = lists:flatten(Env ++ Qry),
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(filename:join(__BaseDir, "contextDecl-045.xq"), Qry1),
xqerl:run(Mod, Opts)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_error(Res, "XPDY0002") of
true -> {comment, "Correct error"};
{true, F} -> {comment, "WE: XPDY0002 " ++ binary_to_list(F)};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'contextDecl-046'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry =
"\n"
" declare context item as xs:double external;\n"
" declare context item as xs:integer := 15;\n"
" . = 17\n"
" ",
{Env, Opts} = xqerl_test:handle_environment(environment('works-mod', __BaseDir)),
Qry1 = lists:flatten(Env ++ Qry),
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(filename:join(__BaseDir, "contextDecl-046.xq"), Qry1),
xqerl:run(Mod, Opts)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_error(Res, "XQST0099") of
true -> {comment, "Correct error"};
{true, F} -> {comment, "WE: XQST0099 " ++ binary_to_list(F)};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'contextDecl-047'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry =
"\n"
" import module namespace m=\"\"; \n"
" . gt xs:date('1900-01-01')\n"
" ",
{Env, Opts} = xqerl_test:handle_environment([
{'decimal-formats', []},
{sources, []},
{collections, []},
{'static-base-uri', []},
{'context-item', ["current-date()"]},
{vars, []},
{params, []},
{namespaces, []},
{schemas, []},
{resources, []},
{modules, [
{filename:join(__BaseDir, "ContextItemDecl/libmodule-2.xq"),
""}
]}
]),
Qry1 = lists:flatten(Env ++ Qry),
io:format("Qry1: ~p~n", [Qry1]),
Hints = [
{filename:join(__BaseDir, "ContextItemDecl/libmodule-2.xq"),
<<"Q{}">>}
],
LibList = xqerl_code_server:compile_files(Hints),
Res =
try
Mod = xqerl_code_server:compile(filename:join(__BaseDir, "contextDecl-047.xq"), Qry1),
xqerl:run(Mod, Opts)
of
Etup when is_tuple(Etup), element(1, Etup) == xqError ->
xqerl_test:combined_error(Etup, LibList);
D ->
D
catch
_:E -> xqerl_test:combined_error(E, LibList)
end,
Out =
case xqerl_test:assert_true(Res) of
true -> {comment, "Empty"};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'contextDecl-048'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry =
"\n"
" import module namespace m=\"\"; \n"
" . = 17\n"
" ",
{Env, Opts} = xqerl_test:handle_environment(environment('empty', __BaseDir)),
Qry1 = lists:flatten(Env ++ Qry),
io:format("Qry1: ~p~n", [Qry1]),
Hints = [
{filename:join(__BaseDir, "ContextItemDecl/libmodule-1.xq"),
<<"Q{}">>}
],
LibList = xqerl_code_server:compile_files(Hints),
Res =
try
Mod = xqerl_code_server:compile(filename:join(__BaseDir, "contextDecl-048.xq"), Qry1),
xqerl:run(Mod, Opts)
of
Etup when is_tuple(Etup), element(1, Etup) == xqError ->
xqerl_test:combined_error(Etup, LibList);
D ->
D
catch
_:E -> xqerl_test:combined_error(E, LibList)
end,
Out =
case xqerl_test:assert_error(Res, "XQST0113") of
true -> {comment, "Correct error"};
{true, F} -> {comment, "WE: XQST0113 " ++ binary_to_list(F)};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'contextDecl-049'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry =
"\n"
" import module namespace m=\"\"; \n"
" declare context item as xs:date := current-date();\n"
" . gt xs:date('1900-01-01')\n"
" ",
{Env, Opts} = xqerl_test:handle_environment(environment('empty', __BaseDir)),
Qry1 = lists:flatten(Env ++ Qry),
io:format("Qry1: ~p~n", [Qry1]),
Hints = [
{filename:join(__BaseDir, "ContextItemDecl/libmodule-2.xq"),
<<"Q{}">>}
],
LibList = xqerl_code_server:compile_files(Hints),
Res =
try
Mod = xqerl_code_server:compile(filename:join(__BaseDir, "contextDecl-049.xq"), Qry1),
xqerl:run(Mod, Opts)
of
Etup when is_tuple(Etup), element(1, Etup) == xqError ->
xqerl_test:combined_error(Etup, LibList);
D ->
D
catch
_:E -> xqerl_test:combined_error(E, LibList)
end,
Out =
case xqerl_test:assert_true(Res) of
true -> {comment, "Empty"};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'contextDecl-050'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry =
"\n"
" import module namespace m=\"\"; \n"
" declare context item as xs:integer := 23;\n"
" . eq 23\n"
" ",
{Env, Opts} = xqerl_test:handle_environment(environment('empty', __BaseDir)),
Qry1 = lists:flatten(Env ++ Qry),
io:format("Qry1: ~p~n", [Qry1]),
Hints = [
{filename:join(__BaseDir, "ContextItemDecl/libmodule-2.xq"),
<<"Q{}">>}
],
LibList = xqerl_code_server:compile_files(Hints),
Res =
try
Mod = xqerl_code_server:compile(filename:join(__BaseDir, "contextDecl-050.xq"), Qry1),
xqerl:run(Mod, Opts)
of
Etup when is_tuple(Etup), element(1, Etup) == xqError ->
xqerl_test:combined_error(Etup, LibList);
D ->
D
catch
_:E -> xqerl_test:combined_error(E, LibList)
end,
Out =
case xqerl_test:assert_error(Res, "XPTY0004") of
true -> {comment, "Correct error"};
{true, F} -> {comment, "WE: XPTY0004 " ++ binary_to_list(F)};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'contextDecl-051'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry =
"\n"
" import module namespace m=\"\"; \n"
" declare context item as node() external;\n"
" . instance of element()\n"
" ",
{Env, Opts} = xqerl_test:handle_environment(environment('works-mod', __BaseDir)),
Qry1 = lists:flatten(Env ++ Qry),
io:format("Qry1: ~p~n", [Qry1]),
Hints = [
{filename:join(__BaseDir, "ContextItemDecl/libmodule-2.xq"),
<<"Q{}">>}
],
LibList = xqerl_code_server:compile_files(Hints),
Res =
try
Mod = xqerl_code_server:compile(filename:join(__BaseDir, "contextDecl-051.xq"), Qry1),
xqerl:run(Mod, Opts)
of
Etup when is_tuple(Etup), element(1, Etup) == xqError ->
xqerl_test:combined_error(Etup, LibList);
D ->
D
catch
_:E -> xqerl_test:combined_error(E, LibList)
end,
Out =
case xqerl_test:assert_error(Res, "XPTY0004") of
true -> {comment, "Correct error"};
{true, F} -> {comment, "WE: XPTY0004 " ++ binary_to_list(F)};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'contextDecl-052'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry =
"\n"
" import module namespace m=\"\"; \n"
" . eq 23\n"
" ",
{Env, Opts} = xqerl_test:handle_environment(environment('empty', __BaseDir)),
Qry1 = lists:flatten(Env ++ Qry),
io:format("Qry1: ~p~n", [Qry1]),
Hints = [
{filename:join(__BaseDir, "ContextItemDecl/libmodule-3.xq"),
<<"Q{}">>}
],
LibList = xqerl_code_server:compile_files(Hints),
Res =
try
Mod = xqerl_code_server:compile(filename:join(__BaseDir, "contextDecl-052.xq"), Qry1),
xqerl:run(Mod, Opts)
of
Etup when is_tuple(Etup), element(1, Etup) == xqError ->
xqerl_test:combined_error(Etup, LibList);
D ->
D
catch
_:E -> xqerl_test:combined_error(E, LibList)
end,
Out =
case xqerl_test:assert_error(Res, "XQST0113") of
true -> {comment, "Correct error"};
{true, F} -> {comment, "WE: XQST0113 " ++ binary_to_list(F)};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'contextDecl-053'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry =
"\n"
" declare variable $p := \"base-uri\";\n"
" declare variable $f := function-lookup(xs:QName(\"fn:\"||$p), 0);\n"
" declare context item := $f();\n"
" .\n"
" ",
{Env, Opts} = xqerl_test:handle_environment(environment('empty', __BaseDir)),
Qry1 = lists:flatten(Env ++ Qry),
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(filename:join(__BaseDir, "contextDecl-053.xq"), Qry1),
xqerl:run(Mod, Opts)
of
D -> D
catch
_:E -> E
end,
Out =
case
lists:any(
fun
({comment, _}) -> true;
(_) -> false
end,
[
case xqerl_test:assert_error(Res, "XPDY0002") of
true -> {comment, "Correct error"};
{true, F} -> {comment, "WE: XPDY0002 " ++ binary_to_list(F)};
{false, F} -> F
end,
case xqerl_test:assert_error(Res, "XQDY0054") of
true -> {comment, "Correct error"};
{true, F} -> {comment, "WE: XQDY0054 " ++ binary_to_list(F)};
{false, F} -> F
end
]
)
of
true -> {comment, "any-of"};
_ -> false
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'contextDecl-054'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry =
"\n"
" import module namespace m=\"\"; \n"
" xs:date(.) gt xs:date('1900-01-01')\n"
" ",
{Env, Opts} = xqerl_test:handle_environment([
{'decimal-formats', []},
{sources, []},
{collections, []},
{'static-base-uri', []},
{'context-item', ["current-dateTime()"]},
{vars, []},
{params, []},
{namespaces, []},
{schemas, []},
{resources, []},
{modules, [
{filename:join(__BaseDir, "ContextItemDecl/libmodule-2.xq"),
""}
]}
]),
Qry1 = lists:flatten(Env ++ Qry),
io:format("Qry1: ~p~n", [Qry1]),
Hints = [
{filename:join(__BaseDir, "ContextItemDecl/libmodule-2.xq"),
<<"Q{}">>}
],
LibList = xqerl_code_server:compile_files(Hints),
Res =
try
Mod = xqerl_code_server:compile(filename:join(__BaseDir, "contextDecl-054.xq"), Qry1),
xqerl:run(Mod, Opts)
of
Etup when is_tuple(Etup), element(1, Etup) == xqError ->
xqerl_test:combined_error(Etup, LibList);
D ->
D
catch
_:E -> xqerl_test:combined_error(E, LibList)
end,
Out =
case xqerl_test:assert_error(Res, "XPTY0004") of
true -> {comment, "Correct error"};
{true, F} -> {comment, "WE: XPTY0004 " ++ binary_to_list(F)};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'contextDecl-055'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry =
"\n"
" declare variable $f := function-lookup(xs:QName(\"fn:\"||$p), 0);\n"
" declare context item := <e/>;\n"
" declare variable $p := \"local-name\";\n"
" $f()\n"
" ",
{Env, Opts} = xqerl_test:handle_environment(environment('empty', __BaseDir)),
Qry1 = lists:flatten(Env ++ Qry),
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(filename:join(__BaseDir, "contextDecl-055.xq"), Qry1),
xqerl:run(Mod, Opts)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_eq(Res, "\"e\"") of
true -> {comment, "Equal"};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'contextDecl-056'(Config) ->
__BaseDir = ?config(base_dir, Config),
{skip, "feature:schemaImport"}.
'contextDecl-057'(Config) ->
__BaseDir = ?config(base_dir, Config),
{skip, "feature:schemaImport"}.
'contextDecl-058'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry =
"\n"
" import module namespace m=\"\";\n"
" declare context item as array(xs:string) external;\n"
" $m:v eq 'green'\n"
" ",
{Env, Opts} = xqerl_test:handle_environment([
{'decimal-formats', []},
{sources, []},
{collections, []},
{'static-base-uri', []},
{'context-item', ["['blue', 'green']"]},
{vars, []},
{params, []},
{namespaces, []},
{schemas, []},
{resources, []},
{modules, [
{filename:join(__BaseDir, "ContextItemDecl/libmodule-5.xq"),
""}
]}
]),
Qry1 = lists:flatten(Env ++ Qry),
io:format("Qry1: ~p~n", [Qry1]),
Hints = [
{filename:join(__BaseDir, "ContextItemDecl/libmodule-5.xq"),
<<"Q{}">>}
],
LibList = xqerl_code_server:compile_files(Hints),
Res =
try
Mod = xqerl_code_server:compile(filename:join(__BaseDir, "contextDecl-058.xq"), Qry1),
xqerl:run(Mod, Opts)
of
Etup when is_tuple(Etup), element(1, Etup) == xqError ->
xqerl_test:combined_error(Etup, LibList);
D ->
D
catch
_:E -> xqerl_test:combined_error(E, LibList)
end,
Out =
case xqerl_test:assert_true(Res) of
true -> {comment, "Empty"};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
| |
bfcc77386d8fc1b44c1f42ff698904e6a13da1498e4d30f3deb7e96b7bdd29f6 | ulrikstrid/dream-routes | main.ml | *
* Copyright 2021 ulrik . All rights reserved .
* Use of this source code is governed by a BSD - style
* license that can be found in the LICENSE file .
* Copyright 2021 ulrik. All rights reserved.
* Use of this source code is governed by a BSD-style
* license that can be found in the LICENSE file.
*)
let () =
Dream.run
@@ Dream.logger
@@ Dream_routes.routes Routes.[
Dream_routes.get @@ empty @--> (fun _request ->
Dream.html "Good morning, world!");
Dream_routes.get @@ s "echo" / int /? nil @--> (fun integer _request ->
Dream.html @@ Printf.sprintf "integer: %i" integer);
Dream_routes.get @@ s "echo" / str /? nil @--> (fun word _request ->
Dream.html word);
]
@@ Dream.not_found
| null | https://raw.githubusercontent.com/ulrikstrid/dream-routes/cea14ecc9fb2f4af5db2408f76f3b6f9ce426e75/src/bin/main.ml | ocaml | *
* Copyright 2021 ulrik . All rights reserved .
* Use of this source code is governed by a BSD - style
* license that can be found in the LICENSE file .
* Copyright 2021 ulrik. All rights reserved.
* Use of this source code is governed by a BSD-style
* license that can be found in the LICENSE file.
*)
let () =
Dream.run
@@ Dream.logger
@@ Dream_routes.routes Routes.[
Dream_routes.get @@ empty @--> (fun _request ->
Dream.html "Good morning, world!");
Dream_routes.get @@ s "echo" / int /? nil @--> (fun integer _request ->
Dream.html @@ Printf.sprintf "integer: %i" integer);
Dream_routes.get @@ s "echo" / str /? nil @--> (fun word _request ->
Dream.html word);
]
@@ Dream.not_found
| |
7acf49898f8d1b887972db38ebc8ea28877828c46aa5fb12f32a29a4f3961e21 | Bogdanp/racket-gui-easy | bidi.rkt | #lang racket/base
(require racket/gui/easy
racket/gui/easy/operator)
(define @msg (@ "Hi"))
(render
(window
#:title @msg
#:size '(200 100)
(vpanel
(input @msg (λ (_event text)
(@msg . := . text)))
(text @msg))))
| null | https://raw.githubusercontent.com/Bogdanp/racket-gui-easy/53f0bf9912b826bdd4ce0d070a04f1620b688978/examples/bidi.rkt | racket | #lang racket/base
(require racket/gui/easy
racket/gui/easy/operator)
(define @msg (@ "Hi"))
(render
(window
#:title @msg
#:size '(200 100)
(vpanel
(input @msg (λ (_event text)
(@msg . := . text)))
(text @msg))))
| |
7c27d780c228a1a656f93394ee712e821a92cdec7537e8d017bc342e68f02e48 | bvaugon/ocapic | proto.ml | (*************************************************************************)
(* *)
(* OCaPIC *)
(* *)
(* *)
This file is distributed under the terms of the CeCILL license .
(* See file ../../../LICENSE-en. *)
(* *)
(*************************************************************************)
open Printf
open Types
let verbose = false
let print = if verbose then prerr_endline else (fun _ -> ())
let refresh display =
if display.display_mode = On then
let addr = display.ram_addr in
Ddram.to_matrix display;
begin match display.cursor_mode with
| Hide -> ()
| Show ->
begin try
let i = addr mod 64 in
let j = addr / 64 in
let old_m = display.matrix.(i).(j) in
let m =
Array.init 8 (fun i -> Array.init 5 (fun j -> old_m.(i).(j)))
in
for j = 0 to 4 do
m.(7).(j) <- true;
done;
display.matrix.(i).(j) <- m;
with Invalid_argument _ -> () end
| Blink ->
begin try
let i = addr mod 64 in
let j = addr / 64 in
let old_m = display.matrix.(i).(j) in
let m =
Array.init 8 (fun i -> Array.init 5 (fun j -> old_m.(i).(j)))
in
for j = 0 to 4 do
m.(0).(j) <- true;
m.(7).(j) <- true;
done;
for i = 1 to 6 do
m.(i).(0) <- true;
m.(i).(4) <- true;
done;
display.matrix.(i).(j) <- m;
with Invalid_argument _ -> () end
end;
Display.show display;
;;
let clear display =
print "clear()";
Ddram.fill ' ' display;
Ddram.set_addr 0 display;
refresh display;
;;
let home display =
print "home()";
Ddram.set_addr 0 display;
refresh display;
;;
let entry_mode_set id sh display =
print (sprintf "entry_mode_set( I/D = %b , SH = %b )" id sh);
display.entry_mode_incr <- if id then Right else Left;
display.shift_display <- sh;
;;
let display_onoff_control d c b display =
print (sprintf "display_onoff_control( D = %b , C = %b , B = %b )" d c b);
display.display_mode <- if d then On else Off;
display.cursor_mode <- if c then if b then Blink else Show else Hide;
refresh display;
;;
let cursor_or_display_shift sc rl display =
print (sprintf "cursor_or_display_shift( S/C = %b , R/L = %b )" sc rl);
begin match (rl, sc) with
| (true, false) -> Ddram.incr_addr display;
| (false, false) -> Ddram.decr_addr display;
| (false, true) -> Ddram.rotate_left display;
| (true, true) -> Ddram.rotate_right display;
end;
refresh display;
;;
let function_set dl n f display =
print (sprintf "function_set( DL = %b , N = %b , F = %b )" dl n f);
display.bus_mode <- if dl then Eight else Four;
Ddram.set_two_line_mode n display;
display.font <- if f then F5x11 else F5x8;
;;
let set_cgram_address addr display =
print (sprintf "set_cgram_address(%02x)" addr);
display.selected_ram <- CGRam;
display.ram_addr <- addr;
;;
let set_ddram_address addr display =
print (sprintf "set_ddram_address(%02x)" addr);
display.selected_ram <- DDRam;
Ddram.set_addr addr display;
refresh display;
;;
let send bus_low bus_port value display =
Simul.write_port bus_port (
match display.bus_mode with
| Eight -> value
| Four ->
if bus_low > 0x0F then (bus_low land 0x0F) lor (value land 0xF0)
else bus_low lor ((value lsl 4) land 0xF0)
)
;;
let read_busy_flag_and_address bus_low bus_port display =
print "read_busy_flag_and_address()";
send bus_low bus_port (display.ram_addr) display;
;;
let write_data_to_ram data display =
print (sprintf "write_data_to_ram(%C)" (char_of_int data));
match display.selected_ram with
| DDRam ->
Ddram.write (char_of_int data) display;
cursor_or_display_shift display.shift_display
(display.entry_mode_incr = Right) display;
| CGRam ->
Cgram.write data display;
;;
let read_data_from_ram bus_low bus_port display=
print "read_data_from_ram()";
match display.selected_ram with
| DDRam ->
send bus_low bus_port (int_of_char (Ddram.read display)) display;
| CGRam ->
send bus_low bus_port (Cgram.read display) display;
;;
let exec_8bit rs rw bus bus_port display =
let bus_bit bit = ((1 lsl bit) land bus) <> 0 in
match (rs, rw) with
| (false, false) ->
if bus = 0 then ()
else if bus = 1 then clear display
else if bus = 2 || bus = 3 then home display
else if bus < 8 then
entry_mode_set (bus_bit 1) (bus_bit 0) display
else if bus < 16 then
display_onoff_control (bus_bit 2) (bus_bit 1) (bus_bit 0) display
else if bus < 32 then
(if bus_bit 3 then
cursor_or_display_shift true (not (bus_bit 2)) display;
cursor_or_display_shift false (bus_bit 2)) display
else if bus < 64 then
function_set (bus_bit 4) (bus_bit 3) (bus_bit 2) display
else if bus < 128 then
set_cgram_address (bus land 0b111111) display
else
set_ddram_address (bus land 0b1111111) display
| (false, true) -> read_busy_flag_and_address bus bus_port display
| (true, false) -> write_data_to_ram bus display
| (true, true) -> read_data_from_ram bus bus_port display
;;
let exec_4bit =
let mem_bus = ref (-1) in
let old_rw = ref false in
fun rs rw bus bus_port display ->
if !old_rw <> rw then ( old_rw := rw ; mem_bus := -1 );
if rw then (
if !mem_bus = -1 then (
mem_bus := 0;
exec_8bit rs rw ((bus land 0x0F) lor 0xF0) bus_port display;
) else (
mem_bus := -1;
exec_8bit rs rw (bus land 0x0F) bus_port display;
)
) else (
let old_bus = !mem_bus in
if old_bus = -1 then mem_bus := bus
else (
mem_bus := -1;
exec_8bit rs rw ((old_bus land 0xF0) lor (bus lsr 4))
bus_port display;
)
)
;;
let register display =
let handler () =
let rs_val = Simul.test_pin display.rs in
let rw_val = Simul.test_pin display.rw in
let bus_val = Simul.read_port display.bus in
match display.bus_mode with
| Eight -> exec_8bit rs_val rw_val bus_val display.bus display;
| Four -> exec_4bit rs_val rw_val bus_val display.bus display;
in
Simul.add_handler (Simul.Set_pin_handler (display.e, handler));
;;
| null | https://raw.githubusercontent.com/bvaugon/ocapic/a14cd9ec3f5022aeb5fe2264d595d7e8f1ddf58a/src/simulator/lcd/proto.ml | ocaml | ***********************************************************************
OCaPIC
See file ../../../LICENSE-en.
*********************************************************************** |
This file is distributed under the terms of the CeCILL license .
open Printf
open Types
let verbose = false
let print = if verbose then prerr_endline else (fun _ -> ())
let refresh display =
if display.display_mode = On then
let addr = display.ram_addr in
Ddram.to_matrix display;
begin match display.cursor_mode with
| Hide -> ()
| Show ->
begin try
let i = addr mod 64 in
let j = addr / 64 in
let old_m = display.matrix.(i).(j) in
let m =
Array.init 8 (fun i -> Array.init 5 (fun j -> old_m.(i).(j)))
in
for j = 0 to 4 do
m.(7).(j) <- true;
done;
display.matrix.(i).(j) <- m;
with Invalid_argument _ -> () end
| Blink ->
begin try
let i = addr mod 64 in
let j = addr / 64 in
let old_m = display.matrix.(i).(j) in
let m =
Array.init 8 (fun i -> Array.init 5 (fun j -> old_m.(i).(j)))
in
for j = 0 to 4 do
m.(0).(j) <- true;
m.(7).(j) <- true;
done;
for i = 1 to 6 do
m.(i).(0) <- true;
m.(i).(4) <- true;
done;
display.matrix.(i).(j) <- m;
with Invalid_argument _ -> () end
end;
Display.show display;
;;
let clear display =
print "clear()";
Ddram.fill ' ' display;
Ddram.set_addr 0 display;
refresh display;
;;
let home display =
print "home()";
Ddram.set_addr 0 display;
refresh display;
;;
let entry_mode_set id sh display =
print (sprintf "entry_mode_set( I/D = %b , SH = %b )" id sh);
display.entry_mode_incr <- if id then Right else Left;
display.shift_display <- sh;
;;
let display_onoff_control d c b display =
print (sprintf "display_onoff_control( D = %b , C = %b , B = %b )" d c b);
display.display_mode <- if d then On else Off;
display.cursor_mode <- if c then if b then Blink else Show else Hide;
refresh display;
;;
let cursor_or_display_shift sc rl display =
print (sprintf "cursor_or_display_shift( S/C = %b , R/L = %b )" sc rl);
begin match (rl, sc) with
| (true, false) -> Ddram.incr_addr display;
| (false, false) -> Ddram.decr_addr display;
| (false, true) -> Ddram.rotate_left display;
| (true, true) -> Ddram.rotate_right display;
end;
refresh display;
;;
let function_set dl n f display =
print (sprintf "function_set( DL = %b , N = %b , F = %b )" dl n f);
display.bus_mode <- if dl then Eight else Four;
Ddram.set_two_line_mode n display;
display.font <- if f then F5x11 else F5x8;
;;
let set_cgram_address addr display =
print (sprintf "set_cgram_address(%02x)" addr);
display.selected_ram <- CGRam;
display.ram_addr <- addr;
;;
let set_ddram_address addr display =
print (sprintf "set_ddram_address(%02x)" addr);
display.selected_ram <- DDRam;
Ddram.set_addr addr display;
refresh display;
;;
let send bus_low bus_port value display =
Simul.write_port bus_port (
match display.bus_mode with
| Eight -> value
| Four ->
if bus_low > 0x0F then (bus_low land 0x0F) lor (value land 0xF0)
else bus_low lor ((value lsl 4) land 0xF0)
)
;;
let read_busy_flag_and_address bus_low bus_port display =
print "read_busy_flag_and_address()";
send bus_low bus_port (display.ram_addr) display;
;;
let write_data_to_ram data display =
print (sprintf "write_data_to_ram(%C)" (char_of_int data));
match display.selected_ram with
| DDRam ->
Ddram.write (char_of_int data) display;
cursor_or_display_shift display.shift_display
(display.entry_mode_incr = Right) display;
| CGRam ->
Cgram.write data display;
;;
let read_data_from_ram bus_low bus_port display=
print "read_data_from_ram()";
match display.selected_ram with
| DDRam ->
send bus_low bus_port (int_of_char (Ddram.read display)) display;
| CGRam ->
send bus_low bus_port (Cgram.read display) display;
;;
let exec_8bit rs rw bus bus_port display =
let bus_bit bit = ((1 lsl bit) land bus) <> 0 in
match (rs, rw) with
| (false, false) ->
if bus = 0 then ()
else if bus = 1 then clear display
else if bus = 2 || bus = 3 then home display
else if bus < 8 then
entry_mode_set (bus_bit 1) (bus_bit 0) display
else if bus < 16 then
display_onoff_control (bus_bit 2) (bus_bit 1) (bus_bit 0) display
else if bus < 32 then
(if bus_bit 3 then
cursor_or_display_shift true (not (bus_bit 2)) display;
cursor_or_display_shift false (bus_bit 2)) display
else if bus < 64 then
function_set (bus_bit 4) (bus_bit 3) (bus_bit 2) display
else if bus < 128 then
set_cgram_address (bus land 0b111111) display
else
set_ddram_address (bus land 0b1111111) display
| (false, true) -> read_busy_flag_and_address bus bus_port display
| (true, false) -> write_data_to_ram bus display
| (true, true) -> read_data_from_ram bus bus_port display
;;
let exec_4bit =
let mem_bus = ref (-1) in
let old_rw = ref false in
fun rs rw bus bus_port display ->
if !old_rw <> rw then ( old_rw := rw ; mem_bus := -1 );
if rw then (
if !mem_bus = -1 then (
mem_bus := 0;
exec_8bit rs rw ((bus land 0x0F) lor 0xF0) bus_port display;
) else (
mem_bus := -1;
exec_8bit rs rw (bus land 0x0F) bus_port display;
)
) else (
let old_bus = !mem_bus in
if old_bus = -1 then mem_bus := bus
else (
mem_bus := -1;
exec_8bit rs rw ((old_bus land 0xF0) lor (bus lsr 4))
bus_port display;
)
)
;;
let register display =
let handler () =
let rs_val = Simul.test_pin display.rs in
let rw_val = Simul.test_pin display.rw in
let bus_val = Simul.read_port display.bus in
match display.bus_mode with
| Eight -> exec_8bit rs_val rw_val bus_val display.bus display;
| Four -> exec_4bit rs_val rw_val bus_val display.bus display;
in
Simul.add_handler (Simul.Set_pin_handler (display.e, handler));
;;
|
3b056638dbe279269cb77ebbad7cae134b9172b7b7a3af434fd4416831748c40 | generateme/cljplot | core.clj | (ns cljplot.core
(:require [clojure2d.core :refer [next-filename]]
[cljplot.common :refer :all]
[clojure2d.extra.utils :as utils]
[cljplot.impl.histogram :refer :all]
[cljplot.build :as b]
[cljplot.render :as r]
[cljplot.impl.strips :refer :all]
[cljplot.impl.scatter :refer :all]
[cljplot.impl.line :refer :all]
[cljplot.impl.heatmap :refer :all]
[cljplot.impl.label :refer :all]
[cljplot.impl.math :refer :all]
[cljplot.impl.free :refer :all]
[cljplot.impl.time-series :refer :all]))
(defn save
"Save `chart`."
([chart name]
(clojure2d.core/save chart name))
([chart]
(clojure2d.core/save chart (next-filename "charts/" ".png"))))
(def show utils/show-image)
;;
(defmacro xy-chart
[conf series & mods]
`(-> ~series
(b/preprocess-series)
~@mods
(r/render-lattice ~conf)))
| null | https://raw.githubusercontent.com/generateme/cljplot/1eb865439653c95940be18421298c574b7ce8db6/src/cljplot/core.clj | clojure | (ns cljplot.core
(:require [clojure2d.core :refer [next-filename]]
[cljplot.common :refer :all]
[clojure2d.extra.utils :as utils]
[cljplot.impl.histogram :refer :all]
[cljplot.build :as b]
[cljplot.render :as r]
[cljplot.impl.strips :refer :all]
[cljplot.impl.scatter :refer :all]
[cljplot.impl.line :refer :all]
[cljplot.impl.heatmap :refer :all]
[cljplot.impl.label :refer :all]
[cljplot.impl.math :refer :all]
[cljplot.impl.free :refer :all]
[cljplot.impl.time-series :refer :all]))
(defn save
"Save `chart`."
([chart name]
(clojure2d.core/save chart name))
([chart]
(clojure2d.core/save chart (next-filename "charts/" ".png"))))
(def show utils/show-image)
(defmacro xy-chart
[conf series & mods]
`(-> ~series
(b/preprocess-series)
~@mods
(r/render-lattice ~conf)))
| |
f4bd19cd0ecb930de99f814656224014bc7ddf1a95b5f5413f86c2a26f93fabd | vii/dysfunkycom | pixels.lisp | Demonstration / Test of using SDL ( Simple Media Layer ) library
using CFFI for foreign function interfacing ...
;;;; (C)2006 Justin Heyes-Jones
;;;; see COPYING for license
(in-package #:sdl-examples)
(defun pixels-1 ()
(sdl:with-init ()
(sdl:window 640 480)
(setf (sdl:frame-rate) 0)
(sdl:with-events ()
(:quit-event () t)
(:idle ()
(sdl:draw-pixel-* (random 640) (random 480)
:color (sdl:color :r (random 255)
:g (random 255)
:b (random 255))
:surface sdl:*default-display*)
(sdl:update-display)))))
(defun pixels-2 ()
(let ((width 640) (height 480))
(sdl:with-init ()
(sdl:window width height)
(setf (sdl:frame-rate) 0)
(sdl:with-color (color (sdl:color))
(sdl:with-events ()
(:quit-event () t)
(:idle ()
(sdl-base::with-pixel (disp (sdl:fp sdl:*default-display*))
(sdl-base::write-pixel disp (random width) (random height)
(sdl:map-color (sdl:set-color-* color
:r (random 255)
:g (random 255)
:b (random 255))
sdl:*default-display*)))
(sdl:update-display)))))))
(defun pixels-3 ()
(let ((width 640) (height 480))
(sdl:with-init ()
(sdl:window width height)
(setf (sdl:frame-rate) 0)
(sdl:with-rectangle (template (sdl:rectangle :w 1 :h 1))
(sdl:with-color (color (sdl:color))
(sdl:with-events ()
(:quit-event () t)
(:idle ()
(sdl:fill-surface (sdl:set-color-* color
:r (random 255)
:g (random 255)
:b (random 255))
:template (sdl:set-rectangle-* template
:x (random width)
:y (random height))
:update t
:surface sdl:*default-display*))))))))
(defun pixels-4 ()
(let ((width 640) (height 480))
(sdl:with-init ()
(sdl:window width height)
(setf (sdl:frame-rate) 0)
(let ((color (sdl:color))
(template (sdl:rectangle :w 1 :h 1)))
(sdl:with-events ()
(:quit-event () t)
(:idle ()
(sdl:fill-surface (sdl:set-color-* color :r (random 255)
:g (random 255)
:b (random 255))
:template (sdl:set-rectangle-* template
:x (random width)
:y (random height))
:update t
:surface sdl:*default-display*)))))))
(defun pixels-5 ()
(sdl:with-init ()
(sdl:window 200 100)
(setf (sdl:frame-rate) 0)
Read the pixel at 0,0 and print the rgba value
(let ((col (sdl:read-pixel (sdl:point :x 0 :y 0)
:surface sdl:*default-display*)))
(format t "READ: ~A, ~A, ~A, ~A~%"
(sdl:r col) (sdl:g col) (sdl:b col) (sdl:a col)))
Write r , , b to 0,0 and then read and print the rgba value
(sdl:draw-pixel (sdl:point)
:surface sdl:*default-display*
:color (sdl:color :r 255 :g 255 :b 255))
(let ((col (sdl:read-pixel (sdl:point :x 0 :y 0)
:surface sdl:*default-display*)))
(format t "READ: ~A, ~A, ~A, ~A~%"
(sdl:r col) (sdl:g col) (sdl:b col) (sdl:a col)))
(sdl:with-events ()
(:quit-event () t)
(:idle () (sdl:update-display)))))
| null | https://raw.githubusercontent.com/vii/dysfunkycom/a493fa72662b79e7c4e70361ad0ea3c7235b6166/addons/lispbuilder-sdl/examples/pixels.lisp | lisp | (C)2006 Justin Heyes-Jones
see COPYING for license | Demonstration / Test of using SDL ( Simple Media Layer ) library
using CFFI for foreign function interfacing ...
(in-package #:sdl-examples)
(defun pixels-1 ()
(sdl:with-init ()
(sdl:window 640 480)
(setf (sdl:frame-rate) 0)
(sdl:with-events ()
(:quit-event () t)
(:idle ()
(sdl:draw-pixel-* (random 640) (random 480)
:color (sdl:color :r (random 255)
:g (random 255)
:b (random 255))
:surface sdl:*default-display*)
(sdl:update-display)))))
(defun pixels-2 ()
(let ((width 640) (height 480))
(sdl:with-init ()
(sdl:window width height)
(setf (sdl:frame-rate) 0)
(sdl:with-color (color (sdl:color))
(sdl:with-events ()
(:quit-event () t)
(:idle ()
(sdl-base::with-pixel (disp (sdl:fp sdl:*default-display*))
(sdl-base::write-pixel disp (random width) (random height)
(sdl:map-color (sdl:set-color-* color
:r (random 255)
:g (random 255)
:b (random 255))
sdl:*default-display*)))
(sdl:update-display)))))))
(defun pixels-3 ()
(let ((width 640) (height 480))
(sdl:with-init ()
(sdl:window width height)
(setf (sdl:frame-rate) 0)
(sdl:with-rectangle (template (sdl:rectangle :w 1 :h 1))
(sdl:with-color (color (sdl:color))
(sdl:with-events ()
(:quit-event () t)
(:idle ()
(sdl:fill-surface (sdl:set-color-* color
:r (random 255)
:g (random 255)
:b (random 255))
:template (sdl:set-rectangle-* template
:x (random width)
:y (random height))
:update t
:surface sdl:*default-display*))))))))
(defun pixels-4 ()
(let ((width 640) (height 480))
(sdl:with-init ()
(sdl:window width height)
(setf (sdl:frame-rate) 0)
(let ((color (sdl:color))
(template (sdl:rectangle :w 1 :h 1)))
(sdl:with-events ()
(:quit-event () t)
(:idle ()
(sdl:fill-surface (sdl:set-color-* color :r (random 255)
:g (random 255)
:b (random 255))
:template (sdl:set-rectangle-* template
:x (random width)
:y (random height))
:update t
:surface sdl:*default-display*)))))))
(defun pixels-5 ()
(sdl:with-init ()
(sdl:window 200 100)
(setf (sdl:frame-rate) 0)
Read the pixel at 0,0 and print the rgba value
(let ((col (sdl:read-pixel (sdl:point :x 0 :y 0)
:surface sdl:*default-display*)))
(format t "READ: ~A, ~A, ~A, ~A~%"
(sdl:r col) (sdl:g col) (sdl:b col) (sdl:a col)))
Write r , , b to 0,0 and then read and print the rgba value
(sdl:draw-pixel (sdl:point)
:surface sdl:*default-display*
:color (sdl:color :r 255 :g 255 :b 255))
(let ((col (sdl:read-pixel (sdl:point :x 0 :y 0)
:surface sdl:*default-display*)))
(format t "READ: ~A, ~A, ~A, ~A~%"
(sdl:r col) (sdl:g col) (sdl:b col) (sdl:a col)))
(sdl:with-events ()
(:quit-event () t)
(:idle () (sdl:update-display)))))
|
af26741b7ad01c6f6fe728e8a53b1b1d05ad4b94aa3631199a98ac1809a66f8c | hypernumbers/LuvvieScript | 1d_records_and_fns.erl | -module('1c_records').
-record(bish, {
bash = [],
bosh = erk
}).
-export([
recordfn/1
]).
recordfn(#bish{bash = Bash}) ->
Bash.
| null | https://raw.githubusercontent.com/hypernumbers/LuvvieScript/d10da50e0719ff26690749570c75e1e614214381/test/not_passing/src/1d_records_and_fns.erl | erlang | -module('1c_records').
-record(bish, {
bash = [],
bosh = erk
}).
-export([
recordfn/1
]).
recordfn(#bish{bash = Bash}) ->
Bash.
| |
358d5ceff44816457213cfd9a4904647e86e6bc34768cccae9495c18b13bf6fc | imrekoszo/polylith-kaocha | bricks_to_test.clj | (ns polylith-kaocha.kaocha-test-runner.bricks-to-test
"Copied from polylith.clj.core.change.bricks-to-test so it doesn't filter out
bricks that don't have dedicated test sources"
(:require [clojure.set :as set]))
(defn bricks-to-test-for-project [{:keys [is-dev alias name base-names component-names]}
settings
changed-projects
changed-components
changed-bases
project-to-indirect-changes
selected-bricks
selected-projects
is-dev-user-input
is-run-all-brick-tests]
(let [include-project? (or (or (contains? selected-projects name)
(contains? selected-projects alias))
(and (empty? selected-projects)
(or (not is-dev)
is-dev-user-input)))
project-has-changed? (contains? (set changed-projects) name)
;;
HERE IS THE CHANGE PART 1
;;
all - brick - names ( into # { } ( : test ) [ base - names component - names ] )
;;
all-brick-names (into #{} (comp (mapcat vals) cat) [base-names component-names])
;;
;;
END OF CHANGE PART 1
;;
;; If the :test key is given for a project in workspace.edn, then only include
;; the specified bricks, otherwise, run tests for all bricks that have tests.
included-bricks (if-let [bricks (get-in settings [:projects name :test :include])]
(set/intersection all-brick-names (set bricks))
all-brick-names)
selected-bricks (if selected-bricks
(set selected-bricks)
all-brick-names)
changed-bricks (if include-project?
(if (or is-run-all-brick-tests project-has-changed?)
;; if we pass in :all or :all-bricks or if the project has changed
;; then always run all brick tests.
included-bricks
(set/intersection included-bricks
selected-bricks
(into #{} cat
[changed-components
changed-bases
(-> name project-to-indirect-changes :src)
(-> name project-to-indirect-changes :test)])))
#{})
;; And finally, if brick:BRICK is given, also filter on that, which means that if we
;; pass in both brick:BRICK and :all, we will run the tests for all these bricks,
;; whether they have changed or not (directly or indirectly).
bricks-to-test (set/intersection changed-bricks selected-bricks)]
;;
HERE IS THE CHANGE PART 2
;;
;; WE ONLY NEED A SET THAT REPRESENTS THE PROJECT'S BRICKS TO TEST
;;
bricks-to-test
;;
END OF CHANGE PART 2
;;
))
(defn bricks-to-test
[project {:keys [changes settings user-input] :as _workspace}]
(let [{:keys [is-dev is-run-all-brick-tests selected-bricks selected-projects]} user-input
{:keys [changed-components
changed-bases
changed-projects
project-to-indirect-changes]} changes]
(bricks-to-test-for-project
project settings changed-projects changed-components changed-bases
project-to-indirect-changes selected-bricks selected-projects is-dev
is-run-all-brick-tests)))
| null | https://raw.githubusercontent.com/imrekoszo/polylith-kaocha/1d5d0dd1fea335969ea11d59dd6f5f4977b8cdfe/components/kaocha-test-runner/src/polylith_kaocha/kaocha_test_runner/bricks_to_test.clj | clojure |
If the :test key is given for a project in workspace.edn, then only include
the specified bricks, otherwise, run tests for all bricks that have tests.
if we pass in :all or :all-bricks or if the project has changed
then always run all brick tests.
And finally, if brick:BRICK is given, also filter on that, which means that if we
pass in both brick:BRICK and :all, we will run the tests for all these bricks,
whether they have changed or not (directly or indirectly).
WE ONLY NEED A SET THAT REPRESENTS THE PROJECT'S BRICKS TO TEST
| (ns polylith-kaocha.kaocha-test-runner.bricks-to-test
"Copied from polylith.clj.core.change.bricks-to-test so it doesn't filter out
bricks that don't have dedicated test sources"
(:require [clojure.set :as set]))
(defn bricks-to-test-for-project [{:keys [is-dev alias name base-names component-names]}
settings
changed-projects
changed-components
changed-bases
project-to-indirect-changes
selected-bricks
selected-projects
is-dev-user-input
is-run-all-brick-tests]
(let [include-project? (or (or (contains? selected-projects name)
(contains? selected-projects alias))
(and (empty? selected-projects)
(or (not is-dev)
is-dev-user-input)))
project-has-changed? (contains? (set changed-projects) name)
HERE IS THE CHANGE PART 1
all - brick - names ( into # { } ( : test ) [ base - names component - names ] )
all-brick-names (into #{} (comp (mapcat vals) cat) [base-names component-names])
END OF CHANGE PART 1
included-bricks (if-let [bricks (get-in settings [:projects name :test :include])]
(set/intersection all-brick-names (set bricks))
all-brick-names)
selected-bricks (if selected-bricks
(set selected-bricks)
all-brick-names)
changed-bricks (if include-project?
(if (or is-run-all-brick-tests project-has-changed?)
included-bricks
(set/intersection included-bricks
selected-bricks
(into #{} cat
[changed-components
changed-bases
(-> name project-to-indirect-changes :src)
(-> name project-to-indirect-changes :test)])))
#{})
bricks-to-test (set/intersection changed-bricks selected-bricks)]
HERE IS THE CHANGE PART 2
bricks-to-test
END OF CHANGE PART 2
))
(defn bricks-to-test
[project {:keys [changes settings user-input] :as _workspace}]
(let [{:keys [is-dev is-run-all-brick-tests selected-bricks selected-projects]} user-input
{:keys [changed-components
changed-bases
changed-projects
project-to-indirect-changes]} changes]
(bricks-to-test-for-project
project settings changed-projects changed-components changed-bases
project-to-indirect-changes selected-bricks selected-projects is-dev
is-run-all-brick-tests)))
|
5ad7c4081fa84a431d98d1cbbdb9f2a63afa0f96ee65e02a8334dfdf0763ca1c | bruz/hotframeworks | stackoverflow.clj | (ns hotframeworks.test.statistic-types.stackoverflow
(:require [hotframeworks.statistic-types.stackoverflow :as stackoverflow]
[environ.core :refer [env]]
[stacktraces.tags :as tags])
(:use midje.sweet))
(fact "statistic provided with valid stackoverflow tag"
(def framework {:stackoverflow_tag "noir"})
(stackoverflow/stat framework) => 300
(provided (tags/by-name "noir" {:key "KEY"}) => {:body {:items [{:count 300}]}})
(provided (env :stackoverflow-api-key) => "KEY"))
(fact "statistic 0 with valid stackoverflow tag"
(def framework {:stackoverflow_tag "uki"})
(stackoverflow/stat framework) => 0
(provided (tags/by-name "uki" {:key "KEY"}) => {:body {:items []}})
(provided (env :stackoverflow-api-key) => "KEY"))
(fact "statistic is nil without a stackoverflow tag"
(def framework {})
(stackoverflow/stat framework) => nil)
| null | https://raw.githubusercontent.com/bruz/hotframeworks/629aa8f3cd7556479ea5cd7720d8b06ee4926ae4/test/hotframeworks/test/statistic_types/stackoverflow.clj | clojure | (ns hotframeworks.test.statistic-types.stackoverflow
(:require [hotframeworks.statistic-types.stackoverflow :as stackoverflow]
[environ.core :refer [env]]
[stacktraces.tags :as tags])
(:use midje.sweet))
(fact "statistic provided with valid stackoverflow tag"
(def framework {:stackoverflow_tag "noir"})
(stackoverflow/stat framework) => 300
(provided (tags/by-name "noir" {:key "KEY"}) => {:body {:items [{:count 300}]}})
(provided (env :stackoverflow-api-key) => "KEY"))
(fact "statistic 0 with valid stackoverflow tag"
(def framework {:stackoverflow_tag "uki"})
(stackoverflow/stat framework) => 0
(provided (tags/by-name "uki" {:key "KEY"}) => {:body {:items []}})
(provided (env :stackoverflow-api-key) => "KEY"))
(fact "statistic is nil without a stackoverflow tag"
(def framework {})
(stackoverflow/stat framework) => nil)
| |
1756c0e049b517b9303955b4871d14b88269e8e6eb2dc4424222102d1694daac | willtim/Expresso | Utils.hs | {-# LANGUAGE DeriveDataTypeable #-}
# LANGUAGE DeriveFunctor #
# LANGUAGE DeriveFoldable #
{-# LANGUAGE DeriveTraversable #-}
# LANGUAGE FlexibleContexts #
# LANGUAGE MultiParamTypeClasses #
# LANGUAGE ScopedTypeVariables #
# LANGUAGE StandaloneDeriving #
# LANGUAGE TypeOperators #
# LANGUAGE UndecidableInstances #
-- |
-- Module : Expresso.Utils
Copyright : ( c ) 2017 - 2019
-- License : BSD3
--
-- Maintainer :
-- Stability : experimental
-- Portability : portable
--
-- Recursion scheme utilities.
--
module Expresso.Utils(
Fix(..),
K(..),
(:*:)(..),
(:+:)(..),
cata,
cataM,
para,
ana,
(&&&),
(***),
first,
second,
showError,
View(..),
annotate,
stripAnn,
getAnn,
withAnn
)
where
import Control.Monad
import Data.Data
newtype Fix f = Fix { unFix :: f (Fix f) }
deriving instance (Typeable f, Data (f (Fix f))) => Data (Fix f)
data K a b = K { unK :: a }
deriving (Eq, Ord, Show, Functor, Foldable, Traversable, Data)
data (f :*: g) a = (:*:) { left :: f a, right :: g a }
deriving (Eq, Ord, Show, Functor, Foldable, Traversable, Data)
data (f :+: g) a = InL (f a) | InR (g a)
deriving (Eq, Ord, Show, Functor, Foldable, Traversable, Data)
cata :: Functor f => (f a -> a) -> Fix f -> a
cata phi = phi . fmap (cata phi) . unFix
cataM :: (Monad m, Traversable f) =>
(f a -> m a) -> Fix f -> m a
cataM algM = algM <=< (mapM (cataM algM) . unFix)
para :: Functor f => (f (b, Fix f) -> b) -> Fix f -> b
para phi = phi . fmap (para phi &&& id) . unFix
ana :: Functor f => (a -> f a) -> a -> Fix f
ana coalg = Fix . fmap (ana coalg) . coalg
Equivalent to specialized version from Arrow
(&&&) :: (a -> b) -> (a -> c) -> (a -> (b,c))
f &&& g = \a -> (f a, g a)
Equivalent to specialized version from Arrow
(***) :: (a -> b) -> (c -> d) -> ((a, c) -> (b, d))
f *** g = \(a, b) -> (f a, g b)
Equivalent to specialized version from Arrow
first :: (a -> b) -> (a,c) -> (b,c)
first f (a,c) = (f a, c)
Equivalent to specialized version from Arrow
second :: (b -> c) -> (a,b) -> (a,c)
second f (a,b) = (a, f b)
instance (Functor f, Show (f (Fix f))) => Show (Fix f) where
showsPrec d (Fix f) = showsPrec d f
instance (Functor f, Eq (f (Fix f))) => Eq (Fix f) where
fa == fb = unFix fa == unFix fb
instance (Functor f, Ord (f (Fix f))) => Ord (Fix f) where
compare fa fb = compare (unFix fa) (unFix fb)
class View f a where
proj :: a -> f a
inj :: f a -> a
showError :: Show a => Either a b -> Either String b
showError = either (Left . show) Right
-- | add annotation
annotate :: forall f a. Functor f => a -> Fix f -> Fix (f :*: K a)
annotate ann = cata alg where
alg :: f (Fix (f :*: K a)) -> Fix (f :*: K a)
alg e = Fix (e :*: K ann)
-- | strip annotations
stripAnn :: forall f a. Functor f => Fix (f :*: K a) -> Fix f
stripAnn = cata alg where
alg :: (f :*: K a) (Fix f) -> Fix f
alg (e :*: _) = Fix e
-- | retrieve annotation
getAnn :: Fix (f :*: K a) -> a
getAnn = unK . right . unFix
-- | fix with annotation
withAnn :: a -> f (Fix (f :*: K a) )-> Fix (f :*: K a)
withAnn ann e = Fix (e :*: K ann)
| null | https://raw.githubusercontent.com/willtim/Expresso/add7480c867b98819a482adb6bcd2da730928f1a/src/Expresso/Utils.hs | haskell | # LANGUAGE DeriveDataTypeable #
# LANGUAGE DeriveTraversable #
|
Module : Expresso.Utils
License : BSD3
Maintainer :
Stability : experimental
Portability : portable
Recursion scheme utilities.
| add annotation
| strip annotations
| retrieve annotation
| fix with annotation | # LANGUAGE DeriveFunctor #
# LANGUAGE DeriveFoldable #
# LANGUAGE FlexibleContexts #
# LANGUAGE MultiParamTypeClasses #
# LANGUAGE ScopedTypeVariables #
# LANGUAGE StandaloneDeriving #
# LANGUAGE TypeOperators #
# LANGUAGE UndecidableInstances #
Copyright : ( c ) 2017 - 2019
module Expresso.Utils(
Fix(..),
K(..),
(:*:)(..),
(:+:)(..),
cata,
cataM,
para,
ana,
(&&&),
(***),
first,
second,
showError,
View(..),
annotate,
stripAnn,
getAnn,
withAnn
)
where
import Control.Monad
import Data.Data
newtype Fix f = Fix { unFix :: f (Fix f) }
deriving instance (Typeable f, Data (f (Fix f))) => Data (Fix f)
data K a b = K { unK :: a }
deriving (Eq, Ord, Show, Functor, Foldable, Traversable, Data)
data (f :*: g) a = (:*:) { left :: f a, right :: g a }
deriving (Eq, Ord, Show, Functor, Foldable, Traversable, Data)
data (f :+: g) a = InL (f a) | InR (g a)
deriving (Eq, Ord, Show, Functor, Foldable, Traversable, Data)
cata :: Functor f => (f a -> a) -> Fix f -> a
cata phi = phi . fmap (cata phi) . unFix
cataM :: (Monad m, Traversable f) =>
(f a -> m a) -> Fix f -> m a
cataM algM = algM <=< (mapM (cataM algM) . unFix)
para :: Functor f => (f (b, Fix f) -> b) -> Fix f -> b
para phi = phi . fmap (para phi &&& id) . unFix
ana :: Functor f => (a -> f a) -> a -> Fix f
ana coalg = Fix . fmap (ana coalg) . coalg
Equivalent to specialized version from Arrow
(&&&) :: (a -> b) -> (a -> c) -> (a -> (b,c))
f &&& g = \a -> (f a, g a)
Equivalent to specialized version from Arrow
(***) :: (a -> b) -> (c -> d) -> ((a, c) -> (b, d))
f *** g = \(a, b) -> (f a, g b)
Equivalent to specialized version from Arrow
first :: (a -> b) -> (a,c) -> (b,c)
first f (a,c) = (f a, c)
Equivalent to specialized version from Arrow
second :: (b -> c) -> (a,b) -> (a,c)
second f (a,b) = (a, f b)
instance (Functor f, Show (f (Fix f))) => Show (Fix f) where
showsPrec d (Fix f) = showsPrec d f
instance (Functor f, Eq (f (Fix f))) => Eq (Fix f) where
fa == fb = unFix fa == unFix fb
instance (Functor f, Ord (f (Fix f))) => Ord (Fix f) where
compare fa fb = compare (unFix fa) (unFix fb)
class View f a where
proj :: a -> f a
inj :: f a -> a
showError :: Show a => Either a b -> Either String b
showError = either (Left . show) Right
annotate :: forall f a. Functor f => a -> Fix f -> Fix (f :*: K a)
annotate ann = cata alg where
alg :: f (Fix (f :*: K a)) -> Fix (f :*: K a)
alg e = Fix (e :*: K ann)
stripAnn :: forall f a. Functor f => Fix (f :*: K a) -> Fix f
stripAnn = cata alg where
alg :: (f :*: K a) (Fix f) -> Fix f
alg (e :*: _) = Fix e
getAnn :: Fix (f :*: K a) -> a
getAnn = unK . right . unFix
withAnn :: a -> f (Fix (f :*: K a) )-> Fix (f :*: K a)
withAnn ann e = Fix (e :*: K ann)
|
6a9ee5aa9d51c0d396717b79f73d7d53234d2a8c9bc18fc8d00f9c6dfe1609bd | kyleburton/sandbox | yaml.clj | (ns com.github.kyleburton.sandbox.yaml
(:import [org.ho.yaml Yaml]))
;; symbol's don't dump?
( Yaml / dump { : a 1 : b 2 : c [ 3 4 5 ] } )
(println
(Yaml/dump
(doto (java.util.HashMap.) (.put "a" 1)
(.put "b" 2)
(.put "c" [3 4 5]))))
;; quite nice, but can we round-trip?
;; ---
b : 2
;; c: !clojure.lang.LazilyPersistentVector
;; - 3
;; - 4
;; - 5
a : 1
;; NO :(
;; (Yaml/load
;; (Yaml/dump
( doto ( java.util . . ) ( .put " a " 1 )
( .put " b " 2 )
;; (.put "c" [3 4 5]))))
pure looks ok :
(println
(Yaml/dump
(doto (java.util.HashMap.) (.put "a" 1)
(.put "b" 2)
(.put "c" (into-array [3 4 5]))))
(print {:a 1 :b 2 :c [1 2 3 "foo"]})
;; and...
(Yaml/load
(Yaml/dump
(doto (java.util.HashMap.) (.put "a" 1)
(.put "b" 2)
(.put "c" (into-array [3 4 5]))))))
;; ...we can read it back, good
so , how do we teach Yaml to work with Clojure data types ?
(bean (org.ho.yaml.YamlConfig/getDefaultConfig))
{ : decodingAccessScope # < HashMap { field = public , property = public , constructor = public } > , : suppressWarnings false , : class org.ho.yaml . YamlConfig , : nil , : , : handlers # < HashMap { java.math . BigInteger=[class java.math . BigInteger ] , java.awt . Color = org.ho.yaml.wrapper . ColorWrapper , java.awt . Point = org.ho.yaml.wrapper . PointWrapper , java.lang . Class = org.ho.yaml.wrapper . ClassWrapper , java.io . File=[class java.io . File ] , java.math . BigDecimal=[class java.math . BigDecimal ] , java.util . Date=[class java.util . Date ] , java.awt . Dimension = org.ho.yaml.wrapper . DimensionWrapper } > , : transfers nil , : minimalOutput false , : encoding " UTF-8 " , : encodingAccessScope # < HashMap { field = public , property = public } > , : indentAmount " " } | null | https://raw.githubusercontent.com/kyleburton/sandbox/cccbcc9a97026336691063a0a7eb59293a35c31a/clojure-utils/kburton-clojure-utils/src/main/clj/com/github/kyleburton/sandbox/yaml.clj | clojure | symbol's don't dump?
quite nice, but can we round-trip?
---
c: !clojure.lang.LazilyPersistentVector
- 3
- 4
- 5
NO :(
(Yaml/load
(Yaml/dump
(.put "c" [3 4 5]))))
and...
...we can read it back, good | (ns com.github.kyleburton.sandbox.yaml
(:import [org.ho.yaml Yaml]))
( Yaml / dump { : a 1 : b 2 : c [ 3 4 5 ] } )
(println
(Yaml/dump
(doto (java.util.HashMap.) (.put "a" 1)
(.put "b" 2)
(.put "c" [3 4 5]))))
b : 2
a : 1
( doto ( java.util . . ) ( .put " a " 1 )
( .put " b " 2 )
pure looks ok :
(println
(Yaml/dump
(doto (java.util.HashMap.) (.put "a" 1)
(.put "b" 2)
(.put "c" (into-array [3 4 5]))))
(print {:a 1 :b 2 :c [1 2 3 "foo"]})
(Yaml/load
(Yaml/dump
(doto (java.util.HashMap.) (.put "a" 1)
(.put "b" 2)
(.put "c" (into-array [3 4 5]))))))
so , how do we teach Yaml to work with Clojure data types ?
(bean (org.ho.yaml.YamlConfig/getDefaultConfig))
{ : decodingAccessScope # < HashMap { field = public , property = public , constructor = public } > , : suppressWarnings false , : class org.ho.yaml . YamlConfig , : nil , : , : handlers # < HashMap { java.math . BigInteger=[class java.math . BigInteger ] , java.awt . Color = org.ho.yaml.wrapper . ColorWrapper , java.awt . Point = org.ho.yaml.wrapper . PointWrapper , java.lang . Class = org.ho.yaml.wrapper . ClassWrapper , java.io . File=[class java.io . File ] , java.math . BigDecimal=[class java.math . BigDecimal ] , java.util . Date=[class java.util . Date ] , java.awt . Dimension = org.ho.yaml.wrapper . DimensionWrapper } > , : transfers nil , : minimalOutput false , : encoding " UTF-8 " , : encodingAccessScope # < HashMap { field = public , property = public } > , : indentAmount " " } |
5492fb0bb7c977780af1a7add8a7443463e56ec97b7e793c27b838fe951aa421 | ennocramer/monad-dijkstra | Main.hs | # LANGUAGE CPP #
module Main ( main ) where
import Control.Monad ( mplus, mzero )
import Control.Monad.Search
import Data.Semigroup as Sem
#if MIN_VERSION_tasty_hspec(1,1,7)
import Test.Hspec
#endif
import Test.Tasty
import Test.Tasty.Hspec
data Side = L | R
deriving (Eq, Show)
newtype C = C Int
deriving (Eq, Ord, Show)
instance Sem.Semigroup C where
(C l) <> (C r) = C (l + r)
instance Monoid C where
mempty = C 0
#if !(MIN_VERSION_base(4,11,0))
mappend = (<>)
#endif
testSearch :: Search C Side -> [(C, Side)]
testSearch = runSearch
testSearchIO :: SearchT C IO Side -> IO (Maybe (C, Side))
testSearchIO = runSearchBestT
infiniteSearch :: Monad m => SearchT C m Side
infiniteSearch = return L `mplus` (cost' (C 1) >> infiniteSearch)
spec :: IO TestTree
spec = testSpec "Control.Monad.Search" $ do
it "Monad return generates one result" $
testSearch (return L) `shouldBe` [ (C 0, L) ]
it "MonadPlus mzero has no result" $
testSearch mzero `shouldBe` []
it "MonadPlus left identity law" $
testSearch (mzero `mplus` return L) `shouldBe` [ (C 0, L) ]
it "MonadPlus right identity law" $
testSearch (return L `mplus` mzero) `shouldBe` [ (C 0, L) ]
it "MonadPlus left distribution law" $
testSearch (return L `mplus` return R) `shouldBe` [ (C 0, L), (C 0, R) ]
it "Results are ordered by cost" $ do
testSearch (return L `mplus` (cost' (C 1) >> return R))
`shouldBe` [ (C 0, L), (C 1, R) ]
testSearch ((cost' (C 1) >> return L) `mplus` return R)
`shouldBe` [ (C 0, R), (C 1, L) ]
it "Collapse suppresses results with higher cost" $
testSearch ((collapse >> return L) `mplus` (cost' (C 1) >> return R))
`shouldBe` [ (C 0, L) ]
it "Collapse can be limited in scope" $
testSearch (seal ((collapse >> return L) `mplus` (cost' (C 1) >> return R))
`mplus` (cost' (C 2) >> return R))
`shouldBe` [ (C 0, L), (C 2, R) ]
it "Results are generated lazily" $ do
head (testSearch (return L `mplus`
(cost' (C 1) >> error "not lazy right")))
`shouldBe` (C 0, L)
head (testSearch ((cost' (C 1) >> error "not lazy left") `mplus`
return R))
`shouldBe` (C 0, R)
it "Results are generated lazily (infinite)" $
head (testSearch infiniteSearch)
`shouldBe` (C 0, L)
it "Results are generated in constant space / linear time" $
testSearch infiniteSearch !! 10000
`shouldBe` (C 10000, L)
it "Results are generated lazily in IO" $ do
testSearchIO (return L `mplus`
(cost' (C 1) >> error "not lazy right"))
`shouldReturn` Just (C 0, L)
testSearchIO ((cost' (C 1) >> error "not lazy left") `mplus`
return R)
`shouldReturn` Just (C 0, R)
it "Results are generated lazily in IO (infinite)" $
testSearchIO infiniteSearch
`shouldReturn` Just (C 0, L)
main :: IO ()
main = do
spec' <- spec
defaultMain spec'
| null | https://raw.githubusercontent.com/ennocramer/monad-dijkstra/c84d30848d6bc6cc80a4058e1de7e03e67c43675/test/Main.hs | haskell | # LANGUAGE CPP #
module Main ( main ) where
import Control.Monad ( mplus, mzero )
import Control.Monad.Search
import Data.Semigroup as Sem
#if MIN_VERSION_tasty_hspec(1,1,7)
import Test.Hspec
#endif
import Test.Tasty
import Test.Tasty.Hspec
data Side = L | R
deriving (Eq, Show)
newtype C = C Int
deriving (Eq, Ord, Show)
instance Sem.Semigroup C where
(C l) <> (C r) = C (l + r)
instance Monoid C where
mempty = C 0
#if !(MIN_VERSION_base(4,11,0))
mappend = (<>)
#endif
testSearch :: Search C Side -> [(C, Side)]
testSearch = runSearch
testSearchIO :: SearchT C IO Side -> IO (Maybe (C, Side))
testSearchIO = runSearchBestT
infiniteSearch :: Monad m => SearchT C m Side
infiniteSearch = return L `mplus` (cost' (C 1) >> infiniteSearch)
spec :: IO TestTree
spec = testSpec "Control.Monad.Search" $ do
it "Monad return generates one result" $
testSearch (return L) `shouldBe` [ (C 0, L) ]
it "MonadPlus mzero has no result" $
testSearch mzero `shouldBe` []
it "MonadPlus left identity law" $
testSearch (mzero `mplus` return L) `shouldBe` [ (C 0, L) ]
it "MonadPlus right identity law" $
testSearch (return L `mplus` mzero) `shouldBe` [ (C 0, L) ]
it "MonadPlus left distribution law" $
testSearch (return L `mplus` return R) `shouldBe` [ (C 0, L), (C 0, R) ]
it "Results are ordered by cost" $ do
testSearch (return L `mplus` (cost' (C 1) >> return R))
`shouldBe` [ (C 0, L), (C 1, R) ]
testSearch ((cost' (C 1) >> return L) `mplus` return R)
`shouldBe` [ (C 0, R), (C 1, L) ]
it "Collapse suppresses results with higher cost" $
testSearch ((collapse >> return L) `mplus` (cost' (C 1) >> return R))
`shouldBe` [ (C 0, L) ]
it "Collapse can be limited in scope" $
testSearch (seal ((collapse >> return L) `mplus` (cost' (C 1) >> return R))
`mplus` (cost' (C 2) >> return R))
`shouldBe` [ (C 0, L), (C 2, R) ]
it "Results are generated lazily" $ do
head (testSearch (return L `mplus`
(cost' (C 1) >> error "not lazy right")))
`shouldBe` (C 0, L)
head (testSearch ((cost' (C 1) >> error "not lazy left") `mplus`
return R))
`shouldBe` (C 0, R)
it "Results are generated lazily (infinite)" $
head (testSearch infiniteSearch)
`shouldBe` (C 0, L)
it "Results are generated in constant space / linear time" $
testSearch infiniteSearch !! 10000
`shouldBe` (C 10000, L)
it "Results are generated lazily in IO" $ do
testSearchIO (return L `mplus`
(cost' (C 1) >> error "not lazy right"))
`shouldReturn` Just (C 0, L)
testSearchIO ((cost' (C 1) >> error "not lazy left") `mplus`
return R)
`shouldReturn` Just (C 0, R)
it "Results are generated lazily in IO (infinite)" $
testSearchIO infiniteSearch
`shouldReturn` Just (C 0, L)
main :: IO ()
main = do
spec' <- spec
defaultMain spec'
| |
5cec3cc499595a709d20cc9cd4c7fdb59e6cdfc28111f6501f00380ad6098b45 | sneeuwballen/zipperposition | arTerm.mli |
This file is free software , part of Zipperposition . See file " license " for more details .
(** {1 Arbitrary Typed Terms and Formulas} *)
open Logtk
type 'a arbitrary = 'a QCheck.arbitrary
type 'a gen = 'a QCheck.Gen.t
val shrink : Term.t QCheck.Shrink.t
val default_g : Term.t gen
val default_fuel : int -> Term.t gen
val default : Term.t arbitrary
(** Default polymorphic term *)
val default_ho_g : Term.t gen
val default_lfho_g : Term.t gen
val default_ho : Term.t arbitrary
(** Default polymorphic term, with lambdas *)
val default_lfho : Term.t arbitrary
val default_ho_fuel : int -> Term.t gen
val ground_g : Term.t gen
val ground : Term.t arbitrary
(** Default ground monomorphic term *)
val pred : Term.t arbitrary
(** predicates (type "o") *)
val pos : Term.t -> Position.t gen
(** Random valid position in the term *)
* { 2 S Terms }
module PT : sig
val shrink : TypedSTerm.t QCheck.Shrink.t
val default_fuel : int -> TypedSTerm.t gen
val default_g : TypedSTerm.t gen
val default : TypedSTerm.t arbitrary
(** Default polymorphic term *)
val ground_g : TypedSTerm.t gen
val ground : TypedSTerm.t arbitrary
(** Default ground monomorphic term *)
val pred_g : TypedSTerm.t gen
val pred : TypedSTerm.t arbitrary
(** predicates (type "prop") *)
end
| null | https://raw.githubusercontent.com/sneeuwballen/zipperposition/7f1455fbe2e7509907f927649c288141b1a3a247/src/arbitrary/arTerm.mli | ocaml | * {1 Arbitrary Typed Terms and Formulas}
* Default polymorphic term
* Default polymorphic term, with lambdas
* Default ground monomorphic term
* predicates (type "o")
* Random valid position in the term
* Default polymorphic term
* Default ground monomorphic term
* predicates (type "prop") |
This file is free software , part of Zipperposition . See file " license " for more details .
open Logtk
type 'a arbitrary = 'a QCheck.arbitrary
type 'a gen = 'a QCheck.Gen.t
val shrink : Term.t QCheck.Shrink.t
val default_g : Term.t gen
val default_fuel : int -> Term.t gen
val default : Term.t arbitrary
val default_ho_g : Term.t gen
val default_lfho_g : Term.t gen
val default_ho : Term.t arbitrary
val default_lfho : Term.t arbitrary
val default_ho_fuel : int -> Term.t gen
val ground_g : Term.t gen
val ground : Term.t arbitrary
val pred : Term.t arbitrary
val pos : Term.t -> Position.t gen
* { 2 S Terms }
module PT : sig
val shrink : TypedSTerm.t QCheck.Shrink.t
val default_fuel : int -> TypedSTerm.t gen
val default_g : TypedSTerm.t gen
val default : TypedSTerm.t arbitrary
val ground_g : TypedSTerm.t gen
val ground : TypedSTerm.t arbitrary
val pred_g : TypedSTerm.t gen
val pred : TypedSTerm.t arbitrary
end
|
b0abde293d69b11f4d2de67dbe2324030d98d4d9911cf1fd0fb8b2e14d9b5d43 | vonli/Ext2-for-movitz | integers.lisp | ;;;;------------------------------------------------------------------
;;;;
Copyright ( C ) 2000 - 2005 ,
Department of Computer Science , University of Tromso , Norway
;;;;
;;;; Filename: integers.lisp
Description : Arithmetics .
Author : < >
;;;; Created at: Wed Nov 8 18:44:57 2000
;;;; Distribution: See the accompanying file COPYING.
;;;;
$ I d : , v 1.124 2008/02/04 10:08:18 ffjeld Exp $
;;;;
;;;;------------------------------------------------------------------
(require :muerte/basic-macros)
(require :muerte/typep)
(require :muerte/arithmetic-macros)
(provide :muerte/integers)
(in-package muerte)
(defconstant most-positive-fixnum #.movitz::+movitz-most-positive-fixnum+)
(defconstant most-negative-fixnum #.movitz::+movitz-most-negative-fixnum+)
Comparison
(define-primitive-function fast-compare-two-reals (n1 n2)
"Compare two numbers (i.e. set EFLAGS accordingly)."
(macrolet
((do-it ()
`(with-inline-assembly (:returns :nothing) ; unspecified
(:testb ,movitz::+movitz-fixnum-zmask+ :al)
(:jnz 'n1-not-fixnum)
(:testb ,movitz::+movitz-fixnum-zmask+ :bl)
(:jnz 'n2-not-fixnum-but-n1-is)
(:cmpl :ebx :eax) ; both were fixnum
(:ret)
n1-not-fixnum ; but we don't know about n2
(:testb ,movitz::+movitz-fixnum-zmask+ :bl)
(:jnz 'neither-is-fixnum)
;; n2 is fixnum
(:locally (:jmp (:edi (:edi-offset fast-compare-real-fixnum))))
n2-not-fixnum-but-n1-is
(:locally (:jmp (:edi (:edi-offset fast-compare-fixnum-real))))
neither-is-fixnum
;; Check that both numbers are bignums, and compare them.
(:leal (:eax ,(- (movitz:tag :other))) :ecx)
(:testb 7 :cl)
(:jnz '(:sub-program (go-complicated)
(:globally (:movl (:edi (:edi-offset complicated-compare)) :esi))
(:jmp (:esi (:offset movitz-funobj code-vector%2op)))))
(:movl (:eax ,movitz:+other-type-offset+) :ecx)
(:cmpb ,(movitz:tag :bignum) :cl)
(:jne 'go-complicated)
If they are EQ , they are certainly =
(:je '(:sub-program (n1-and-n2-are-eq)
(:ret)))
(:leal (:ebx ,(- (movitz:tag :other))) :ecx)
(:testb 7 :cl)
(:jnz 'go-complicated)
(:movl (:ebx ,movitz:+other-type-offset+) :ecx)
(:cmpb ,(movitz:tag :bignum) :cl)
(:jne 'go-complicated)
(:cmpb :ch (:eax (:offset movitz-bignum sign)))
(:jne '(:sub-program (different-signs)
;; Comparing the sign-bytes sets up EFLAGS correctly!
(:ret)))
(:testl #xff00 :ecx)
(:jnz 'compare-negatives)
Both n1 and n2 are positive bignums .
(:shrl 16 :ecx)
(:movzxw (:eax (:offset movitz-bignum length)) :edx)
(: cmpw : cx (: eax (: offset ) ) )
(:cmpl :ecx :edx)
(:jne '(:sub-program (positive-different-sizes)
(:ret)))
Both n1 and n2 are positive bignums of the same size , namely ECX .
(: : ecx : edx ) ; counter
positive-compare-loop
(:subl ,movitz:+movitz-fixnum-factor+ :edx)
(:jz 'positive-compare-lsb)
(:movl (:ebx :edx (:offset movitz-bignum bigit0)) :ecx)
(:cmpl :ecx (:eax :edx (:offset movitz-bignum bigit0)))
(:je 'positive-compare-loop)
positive-compare-lsb
;; Now we have to make the compare act as unsigned, which is why
we compare zero - extended 16 - bit quantities .
First compare upper 16 bits .
(:locally (:movl :ecx (:edi (:edi-offset raw-scratch0))))
(:movzxw (:eax :edx (:offset movitz-bignum bigit0 2)) :ecx)
(:locally (:cmpl (:edi (:edi-offset raw-scratch0)) :ecx))
(:jne 'upper-16-decisive)
(:movzxw (:ebx :edx (:offset movitz-bignum bigit0))
Then compare lower 16 bits .
(:locally (:movl :ecx (:edi (:edi-offset raw-scratch0))))
(:movzxw (:eax :edx (:offset movitz-bignum bigit0))
Then compare lower 16 bits .
(:locally (:cmpl (:edi (:edi-offset raw-scratch0)) :ecx))
upper-16-decisive
(:ret)
compare-negatives
;; Moth n1 and n2 are negative bignums.
(:shrl 16 :ecx)
(:cmpw (:eax (:offset movitz-bignum length)) :cx)
(:jne '(:sub-program (negative-different-sizes)
(:ret)))
Both n1 and n2 are negative bignums of the same size , namely ECX .
(:movl :ecx :edx) ; counter
negative-compare-loop
(:subl ,movitz:+movitz-fixnum-factor+ :edx)
(:jz 'negative-compare-lsb)
(:movl (:eax :edx (:offset movitz-bignum bigit0)) :ecx)
(:cmpl :ecx (:ebx :edx (:offset movitz-bignum bigit0)))
(:je 'negative-compare-loop)
(:ret)
it 's down to .
;; Now we have to make the compare act as unsigned, which is why
we compare zero - extended 16 - bit quantities .
(:movzxw (:ebx :edx (:offset movitz-bignum bigit0 2))
First compare upper 16 bits .
(:locally (:movl :ecx (:edi (:edi-offset raw-scratch0))))
(:movzxw (:eax :edx (:offset movitz-bignum bigit0)) :ecx)
(:locally (:cmpl :ecx (:edi (:edi-offset raw-scratch0))))
(:jne 'negative-upper-16-decisive)
(:movzxw (:ebx :edx (:offset movitz-bignum bigit0))
Then compare lower 16 bits .
(:locally (:movl :ecx (:edi (:edi-offset raw-scratch0))))
(:movzxw (:eax :edx (:offset movitz-bignum bigit0))
Then compare lower 16 bits .
(:locally (:cmpl :ecx (:edi (:edi-offset raw-scratch0))))
negative-upper-16-decisive
(:ret))))
(do-it)))
(defun complicated-eql (x y)
(macrolet
((do-it ()
`(with-inline-assembly (:returns :multiple-values) ; well..
(:compile-two-forms (:eax :ebx) x y)
(:cmpl :eax :ebx) ; EQ?
(:je 'done)
(:leal (:eax ,(- (movitz:tag :other))) :ecx)
(:testb 7 :cl)
(:jne 'done)
(:leal (:ebx ,(- (movitz:tag :other))) :ecx)
(:testb 7 :cl)
(:jne 'done)
(:movl (:eax ,movitz:+other-type-offset+) :ecx)
(:cmpb ,(movitz:tag :bignum) :cl)
(:jne 'not-bignum)
(:cmpl :ecx (:ebx ,movitz:+other-type-offset+))
(:jne 'done)
Ok .. we have two bignums of identical sign and size .
(:shrl 16 :ecx)
(:leal (:ecx 4) :edx) ; counter
compare-loop
(:subl ,movitz:+movitz-fixnum-factor+ :edx)
(:jz 'done)
(:movl (:eax :edx (:offset movitz-bignum bigit0 -4)) :ecx)
(:cmpl :ecx (:ebx :edx (:offset movitz-bignum bigit0 -4)))
(:je 'compare-loop)
(:jmp 'done)
not-bignum
(:cmpb ,(movitz:tag :ratio) :cl)
(:jne 'not-ratio)
(:cmpl :ecx (:ebx ,movitz:+other-type-offset+))
(:jne 'done)
(:movl (:eax (:offset movitz-ratio numerator)) :eax)
(:movl (:ebx (:offset movitz-ratio numerator)) :ebx)
(:call (:esi (:offset movitz-funobj code-vector%2op)))
(:jne 'done)
(:compile-two-forms (:eax :ebx) x y)
(:movl (:eax (:offset movitz-ratio denominator)) :eax)
(:movl (:ebx (:offset movitz-ratio denominator)) :ebx)
(:call (:esi (:offset movitz-funobj code-vector%2op)))
(:jmp 'done)
not-ratio
done
(:movl :edi :eax)
(:clc)
)))
(do-it)))
(define-primitive-function fast-compare-fixnum-real (n1 n2)
"Compare (known) fixnum <n1> with real <n2>."
(macrolet
((do-it ()
`(with-inline-assembly (:returns :nothing) ; unspecified
(:testb ,movitz::+movitz-fixnum-zmask+ :bl)
(:jnz 'n2-not-fixnum)
(:cmpl :ebx :eax)
(:ret)
n2-not-fixnum
(:leal (:ebx ,(- (movitz:tag :other))) :ecx)
(:testb 7 :cl)
(:jnz '(:sub-program (go-complicated)
(:globally (:movl (:edi (:edi-offset complicated-compare)) :esi))
(:jmp (:esi (:offset movitz-funobj code-vector%2op)))))
(:movl (:ebx ,movitz:+other-type-offset+) :ecx)
(:cmpw ,(movitz:tag :bignum 0) :cx)
(:jne 'not-plusbignum)
;; compare eax with something bigger
(:cmpl #x10000000 :edi)
(:ret)
not-plusbignum
(:cmpw ,(movitz:tag :bignum #xff) :cx)
(:jne 'go-complicated)
;; compare ebx with something bigger
(:cmpl #x-10000000 :edi)
(:ret))))
(do-it)))
(define-primitive-function fast-compare-real-fixnum (n1 n2)
"Compare real <n1> with fixnum <n2>."
(with-inline-assembly (:returns :nothing) ; unspecified
(:testb #.movitz::+movitz-fixnum-zmask+ :al)
(:jnz 'not-fixnum)
(:cmpl :ebx :eax)
(:ret)
not-fixnum
(:leal (:eax #.(cl:- (movitz:tag :other))) :ecx)
(:testb 7 :cl)
(:jnz '(:sub-program (go-complicated)
(:globally (:movl (:edi (:edi-offset complicated-compare)) :esi))
(:jmp (:esi (:offset movitz-funobj code-vector%2op)))))
(:movl (:eax #.movitz:+other-type-offset+) :ecx)
(:cmpw #.(movitz:tag :bignum 0) :cx)
(:jne 'not-plusbignum)
;; compare ebx with something bigger
(:cmpl #x-10000000 :edi)
(:ret)
not-plusbignum
(:cmpw #.(movitz:tag :bignum #xff) :cx)
(:jne 'go-complicated)
;; compare ebx with something bigger
(:cmpl #x10000000 :edi)
(:ret)))
(defun complicated-compare (x y)
(let ((ix (* (numerator x) (denominator y)))
(iy (* (numerator y) (denominator x))))
(with-inline-assembly (:returns :multiple-values)
(:compile-two-forms (:eax :ebx) ix iy)
(:call-global-pf fast-compare-two-reals)
(:movl 1 :ecx) ; The real result is in EFLAGS.
(:movl :edi :eax))))
;;;
;;; Unsigned
(defun below (x max)
"Is x between 0 and max?"
(compiler-macro-call below x max))
;;; Equality
(define-compiler-macro =%2op (n1 n2 &environment env)
(cond
#+ignore
((movitz:movitz-constantp n1 env)
(let ((n1 (movitz:movitz-eval n1 env)))
(etypecase n1
((eql 0)
`(do-result-mode-case ()
(:booleans
(with-inline-assembly (:returns :boolean-zf=1 :side-effects nil)
(:compile-form (:result-mode :eax) ,n2)
(:testl :eax :eax)))
(t (with-inline-assembly (:returns :boolean-cf=1 :side-effects nil)
(:compile-form (:result-mode :eax) ,n2)
(:cmpl 1 :eax)))))
((signed-byte 30)
`(with-inline-assembly (:returns :boolean-zf=1 :side-effects nil)
(:compile-two-forms (:eax :ebx) ,n1 ,n2)
(:call-global-pf fast-compare-fixnum-real)))
(integer
`(with-inline-assembly (:returns :boolean-zf=1 :side-effects nil)
(:compile-two-forms (:eax :ebx) ,n1 ,n2)
(:call-global-pf fast-compare-two-reals))))))
#+ignore
((movitz:movitz-constantp n2 env)
`(=%2op ,n2 ,n1))
(t `(eql ,n1 ,n2))))
(define-number-relational = =%2op nil :defun-p nil)
(defun = (first-number &rest numbers)
(declare (dynamic-extent numbers))
(dolist (n numbers t)
(unless (= first-number n)
(return nil))))
(define-compiler-macro /=%2op (n1 n2)
`(not (= ,n1 ,n2)))
(define-number-relational /= /=%2op nil :defun-p nil)
(defun /= (&rest numbers)
(declare (dynamic-extent numbers))
(do ((p (cdr numbers) (cdr p)))
((null p) t)
(do ((v numbers (cdr v)))
((eq p v))
(when (= (car p) (car v))
(return-from /= nil)))))
;;;;
(deftype positive-fixnum ()
'(integer 0 #.movitz:+movitz-most-positive-fixnum+))
(deftype positive-bignum ()
`(integer #.(cl:1+ movitz:+movitz-most-positive-fixnum+) *))
(deftype negative-fixnum ()
`(integer #.movitz:+movitz-most-negative-fixnum+ -1))
(deftype negative-bignum ()
`(integer * #.(cl:1- movitz::+movitz-most-negative-fixnum+)))
(defun fixnump (x)
(typep x 'fixnum))
(defun evenp (x)
(compiler-macro-call evenp x))
(defun oddp (x)
(compiler-macro-call oddp x))
;;;
(defun %negatef (x p0 p1)
"Negate x. If x is not eq to p0 or p1, negate x destructively."
(etypecase x
(fixnum (- x))
(bignum
(if (or (eq x p0) (eq x p1))
(- x)
(with-inline-assembly (:returns :eax)
(:compile-form (:result-mode :eax) x)
(:xorl #xff00 (:eax #.movitz:+other-type-offset+)))))))
;;; Addition
(defun + (&rest terms)
(declare (without-check-stack-limit))
(numargs-case
(1 (x) x)
(2 (x y)
(macrolet
((do-it ()
`(number-double-dispatch (x y)
((fixnum fixnum)
(with-inline-assembly (:returns :eax)
(:compile-form (:result-mode :eax) x)
(:compile-form (:result-mode :ebx) y)
(:addl :ebx :eax)
(:jo '(:sub-program (fix-fix-overflow)
(:movl :eax :ecx)
(:jns 'fix-fix-negative)
(:shrl ,movitz:+movitz-fixnum-shift+ :ecx)
(:call-local-pf box-u32-ecx)
(:jmp 'fix-fix-ok)
fix-fix-negative
(:jz 'fix-double-negative)
(:negl :ecx)
(:shrl ,movitz:+movitz-fixnum-shift+ :ecx)
(:call-local-pf box-u32-ecx)
(:movl ,(dpb 4 (byte 16 16)
(movitz:tag :bignum #xff))
(:eax ,movitz:+other-type-offset+))
(:jmp 'fix-fix-ok)
fix-double-negative
(:compile-form (:result-mode :eax)
,(* 2 movitz:+movitz-most-negative-fixnum+))
(:jmp 'fix-fix-ok)))
fix-fix-ok))
((positive-bignum positive-fixnum)
(+ y x))
((positive-fixnum positive-bignum)
(bignum-add-fixnum y x))
((positive-bignum negative-fixnum)
(+ y x))
((negative-fixnum positive-bignum)
(with-inline-assembly (:returns :eax :labels (restart-addition
retry-jumper
not-size1
copy-bignum-loop
add-bignum-loop
add-bignum-done
no-expansion
pfix-pbig-done))
(:compile-two-forms (:eax :ebx) y x)
(:movzxw (:eax (:offset movitz-bignum length)) :ecx)
(:cmpl 4 :ecx)
(:jne 'not-size1)
(:compile-form (:result-mode :ecx) x)
(:sarl ,movitz:+movitz-fixnum-shift+ :ecx)
(:addl (:eax (:offset movitz-bignum bigit0)) :ecx)
(:call-local-pf box-u32-ecx)
(:jmp 'pfix-pbig-done)
not-size1
(:declare-label-set retry-jumper (restart-addition))
(:locally (:pushl (:edi (:edi-offset :dynamic-env))))
(:pushl 'retry-jumper)
;; ..this allows us to detect recursive atomicallies.
(:locally (:pushl (:edi (:edi-offset :atomically-continuation))))
(:pushl :ebp)
restart-addition
(:movl (:esp) :ebp)
(:compile-form (:result-mode :eax) y)
(:movzxw (:eax (:offset movitz-bignum length)) :ecx)
(:locally (:movl :esp (:edi (:edi-offset :atomically-continuation))))
;; Now inside atomically section.
(:leal ((:ecx 1) ,(* 1 movitz:+movitz-fixnum-factor+))
:eax) ; Number of words
(:call-local-pf cons-pointer)
(:load-lexical (:lexical-binding y) :ebx) ; bignum
(:movzxw (:ebx (:offset movitz-bignum length)) :ecx)
(:leal ((:ecx 1) ,movitz:+movitz-fixnum-factor+)
:edx)
copy-bignum-loop
(:subl ,movitz:+movitz-fixnum-factor+ :edx)
(:movl (:ebx :edx ,movitz:+other-type-offset+) :ecx)
(:movl :ecx (:eax :edx ,movitz:+other-type-offset+))
(:jnz 'copy-bignum-loop)
(:load-lexical (:lexical-binding x) :ecx)
(:sarl ,movitz:+movitz-fixnum-shift+ :ecx)
(:xorl :ebx :ebx) ; counter
(:negl :ecx)
(:subl :ecx (:eax (:offset movitz-bignum bigit0)))
(:jnc 'add-bignum-done)
add-bignum-loop
(:addl 4 :ebx)
(:subl 1 (:eax :ebx (:offset movitz-bignum bigit0)))
(:jc 'add-bignum-loop)
add-bignum-done
(:movzxw (:eax (:offset movitz-bignum length))
:ecx)
(:leal ((:ecx 1) ,movitz:+movitz-fixnum-factor+)
:ecx) ; result bignum word-size
(:cmpl 0 (:eax :ecx (:offset movitz-bignum bigit0 -8)))
(:jne 'no-expansion)
(:subl #x40000 (:eax ,movitz:+other-type-offset+))
(:subl ,movitz:+movitz-fixnum-factor+ :ecx)
no-expansion
(:call-local-pf cons-commit-non-pointer)
(:locally (:movl 0 (:edi (:edi-offset atomically-continuation))))
(:leal (:esp 16) :esp)
pfix-pbig-done))
((positive-bignum positive-bignum)
(if (< (%bignum-bigits y) (%bignum-bigits x))
(+ y x)
;; Assume x is smallest.
(with-inline-assembly (:returns :eax :labels (restart-addition
retry-jumper
not-size1
copy-bignum-loop
add-bignum-loop
add-bignum-done
no-expansion
pfix-pbig-done
zero-padding-loop))
(:compile-two-forms (:eax :ebx) y x)
(:testl :ebx :ebx)
(:jz 'pfix-pbig-done)
(:movzxw (:eax (:offset movitz-bignum length)) :ecx)
(:cmpl ,movitz:+movitz-fixnum-factor+ :ecx)
(:jne 'not-size1)
(:movl (:ebx (:offset movitz-bignum bigit0)) :ecx)
(:addl (:eax (:offset movitz-bignum bigit0)) :ecx)
(:jc 'not-size1)
(:call-local-pf box-u32-ecx)
(:jmp 'pfix-pbig-done)
not-size1
;; Set up atomically continuation.
(:declare-label-set restart-jumper (restart-addition))
(:locally (:pushl (:edi (:edi-offset :dynamic-env))))
(:pushl 'restart-jumper)
;; ..this allows us to detect recursive atomicallies.
(:locally (:pushl (:edi (:edi-offset :atomically-continuation))))
(:pushl :ebp)
restart-addition
(:movl (:esp) :ebp)
(:compile-form (:result-mode :eax) y)
(:movzxw (:eax (:offset movitz-bignum length)) :ecx)
(:leal ((:ecx 1) ,(* 2 movitz:+movitz-fixnum-factor+))
:eax) ; Number of words
(:locally (:movl :esp (:edi (:edi-offset :atomically-continuation))))
;; Now inside atomically section.
(:call-local-pf cons-non-pointer)
(:load-lexical (:lexical-binding y) :ebx) ; bignum
(:movzxw (:ebx (:offset movitz-bignum length)) :ecx)
(:leal ((:ecx 1) ,movitz:+movitz-fixnum-factor+)
:edx)
MSB
copy-bignum-loop
(:subl ,movitz:+movitz-fixnum-factor+ :edx)
(:movl (:ebx :edx ,movitz:+other-type-offset+) :ecx)
(:movl :ecx (:eax :edx ,movitz:+other-type-offset+))
(:jnz 'copy-bignum-loop)
(:load-lexical (:lexical-binding x) :ebx)
(:xorl :edx :edx) ; counter
(:xorl :ecx :ecx) ; Carry
add-bignum-loop
(:cmpw :dx (:ebx (:offset movitz-bignum length)))
(:jbe '(:sub-program (zero-padding-loop)
(:addl :ecx (:eax :edx (:offset movitz-bignum
bigit0)))
(:sbbl :ecx :ecx)
ECX = Add 's Carry .
(:addl 4 :edx)
(:cmpw :dx (:eax (:offset movitz-bignum length)))
(:jae 'zero-padding-loop)
(:jmp 'add-bignum-done)))
(:addl (:ebx :edx (:offset movitz-bignum bigit0))
:ecx)
(:jc '(:sub-program (term1-carry)
The digit + carry carried over , ECX = 0
(:addl 1 :ecx)
(:addl 4 :edx)
(:cmpw :dx (:eax (:offset movitz-bignum length)))
(:jae 'add-bignum-loop)
(:jmp 'add-bignum-done)))
(:addl :ecx (:eax :edx (:offset movitz-bignum bigit0)))
(:sbbl :ecx :ecx)
ECX = Add 's Carry .
(:addl 4 :edx)
(:cmpw :dx (:eax (:offset movitz-bignum length)))
(:jae 'add-bignum-loop)
add-bignum-done
(:movzxw (:eax (:offset movitz-bignum length))
:ecx)
(:leal ((:ecx 1) ,movitz:+movitz-fixnum-factor+)
:ecx)
(:cmpl 0 (:eax :ecx (:offset movitz-bignum bigit0 -4)))
(:je 'no-expansion)
(:addl #x40000 (:eax ,movitz:+other-type-offset+))
(:addl ,movitz:+movitz-fixnum-factor+ :ecx)
no-expansion
(:call-local-pf cons-commit-non-pointer)
(:locally (:movl 0 (:edi (:edi-offset atomically-continuation))))
(:leal (:esp 16) :esp)
pfix-pbig-done)
))
(((integer * -1) (integer 0 *))
(- y (- x)))
(((integer 0 *) (integer * -1))
(- x (- y)))
(((integer * -1) (integer * -1))
(%negatef (+ (- x) (- y)) x y))
((rational rational)
(/ (+ (* (numerator x) (denominator y))
(* (numerator y) (denominator x)))
(* (denominator x) (denominator y))))
)))
(do-it)))
(t (&rest terms)
(declare (dynamic-extent terms))
(if (null terms)
0
(reduce #'+ terms)))))
(defun 1+ (number)
(+ 1 number))
(defun 1- (number)
(+ -1 number))
;;; Subtraction
(defun - (minuend &rest subtrahends)
(declare (dynamic-extent subtrahends))
(numargs-case
(1 (x)
(etypecase x
(fixnum
(macrolet
((do-it ()
`(with-inline-assembly (:returns :eax)
(:compile-form (:result-mode :eax) x)
(:negl :eax)
(:jo '(:sub-program (fix-overflow)
(:compile-form (:result-mode :eax)
,(1+ movitz:+movitz-most-positive-fixnum+))
(:jmp 'fix-ok)))
fix-ok)))
(do-it)))
(bignum
(%bignum-negate (copy-bignum x)))
(ratio
(make-ratio (- (ratio-numerator x)) (ratio-denominator x)))))
(2 (minuend subtrahend)
(macrolet
((do-it ()
`(number-double-dispatch (minuend subtrahend)
((number (eql 0))
minuend)
(((eql 0) t)
(- subtrahend))
((fixnum fixnum)
(with-inline-assembly (:returns :eax :labels (done negative-result))
(:compile-two-forms (:eax :ebx) minuend subtrahend)
(:subl :ebx :eax)
(:jno 'done)
(:jnc 'negative-result)
(:movl :eax :ecx)
(:shrl ,movitz:+movitz-fixnum-shift+ :ecx)
(:orl ,(- movitz:+movitz-most-negative-fixnum+) :ecx)
(:call-local-pf box-u32-ecx)
(:jmp 'done)
negative-result
(:movl :eax :ecx)
(:negl :ecx)
(:shrl ,movitz:+movitz-fixnum-shift+ :ecx)
(:call-local-pf box-u32-ecx)
(:xorl #xff00 (:eax (:offset movitz-bignum type)))
done))
((positive-bignum fixnum)
(+ (- subtrahend) minuend))
((fixnum positive-bignum)
(%negatef (+ subtrahend (- minuend))
subtrahend minuend))
;;; ((positive-fixnum positive-bignum)
;;; (bignum-canonicalize
;;; (%bignum-negate
;;; (bignum-subf (copy-bignum subtrahend) minuend))))
;;; ((negative-fixnum positive-bignum)
;;; (bignum-canonicalize
;;; (%negatef (bignum-add-fixnum subtrahend minuend)
;;; subtrahend minuend)))
((positive-bignum positive-bignum)
(cond
((= minuend subtrahend)
0)
((< minuend subtrahend)
(let ((x (- subtrahend minuend)))
(%negatef x subtrahend minuend)))
(t (bignum-canonicalize
(with-inline-assembly (:returns :eax)
(:compile-two-forms (:eax :ebx) (copy-bignum minuend) subtrahend)
(:xorl :edx :edx) ; counter
(:xorl :ecx :ecx) ; carry
sub-loop
(:addl (:ebx :edx (:offset movitz-bignum bigit0))
:ecx)
(:jc '(:sub-program (carry-overflow)
;; Just propagate carry
(:addl 1 :ecx)
(:addl 4 :edx)
(:cmpw :dx (:ebx (:offset movitz-bignum length)))
(:jne 'sub-loop)
(:jmp 'bignum-sub-done)))
(:subl :ecx (:eax :edx (:offset movitz-bignum bigit0)))
(:sbbl :ecx :ecx)
(:negl :ecx)
(:addl 4 :edx)
(:cmpw :dx (:ebx (:offset movitz-bignum length)))
(:jne 'sub-loop)
(:subl :ecx (:eax :edx (:offset movitz-bignum bigit0)))
(:jnc 'bignum-sub-done)
propagate-carry
(:addl 4 :edx)
(:subl 1 (:eax :edx (:offset movitz-bignum bigit0)))
(:jc 'propagate-carry)
bignum-sub-done
)))))
(((integer 0 *) (integer * -1))
(+ minuend (- subtrahend)))
(((integer * -1) (integer 0 *))
(%negatef (+ (- minuend) subtrahend) minuend subtrahend))
(((integer * -1) (integer * -1))
(+ minuend (- subtrahend)))
((rational rational)
(/ (- (* (numerator minuend) (denominator subtrahend))
(* (numerator subtrahend) (denominator minuend)))
(* (denominator minuend) (denominator subtrahend))))
)))
(do-it)))
(t (minuend &rest subtrahends)
(declare (dynamic-extent subtrahends))
(if subtrahends
(reduce #'- subtrahends :initial-value minuend)
(- minuend)))))
;;;
(defun zerop (number)
(= 0 number))
(defun plusp (number)
(> number 0))
(defun minusp (number)
(< number 0))
(defun abs (x)
(compiler-macro-call abs x))
(defun signum (x)
(cond
((> x 0) 1)
((< x 0) -1)
(t 0)))
;;;
(defun max (number1 &rest numbers)
(numargs-case
(2 (x y)
(compiler-macro-call max x y))
(t (number1 &rest numbers)
(declare (dynamic-extent numbers))
(let ((max number1))
(dolist (x numbers max)
(when (> x max)
(setq max x)))))))
(defun min (number1 &rest numbers)
(numargs-case
(2 (x y)
(compiler-macro-call min x y))
(t (number1 &rest numbers)
(declare (dynamic-extent numbers))
(let ((min number1))
(dolist (x numbers min)
(when (< x min)
(setq min x)))))))
;; shift
(defun ash (integer count)
(cond
((= 0 count)
integer)
((= 0 integer) 0)
((typep count '(integer 0 *))
(let ((result-length (+ (integer-length (if (minusp integer) (1- integer) integer))
count)))
(cond
((<= result-length 29)
(with-inline-assembly (:returns :eax)
(:compile-two-forms (:eax :ecx) integer count)
(:shrl #.movitz:+movitz-fixnum-shift+ :ecx)
(:shll :cl :eax)))
((typep integer 'positive-fixnum)
(let ((result (%make-bignum (ceiling result-length 32) 0)))
(setf (memref result (movitz-type-slot-offset 'movitz-bignum 'bigit0)
:type :unsigned-byte32)
integer)
(bignum-shift-leftf result count)))
((typep integer 'positive-bignum)
(let ((result (%make-bignum (ceiling result-length 32))))
(dotimes (i (* 2 (%bignum-bigits result)))
(setf (memref result -2 :index i :type :unsigned-byte16)
(let ((pos (- (* i 16) count)))
(cond
((minusp (+ pos 16)) 0)
((<= 0 pos)
(ldb (byte 16 pos) integer))
(t (ash (ldb (byte (+ pos 16) 0) integer)
(- pos)))))))
(assert (or (plusp (memref result -2
:index (+ -1 (* 2 (%bignum-bigits result)))
:type :unsigned-byte16))
(plusp (memref result -2
:index (+ -2 (* 2 (%bignum-bigits result)))
:type :unsigned-byte16))))
(bignum-canonicalize result)))
((typep integer 'negative-fixnum)
(let ((result (%make-bignum (ceiling result-length 32) 0)))
(setf (memref result (movitz-type-slot-offset 'movitz-bignum 'bigit0)
:type :unsigned-byte32)
(- integer))
(%bignum-negate (bignum-shift-leftf result count))))
((typep integer 'negative-bignum)
(let ((result (%make-bignum (ceiling result-length 32) 0)))
(dotimes (i (%bignum-bigits integer))
(setf (memref result (movitz-type-slot-offset 'movitz-bignum 'bigit0)
:index i :type :unsigned-byte32)
(memref integer (movitz-type-slot-offset 'movitz-bignum 'bigit0)
:index i :type :unsigned-byte32)))
(%bignum-negate (bignum-shift-leftf result count))))
(t (error 'program-error)))))
(t (let ((count (- count)))
(etypecase integer
(fixnum
(with-inline-assembly (:returns :eax :type fixnum)
(:compile-two-forms (:eax :ecx) integer count)
(:shrl #.movitz:+movitz-fixnum-shift+ :ecx)
(:std)
(:sarl :cl :eax)
(:andl -4 :eax)
(:cld)))
(positive-bignum
(let ((result-length (- (integer-length integer) count)))
(cond
((<= result-length 1)
1 or 0 .
(t (multiple-value-bind (long short)
(truncate count 16)
(let ((result (%make-bignum (1+ (ceiling result-length 32)))))
(let ((src-max-bigit (* 2 (%bignum-bigits integer))))
(dotimes (i (* 2 (%bignum-bigits result)))
(declare (index i))
(let ((src (+ i long)))
(setf (memref result -2 :index i :type :unsigned-byte16)
(if (< src src-max-bigit)
(memref integer -2 :index src :type :unsigned-byte16)
0)))))
(bignum-canonicalize
(macrolet
((do-it ()
`(with-inline-assembly (:returns :ebx)
(:compile-two-forms (:ecx :ebx) short result)
(:xorl :edx :edx) ; counter
We need to use EAX for u32 storage .
(:shrl ,movitz:+movitz-fixnum-shift+ :ecx)
(:std)
shift-short-loop
(:addl 4 :edx)
(:cmpw :dx (:ebx (:offset movitz-bignum length)))
(:jbe 'end-shift-short-loop)
(:movl (:ebx :edx (:offset movitz-bignum bigit0))
:eax)
(:shrdl :cl :eax
(:ebx :edx (:offset movitz-bignum bigit0 -4)))
(:jmp 'shift-short-loop)
end-shift-short-loop
(:movl :edx :eax) ; Safe EAX
(:shrl :cl (:ebx :edx (:offset movitz-bignum bigit0 -4)))
(:cld))))
(do-it))))))))))))))
;;;;
(defun integer-length (integer)
"=> number-of-bits"
(etypecase integer
(fixnum
(macrolet
((do-it ()
`(with-inline-assembly (:returns :eax)
(:xorl :eax :eax)
(:compile-form (:result-mode :ecx) integer)
(:testl :ecx :ecx)
(:jns 'not-negative)
(:notl :ecx)
not-negative
(:bsrl :ecx :ecx)
(:jz 'zero)
(:leal ((:ecx ,movitz:+movitz-fixnum-factor+)
,(* -1 movitz:+movitz-fixnum-factor+))
:eax)
zero)))
(do-it)))
(positive-bignum
(macrolet
((do-it ()
`(with-inline-assembly (:returns :eax)
(:compile-form (:result-mode :ebx) integer)
(:movzxw (:ebx (:offset movitz-bignum length))
:edx)
(:xorl :eax :eax)
bigit-scan-loop
(:subl 4 :edx)
(:jc 'done)
(:cmpl 0 (:ebx :edx (:offset movitz-bignum bigit0)))
(:jz 'bigit-scan-loop)
Now , EAX must be loaded with ( + ( * EDX 32 ) bit - index 1 ) .
Factor 8
(:bsrl (:ebx :edx (:offset movitz-bignum bigit0))
:ecx)
Factor 4
(:leal ((:ecx 4) :eax 4) :eax)
done)))
(do-it)))
(negative-bignum
(let ((abs-length (bignum-integer-length integer)))
(if (= 1 (bignum-logcount integer))
(1- abs-length)
abs-length)))))
;;; Multiplication
(defun * (&rest factors)
(numargs-case
(1 (x) x)
(2 (x y)
(macrolet
((do-it ()
`(number-double-dispatch (x y)
((fixnum fixnum)
(let (d0 d1)
(with-inline-assembly (:returns :eax)
(:compile-two-forms (:eax :ecx) x y)
(:sarl ,movitz::+movitz-fixnum-shift+ :ecx)
(:std)
(:imull :ecx :eax :edx)
(:jno 'fixnum-result) ; most likely/optimized path.
(:cmpl ,movitz::+movitz-fixnum-factor+ :edx)
(:jc 'u32-result)
(:cmpl #xfffffffc :edx)
(:ja 'u32-negative-result)
(:jne 'two-bigits)
(:testl :eax :eax)
(:jnz 'u32-negative-result)
The result requires 2 ..
two-bigits
(:shll ,movitz::+movitz-fixnum-shift+ :edx) ; guaranteed won't overflow.
(:cld)
(:store-lexical (:lexical-binding d0) :eax :type fixnum)
(:store-lexical (:lexical-binding d1) :edx :type fixnum)
(:compile-form (:result-mode :eax) (%make-bignum 2))
(:movl ,(dpb (* 2 movitz:+movitz-fixnum-factor+)
(byte 16 16) (movitz:tag :bignum 0))
(:eax ,movitz:+other-type-offset+))
(:load-lexical (:lexical-binding d0) :ecx)
(:movl :ecx (:eax (:offset movitz-bignum bigit0)))
(:load-lexical (:lexical-binding d1) :ecx)
(:sarl ,movitz:+movitz-fixnum-shift+
:ecx)
(:shrdl ,movitz:+movitz-fixnum-shift+ :ecx
(:eax (:offset movitz-bignum bigit0)))
(:sarl ,movitz:+movitz-fixnum-shift+
:ecx)
(:movl :ecx (:eax (:offset movitz-bignum bigit0 4)))
(:jns 'fixnum-done)
;; if result was negative, we must negate bignum
(:notl (:eax (:offset movitz-bignum bigit0 4)))
(:negl (:eax (:offset movitz-bignum bigit0)))
(:cmc)
(:adcl 0 (:eax (:offset movitz-bignum bigit0 4)))
(:xorl #xff00 (:eax ,movitz:+other-type-offset+))
(:jmp 'fixnum-done)
u32-result
(:movl :eax :ecx)
(:shrdl ,movitz::+movitz-fixnum-shift+ :edx :ecx)
(:movl :edi :edx)
(:cld)
(:call-local-pf box-u32-ecx)
(:jmp 'fixnum-done)
u32-negative-result
(:movl :eax :ecx)
(:shrdl ,movitz::+movitz-fixnum-shift+ :edx :ecx)
(:movl :edi :edx)
(:cld)
(:negl :ecx)
(:call-local-pf box-u32-ecx)
(:xorl #xff00 (:eax ,movitz:+other-type-offset+))
(:jmp 'fixnum-done)
fixnum-result
(:movl :edi :edx)
(:cld)
fixnum-done)))
(((eql 0) t) 0)
(((eql 1) t) y)
(((eql -1) t) (- y))
((t fixnum) (* y x))
((fixnum bignum)
(let (r)
(with-inline-assembly (:returns :eax)
;; Set up atomically continuation.
(:declare-label-set restart-jumper (restart-multiplication))
(:locally (:pushl (:edi (:edi-offset :dynamic-env))))
(:pushl 'restart-jumper)
;; ..this allows us to detect recursive atomicallies:
(:locally (:pushl (:edi (:edi-offset :atomically-continuation))))
(:pushl :ebp)
restart-multiplication
(:movl (:esp) :ebp)
(:compile-two-forms (:eax :ebx) (integer-length x) (integer-length y))
Compute ( 1 + ( ceiling ( + ( len x ) ( len y ) ) 32 ) ) ..
(:locally (:movl :esp (:edi (:edi-offset :atomically-continuation))))
;; Now inside atomically section.
(:leal (:eax :ebx ,(* 4 (+ 31 32))) :eax)
(:andl ,(logxor #xffffffff (* 31 4)) :eax)
(:shrl 5 :eax)
New bignum into EAX
(:load-lexical (:lexical-binding y) :ebx) ; bignum
(:movl (:ebx ,movitz:+other-type-offset+) :ecx)
(:movl :ecx (:eax ,movitz:+other-type-offset+))
(:store-lexical (:lexical-binding r) :eax :type bignum)
(:movl :eax :ebx) ; r into ebx
(:xorl :esi :esi) ; counter
(:xorl :edx :edx) ; initial carry
Make EAX , EDX , ESI non - GC - roots .
(:compile-form (:result-mode :ecx) x)
(:sarl ,movitz:+movitz-fixnum-shift+ :ecx)
(:jns 'multiply-loop)
(:negl :ecx) ; can't overflow
multiply-loop
(:movl :edx (:ebx (:esi 1) ; new
(:offset movitz-bignum bigit0)))
(:compile-form (:result-mode :ebx) y)
(:movl (:ebx (:esi 1) (:offset movitz-bignum bigit0))
:eax)
(:mull :ecx :eax :edx)
(:compile-form (:result-mode :ebx) r)
(:addl :eax (:ebx :esi (:offset movitz-bignum bigit0)))
(:adcl 0 :edx)
(:addl 4 :esi)
(:cmpw :si (:ebx (:offset movitz-bignum length)))
(:ja 'multiply-loop)
(:testl :edx :edx)
(:jz 'no-carry-expansion)
(:movl :edx (:ebx :esi (:offset movitz-bignum bigit0)))
(:addl 4 :esi)
(:movw :si (:ebx (:offset movitz-bignum length)))
no-carry-expansion
(:leal (:esi ,movitz:+movitz-fixnum-factor+)
Put bignum length into ECX
(:movl (:ebp -4) :esi)
(:movl :ebx :eax)
(:movl :edi :edx)
EAX , EDX , and ESI are GC roots again .
(:call-local-pf cons-commit-non-pointer)
(:locally (:movl 0 (:edi (:edi-offset atomically-continuation))))
(:leal (:esp 16) :esp)
(:compile-form (:result-mode :ebx) x)
(:testl :ebx :ebx)
(:jns 'positive-result)
;; Negate the resulting bignum
(:xorl #xff00 (:eax ,movitz:+other-type-offset+))
positive-result
)))
((positive-bignum positive-bignum)
(if (< x y)
(* y x)
;; X is the biggest factor.
#-movitz-reference-code
(do ((tmp (%make-bignum (ceiling (+ (integer-length x)
(integer-length y))
32)))
(r (bignum-set-zerof (%make-bignum (ceiling (+ (integer-length x)
(integer-length y))
32))))
(length (integer-length y))
(i 0 (+ i 29)))
((>= i length) (bignum-canonicalize r))
(bignum-set-zerof tmp)
(bignum-addf r (bignum-shift-leftf (bignum-mulf (bignum-addf tmp x)
(ldb (byte 29 i) y))
i)))
#+movitz-reference-code
(do ((r 0)
(length (integer-length y))
(i 0 (+ i 29)))
((>= i length) r)
(incf r (ash (* x (ldb (byte 29 i) y)) i)))))
((ratio ratio)
(make-rational (* (ratio-numerator x) (ratio-numerator y))
(* (ratio-denominator x) (ratio-denominator y))))
((ratio t)
(make-rational (* y (ratio-numerator x))
(ratio-denominator x)))
((t ratio)
(make-rational (* x (ratio-numerator y))
(ratio-denominator y)))
((t (integer * -1))
(%negatef (* x (- y)) x y))
(((integer * -1) t)
(%negatef (* (- x) y) x y))
(((integer * -1) (integer * -1))
(* (- x) (- y))))))
(do-it)))
(t (&rest factors)
(declare (dynamic-extent factors))
(if (null factors)
1
(reduce '* factors)))))
Division
(defun truncate (number &optional (divisor 1))
(numargs-case
(1 (number)
(if (not (typep number 'ratio))
(values number 0)
(multiple-value-bind (q r)
(truncate (%ratio-numerator number)
(%ratio-denominator number))
(values q (make-rational r (%ratio-denominator number))))))
(t (number divisor)
(number-double-dispatch (number divisor)
((t (eql 1))
(if (not (typep number 'ratio))
(values number 0)
(multiple-value-bind (q r)
(truncate (%ratio-numerator number)
(%ratio-denominator number))
(values q (make-rational r (%ratio-denominator number))))))
((fixnum fixnum)
(with-inline-assembly (:returns :multiple-values)
(:compile-form (:result-mode :eax) number)
(:compile-form (:result-mode :ebx) divisor)
(:std)
(:cdq :eax :edx)
(:idivl :ebx :eax :edx)
(:shll #.movitz::+movitz-fixnum-shift+ :eax)
(:cld)
(:movl :edx :ebx)
(:xorl :ecx :ecx)
(:movb 2 :cl) ; return values: qutient, remainder.
(:stc)))
((positive-fixnum positive-bignum)
(values 0 number))
((positive-bignum positive-fixnum)
(macrolet
((do-it ()
`(let (r n)
(with-inline-assembly (:returns :multiple-values)
(:compile-form (:result-mode :ebx) number)
(:cmpw ,movitz:+movitz-fixnum-factor+
(:ebx (:offset movitz-bignum length)))
(:jne 'not-size1)
(:compile-form (:result-mode :ecx) divisor)
(:shrl ,movitz:+movitz-fixnum-shift+ :ecx)
(:std)
(:movl (:ebx (:offset movitz-bignum bigit0)) :eax)
(:xorl :edx :edx)
(:divl :ecx :eax :edx)
(:movl :eax :ecx)
(:shll ,movitz:+movitz-fixnum-shift+ :edx)
(:movl :edi :eax)
(:cld)
(:pushl :edx)
(:call-local-pf box-u32-ecx)
(:popl :ebx)
(:jmp 'done)
not-size1
;; Set up atomically continuation.
(:declare-label-set restart-jumper (restart-truncation))
(:locally (:pushl (:edi (:edi-offset :dynamic-env))))
(:pushl 'restart-jumper)
;; ..this allows us to detect recursive atomicallies.
(:locally (:pushl (:edi (:edi-offset :atomically-continuation))))
(:pushl :ebp)
restart-truncation
(:movl (:esp) :ebp)
(:xorl :eax :eax)
(:compile-form (:result-mode :ebx) number)
(:movw (:ebx (:offset movitz-bignum length)) :ax)
(:addl 4 :eax)
(:locally (:movl :esp (:edi (:edi-offset :atomically-continuation))))
;; Now inside atomically section.
New bignum into EAX
XXX breaks GC invariant !
(:compile-form (:result-mode :ebx) number)
(:movl (:ebx ,movitz:+other-type-offset+) :ecx)
(:movl :ecx (:eax ,movitz:+other-type-offset+))
(:shrl 16 :ecx)
(:testb 3 :cl)
(:jnz '(:sub-program () (:int 63)))
(:movl :ecx :esi)
(:xorl :edx :edx) ; edx=hi-digit=0
; eax=lo-digit=msd(number)
(:compile-form (:result-mode :ecx) divisor)
(:shrl ,movitz:+movitz-fixnum-shift+ :ecx)
(:std)
divide-loop
(:load-lexical (:lexical-binding number) :ebx)
(:movl (:ebx :esi (:offset movitz-bignum bigit0 -4))
:eax)
(:divl :ecx :eax :edx)
(:load-lexical (:lexical-binding r) :ebx)
(:movl :eax (:ebx :esi (:offset movitz-bignum bigit0 -4)))
(:subl 4 :esi)
(:jnz 'divide-loop)
(:movl :edi :eax) ; safe value
(:leal ((:edx ,movitz:+movitz-fixnum-factor+)) :edx)
(:cld)
(:movl (:ebp -4) :esi)
(:movl :ebx :eax)
(:movl :edx :ebx)
(:movzxw (:eax (:offset movitz-bignum length))
:ecx)
(:leal ((:ecx 1) ,movitz:+movitz-fixnum-factor+)
:ecx)
(:cmpl 0 (:eax :ecx (:offset movitz-bignum bigit0 -8)))
(:jne 'no-more-shrinkage)
(:subw 4 (:eax (:offset movitz-bignum length)))
(:subl ,movitz:+movitz-fixnum-factor+ :ecx)
(:cmpl ,(* 2 movitz:+movitz-fixnum-factor+) :ecx)
(:jne 'no-more-shrinkage)
(:cmpl ,movitz:+movitz-most-positive-fixnum+
(:eax (:offset movitz-bignum bigit0)))
(:jnc 'no-more-shrinkage)
(:movl (:eax (:offset movitz-bignum bigit0))
:ecx)
(:leal ((:ecx ,movitz:+movitz-fixnum-factor+)) :eax)
(:jmp 'fixnum-result) ; don't commit the bignum
no-more-shrinkage
(:call-local-pf cons-commit-non-pointer)
fixnum-result
Exit atomically block .
(:locally (:movl 0 (:edi (:edi-offset atomically-continuation))))
(:leal (:esp 16) :esp)
done
(:movl 2 :ecx)
(:stc)))))
(do-it)))
((positive-bignum positive-bignum)
(cond
((= number divisor) (values 1 0))
((< number divisor) (values 0 number))
(t
#-movitz-reference-code
(let* ((divisor-length (integer-length divisor))
(guess-pos (- divisor-length 29))
(msb (ldb (byte 29 guess-pos) divisor)))
(when (eq msb most-positive-fixnum)
(incf guess-pos)
(setf msb (ash msb -1)))
(incf msb)
(do ((tmp (copy-bignum number))
(tmp2 (copy-bignum number))
(q (bignum-set-zerof (%make-bignum (ceiling (1+ (- (integer-length number)
divisor-length))
32))))
(r (copy-bignum number)))
((%bignum< r divisor)
(values (bignum-canonicalize q)
(bignum-canonicalize r)))
(let ((guess (bignum-shift-rightf
(bignum-truncatef (bignum-addf (bignum-set-zerof tmp)
r)
msb)
guess-pos)))
(if (%bignum-zerop guess)
(setf q (bignum-addf-fixnum q 1)
r (bignum-subf r divisor))
(setf q (bignum-addf q guess)
r (do ((i 0 (+ i 29)))
((>= i divisor-length) r)
(bignum-subf r (bignum-shift-leftf
(bignum-mulf (bignum-addf (bignum-set-zerof tmp2) guess)
(ldb (byte 29 i) divisor))
i))))))))
#+movitz-reference-code
(let* ((guess-pos (- (integer-length divisor) 29))
(msb (ldb (byte 29 guess-pos) divisor)))
(when (eq msb most-positive-fixnum)
(incf guess-pos)
(setf msb (ash msb -1)))
(incf msb)
(do ((shift (- guess-pos))
(q 0)
(r number))
((< r divisor)
(values q r))
(let ((guess (ash (truncate r msb) shift)))
(if (= 0 guess)
(setf q (1+ q)
r (- r divisor))
(setf q (+ q guess)
r (- r (* guess divisor))))))))))
(((integer * -1) (integer 0 *))
(multiple-value-bind (q r)
(truncate (- number) divisor)
(values (%negatef q number divisor)
(%negatef r number divisor))))
(((integer 0 *) (integer * -1))
(multiple-value-bind (q r)
(truncate number (- divisor))
(values (%negatef q number divisor)
r)))
(((integer * -1) (integer * -1))
(multiple-value-bind (q r)
(truncate (- number) (- divisor))
(values q (%negatef r number divisor))))
((rational rational)
(multiple-value-bind (q r)
(truncate (* (numerator number)
(denominator divisor))
(* (denominator number)
(numerator divisor)))
(values q (make-rational r (* (denominator number)
(denominator divisor))))))
))))
(defun / (number &rest denominators)
(numargs-case
(1 (x)
(if (not (typep x 'ratio))
(make-rational 1 x)
(make-rational (%ratio-denominator x)
(%ratio-numerator x))))
(2 (x y)
(multiple-value-bind (q r)
(truncate x y)
(cond
((= 0 r)
q)
(t (make-rational (* (numerator x) (denominator y))
(* (denominator x) (numerator y)))))))
(t (number &rest denominators)
(declare (dynamic-extent denominators))
(cond
((null denominators)
(make-rational 1 number))
((null (cdr denominators))
(multiple-value-bind (q r)
(truncate number (first denominators))
(if (= 0 r)
q
(make-rational number (first denominators)))))
(t (/ number (reduce '* denominators)))))))
(defun round (number &optional (divisor 1))
"Mathematical rounding."
(multiple-value-bind (quotient remainder)
(truncate number divisor)
(let ((rem2 (* 2 remainder)))
(case (+ (if (minusp number) #b10 0)
(if (minusp divisor) #b01 0))
(#b00 (cond
((= divisor rem2)
(if (evenp quotient)
(values quotient remainder)
(values (1+ quotient) (- remainder divisor))))
((< rem2 divisor)
(values quotient remainder))
(t (values (1+ quotient) (- remainder divisor)))))
(#b11 (cond
((= divisor rem2)
(if (evenp quotient)
(values quotient remainder)
(values (1+ quotient) (- remainder divisor))))
((> rem2 divisor)
(values quotient remainder))
(t (values (1+ quotient) (- remainder divisor)))))
(#b10 (cond
((= (- divisor) rem2)
(if (evenp quotient)
(values quotient remainder)
(values (1- quotient) (- remainder))))
((< rem2 divisor)
(values quotient remainder))
(t (values (1+ quotient) (- remainder divisor)))))
(#b01 (cond
((= (- divisor) rem2)
(if (evenp quotient)
(values quotient remainder)
(values (1- quotient) (- remainder))))
((> rem2 divisor)
(values quotient remainder))
(t (values (1- quotient) (- remainder)))))))))
(defun ceiling (number &optional (divisor 1))
(case (+ (if (minusp number) #b10 0)
(if (minusp divisor) #b01 0))
(#b00 (multiple-value-bind (q r)
(truncate (+ number divisor -1) divisor)
(values q (- r (1- divisor)))))
(t (error "Don't know."))))
(defun rem (dividend divisor)
(nth-value 1 (truncate dividend divisor)))
(defun mod (number divisor)
"Returns second result of FLOOR."
(let ((rem (rem number divisor)))
(if (and (not (zerop rem))
(if (minusp divisor)
(plusp number)
(minusp number)))
(+ rem divisor)
rem)))
;;; bytes
(defun byte (size position)
(check-type size positive-fixnum)
(let ((position (check-the (unsigned-byte 20) position)))
(+ position (ash size 20))))
(defun byte-size (bytespec)
(ash bytespec -20))
(defun byte-position (bytespec)
(ldb (byte 20 0) bytespec))
(defun logbitp (index integer)
(check-type index positive-fixnum)
(macrolet
((do-it ()
`(etypecase integer
(fixnum
(with-inline-assembly (:returns :boolean-cf=1)
(:compile-two-forms (:ecx :ebx) index integer)
(:shrl ,movitz::+movitz-fixnum-shift+ :ecx)
(:addl ,movitz::+movitz-fixnum-shift+ :ecx)
(:btl :ecx :ebx)))
(positive-bignum
(with-inline-assembly (:returns :boolean-cf=1)
(:compile-two-forms (:ecx :ebx) index integer)
(:shrl ,movitz::+movitz-fixnum-shift+ :ecx)
(:btl :ecx (:ebx (:offset movitz-bignum bigit0))))))))
(do-it)))
(define-compiler-macro logbitp (&whole form &environment env index integer)
(if (not (movitz:movitz-constantp index env))
form
(let ((index (movitz:movitz-eval index env)))
(check-type index (integer 0 *))
(typecase index
((integer 0 31)
`(with-inline-assembly (:returns :boolean-cf=1)
(:compile-form (:result-mode :untagged-fixnum-ecx) ,integer)
(:btl ,index :ecx)))
(t form)))))
(defun logand (&rest integers)
(numargs-case
(1 (x) x)
(2 (x y)
(macrolet
((do-it ()
`(number-double-dispatch (x y)
((fixnum fixnum)
(with-inline-assembly (:returns :eax)
(:compile-two-forms (:eax :ebx) x y)
(:andl :ebx :eax)))
((positive-bignum positive-fixnum)
(with-inline-assembly (:returns :eax)
(:compile-form (:result-mode :eax) x)
(:call-global-pf unbox-u32)
(:compile-form (:result-mode :eax) y)
(:leal ((:ecx ,movitz:+movitz-fixnum-factor+)) :ecx)
(:andl :ecx :eax)))
((positive-fixnum positive-bignum)
(with-inline-assembly (:returns :eax)
(:compile-form (:result-mode :eax) y)
(:call-global-pf unbox-u32)
(:compile-form (:result-mode :eax) x)
(:leal ((:ecx ,movitz:+movitz-fixnum-factor+)) :ecx)
(:andl :ecx :eax)))
((fixnum positive-bignum)
(let ((result (copy-bignum y)))
(with-inline-assembly (:returns :eax)
(:compile-two-forms (:eax :untagged-fixnum-ecx) result x)
(:andl :ecx (:eax (:offset movitz-bignum bigit0))))))
((positive-bignum fixnum)
(let ((result (copy-bignum x)))
(with-inline-assembly (:returns :eax)
(:compile-two-forms (:eax :untagged-fixnum-ecx) result y)
(:andl :ecx (:eax (:offset movitz-bignum bigit0))))))
((positive-bignum positive-bignum)
(if (< (%bignum-bigits y) (%bignum-bigits x))
(logand y x)
(bignum-canonicalize
(with-inline-assembly (:returns :eax)
(:compile-two-forms (:eax :ebx) (copy-bignum x) y)
(:movzxw (:eax (:offset movitz-bignum length))
:ecx)
(:leal ((:ecx 1) -4) :edx)
pb-pb-and-loop
(:movl (:ebx :edx (:offset movitz-bignum bigit0))
:ecx)
(:andl :ecx
(:eax :edx (:offset movitz-bignum bigit0)))
(:subl 4 :edx)
(:jnc 'pb-pb-and-loop)))))
((negative-bignum fixnum)
(with-inline-assembly (:returns :eax)
(:load-lexical (:lexical-binding x) :untagged-fixnum-ecx)
(:load-lexical (:lexical-binding y) :eax)
(:leal ((:ecx 4) -4) :ecx)
(:notl :ecx)
(:andl :ecx :eax)))
((negative-bignum positive-bignum)
(cond
((<= (%bignum-bigits y) (%bignum-bigits x))
(let ((r (copy-bignum y)))
(with-inline-assembly (:returns :eax)
(:load-lexical (:lexical-binding r) :eax)
(:load-lexical (:lexical-binding x) :ebx)
(:xorl :edx :edx)
(:movl #xffffffff :ecx)
loop
(:addl (:ebx :edx (:offset movitz-bignum bigit0))
:ecx)
(:notl :ecx)
(:andl :ecx (:eax :edx (:offset movitz-bignum bigit0)))
(:notl :ecx)
(:cmpl -1 :ecx)
(:je 'carry)
(:xorl :ecx :ecx)
carry
(:addl 4 :edx)
(:cmpw :dx (:eax (:offset movitz-bignum length)))
(:ja 'loop))))
(t (error "Logand not implemented."))))
)))
(do-it)))
(t (&rest integers)
(declare (dynamic-extent integers))
(if (null integers)
-1
(reduce #'logand integers)))))
(defun logandc1 (integer1 integer2)
(macrolet
((do-it ()
`(number-double-dispatch (integer1 integer2)
((t positive-fixnum)
(with-inline-assembly (:returns :eax :type fixnum)
(:compile-form (:result-mode :eax) integer1)
(:call-global-pf unbox-u32)
(:shll ,movitz:+movitz-fixnum-shift+ :ecx)
(:compile-form (:result-mode :eax) integer2)
(:notl :ecx)
(:andl :ecx :eax)))
(((eql 0) t) integer2)
(((eql -1) t) 0)
((positive-fixnum positive-bignum)
(bignum-canonicalize
(with-inline-assembly (:returns :eax)
(:compile-two-forms (:eax :ecx) (copy-bignum integer2) integer1)
(:shrl ,movitz:+movitz-fixnum-shift+ :ecx)
(:notl :ecx)
(:andl :ecx (:eax (:offset movitz-bignum bigit0))))))
((positive-bignum positive-bignum)
(bignum-canonicalize
(with-inline-assembly (:returns :eax)
(:compile-two-forms (:eax :ebx) (copy-bignum integer2) integer1)
(:movzxw (:eax (:offset movitz-bignum length))
:ecx)
(:leal ((:ecx 1) -4) :edx)
pb-pb-andc1-loop
(:movl (:ebx :edx (:offset movitz-bignum bigit0))
:ecx)
(:notl :ecx)
(:andl :ecx (:eax :edx (:offset movitz-bignum bigit0)))
(:subl 4 :edx)
(:jnc 'pb-pb-andc1-loop)))))))
(do-it)))
(defun logandc2 (integer1 integer2)
(logandc1 integer2 integer1))
(defun logior (&rest integers)
(numargs-case
(1 (x) x)
(2 (x y)
(number-double-dispatch (x y)
((fixnum fixnum)
(with-inline-assembly (:returns :eax)
(:compile-two-forms (:eax :ebx) x y)
(:orl :ebx :eax)))
((positive-fixnum positive-bignum)
(macrolet
((do-it ()
`(let ((r (copy-bignum y)))
(with-inline-assembly (:returns :eax)
(:compile-two-forms (:eax :ecx) r x)
(:shrl ,movitz:+movitz-fixnum-shift+ :ecx)
(:orl :ecx (:eax (:offset movitz-bignum bigit0)))))))
(do-it)))
((positive-bignum positive-fixnum)
(macrolet
((do-it ()
`(let ((r (copy-bignum x)))
(with-inline-assembly (:returns :eax)
(:compile-two-forms (:eax :ecx) r y)
(:shrl ,movitz:+movitz-fixnum-shift+ :ecx)
(:orl :ecx (:eax (:offset movitz-bignum bigit0)))))))
(do-it)))
((positive-bignum positive-bignum)
(if (< (%bignum-bigits x) (%bignum-bigits y))
(logior y x)
(let ((r (copy-bignum x)))
(macrolet
((do-it ()
`(with-inline-assembly (:returns :eax)
(:compile-two-forms (:eax :ebx) r y)
(:movzxw (:ebx (:offset movitz-bignum length))
:ecx)
(:leal ((:ecx 1) ,(* -1 movitz:+movitz-fixnum-factor+))
EDX is loop counter
or-loop
(:movl (:ebx :edx (:offset movitz-bignum bigit0))
:ecx)
(:orl :ecx
(:eax :edx (:offset movitz-bignum bigit0)))
(:subl 4 :edx)
(:jnc 'or-loop))))
(do-it)))))))
(t (&rest integers)
(declare (dynamic-extent integers))
(if (null integers)
0
(reduce #'logior integers)))))
(defun logxor (&rest integers)
(numargs-case
(1 (x) x)
(2 (x y)
(number-double-dispatch (x y)
((fixnum fixnum)
(with-inline-assembly (:returns :eax)
(:compile-two-forms (:eax :ebx) x y)
(:xorl :ebx :eax)))
(((eql 0) t) y)
((t (eql 0)) x)
((positive-fixnum positive-bignum)
(macrolet
((do-it ()
`(with-inline-assembly (:returns :eax)
(:compile-two-forms (:eax :ecx) (copy-bignum y) x)
(:shrl ,movitz:+movitz-fixnum-shift+ :ecx)
(:xorl :ecx (:eax (:offset movitz-bignum bigit0))))))
(do-it)))
((positive-bignum positive-fixnum)
(macrolet
((do-it ()
`(with-inline-assembly (:returns :eax)
(:compile-two-forms (:eax :ecx) (copy-bignum x) y)
(:shrl ,movitz:+movitz-fixnum-shift+ :ecx)
(:xorl :ecx (:eax (:offset movitz-bignum bigit0))))))
(do-it)))
((positive-bignum positive-bignum)
(if (< (%bignum-bigits x) (%bignum-bigits y))
(logxor y x)
(let ((r (copy-bignum x)))
(macrolet
((do-it ()
`(bignum-canonicalize
(with-inline-assembly (:returns :eax)
(:compile-two-forms (:eax :ebx) r y)
(:movzxw (:ebx (:offset movitz-bignum length))
:ecx)
(:leal ((:ecx 1),(* -1 movitz:+movitz-fixnum-factor+))
EDX is loop counter
xor-loop
(:movl (:ebx :edx (:offset movitz-bignum bigit0))
:ecx)
(:xorl :ecx (:eax :edx (:offset movitz-bignum bigit0)))
(:subl 4 :edx)
(:jnc 'xor-loop)
))))
(do-it)))))))
(t (&rest integers)
(declare (dynamic-extent integers))
(if (null integers)
0
(reduce #'logxor integers)))))
(defun lognot (integer)
(- -1 integer))
(defun ldb%byte (size position integer)
"This is LDB with explicit byte-size and position parameters."
(check-type size positive-fixnum)
(check-type position positive-fixnum)
(etypecase integer
(fixnum
(macrolet
((do-it ()
`(with-inline-assembly (:returns :eax)
(:compile-two-forms (:eax :ecx) integer position)
(:cmpl ,(* (1- movitz:+movitz-fixnum-bits+) movitz:+movitz-fixnum-factor+)
:ecx)
(:ja '(:sub-program (outside-fixnum)
(:addl #x80000000 :eax) ; sign into carry
(:sbbl :ecx :ecx)
(:leal ((:ecx ,movitz:+movitz-fixnum-factor+)) :eax)
(:jmp 'mask-fixnum)))
(:shrl ,movitz:+movitz-fixnum-shift+ :ecx)
(:std) ; <================= STD
(:sarl :cl :eax) ; shift..
(:andl ,(logxor #xffffffff movitz:+movitz-fixnum-zmask+) :eax)
(:cld) ; =================> CLD
mask-fixnum
(:compile-form (:result-mode :ecx) size)
(:cmpl ,(* (1- movitz:+movitz-fixnum-bits+) movitz:+movitz-fixnum-factor+)
:ecx)
(:jna 'fixnum-result)
(:testl :eax :eax)
(:jns 'fixnum-done)
;; We need to generate a bignum..
.. filling in 1 - bits since the integer is negative .
(:pushl :eax) ; This will become the LSB bigit.
;; Set up atomically continuation.
(:declare-label-set restart-jumper (restart-ones-expanded-bignum))
(:locally (:pushl (:edi (:edi-offset :dynamic-env))))
(:pushl 'restart-jumper)
;; ..this allows us to detect recursive atomicallies.
(:locally (:pushl (:edi (:edi-offset :atomically-continuation))))
(:pushl :ebp)
restart-ones-expanded-bignum
(:movl (:esp) :ebp)
;;; (:declare-label-set retry-jumper-ones-expanded-bignum (retry-ones-expanded-bignum))
Calculate word - size from bytespec - size .
(:compile-form (:result-mode :ecx) size)
Add 31
Divide by 32
(:andl ,(- movitz:+movitz-fixnum-factor+) :ecx)
Add 1 for header .
:eax)
(:locally (:movl :esp (:edi (:edi-offset :atomically-continuation))))
;; Now inside atomically section.
(:call-local-pf cons-non-pointer)
(:shll 16 :ecx)
(:orl ,(movitz:tag :bignum 0) :ecx)
(:movl :ecx (:eax ,movitz:+other-type-offset+))
(:shrl 16 :ecx)
(:leal ((:ecx ,movitz:+movitz-fixnum-factor+)
add 1 for header .
:ecx)
(:call-local-pf cons-commit-non-pointer)
(:locally (:movl 0 (:edi (:edi-offset atomically-continuation))))
(:leal (:esp 16) :esp)
Have fresh bignum in EAX , now fill it with ones .
(:xorl :ecx :ecx) ; counter
fill-ones-loop
(:movl #xffffffff (:eax :ecx (:offset movitz-bignum bigit0)))
(:addl 4 :ecx)
(:cmpw :cx (:eax (:offset movitz-bignum length)))
(:jne 'fill-ones-loop)
(:popl :ecx) ; The LSB bigit.
(:sarl ,movitz:+movitz-fixnum-shift+ :ecx)
(:movl :ecx (:eax (:offset movitz-bignum bigit0)))
(:movl :eax :ebx)
Compute MSB bigit mask in EDX
(:compile-form (:result-mode :ecx) size)
(:shrl ,movitz:+movitz-fixnum-shift+ :ecx)
(:std) ; <================= STD
(:xorl :edx :edx)
(:andl 31 :ecx)
(:jz 'fixnum-mask-ok)
(:addl 1 :edx)
(:shll :cl :edx)
fixnum-mask-ok
(:subl 1 :edx)
(:movzxw (:ebx (:offset movitz-bignum length))
:ecx)
And EDX with the MSB bigit .
(:ebx :ecx (:offset movitz-bignum bigit0 -4)))
(:movl :edi :edx)
(:movl :edi :eax)
(:cld) ; =================> CLD
(:movl :ebx :eax)
(:jmp 'fixnum-done)
fixnum-result
(:shrl ,movitz:+movitz-fixnum-shift+ :ecx)
generate fixnum mask in EDX
(:shll :cl :edx)
(:subl ,movitz:+movitz-fixnum-factor+ :edx)
(:andl :edx :eax)
(:jmp 'fixnum-done)
fixnum-done
)))
(do-it)))
(positive-bignum
(cond
((= size 0) 0)
((<= size 32)
;; The result is likely to be a fixnum (or at least an u32), due to byte-size.
(macrolet
((do-it ()
`(with-inline-assembly (:returns :eax)
(:compile-form (:result-mode :ebx) integer)
(:compile-form (:result-mode :eax) position)
(:movl :eax :ecx) ; compute bigit-number in ecx
(:sarl 5 :ecx)
(:andl -4 :ecx)
(:addl 4 :ecx)
(:cmpl ,(* #x4000 movitz:+movitz-fixnum-factor+)
:ecx)
(:jae 'position-outside-integer)
(:cmpw :cx (:ebx (:offset movitz-bignum length)))
(:jc '(:sub-program (position-outside-integer)
(:movsxb (:ebx (:offset movitz-bignum sign)) :ecx)
(:leal ((:ecx ,movitz:+movitz-fixnum-factor+)) :eax)
(:jmp 'done-u32)))
(:std)
(:movl (:ebx :ecx (:offset movitz-bignum bigit0 -4))
:eax)
(:movl 0 :edx) ; If position was in last bigit.. (don't touch EFLAGS)
.. we must zero - extend rather than read top bigit .
(:movl (:ebx :ecx (:offset movitz-bignum bigit0))
Read top bigit into EDX
no-top-bigit
(:testl #xff00 (:ebx ,movitz:+other-type-offset+))
(:jnz '(:sub-program (negative-bignum)
We must negate the ..
(:break)
))
edx-eax-ok
EDX : EAX now holds the number that must be shifted and masked .
(:compile-form (:result-mode :ecx) position)
(:shrl ,movitz:+movitz-fixnum-shift+ :ecx)
Shifted value into EAX
(:compile-form (:result-mode :ecx) size)
Generate a mask in EDX
(:shrl ,movitz:+movitz-fixnum-shift+ :ecx)
(:testl 31 :ecx)
(:jz 'mask-ok-u32)
(:addl 1 :edx)
(:shll :cl :edx)
mask-ok-u32
(:subl 1 :edx)
(:andl :edx :eax)
(:movl :eax :ecx) ; For boxing..
(:movl :edi :eax)
(:movl :edi :edx)
(:cld)
;; See if we can return same bignum..
(:cmpl ,(dpb movitz:+movitz-fixnum-factor+
(byte 16 16) (movitz:tag :bignum 0))
(:ebx ,movitz:+other-type-offset+))
(:jne 'cant-return-same)
(:cmpl :ecx (:ebx (:offset movitz-bignum bigit0)))
(:jne 'cant-return-same)
(:movl :ebx :eax)
(:jmp 'done-u32)
cant-return-same
(:call-local-pf box-u32-ecx)
done-u32
)))
(do-it)))
(t (macrolet
((do-it ()
`(let (new-size)
(with-inline-assembly (:returns :eax)
(:compile-form (:result-mode :ebx) integer)
(:compile-form (:result-mode :ecx) position)
(:shrl 5 :ecx) ; compute fixnum bigit-number in ecx
(:cmpl ,(* #x4000 movitz:+movitz-fixnum-factor+)
:ecx)
(:jnc 'position-outside-integer)
(:cmpw :cx (:ebx (:offset movitz-bignum length)))
(:jbe '(:sub-program (position-outside-integer)
(:movsxb (:ebx (:offset movitz-bignum sign)) :ecx)
(:leal ((:ecx ,movitz:+movitz-fixnum-factor+)) :eax)
(:jmp 'done-u32)))
(:compile-two-forms (:edx :ecx) position size)
keep size / fixnum in EAX .
(:addl :edx :ecx)
(:into) ; just to make sure
compute msb bigit index / fixnum in ecx
(:addl 4 :ecx)
(:cmpw :cx (:ebx (:offset movitz-bignum length)))
(:je '(:sub-program (equal-size-maybe-return-same)
Can only return same if ( zerop position ) .
(:jnz 'adjust-size)
(:movl :eax :ecx) ; size/fixnum
(:shrl ,movitz:+movitz-fixnum-shift+ :ecx)
(:andl 31 :ecx)
(:jz 'yes-return-same)
(:std) ; <================
we know EDX=0 , now generate mask in EDX
(:addl 1 :edx)
(:shll :cl :edx)
(:movzxw (:ebx (:offset movitz-bignum length))
:ecx)
(:cmpl :edx (:ebx :ecx (:offset movitz-bignum bigit0 -4)))
(:movl 0 :edx) ; Safe value, and correct if we need to go to adjust-size.
(:cld) ; =================>
(:jnc 'adjust-size) ; nope, we have to generate a new bignum.
yes-return-same
(:movl :ebx :eax) ; yep, we can return same bignum.
(:jmp 'ldb-done)))
(:jnc 'size-ok)
;; We now know that (+ size position) is beyond the size of the bignum.
So , if ( zerop position ) , we can return the bignum as our result .
(:testl :edx :edx)
(:jz '(:sub-program ()
(:movl :ebx :eax) ; return the source bignum.
(:jmp 'ldb-done)))
adjust-size
The bytespec is ( partially ) outside source - integer , so we make the
;; size smaller before proceeding. new-size = (- source-int-length position)
(:movzxw (:ebx (:offset movitz-bignum length))
:ecx) ; length of source-integer
(:shll 5 :ecx) ; fixnum bit-position
In case the new size is zero .
(:subl :edx :ecx) ; subtract position
(:js '(:sub-program (should-not-happen)
;; new size should never be negative.
(:break)))
New size was zero , so the result of ldb is zero .
New size into EAX .
size-ok
(:store-lexical (:lexical-binding new-size) :eax :type fixnum)
;; Set up atomically continuation.
(:declare-label-set restart-ldb-jumper (restart-ldb))
(:locally (:pushl (:edi (:edi-offset :dynamic-env))))
(:pushl 'restart-ldb-jumper)
;; ..this allows us to detect recursive atomicallies.
(:locally (:pushl (:edi (:edi-offset :atomically-continuation))))
(:pushl :ebp)
restart-ldb
(:movl (:esp) :ebp)
(:load-lexical (:lexical-binding new-size) :eax)
(:locally (:movl :esp (:edi (:edi-offset :atomically-continuation))))
;; Now inside atomically section.
( new ) Size is in EAX .
(:subl ,movitz:+movitz-fixnum-factor+ :eax)
(:andl ,(logxor #xffffffff
(mask-field (byte (+ 5 movitz:+movitz-fixnum-shift+) 0) -1))
:eax)
Divide ( size-1 ) by 32 to get number of bigits-1
Now add 1 for index->size , 1 for header , and 1 for tmp storage before shift .
(:addl ,(* 3 movitz:+movitz-fixnum-factor+) :eax)
(:pushl :eax)
(:call-local-pf cons-non-pointer)
;; (:store-lexical (:lexical-binding r) :eax :type t)
(:popl :ecx)
(:subl ,(* 2 movitz:+movitz-fixnum-factor+) :ecx) ; for tmp storage and header.
(:shll 16 :ecx)
(:orl ,(movitz:tag :bignum 0) :ecx)
(:movl :ecx (:eax ,movitz:+other-type-offset+))
(:compile-form (:result-mode :ebx) integer)
(:xchgl :eax :ebx)
now : EAX = old integer , EBX = new result bignum
Edge case : When size(old)=size(new ) , the tail - tmp must be zero .
;; We check here, setting the tail-tmp to a mask for and-ing below.
(:movzxw (:ebx (:offset movitz-bignum length))
:ecx) ; length of source-integer
Initialize tail - tmp to # xffffffff , meaning copy from source - integer .
(:movl #xffffffff (:ebx :ecx (:offset movitz-bignum bigit0)))
(:cmpw :cx (:eax (:offset movitz-bignum length)))
(:jc '(:sub-program (result-too-big-shouldnt-happen)
(:int 4)))
(:jne 'tail-tmp-ok)
Sizes was equal , so set tail - tmp to zero .
(:movl 0 (:ebx :ecx (:offset movitz-bignum bigit0)))
tail-tmp-ok
;; Now copy the relevant part of the integer
(:std)
(:compile-form (:result-mode :ecx) position)
(:sarl ,(+ 5 movitz:+movitz-fixnum-shift+) :ecx) ; compute bigit-number in ecx
;; We can use primitive pointers because we're both inside atomically and std.
(:leal (:eax (:ecx 4) (:offset movitz-bignum bigit0))
Use EAX as primitive pointer into source
(:xorl :ecx :ecx) ; counter
copy-integer
(:movl (:eax) :edx)
(:addl 4 :eax)
(:movl :edx (:ebx :ecx (:offset movitz-bignum bigit0)))
(:addl 4 :ecx)
(:cmpw :cx (:ebx (:offset movitz-bignum length)))
(:jne 'copy-integer)
Copy one more than the length , namely the tmp at the end .
;; Tail-tmp was initialized to a bit-mask above.
(:movl (:eax) :edx)
(:andl :edx (:ebx :ecx (:offset movitz-bignum bigit0)))
;; Copy done, now shift
(:compile-form (:result-mode :ecx) position)
(:shrl ,movitz:+movitz-fixnum-shift+ :ecx)
(:andl 31 :ecx)
if ( zerop ( mod position 32 ) ) , no shift needed .
(:xorl :edx :edx) ; counter
shift-loop
(:movl (:ebx :edx (:offset movitz-bignum bigit0 4))
:eax) ; Next bigit into eax
Now shift bigit , with msbs from eax .
(:ebx :edx (:offset movitz-bignum bigit0)))
(:addl 4 :edx)
(:cmpw :dx (:ebx (:offset movitz-bignum length)))
(:jne 'shift-loop)
shift-done
Now we must mask MSB bigit .
(:movzxw (:ebx (:offset movitz-bignum length))
:edx)
(:load-lexical (:lexical-binding size) :ecx)
(:shrl 5 :ecx)
ECX = index of ( conceptual ) MSB
(:cmpl :ecx :edx)
(:jbe 'mask-done)
(:load-lexical (:lexical-binding size) :ecx)
(:shrl ,movitz:+movitz-fixnum-shift+ :ecx)
(:andl 31 :ecx)
(:jz 'mask-done)
Generate mask in EAX
(:shll :cl :eax)
(:subl 1 :eax)
(:andl :eax (:ebx :edx (:offset movitz-bignum bigit0 -4)))
mask-done
(: : edi : edx ) ; safe EDX
safe EAX
(:cld)
Now we must zero - truncate the result bignum in EBX .
(:movzxw (:ebx (:offset movitz-bignum length))
:ecx)
zero-truncate-loop
(:cmpl 0 (:ebx :ecx (:offset movitz-bignum bigit0 -4)))
(:jne 'zero-truncate-done)
(:subl 4 :ecx)
(:jnz 'zero-truncate-loop)
Zero bigits means the entire result collapsed to zero .
(:xorl :eax :eax)
(:jmp 'return-fixnum) ; don't commit the bignum allocation.
zero-truncate-done
If result size is 1 , the result might have ..
(:jne 'complete-bignum-allocation) ; ..collapsed to a fixnum.
(:cmpl ,movitz:+movitz-most-positive-fixnum+
(:ebx (:offset movitz-bignum bigit0)))
(:ja 'complete-bignum-allocation)
(:movl (:ebx (:offset movitz-bignum bigit0))
:ecx)
(:leal ((:ecx ,movitz:+movitz-fixnum-factor+)) :eax)
(:jmp 'return-fixnum)
complete-bignum-allocation
(:movw :cx (:ebx (:offset movitz-bignum length)))
(:movl :ebx :eax)
(:leal (:ecx ,movitz:+movitz-fixnum-factor+)
:ecx)
(:call-local-pf cons-commit-non-pointer)
return-fixnum
(:locally (:movl 0 (:edi (:edi-offset atomically-continuation))))
(:leal (:esp 16) :esp)
ldb-done))))
(do-it)))))))
(defun ldb (bytespec integer)
(ldb%byte (byte-size bytespec) (byte-position bytespec) integer))
(defun ldb-test (bytespec integer)
(case (byte-size bytespec)
(0 nil)
(1 (logbitp (byte-position bytespec) integer))
(t (/= 0 (ldb bytespec integer)))))
(defun logtest (integer-1 integer-2)
"=> generalized-boolean"
(not (= 0 (logand integer-1 integer-2))))
(defun logcount (integer)
(etypecase integer
(positive-fixnum
(with-inline-assembly (:returns :untagged-fixnum-ecx :type (integer 0 29))
(:load-lexical (:lexical-binding integer) :eax)
(:xorl :ecx :ecx)
count-loop
(:shll 1 :eax)
(:adcl 0 :ecx)
(:testl :eax :eax)
(:jnz 'count-loop)))
(positive-bignum
(bignum-logcount integer))))
(defun dpb (newbyte bytespec integer)
(logior (if (= 0 newbyte)
0
(mask-field bytespec (ash newbyte (byte-position bytespec))))
(if (= 0 integer)
0
(logandc2 integer (mask-field bytespec -1)))))
(defun mask-field (bytespec integer)
(ash (ldb bytespec integer) (byte-position bytespec)))
(defun deposit-field (newbyte bytespec integer)
(logior (mask-field bytespec newbyte)
(logandc2 integer (mask-field bytespec -1))))
;;;
(defun plus-if (x y)
(if (integerp x) (+ x y) x))
(defun minus-if (x y)
(if (integerp x) (- x y) x))
(defun gcd (&rest integers)
(numargs-case
(1 (u) u)
(2 (u v)
Code borrowed from CMUCL .
(cond
((= 0 u) v)
((= 0 v) u)
(t (do ((k 0 (1+ k))
(u (abs u) (truncate u 2))
(v (abs v) (truncate v 2)))
((or (oddp u) (oddp v))
(do ((temp (if (oddp u)
(- v)
(truncate u 2))
(truncate temp 2)))
(nil)
(when (oddp temp)
(if (plusp temp)
(setq u temp)
(setq v (- temp)))
(setq temp (- u v))
(when (zerop temp)
(return (ash u k))))))))))
(t (&rest integers)
(declare (dynamic-extent integers))
(do ((gcd (car integers)
(gcd gcd (car rest)))
(rest (cdr integers) (cdr rest)))
((null rest) gcd)))))
(defun lcm (&rest numbers)
"Returns the least common multiple of one or more integers. LCM of no
arguments is defined to be 1."
(numargs-case
(1 (n)
(abs n))
(2 (n m)
(abs (* (truncate (max n m) (gcd n m)) (min n m))))
(t (&rest numbers)
(declare (dynamic-extent numbers))
(reduce #'lcm numbers))))
(defun floor (n &optional (divisor 1))
"This is floor written in terms of truncate."
(numargs-case
(1 (n)
(if (not (typep n 'ratio))
(values n 0)
(multiple-value-bind (r q)
(floor (%ratio-numerator n) (%ratio-denominator n))
(values r (make-rational q (%ratio-denominator n))))))
(2 (n divisor)
(multiple-value-bind (q r)
(truncate n divisor)
(cond
((= 0 r)
(values q r))
((or (and (minusp r) (plusp divisor))
(and (plusp r) (minusp divisor)))
(values (1- q) (+ r divisor)))
(t (values q r)))))
(t (n &optional (divisor 1))
(floor n divisor))))
(defun isqrt (natural)
"=> natural-root"
(check-type natural (integer 0 *))
(if (= 0 natural)
0
(let ((r 1))
(do ((next-r (truncate (+ r (truncate natural r)) 2)
(truncate (+ r (truncate natural r)) 2)))
((typep (- next-r r) '(integer 0 1))
(let ((r+1 (1+ r)))
(if (<= (* r+1 r+1) natural)
r+1
r)))
(setf r next-r)))))
(defun rootn (x root)
(check-type root (integer 2 *))
(let ((root-1 (1- root))
(r (/ x root)))
(dotimes (i 10 r)
(let ((m (min (integer-length (numerator r))
(integer-length (denominator r)))))
(when (>= m 32)
(setf r (/ (ash (numerator r) (- 24 m))
(ash (denominator r) (- 24 m))))))
#+ignore (format t "~&~D: ~X~%~D: ~F [~D ~D]~%" i r i r
(integer-length (numerator r))
(integer-length (denominator r)))
(setf r (/ (+ (* root-1 r)
(/ x (expt r root-1)))
root)))))
(defun sqrt (x)
(rootn x 2))
(defun expt (base-number power-number)
"Take base-number to the power-number."
(etypecase power-number
(positive-fixnum
(do ((i 0 (1+ i))
(r 1 (* r base-number)))
((>= i power-number) r)
(declare (index i))))
(positive-bignum
(do ((i 0 (1+ i))
(r 1 (* r base-number)))
((>= i power-number) r)))
((number * -1)
(/ (expt base-number (- power-number))))
(ratio
(expt (rootn base-number (denominator power-number))
(numerator power-number)))))
(defun floatp (x)
(declare (ignore x))
nil)
(defun realpart (number)
number)
(defun imagpart (number)
(declare (ignore number))
0)
(defun rational (number)
number)
(defun realp (x)
(typep x 'real))
| null | https://raw.githubusercontent.com/vonli/Ext2-for-movitz/81b6f8e165de3e1ea9cc7d2035b9259af83a6d26/losp/muerte/integers.lisp | lisp | ------------------------------------------------------------------
Filename: integers.lisp
Created at: Wed Nov 8 18:44:57 2000
Distribution: See the accompanying file COPYING.
------------------------------------------------------------------
unspecified
both were fixnum
but we don't know about n2
n2 is fixnum
Check that both numbers are bignums, and compare them.
Comparing the sign-bytes sets up EFLAGS correctly!
counter
Now we have to make the compare act as unsigned, which is why
Moth n1 and n2 are negative bignums.
counter
Now we have to make the compare act as unsigned, which is why
well..
EQ?
counter
unspecified
compare eax with something bigger
compare ebx with something bigger
unspecified
compare ebx with something bigger
compare ebx with something bigger
The real result is in EFLAGS.
Unsigned
Equality
Addition
..this allows us to detect recursive atomicallies.
Now inside atomically section.
Number of words
bignum
counter
result bignum word-size
Assume x is smallest.
Set up atomically continuation.
..this allows us to detect recursive atomicallies.
Number of words
Now inside atomically section.
bignum
counter
Carry
Subtraction
((positive-fixnum positive-bignum)
(bignum-canonicalize
(%bignum-negate
(bignum-subf (copy-bignum subtrahend) minuend))))
((negative-fixnum positive-bignum)
(bignum-canonicalize
(%negatef (bignum-add-fixnum subtrahend minuend)
subtrahend minuend)))
counter
carry
Just propagate carry
shift
counter
Safe EAX
Multiplication
most likely/optimized path.
guaranteed won't overflow.
if result was negative, we must negate bignum
Set up atomically continuation.
..this allows us to detect recursive atomicallies:
Now inside atomically section.
bignum
r into ebx
counter
initial carry
can't overflow
new
Negate the resulting bignum
X is the biggest factor.
return values: qutient, remainder.
Set up atomically continuation.
..this allows us to detect recursive atomicallies.
Now inside atomically section.
edx=hi-digit=0
eax=lo-digit=msd(number)
safe value
don't commit the bignum
bytes
sign into carry
<================= STD
shift..
=================> CLD
We need to generate a bignum..
This will become the LSB bigit.
Set up atomically continuation.
..this allows us to detect recursive atomicallies.
(:declare-label-set retry-jumper-ones-expanded-bignum (retry-ones-expanded-bignum))
Now inside atomically section.
counter
The LSB bigit.
<================= STD
=================> CLD
The result is likely to be a fixnum (or at least an u32), due to byte-size.
compute bigit-number in ecx
If position was in last bigit.. (don't touch EFLAGS)
For boxing..
See if we can return same bignum..
compute fixnum bigit-number in ecx
just to make sure
size/fixnum
<================
Safe value, and correct if we need to go to adjust-size.
=================>
nope, we have to generate a new bignum.
yep, we can return same bignum.
We now know that (+ size position) is beyond the size of the bignum.
return the source bignum.
size smaller before proceeding. new-size = (- source-int-length position)
length of source-integer
fixnum bit-position
subtract position
new size should never be negative.
Set up atomically continuation.
..this allows us to detect recursive atomicallies.
Now inside atomically section.
(:store-lexical (:lexical-binding r) :eax :type t)
for tmp storage and header.
We check here, setting the tail-tmp to a mask for and-ing below.
length of source-integer
Now copy the relevant part of the integer
compute bigit-number in ecx
We can use primitive pointers because we're both inside atomically and std.
counter
Tail-tmp was initialized to a bit-mask above.
Copy done, now shift
counter
Next bigit into eax
safe EDX
don't commit the bignum allocation.
..collapsed to a fixnum.
| Copyright ( C ) 2000 - 2005 ,
Department of Computer Science , University of Tromso , Norway
Description : Arithmetics .
Author : < >
$ I d : , v 1.124 2008/02/04 10:08:18 ffjeld Exp $
(require :muerte/basic-macros)
(require :muerte/typep)
(require :muerte/arithmetic-macros)
(provide :muerte/integers)
(in-package muerte)
(defconstant most-positive-fixnum #.movitz::+movitz-most-positive-fixnum+)
(defconstant most-negative-fixnum #.movitz::+movitz-most-negative-fixnum+)
Comparison
(define-primitive-function fast-compare-two-reals (n1 n2)
"Compare two numbers (i.e. set EFLAGS accordingly)."
(macrolet
((do-it ()
(:testb ,movitz::+movitz-fixnum-zmask+ :al)
(:jnz 'n1-not-fixnum)
(:testb ,movitz::+movitz-fixnum-zmask+ :bl)
(:jnz 'n2-not-fixnum-but-n1-is)
(:ret)
(:testb ,movitz::+movitz-fixnum-zmask+ :bl)
(:jnz 'neither-is-fixnum)
(:locally (:jmp (:edi (:edi-offset fast-compare-real-fixnum))))
n2-not-fixnum-but-n1-is
(:locally (:jmp (:edi (:edi-offset fast-compare-fixnum-real))))
neither-is-fixnum
(:leal (:eax ,(- (movitz:tag :other))) :ecx)
(:testb 7 :cl)
(:jnz '(:sub-program (go-complicated)
(:globally (:movl (:edi (:edi-offset complicated-compare)) :esi))
(:jmp (:esi (:offset movitz-funobj code-vector%2op)))))
(:movl (:eax ,movitz:+other-type-offset+) :ecx)
(:cmpb ,(movitz:tag :bignum) :cl)
(:jne 'go-complicated)
If they are EQ , they are certainly =
(:je '(:sub-program (n1-and-n2-are-eq)
(:ret)))
(:leal (:ebx ,(- (movitz:tag :other))) :ecx)
(:testb 7 :cl)
(:jnz 'go-complicated)
(:movl (:ebx ,movitz:+other-type-offset+) :ecx)
(:cmpb ,(movitz:tag :bignum) :cl)
(:jne 'go-complicated)
(:cmpb :ch (:eax (:offset movitz-bignum sign)))
(:jne '(:sub-program (different-signs)
(:ret)))
(:testl #xff00 :ecx)
(:jnz 'compare-negatives)
Both n1 and n2 are positive bignums .
(:shrl 16 :ecx)
(:movzxw (:eax (:offset movitz-bignum length)) :edx)
(: cmpw : cx (: eax (: offset ) ) )
(:cmpl :ecx :edx)
(:jne '(:sub-program (positive-different-sizes)
(:ret)))
Both n1 and n2 are positive bignums of the same size , namely ECX .
positive-compare-loop
(:subl ,movitz:+movitz-fixnum-factor+ :edx)
(:jz 'positive-compare-lsb)
(:movl (:ebx :edx (:offset movitz-bignum bigit0)) :ecx)
(:cmpl :ecx (:eax :edx (:offset movitz-bignum bigit0)))
(:je 'positive-compare-loop)
positive-compare-lsb
we compare zero - extended 16 - bit quantities .
First compare upper 16 bits .
(:locally (:movl :ecx (:edi (:edi-offset raw-scratch0))))
(:movzxw (:eax :edx (:offset movitz-bignum bigit0 2)) :ecx)
(:locally (:cmpl (:edi (:edi-offset raw-scratch0)) :ecx))
(:jne 'upper-16-decisive)
(:movzxw (:ebx :edx (:offset movitz-bignum bigit0))
Then compare lower 16 bits .
(:locally (:movl :ecx (:edi (:edi-offset raw-scratch0))))
(:movzxw (:eax :edx (:offset movitz-bignum bigit0))
Then compare lower 16 bits .
(:locally (:cmpl (:edi (:edi-offset raw-scratch0)) :ecx))
upper-16-decisive
(:ret)
compare-negatives
(:shrl 16 :ecx)
(:cmpw (:eax (:offset movitz-bignum length)) :cx)
(:jne '(:sub-program (negative-different-sizes)
(:ret)))
Both n1 and n2 are negative bignums of the same size , namely ECX .
negative-compare-loop
(:subl ,movitz:+movitz-fixnum-factor+ :edx)
(:jz 'negative-compare-lsb)
(:movl (:eax :edx (:offset movitz-bignum bigit0)) :ecx)
(:cmpl :ecx (:ebx :edx (:offset movitz-bignum bigit0)))
(:je 'negative-compare-loop)
(:ret)
it 's down to .
we compare zero - extended 16 - bit quantities .
(:movzxw (:ebx :edx (:offset movitz-bignum bigit0 2))
First compare upper 16 bits .
(:locally (:movl :ecx (:edi (:edi-offset raw-scratch0))))
(:movzxw (:eax :edx (:offset movitz-bignum bigit0)) :ecx)
(:locally (:cmpl :ecx (:edi (:edi-offset raw-scratch0))))
(:jne 'negative-upper-16-decisive)
(:movzxw (:ebx :edx (:offset movitz-bignum bigit0))
Then compare lower 16 bits .
(:locally (:movl :ecx (:edi (:edi-offset raw-scratch0))))
(:movzxw (:eax :edx (:offset movitz-bignum bigit0))
Then compare lower 16 bits .
(:locally (:cmpl :ecx (:edi (:edi-offset raw-scratch0))))
negative-upper-16-decisive
(:ret))))
(do-it)))
(defun complicated-eql (x y)
(macrolet
((do-it ()
(:compile-two-forms (:eax :ebx) x y)
(:je 'done)
(:leal (:eax ,(- (movitz:tag :other))) :ecx)
(:testb 7 :cl)
(:jne 'done)
(:leal (:ebx ,(- (movitz:tag :other))) :ecx)
(:testb 7 :cl)
(:jne 'done)
(:movl (:eax ,movitz:+other-type-offset+) :ecx)
(:cmpb ,(movitz:tag :bignum) :cl)
(:jne 'not-bignum)
(:cmpl :ecx (:ebx ,movitz:+other-type-offset+))
(:jne 'done)
Ok .. we have two bignums of identical sign and size .
(:shrl 16 :ecx)
compare-loop
(:subl ,movitz:+movitz-fixnum-factor+ :edx)
(:jz 'done)
(:movl (:eax :edx (:offset movitz-bignum bigit0 -4)) :ecx)
(:cmpl :ecx (:ebx :edx (:offset movitz-bignum bigit0 -4)))
(:je 'compare-loop)
(:jmp 'done)
not-bignum
(:cmpb ,(movitz:tag :ratio) :cl)
(:jne 'not-ratio)
(:cmpl :ecx (:ebx ,movitz:+other-type-offset+))
(:jne 'done)
(:movl (:eax (:offset movitz-ratio numerator)) :eax)
(:movl (:ebx (:offset movitz-ratio numerator)) :ebx)
(:call (:esi (:offset movitz-funobj code-vector%2op)))
(:jne 'done)
(:compile-two-forms (:eax :ebx) x y)
(:movl (:eax (:offset movitz-ratio denominator)) :eax)
(:movl (:ebx (:offset movitz-ratio denominator)) :ebx)
(:call (:esi (:offset movitz-funobj code-vector%2op)))
(:jmp 'done)
not-ratio
done
(:movl :edi :eax)
(:clc)
)))
(do-it)))
(define-primitive-function fast-compare-fixnum-real (n1 n2)
"Compare (known) fixnum <n1> with real <n2>."
(macrolet
((do-it ()
(:testb ,movitz::+movitz-fixnum-zmask+ :bl)
(:jnz 'n2-not-fixnum)
(:cmpl :ebx :eax)
(:ret)
n2-not-fixnum
(:leal (:ebx ,(- (movitz:tag :other))) :ecx)
(:testb 7 :cl)
(:jnz '(:sub-program (go-complicated)
(:globally (:movl (:edi (:edi-offset complicated-compare)) :esi))
(:jmp (:esi (:offset movitz-funobj code-vector%2op)))))
(:movl (:ebx ,movitz:+other-type-offset+) :ecx)
(:cmpw ,(movitz:tag :bignum 0) :cx)
(:jne 'not-plusbignum)
(:cmpl #x10000000 :edi)
(:ret)
not-plusbignum
(:cmpw ,(movitz:tag :bignum #xff) :cx)
(:jne 'go-complicated)
(:cmpl #x-10000000 :edi)
(:ret))))
(do-it)))
(define-primitive-function fast-compare-real-fixnum (n1 n2)
"Compare real <n1> with fixnum <n2>."
(:testb #.movitz::+movitz-fixnum-zmask+ :al)
(:jnz 'not-fixnum)
(:cmpl :ebx :eax)
(:ret)
not-fixnum
(:leal (:eax #.(cl:- (movitz:tag :other))) :ecx)
(:testb 7 :cl)
(:jnz '(:sub-program (go-complicated)
(:globally (:movl (:edi (:edi-offset complicated-compare)) :esi))
(:jmp (:esi (:offset movitz-funobj code-vector%2op)))))
(:movl (:eax #.movitz:+other-type-offset+) :ecx)
(:cmpw #.(movitz:tag :bignum 0) :cx)
(:jne 'not-plusbignum)
(:cmpl #x-10000000 :edi)
(:ret)
not-plusbignum
(:cmpw #.(movitz:tag :bignum #xff) :cx)
(:jne 'go-complicated)
(:cmpl #x10000000 :edi)
(:ret)))
(defun complicated-compare (x y)
(let ((ix (* (numerator x) (denominator y)))
(iy (* (numerator y) (denominator x))))
(with-inline-assembly (:returns :multiple-values)
(:compile-two-forms (:eax :ebx) ix iy)
(:call-global-pf fast-compare-two-reals)
(:movl :edi :eax))))
(defun below (x max)
"Is x between 0 and max?"
(compiler-macro-call below x max))
(define-compiler-macro =%2op (n1 n2 &environment env)
(cond
#+ignore
((movitz:movitz-constantp n1 env)
(let ((n1 (movitz:movitz-eval n1 env)))
(etypecase n1
((eql 0)
`(do-result-mode-case ()
(:booleans
(with-inline-assembly (:returns :boolean-zf=1 :side-effects nil)
(:compile-form (:result-mode :eax) ,n2)
(:testl :eax :eax)))
(t (with-inline-assembly (:returns :boolean-cf=1 :side-effects nil)
(:compile-form (:result-mode :eax) ,n2)
(:cmpl 1 :eax)))))
((signed-byte 30)
`(with-inline-assembly (:returns :boolean-zf=1 :side-effects nil)
(:compile-two-forms (:eax :ebx) ,n1 ,n2)
(:call-global-pf fast-compare-fixnum-real)))
(integer
`(with-inline-assembly (:returns :boolean-zf=1 :side-effects nil)
(:compile-two-forms (:eax :ebx) ,n1 ,n2)
(:call-global-pf fast-compare-two-reals))))))
#+ignore
((movitz:movitz-constantp n2 env)
`(=%2op ,n2 ,n1))
(t `(eql ,n1 ,n2))))
(define-number-relational = =%2op nil :defun-p nil)
(defun = (first-number &rest numbers)
(declare (dynamic-extent numbers))
(dolist (n numbers t)
(unless (= first-number n)
(return nil))))
(define-compiler-macro /=%2op (n1 n2)
`(not (= ,n1 ,n2)))
(define-number-relational /= /=%2op nil :defun-p nil)
(defun /= (&rest numbers)
(declare (dynamic-extent numbers))
(do ((p (cdr numbers) (cdr p)))
((null p) t)
(do ((v numbers (cdr v)))
((eq p v))
(when (= (car p) (car v))
(return-from /= nil)))))
(deftype positive-fixnum ()
'(integer 0 #.movitz:+movitz-most-positive-fixnum+))
(deftype positive-bignum ()
`(integer #.(cl:1+ movitz:+movitz-most-positive-fixnum+) *))
(deftype negative-fixnum ()
`(integer #.movitz:+movitz-most-negative-fixnum+ -1))
(deftype negative-bignum ()
`(integer * #.(cl:1- movitz::+movitz-most-negative-fixnum+)))
(defun fixnump (x)
(typep x 'fixnum))
(defun evenp (x)
(compiler-macro-call evenp x))
(defun oddp (x)
(compiler-macro-call oddp x))
(defun %negatef (x p0 p1)
"Negate x. If x is not eq to p0 or p1, negate x destructively."
(etypecase x
(fixnum (- x))
(bignum
(if (or (eq x p0) (eq x p1))
(- x)
(with-inline-assembly (:returns :eax)
(:compile-form (:result-mode :eax) x)
(:xorl #xff00 (:eax #.movitz:+other-type-offset+)))))))
(defun + (&rest terms)
(declare (without-check-stack-limit))
(numargs-case
(1 (x) x)
(2 (x y)
(macrolet
((do-it ()
`(number-double-dispatch (x y)
((fixnum fixnum)
(with-inline-assembly (:returns :eax)
(:compile-form (:result-mode :eax) x)
(:compile-form (:result-mode :ebx) y)
(:addl :ebx :eax)
(:jo '(:sub-program (fix-fix-overflow)
(:movl :eax :ecx)
(:jns 'fix-fix-negative)
(:shrl ,movitz:+movitz-fixnum-shift+ :ecx)
(:call-local-pf box-u32-ecx)
(:jmp 'fix-fix-ok)
fix-fix-negative
(:jz 'fix-double-negative)
(:negl :ecx)
(:shrl ,movitz:+movitz-fixnum-shift+ :ecx)
(:call-local-pf box-u32-ecx)
(:movl ,(dpb 4 (byte 16 16)
(movitz:tag :bignum #xff))
(:eax ,movitz:+other-type-offset+))
(:jmp 'fix-fix-ok)
fix-double-negative
(:compile-form (:result-mode :eax)
,(* 2 movitz:+movitz-most-negative-fixnum+))
(:jmp 'fix-fix-ok)))
fix-fix-ok))
((positive-bignum positive-fixnum)
(+ y x))
((positive-fixnum positive-bignum)
(bignum-add-fixnum y x))
((positive-bignum negative-fixnum)
(+ y x))
((negative-fixnum positive-bignum)
(with-inline-assembly (:returns :eax :labels (restart-addition
retry-jumper
not-size1
copy-bignum-loop
add-bignum-loop
add-bignum-done
no-expansion
pfix-pbig-done))
(:compile-two-forms (:eax :ebx) y x)
(:movzxw (:eax (:offset movitz-bignum length)) :ecx)
(:cmpl 4 :ecx)
(:jne 'not-size1)
(:compile-form (:result-mode :ecx) x)
(:sarl ,movitz:+movitz-fixnum-shift+ :ecx)
(:addl (:eax (:offset movitz-bignum bigit0)) :ecx)
(:call-local-pf box-u32-ecx)
(:jmp 'pfix-pbig-done)
not-size1
(:declare-label-set retry-jumper (restart-addition))
(:locally (:pushl (:edi (:edi-offset :dynamic-env))))
(:pushl 'retry-jumper)
(:locally (:pushl (:edi (:edi-offset :atomically-continuation))))
(:pushl :ebp)
restart-addition
(:movl (:esp) :ebp)
(:compile-form (:result-mode :eax) y)
(:movzxw (:eax (:offset movitz-bignum length)) :ecx)
(:locally (:movl :esp (:edi (:edi-offset :atomically-continuation))))
(:leal ((:ecx 1) ,(* 1 movitz:+movitz-fixnum-factor+))
(:call-local-pf cons-pointer)
(:movzxw (:ebx (:offset movitz-bignum length)) :ecx)
(:leal ((:ecx 1) ,movitz:+movitz-fixnum-factor+)
:edx)
copy-bignum-loop
(:subl ,movitz:+movitz-fixnum-factor+ :edx)
(:movl (:ebx :edx ,movitz:+other-type-offset+) :ecx)
(:movl :ecx (:eax :edx ,movitz:+other-type-offset+))
(:jnz 'copy-bignum-loop)
(:load-lexical (:lexical-binding x) :ecx)
(:sarl ,movitz:+movitz-fixnum-shift+ :ecx)
(:negl :ecx)
(:subl :ecx (:eax (:offset movitz-bignum bigit0)))
(:jnc 'add-bignum-done)
add-bignum-loop
(:addl 4 :ebx)
(:subl 1 (:eax :ebx (:offset movitz-bignum bigit0)))
(:jc 'add-bignum-loop)
add-bignum-done
(:movzxw (:eax (:offset movitz-bignum length))
:ecx)
(:leal ((:ecx 1) ,movitz:+movitz-fixnum-factor+)
(:cmpl 0 (:eax :ecx (:offset movitz-bignum bigit0 -8)))
(:jne 'no-expansion)
(:subl #x40000 (:eax ,movitz:+other-type-offset+))
(:subl ,movitz:+movitz-fixnum-factor+ :ecx)
no-expansion
(:call-local-pf cons-commit-non-pointer)
(:locally (:movl 0 (:edi (:edi-offset atomically-continuation))))
(:leal (:esp 16) :esp)
pfix-pbig-done))
((positive-bignum positive-bignum)
(if (< (%bignum-bigits y) (%bignum-bigits x))
(+ y x)
(with-inline-assembly (:returns :eax :labels (restart-addition
retry-jumper
not-size1
copy-bignum-loop
add-bignum-loop
add-bignum-done
no-expansion
pfix-pbig-done
zero-padding-loop))
(:compile-two-forms (:eax :ebx) y x)
(:testl :ebx :ebx)
(:jz 'pfix-pbig-done)
(:movzxw (:eax (:offset movitz-bignum length)) :ecx)
(:cmpl ,movitz:+movitz-fixnum-factor+ :ecx)
(:jne 'not-size1)
(:movl (:ebx (:offset movitz-bignum bigit0)) :ecx)
(:addl (:eax (:offset movitz-bignum bigit0)) :ecx)
(:jc 'not-size1)
(:call-local-pf box-u32-ecx)
(:jmp 'pfix-pbig-done)
not-size1
(:declare-label-set restart-jumper (restart-addition))
(:locally (:pushl (:edi (:edi-offset :dynamic-env))))
(:pushl 'restart-jumper)
(:locally (:pushl (:edi (:edi-offset :atomically-continuation))))
(:pushl :ebp)
restart-addition
(:movl (:esp) :ebp)
(:compile-form (:result-mode :eax) y)
(:movzxw (:eax (:offset movitz-bignum length)) :ecx)
(:leal ((:ecx 1) ,(* 2 movitz:+movitz-fixnum-factor+))
(:locally (:movl :esp (:edi (:edi-offset :atomically-continuation))))
(:call-local-pf cons-non-pointer)
(:movzxw (:ebx (:offset movitz-bignum length)) :ecx)
(:leal ((:ecx 1) ,movitz:+movitz-fixnum-factor+)
:edx)
MSB
copy-bignum-loop
(:subl ,movitz:+movitz-fixnum-factor+ :edx)
(:movl (:ebx :edx ,movitz:+other-type-offset+) :ecx)
(:movl :ecx (:eax :edx ,movitz:+other-type-offset+))
(:jnz 'copy-bignum-loop)
(:load-lexical (:lexical-binding x) :ebx)
add-bignum-loop
(:cmpw :dx (:ebx (:offset movitz-bignum length)))
(:jbe '(:sub-program (zero-padding-loop)
(:addl :ecx (:eax :edx (:offset movitz-bignum
bigit0)))
(:sbbl :ecx :ecx)
ECX = Add 's Carry .
(:addl 4 :edx)
(:cmpw :dx (:eax (:offset movitz-bignum length)))
(:jae 'zero-padding-loop)
(:jmp 'add-bignum-done)))
(:addl (:ebx :edx (:offset movitz-bignum bigit0))
:ecx)
(:jc '(:sub-program (term1-carry)
The digit + carry carried over , ECX = 0
(:addl 1 :ecx)
(:addl 4 :edx)
(:cmpw :dx (:eax (:offset movitz-bignum length)))
(:jae 'add-bignum-loop)
(:jmp 'add-bignum-done)))
(:addl :ecx (:eax :edx (:offset movitz-bignum bigit0)))
(:sbbl :ecx :ecx)
ECX = Add 's Carry .
(:addl 4 :edx)
(:cmpw :dx (:eax (:offset movitz-bignum length)))
(:jae 'add-bignum-loop)
add-bignum-done
(:movzxw (:eax (:offset movitz-bignum length))
:ecx)
(:leal ((:ecx 1) ,movitz:+movitz-fixnum-factor+)
:ecx)
(:cmpl 0 (:eax :ecx (:offset movitz-bignum bigit0 -4)))
(:je 'no-expansion)
(:addl #x40000 (:eax ,movitz:+other-type-offset+))
(:addl ,movitz:+movitz-fixnum-factor+ :ecx)
no-expansion
(:call-local-pf cons-commit-non-pointer)
(:locally (:movl 0 (:edi (:edi-offset atomically-continuation))))
(:leal (:esp 16) :esp)
pfix-pbig-done)
))
(((integer * -1) (integer 0 *))
(- y (- x)))
(((integer 0 *) (integer * -1))
(- x (- y)))
(((integer * -1) (integer * -1))
(%negatef (+ (- x) (- y)) x y))
((rational rational)
(/ (+ (* (numerator x) (denominator y))
(* (numerator y) (denominator x)))
(* (denominator x) (denominator y))))
)))
(do-it)))
(t (&rest terms)
(declare (dynamic-extent terms))
(if (null terms)
0
(reduce #'+ terms)))))
(defun 1+ (number)
(+ 1 number))
(defun 1- (number)
(+ -1 number))
(defun - (minuend &rest subtrahends)
(declare (dynamic-extent subtrahends))
(numargs-case
(1 (x)
(etypecase x
(fixnum
(macrolet
((do-it ()
`(with-inline-assembly (:returns :eax)
(:compile-form (:result-mode :eax) x)
(:negl :eax)
(:jo '(:sub-program (fix-overflow)
(:compile-form (:result-mode :eax)
,(1+ movitz:+movitz-most-positive-fixnum+))
(:jmp 'fix-ok)))
fix-ok)))
(do-it)))
(bignum
(%bignum-negate (copy-bignum x)))
(ratio
(make-ratio (- (ratio-numerator x)) (ratio-denominator x)))))
(2 (minuend subtrahend)
(macrolet
((do-it ()
`(number-double-dispatch (minuend subtrahend)
((number (eql 0))
minuend)
(((eql 0) t)
(- subtrahend))
((fixnum fixnum)
(with-inline-assembly (:returns :eax :labels (done negative-result))
(:compile-two-forms (:eax :ebx) minuend subtrahend)
(:subl :ebx :eax)
(:jno 'done)
(:jnc 'negative-result)
(:movl :eax :ecx)
(:shrl ,movitz:+movitz-fixnum-shift+ :ecx)
(:orl ,(- movitz:+movitz-most-negative-fixnum+) :ecx)
(:call-local-pf box-u32-ecx)
(:jmp 'done)
negative-result
(:movl :eax :ecx)
(:negl :ecx)
(:shrl ,movitz:+movitz-fixnum-shift+ :ecx)
(:call-local-pf box-u32-ecx)
(:xorl #xff00 (:eax (:offset movitz-bignum type)))
done))
((positive-bignum fixnum)
(+ (- subtrahend) minuend))
((fixnum positive-bignum)
(%negatef (+ subtrahend (- minuend))
subtrahend minuend))
((positive-bignum positive-bignum)
(cond
((= minuend subtrahend)
0)
((< minuend subtrahend)
(let ((x (- subtrahend minuend)))
(%negatef x subtrahend minuend)))
(t (bignum-canonicalize
(with-inline-assembly (:returns :eax)
(:compile-two-forms (:eax :ebx) (copy-bignum minuend) subtrahend)
sub-loop
(:addl (:ebx :edx (:offset movitz-bignum bigit0))
:ecx)
(:jc '(:sub-program (carry-overflow)
(:addl 1 :ecx)
(:addl 4 :edx)
(:cmpw :dx (:ebx (:offset movitz-bignum length)))
(:jne 'sub-loop)
(:jmp 'bignum-sub-done)))
(:subl :ecx (:eax :edx (:offset movitz-bignum bigit0)))
(:sbbl :ecx :ecx)
(:negl :ecx)
(:addl 4 :edx)
(:cmpw :dx (:ebx (:offset movitz-bignum length)))
(:jne 'sub-loop)
(:subl :ecx (:eax :edx (:offset movitz-bignum bigit0)))
(:jnc 'bignum-sub-done)
propagate-carry
(:addl 4 :edx)
(:subl 1 (:eax :edx (:offset movitz-bignum bigit0)))
(:jc 'propagate-carry)
bignum-sub-done
)))))
(((integer 0 *) (integer * -1))
(+ minuend (- subtrahend)))
(((integer * -1) (integer 0 *))
(%negatef (+ (- minuend) subtrahend) minuend subtrahend))
(((integer * -1) (integer * -1))
(+ minuend (- subtrahend)))
((rational rational)
(/ (- (* (numerator minuend) (denominator subtrahend))
(* (numerator subtrahend) (denominator minuend)))
(* (denominator minuend) (denominator subtrahend))))
)))
(do-it)))
(t (minuend &rest subtrahends)
(declare (dynamic-extent subtrahends))
(if subtrahends
(reduce #'- subtrahends :initial-value minuend)
(- minuend)))))
(defun zerop (number)
(= 0 number))
(defun plusp (number)
(> number 0))
(defun minusp (number)
(< number 0))
(defun abs (x)
(compiler-macro-call abs x))
(defun signum (x)
(cond
((> x 0) 1)
((< x 0) -1)
(t 0)))
(defun max (number1 &rest numbers)
(numargs-case
(2 (x y)
(compiler-macro-call max x y))
(t (number1 &rest numbers)
(declare (dynamic-extent numbers))
(let ((max number1))
(dolist (x numbers max)
(when (> x max)
(setq max x)))))))
(defun min (number1 &rest numbers)
(numargs-case
(2 (x y)
(compiler-macro-call min x y))
(t (number1 &rest numbers)
(declare (dynamic-extent numbers))
(let ((min number1))
(dolist (x numbers min)
(when (< x min)
(setq min x)))))))
(defun ash (integer count)
(cond
((= 0 count)
integer)
((= 0 integer) 0)
((typep count '(integer 0 *))
(let ((result-length (+ (integer-length (if (minusp integer) (1- integer) integer))
count)))
(cond
((<= result-length 29)
(with-inline-assembly (:returns :eax)
(:compile-two-forms (:eax :ecx) integer count)
(:shrl #.movitz:+movitz-fixnum-shift+ :ecx)
(:shll :cl :eax)))
((typep integer 'positive-fixnum)
(let ((result (%make-bignum (ceiling result-length 32) 0)))
(setf (memref result (movitz-type-slot-offset 'movitz-bignum 'bigit0)
:type :unsigned-byte32)
integer)
(bignum-shift-leftf result count)))
((typep integer 'positive-bignum)
(let ((result (%make-bignum (ceiling result-length 32))))
(dotimes (i (* 2 (%bignum-bigits result)))
(setf (memref result -2 :index i :type :unsigned-byte16)
(let ((pos (- (* i 16) count)))
(cond
((minusp (+ pos 16)) 0)
((<= 0 pos)
(ldb (byte 16 pos) integer))
(t (ash (ldb (byte (+ pos 16) 0) integer)
(- pos)))))))
(assert (or (plusp (memref result -2
:index (+ -1 (* 2 (%bignum-bigits result)))
:type :unsigned-byte16))
(plusp (memref result -2
:index (+ -2 (* 2 (%bignum-bigits result)))
:type :unsigned-byte16))))
(bignum-canonicalize result)))
((typep integer 'negative-fixnum)
(let ((result (%make-bignum (ceiling result-length 32) 0)))
(setf (memref result (movitz-type-slot-offset 'movitz-bignum 'bigit0)
:type :unsigned-byte32)
(- integer))
(%bignum-negate (bignum-shift-leftf result count))))
((typep integer 'negative-bignum)
(let ((result (%make-bignum (ceiling result-length 32) 0)))
(dotimes (i (%bignum-bigits integer))
(setf (memref result (movitz-type-slot-offset 'movitz-bignum 'bigit0)
:index i :type :unsigned-byte32)
(memref integer (movitz-type-slot-offset 'movitz-bignum 'bigit0)
:index i :type :unsigned-byte32)))
(%bignum-negate (bignum-shift-leftf result count))))
(t (error 'program-error)))))
(t (let ((count (- count)))
(etypecase integer
(fixnum
(with-inline-assembly (:returns :eax :type fixnum)
(:compile-two-forms (:eax :ecx) integer count)
(:shrl #.movitz:+movitz-fixnum-shift+ :ecx)
(:std)
(:sarl :cl :eax)
(:andl -4 :eax)
(:cld)))
(positive-bignum
(let ((result-length (- (integer-length integer) count)))
(cond
((<= result-length 1)
1 or 0 .
(t (multiple-value-bind (long short)
(truncate count 16)
(let ((result (%make-bignum (1+ (ceiling result-length 32)))))
(let ((src-max-bigit (* 2 (%bignum-bigits integer))))
(dotimes (i (* 2 (%bignum-bigits result)))
(declare (index i))
(let ((src (+ i long)))
(setf (memref result -2 :index i :type :unsigned-byte16)
(if (< src src-max-bigit)
(memref integer -2 :index src :type :unsigned-byte16)
0)))))
(bignum-canonicalize
(macrolet
((do-it ()
`(with-inline-assembly (:returns :ebx)
(:compile-two-forms (:ecx :ebx) short result)
We need to use EAX for u32 storage .
(:shrl ,movitz:+movitz-fixnum-shift+ :ecx)
(:std)
shift-short-loop
(:addl 4 :edx)
(:cmpw :dx (:ebx (:offset movitz-bignum length)))
(:jbe 'end-shift-short-loop)
(:movl (:ebx :edx (:offset movitz-bignum bigit0))
:eax)
(:shrdl :cl :eax
(:ebx :edx (:offset movitz-bignum bigit0 -4)))
(:jmp 'shift-short-loop)
end-shift-short-loop
(:shrl :cl (:ebx :edx (:offset movitz-bignum bigit0 -4)))
(:cld))))
(do-it))))))))))))))
(defun integer-length (integer)
"=> number-of-bits"
(etypecase integer
(fixnum
(macrolet
((do-it ()
`(with-inline-assembly (:returns :eax)
(:xorl :eax :eax)
(:compile-form (:result-mode :ecx) integer)
(:testl :ecx :ecx)
(:jns 'not-negative)
(:notl :ecx)
not-negative
(:bsrl :ecx :ecx)
(:jz 'zero)
(:leal ((:ecx ,movitz:+movitz-fixnum-factor+)
,(* -1 movitz:+movitz-fixnum-factor+))
:eax)
zero)))
(do-it)))
(positive-bignum
(macrolet
((do-it ()
`(with-inline-assembly (:returns :eax)
(:compile-form (:result-mode :ebx) integer)
(:movzxw (:ebx (:offset movitz-bignum length))
:edx)
(:xorl :eax :eax)
bigit-scan-loop
(:subl 4 :edx)
(:jc 'done)
(:cmpl 0 (:ebx :edx (:offset movitz-bignum bigit0)))
(:jz 'bigit-scan-loop)
Now , EAX must be loaded with ( + ( * EDX 32 ) bit - index 1 ) .
Factor 8
(:bsrl (:ebx :edx (:offset movitz-bignum bigit0))
:ecx)
Factor 4
(:leal ((:ecx 4) :eax 4) :eax)
done)))
(do-it)))
(negative-bignum
(let ((abs-length (bignum-integer-length integer)))
(if (= 1 (bignum-logcount integer))
(1- abs-length)
abs-length)))))
(defun * (&rest factors)
(numargs-case
(1 (x) x)
(2 (x y)
(macrolet
((do-it ()
`(number-double-dispatch (x y)
((fixnum fixnum)
(let (d0 d1)
(with-inline-assembly (:returns :eax)
(:compile-two-forms (:eax :ecx) x y)
(:sarl ,movitz::+movitz-fixnum-shift+ :ecx)
(:std)
(:imull :ecx :eax :edx)
(:cmpl ,movitz::+movitz-fixnum-factor+ :edx)
(:jc 'u32-result)
(:cmpl #xfffffffc :edx)
(:ja 'u32-negative-result)
(:jne 'two-bigits)
(:testl :eax :eax)
(:jnz 'u32-negative-result)
The result requires 2 ..
two-bigits
(:cld)
(:store-lexical (:lexical-binding d0) :eax :type fixnum)
(:store-lexical (:lexical-binding d1) :edx :type fixnum)
(:compile-form (:result-mode :eax) (%make-bignum 2))
(:movl ,(dpb (* 2 movitz:+movitz-fixnum-factor+)
(byte 16 16) (movitz:tag :bignum 0))
(:eax ,movitz:+other-type-offset+))
(:load-lexical (:lexical-binding d0) :ecx)
(:movl :ecx (:eax (:offset movitz-bignum bigit0)))
(:load-lexical (:lexical-binding d1) :ecx)
(:sarl ,movitz:+movitz-fixnum-shift+
:ecx)
(:shrdl ,movitz:+movitz-fixnum-shift+ :ecx
(:eax (:offset movitz-bignum bigit0)))
(:sarl ,movitz:+movitz-fixnum-shift+
:ecx)
(:movl :ecx (:eax (:offset movitz-bignum bigit0 4)))
(:jns 'fixnum-done)
(:notl (:eax (:offset movitz-bignum bigit0 4)))
(:negl (:eax (:offset movitz-bignum bigit0)))
(:cmc)
(:adcl 0 (:eax (:offset movitz-bignum bigit0 4)))
(:xorl #xff00 (:eax ,movitz:+other-type-offset+))
(:jmp 'fixnum-done)
u32-result
(:movl :eax :ecx)
(:shrdl ,movitz::+movitz-fixnum-shift+ :edx :ecx)
(:movl :edi :edx)
(:cld)
(:call-local-pf box-u32-ecx)
(:jmp 'fixnum-done)
u32-negative-result
(:movl :eax :ecx)
(:shrdl ,movitz::+movitz-fixnum-shift+ :edx :ecx)
(:movl :edi :edx)
(:cld)
(:negl :ecx)
(:call-local-pf box-u32-ecx)
(:xorl #xff00 (:eax ,movitz:+other-type-offset+))
(:jmp 'fixnum-done)
fixnum-result
(:movl :edi :edx)
(:cld)
fixnum-done)))
(((eql 0) t) 0)
(((eql 1) t) y)
(((eql -1) t) (- y))
((t fixnum) (* y x))
((fixnum bignum)
(let (r)
(with-inline-assembly (:returns :eax)
(:declare-label-set restart-jumper (restart-multiplication))
(:locally (:pushl (:edi (:edi-offset :dynamic-env))))
(:pushl 'restart-jumper)
(:locally (:pushl (:edi (:edi-offset :atomically-continuation))))
(:pushl :ebp)
restart-multiplication
(:movl (:esp) :ebp)
(:compile-two-forms (:eax :ebx) (integer-length x) (integer-length y))
Compute ( 1 + ( ceiling ( + ( len x ) ( len y ) ) 32 ) ) ..
(:locally (:movl :esp (:edi (:edi-offset :atomically-continuation))))
(:leal (:eax :ebx ,(* 4 (+ 31 32))) :eax)
(:andl ,(logxor #xffffffff (* 31 4)) :eax)
(:shrl 5 :eax)
New bignum into EAX
(:movl (:ebx ,movitz:+other-type-offset+) :ecx)
(:movl :ecx (:eax ,movitz:+other-type-offset+))
(:store-lexical (:lexical-binding r) :eax :type bignum)
Make EAX , EDX , ESI non - GC - roots .
(:compile-form (:result-mode :ecx) x)
(:sarl ,movitz:+movitz-fixnum-shift+ :ecx)
(:jns 'multiply-loop)
multiply-loop
(:offset movitz-bignum bigit0)))
(:compile-form (:result-mode :ebx) y)
(:movl (:ebx (:esi 1) (:offset movitz-bignum bigit0))
:eax)
(:mull :ecx :eax :edx)
(:compile-form (:result-mode :ebx) r)
(:addl :eax (:ebx :esi (:offset movitz-bignum bigit0)))
(:adcl 0 :edx)
(:addl 4 :esi)
(:cmpw :si (:ebx (:offset movitz-bignum length)))
(:ja 'multiply-loop)
(:testl :edx :edx)
(:jz 'no-carry-expansion)
(:movl :edx (:ebx :esi (:offset movitz-bignum bigit0)))
(:addl 4 :esi)
(:movw :si (:ebx (:offset movitz-bignum length)))
no-carry-expansion
(:leal (:esi ,movitz:+movitz-fixnum-factor+)
Put bignum length into ECX
(:movl (:ebp -4) :esi)
(:movl :ebx :eax)
(:movl :edi :edx)
EAX , EDX , and ESI are GC roots again .
(:call-local-pf cons-commit-non-pointer)
(:locally (:movl 0 (:edi (:edi-offset atomically-continuation))))
(:leal (:esp 16) :esp)
(:compile-form (:result-mode :ebx) x)
(:testl :ebx :ebx)
(:jns 'positive-result)
(:xorl #xff00 (:eax ,movitz:+other-type-offset+))
positive-result
)))
((positive-bignum positive-bignum)
(if (< x y)
(* y x)
#-movitz-reference-code
(do ((tmp (%make-bignum (ceiling (+ (integer-length x)
(integer-length y))
32)))
(r (bignum-set-zerof (%make-bignum (ceiling (+ (integer-length x)
(integer-length y))
32))))
(length (integer-length y))
(i 0 (+ i 29)))
((>= i length) (bignum-canonicalize r))
(bignum-set-zerof tmp)
(bignum-addf r (bignum-shift-leftf (bignum-mulf (bignum-addf tmp x)
(ldb (byte 29 i) y))
i)))
#+movitz-reference-code
(do ((r 0)
(length (integer-length y))
(i 0 (+ i 29)))
((>= i length) r)
(incf r (ash (* x (ldb (byte 29 i) y)) i)))))
((ratio ratio)
(make-rational (* (ratio-numerator x) (ratio-numerator y))
(* (ratio-denominator x) (ratio-denominator y))))
((ratio t)
(make-rational (* y (ratio-numerator x))
(ratio-denominator x)))
((t ratio)
(make-rational (* x (ratio-numerator y))
(ratio-denominator y)))
((t (integer * -1))
(%negatef (* x (- y)) x y))
(((integer * -1) t)
(%negatef (* (- x) y) x y))
(((integer * -1) (integer * -1))
(* (- x) (- y))))))
(do-it)))
(t (&rest factors)
(declare (dynamic-extent factors))
(if (null factors)
1
(reduce '* factors)))))
Division
(defun truncate (number &optional (divisor 1))
(numargs-case
(1 (number)
(if (not (typep number 'ratio))
(values number 0)
(multiple-value-bind (q r)
(truncate (%ratio-numerator number)
(%ratio-denominator number))
(values q (make-rational r (%ratio-denominator number))))))
(t (number divisor)
(number-double-dispatch (number divisor)
((t (eql 1))
(if (not (typep number 'ratio))
(values number 0)
(multiple-value-bind (q r)
(truncate (%ratio-numerator number)
(%ratio-denominator number))
(values q (make-rational r (%ratio-denominator number))))))
((fixnum fixnum)
(with-inline-assembly (:returns :multiple-values)
(:compile-form (:result-mode :eax) number)
(:compile-form (:result-mode :ebx) divisor)
(:std)
(:cdq :eax :edx)
(:idivl :ebx :eax :edx)
(:shll #.movitz::+movitz-fixnum-shift+ :eax)
(:cld)
(:movl :edx :ebx)
(:xorl :ecx :ecx)
(:stc)))
((positive-fixnum positive-bignum)
(values 0 number))
((positive-bignum positive-fixnum)
(macrolet
((do-it ()
`(let (r n)
(with-inline-assembly (:returns :multiple-values)
(:compile-form (:result-mode :ebx) number)
(:cmpw ,movitz:+movitz-fixnum-factor+
(:ebx (:offset movitz-bignum length)))
(:jne 'not-size1)
(:compile-form (:result-mode :ecx) divisor)
(:shrl ,movitz:+movitz-fixnum-shift+ :ecx)
(:std)
(:movl (:ebx (:offset movitz-bignum bigit0)) :eax)
(:xorl :edx :edx)
(:divl :ecx :eax :edx)
(:movl :eax :ecx)
(:shll ,movitz:+movitz-fixnum-shift+ :edx)
(:movl :edi :eax)
(:cld)
(:pushl :edx)
(:call-local-pf box-u32-ecx)
(:popl :ebx)
(:jmp 'done)
not-size1
(:declare-label-set restart-jumper (restart-truncation))
(:locally (:pushl (:edi (:edi-offset :dynamic-env))))
(:pushl 'restart-jumper)
(:locally (:pushl (:edi (:edi-offset :atomically-continuation))))
(:pushl :ebp)
restart-truncation
(:movl (:esp) :ebp)
(:xorl :eax :eax)
(:compile-form (:result-mode :ebx) number)
(:movw (:ebx (:offset movitz-bignum length)) :ax)
(:addl 4 :eax)
(:locally (:movl :esp (:edi (:edi-offset :atomically-continuation))))
New bignum into EAX
XXX breaks GC invariant !
(:compile-form (:result-mode :ebx) number)
(:movl (:ebx ,movitz:+other-type-offset+) :ecx)
(:movl :ecx (:eax ,movitz:+other-type-offset+))
(:shrl 16 :ecx)
(:testb 3 :cl)
(:jnz '(:sub-program () (:int 63)))
(:movl :ecx :esi)
(:compile-form (:result-mode :ecx) divisor)
(:shrl ,movitz:+movitz-fixnum-shift+ :ecx)
(:std)
divide-loop
(:load-lexical (:lexical-binding number) :ebx)
(:movl (:ebx :esi (:offset movitz-bignum bigit0 -4))
:eax)
(:divl :ecx :eax :edx)
(:load-lexical (:lexical-binding r) :ebx)
(:movl :eax (:ebx :esi (:offset movitz-bignum bigit0 -4)))
(:subl 4 :esi)
(:jnz 'divide-loop)
(:leal ((:edx ,movitz:+movitz-fixnum-factor+)) :edx)
(:cld)
(:movl (:ebp -4) :esi)
(:movl :ebx :eax)
(:movl :edx :ebx)
(:movzxw (:eax (:offset movitz-bignum length))
:ecx)
(:leal ((:ecx 1) ,movitz:+movitz-fixnum-factor+)
:ecx)
(:cmpl 0 (:eax :ecx (:offset movitz-bignum bigit0 -8)))
(:jne 'no-more-shrinkage)
(:subw 4 (:eax (:offset movitz-bignum length)))
(:subl ,movitz:+movitz-fixnum-factor+ :ecx)
(:cmpl ,(* 2 movitz:+movitz-fixnum-factor+) :ecx)
(:jne 'no-more-shrinkage)
(:cmpl ,movitz:+movitz-most-positive-fixnum+
(:eax (:offset movitz-bignum bigit0)))
(:jnc 'no-more-shrinkage)
(:movl (:eax (:offset movitz-bignum bigit0))
:ecx)
(:leal ((:ecx ,movitz:+movitz-fixnum-factor+)) :eax)
no-more-shrinkage
(:call-local-pf cons-commit-non-pointer)
fixnum-result
Exit atomically block .
(:locally (:movl 0 (:edi (:edi-offset atomically-continuation))))
(:leal (:esp 16) :esp)
done
(:movl 2 :ecx)
(:stc)))))
(do-it)))
((positive-bignum positive-bignum)
(cond
((= number divisor) (values 1 0))
((< number divisor) (values 0 number))
(t
#-movitz-reference-code
(let* ((divisor-length (integer-length divisor))
(guess-pos (- divisor-length 29))
(msb (ldb (byte 29 guess-pos) divisor)))
(when (eq msb most-positive-fixnum)
(incf guess-pos)
(setf msb (ash msb -1)))
(incf msb)
(do ((tmp (copy-bignum number))
(tmp2 (copy-bignum number))
(q (bignum-set-zerof (%make-bignum (ceiling (1+ (- (integer-length number)
divisor-length))
32))))
(r (copy-bignum number)))
((%bignum< r divisor)
(values (bignum-canonicalize q)
(bignum-canonicalize r)))
(let ((guess (bignum-shift-rightf
(bignum-truncatef (bignum-addf (bignum-set-zerof tmp)
r)
msb)
guess-pos)))
(if (%bignum-zerop guess)
(setf q (bignum-addf-fixnum q 1)
r (bignum-subf r divisor))
(setf q (bignum-addf q guess)
r (do ((i 0 (+ i 29)))
((>= i divisor-length) r)
(bignum-subf r (bignum-shift-leftf
(bignum-mulf (bignum-addf (bignum-set-zerof tmp2) guess)
(ldb (byte 29 i) divisor))
i))))))))
#+movitz-reference-code
(let* ((guess-pos (- (integer-length divisor) 29))
(msb (ldb (byte 29 guess-pos) divisor)))
(when (eq msb most-positive-fixnum)
(incf guess-pos)
(setf msb (ash msb -1)))
(incf msb)
(do ((shift (- guess-pos))
(q 0)
(r number))
((< r divisor)
(values q r))
(let ((guess (ash (truncate r msb) shift)))
(if (= 0 guess)
(setf q (1+ q)
r (- r divisor))
(setf q (+ q guess)
r (- r (* guess divisor))))))))))
(((integer * -1) (integer 0 *))
(multiple-value-bind (q r)
(truncate (- number) divisor)
(values (%negatef q number divisor)
(%negatef r number divisor))))
(((integer 0 *) (integer * -1))
(multiple-value-bind (q r)
(truncate number (- divisor))
(values (%negatef q number divisor)
r)))
(((integer * -1) (integer * -1))
(multiple-value-bind (q r)
(truncate (- number) (- divisor))
(values q (%negatef r number divisor))))
((rational rational)
(multiple-value-bind (q r)
(truncate (* (numerator number)
(denominator divisor))
(* (denominator number)
(numerator divisor)))
(values q (make-rational r (* (denominator number)
(denominator divisor))))))
))))
(defun / (number &rest denominators)
(numargs-case
(1 (x)
(if (not (typep x 'ratio))
(make-rational 1 x)
(make-rational (%ratio-denominator x)
(%ratio-numerator x))))
(2 (x y)
(multiple-value-bind (q r)
(truncate x y)
(cond
((= 0 r)
q)
(t (make-rational (* (numerator x) (denominator y))
(* (denominator x) (numerator y)))))))
(t (number &rest denominators)
(declare (dynamic-extent denominators))
(cond
((null denominators)
(make-rational 1 number))
((null (cdr denominators))
(multiple-value-bind (q r)
(truncate number (first denominators))
(if (= 0 r)
q
(make-rational number (first denominators)))))
(t (/ number (reduce '* denominators)))))))
(defun round (number &optional (divisor 1))
"Mathematical rounding."
(multiple-value-bind (quotient remainder)
(truncate number divisor)
(let ((rem2 (* 2 remainder)))
(case (+ (if (minusp number) #b10 0)
(if (minusp divisor) #b01 0))
(#b00 (cond
((= divisor rem2)
(if (evenp quotient)
(values quotient remainder)
(values (1+ quotient) (- remainder divisor))))
((< rem2 divisor)
(values quotient remainder))
(t (values (1+ quotient) (- remainder divisor)))))
(#b11 (cond
((= divisor rem2)
(if (evenp quotient)
(values quotient remainder)
(values (1+ quotient) (- remainder divisor))))
((> rem2 divisor)
(values quotient remainder))
(t (values (1+ quotient) (- remainder divisor)))))
(#b10 (cond
((= (- divisor) rem2)
(if (evenp quotient)
(values quotient remainder)
(values (1- quotient) (- remainder))))
((< rem2 divisor)
(values quotient remainder))
(t (values (1+ quotient) (- remainder divisor)))))
(#b01 (cond
((= (- divisor) rem2)
(if (evenp quotient)
(values quotient remainder)
(values (1- quotient) (- remainder))))
((> rem2 divisor)
(values quotient remainder))
(t (values (1- quotient) (- remainder)))))))))
(defun ceiling (number &optional (divisor 1))
(case (+ (if (minusp number) #b10 0)
(if (minusp divisor) #b01 0))
(#b00 (multiple-value-bind (q r)
(truncate (+ number divisor -1) divisor)
(values q (- r (1- divisor)))))
(t (error "Don't know."))))
(defun rem (dividend divisor)
(nth-value 1 (truncate dividend divisor)))
(defun mod (number divisor)
"Returns second result of FLOOR."
(let ((rem (rem number divisor)))
(if (and (not (zerop rem))
(if (minusp divisor)
(plusp number)
(minusp number)))
(+ rem divisor)
rem)))
(defun byte (size position)
(check-type size positive-fixnum)
(let ((position (check-the (unsigned-byte 20) position)))
(+ position (ash size 20))))
(defun byte-size (bytespec)
(ash bytespec -20))
(defun byte-position (bytespec)
(ldb (byte 20 0) bytespec))
(defun logbitp (index integer)
(check-type index positive-fixnum)
(macrolet
((do-it ()
`(etypecase integer
(fixnum
(with-inline-assembly (:returns :boolean-cf=1)
(:compile-two-forms (:ecx :ebx) index integer)
(:shrl ,movitz::+movitz-fixnum-shift+ :ecx)
(:addl ,movitz::+movitz-fixnum-shift+ :ecx)
(:btl :ecx :ebx)))
(positive-bignum
(with-inline-assembly (:returns :boolean-cf=1)
(:compile-two-forms (:ecx :ebx) index integer)
(:shrl ,movitz::+movitz-fixnum-shift+ :ecx)
(:btl :ecx (:ebx (:offset movitz-bignum bigit0))))))))
(do-it)))
(define-compiler-macro logbitp (&whole form &environment env index integer)
(if (not (movitz:movitz-constantp index env))
form
(let ((index (movitz:movitz-eval index env)))
(check-type index (integer 0 *))
(typecase index
((integer 0 31)
`(with-inline-assembly (:returns :boolean-cf=1)
(:compile-form (:result-mode :untagged-fixnum-ecx) ,integer)
(:btl ,index :ecx)))
(t form)))))
(defun logand (&rest integers)
(numargs-case
(1 (x) x)
(2 (x y)
(macrolet
((do-it ()
`(number-double-dispatch (x y)
((fixnum fixnum)
(with-inline-assembly (:returns :eax)
(:compile-two-forms (:eax :ebx) x y)
(:andl :ebx :eax)))
((positive-bignum positive-fixnum)
(with-inline-assembly (:returns :eax)
(:compile-form (:result-mode :eax) x)
(:call-global-pf unbox-u32)
(:compile-form (:result-mode :eax) y)
(:leal ((:ecx ,movitz:+movitz-fixnum-factor+)) :ecx)
(:andl :ecx :eax)))
((positive-fixnum positive-bignum)
(with-inline-assembly (:returns :eax)
(:compile-form (:result-mode :eax) y)
(:call-global-pf unbox-u32)
(:compile-form (:result-mode :eax) x)
(:leal ((:ecx ,movitz:+movitz-fixnum-factor+)) :ecx)
(:andl :ecx :eax)))
((fixnum positive-bignum)
(let ((result (copy-bignum y)))
(with-inline-assembly (:returns :eax)
(:compile-two-forms (:eax :untagged-fixnum-ecx) result x)
(:andl :ecx (:eax (:offset movitz-bignum bigit0))))))
((positive-bignum fixnum)
(let ((result (copy-bignum x)))
(with-inline-assembly (:returns :eax)
(:compile-two-forms (:eax :untagged-fixnum-ecx) result y)
(:andl :ecx (:eax (:offset movitz-bignum bigit0))))))
((positive-bignum positive-bignum)
(if (< (%bignum-bigits y) (%bignum-bigits x))
(logand y x)
(bignum-canonicalize
(with-inline-assembly (:returns :eax)
(:compile-two-forms (:eax :ebx) (copy-bignum x) y)
(:movzxw (:eax (:offset movitz-bignum length))
:ecx)
(:leal ((:ecx 1) -4) :edx)
pb-pb-and-loop
(:movl (:ebx :edx (:offset movitz-bignum bigit0))
:ecx)
(:andl :ecx
(:eax :edx (:offset movitz-bignum bigit0)))
(:subl 4 :edx)
(:jnc 'pb-pb-and-loop)))))
((negative-bignum fixnum)
(with-inline-assembly (:returns :eax)
(:load-lexical (:lexical-binding x) :untagged-fixnum-ecx)
(:load-lexical (:lexical-binding y) :eax)
(:leal ((:ecx 4) -4) :ecx)
(:notl :ecx)
(:andl :ecx :eax)))
((negative-bignum positive-bignum)
(cond
((<= (%bignum-bigits y) (%bignum-bigits x))
(let ((r (copy-bignum y)))
(with-inline-assembly (:returns :eax)
(:load-lexical (:lexical-binding r) :eax)
(:load-lexical (:lexical-binding x) :ebx)
(:xorl :edx :edx)
(:movl #xffffffff :ecx)
loop
(:addl (:ebx :edx (:offset movitz-bignum bigit0))
:ecx)
(:notl :ecx)
(:andl :ecx (:eax :edx (:offset movitz-bignum bigit0)))
(:notl :ecx)
(:cmpl -1 :ecx)
(:je 'carry)
(:xorl :ecx :ecx)
carry
(:addl 4 :edx)
(:cmpw :dx (:eax (:offset movitz-bignum length)))
(:ja 'loop))))
(t (error "Logand not implemented."))))
)))
(do-it)))
(t (&rest integers)
(declare (dynamic-extent integers))
(if (null integers)
-1
(reduce #'logand integers)))))
(defun logandc1 (integer1 integer2)
(macrolet
((do-it ()
`(number-double-dispatch (integer1 integer2)
((t positive-fixnum)
(with-inline-assembly (:returns :eax :type fixnum)
(:compile-form (:result-mode :eax) integer1)
(:call-global-pf unbox-u32)
(:shll ,movitz:+movitz-fixnum-shift+ :ecx)
(:compile-form (:result-mode :eax) integer2)
(:notl :ecx)
(:andl :ecx :eax)))
(((eql 0) t) integer2)
(((eql -1) t) 0)
((positive-fixnum positive-bignum)
(bignum-canonicalize
(with-inline-assembly (:returns :eax)
(:compile-two-forms (:eax :ecx) (copy-bignum integer2) integer1)
(:shrl ,movitz:+movitz-fixnum-shift+ :ecx)
(:notl :ecx)
(:andl :ecx (:eax (:offset movitz-bignum bigit0))))))
((positive-bignum positive-bignum)
(bignum-canonicalize
(with-inline-assembly (:returns :eax)
(:compile-two-forms (:eax :ebx) (copy-bignum integer2) integer1)
(:movzxw (:eax (:offset movitz-bignum length))
:ecx)
(:leal ((:ecx 1) -4) :edx)
pb-pb-andc1-loop
(:movl (:ebx :edx (:offset movitz-bignum bigit0))
:ecx)
(:notl :ecx)
(:andl :ecx (:eax :edx (:offset movitz-bignum bigit0)))
(:subl 4 :edx)
(:jnc 'pb-pb-andc1-loop)))))))
(do-it)))
(defun logandc2 (integer1 integer2)
(logandc1 integer2 integer1))
(defun logior (&rest integers)
(numargs-case
(1 (x) x)
(2 (x y)
(number-double-dispatch (x y)
((fixnum fixnum)
(with-inline-assembly (:returns :eax)
(:compile-two-forms (:eax :ebx) x y)
(:orl :ebx :eax)))
((positive-fixnum positive-bignum)
(macrolet
((do-it ()
`(let ((r (copy-bignum y)))
(with-inline-assembly (:returns :eax)
(:compile-two-forms (:eax :ecx) r x)
(:shrl ,movitz:+movitz-fixnum-shift+ :ecx)
(:orl :ecx (:eax (:offset movitz-bignum bigit0)))))))
(do-it)))
((positive-bignum positive-fixnum)
(macrolet
((do-it ()
`(let ((r (copy-bignum x)))
(with-inline-assembly (:returns :eax)
(:compile-two-forms (:eax :ecx) r y)
(:shrl ,movitz:+movitz-fixnum-shift+ :ecx)
(:orl :ecx (:eax (:offset movitz-bignum bigit0)))))))
(do-it)))
((positive-bignum positive-bignum)
(if (< (%bignum-bigits x) (%bignum-bigits y))
(logior y x)
(let ((r (copy-bignum x)))
(macrolet
((do-it ()
`(with-inline-assembly (:returns :eax)
(:compile-two-forms (:eax :ebx) r y)
(:movzxw (:ebx (:offset movitz-bignum length))
:ecx)
(:leal ((:ecx 1) ,(* -1 movitz:+movitz-fixnum-factor+))
EDX is loop counter
or-loop
(:movl (:ebx :edx (:offset movitz-bignum bigit0))
:ecx)
(:orl :ecx
(:eax :edx (:offset movitz-bignum bigit0)))
(:subl 4 :edx)
(:jnc 'or-loop))))
(do-it)))))))
(t (&rest integers)
(declare (dynamic-extent integers))
(if (null integers)
0
(reduce #'logior integers)))))
(defun logxor (&rest integers)
(numargs-case
(1 (x) x)
(2 (x y)
(number-double-dispatch (x y)
((fixnum fixnum)
(with-inline-assembly (:returns :eax)
(:compile-two-forms (:eax :ebx) x y)
(:xorl :ebx :eax)))
(((eql 0) t) y)
((t (eql 0)) x)
((positive-fixnum positive-bignum)
(macrolet
((do-it ()
`(with-inline-assembly (:returns :eax)
(:compile-two-forms (:eax :ecx) (copy-bignum y) x)
(:shrl ,movitz:+movitz-fixnum-shift+ :ecx)
(:xorl :ecx (:eax (:offset movitz-bignum bigit0))))))
(do-it)))
((positive-bignum positive-fixnum)
(macrolet
((do-it ()
`(with-inline-assembly (:returns :eax)
(:compile-two-forms (:eax :ecx) (copy-bignum x) y)
(:shrl ,movitz:+movitz-fixnum-shift+ :ecx)
(:xorl :ecx (:eax (:offset movitz-bignum bigit0))))))
(do-it)))
((positive-bignum positive-bignum)
(if (< (%bignum-bigits x) (%bignum-bigits y))
(logxor y x)
(let ((r (copy-bignum x)))
(macrolet
((do-it ()
`(bignum-canonicalize
(with-inline-assembly (:returns :eax)
(:compile-two-forms (:eax :ebx) r y)
(:movzxw (:ebx (:offset movitz-bignum length))
:ecx)
(:leal ((:ecx 1),(* -1 movitz:+movitz-fixnum-factor+))
EDX is loop counter
xor-loop
(:movl (:ebx :edx (:offset movitz-bignum bigit0))
:ecx)
(:xorl :ecx (:eax :edx (:offset movitz-bignum bigit0)))
(:subl 4 :edx)
(:jnc 'xor-loop)
))))
(do-it)))))))
(t (&rest integers)
(declare (dynamic-extent integers))
(if (null integers)
0
(reduce #'logxor integers)))))
(defun lognot (integer)
(- -1 integer))
(defun ldb%byte (size position integer)
"This is LDB with explicit byte-size and position parameters."
(check-type size positive-fixnum)
(check-type position positive-fixnum)
(etypecase integer
(fixnum
(macrolet
((do-it ()
`(with-inline-assembly (:returns :eax)
(:compile-two-forms (:eax :ecx) integer position)
(:cmpl ,(* (1- movitz:+movitz-fixnum-bits+) movitz:+movitz-fixnum-factor+)
:ecx)
(:ja '(:sub-program (outside-fixnum)
(:sbbl :ecx :ecx)
(:leal ((:ecx ,movitz:+movitz-fixnum-factor+)) :eax)
(:jmp 'mask-fixnum)))
(:shrl ,movitz:+movitz-fixnum-shift+ :ecx)
(:andl ,(logxor #xffffffff movitz:+movitz-fixnum-zmask+) :eax)
mask-fixnum
(:compile-form (:result-mode :ecx) size)
(:cmpl ,(* (1- movitz:+movitz-fixnum-bits+) movitz:+movitz-fixnum-factor+)
:ecx)
(:jna 'fixnum-result)
(:testl :eax :eax)
(:jns 'fixnum-done)
.. filling in 1 - bits since the integer is negative .
(:declare-label-set restart-jumper (restart-ones-expanded-bignum))
(:locally (:pushl (:edi (:edi-offset :dynamic-env))))
(:pushl 'restart-jumper)
(:locally (:pushl (:edi (:edi-offset :atomically-continuation))))
(:pushl :ebp)
restart-ones-expanded-bignum
(:movl (:esp) :ebp)
Calculate word - size from bytespec - size .
(:compile-form (:result-mode :ecx) size)
Add 31
Divide by 32
(:andl ,(- movitz:+movitz-fixnum-factor+) :ecx)
Add 1 for header .
:eax)
(:locally (:movl :esp (:edi (:edi-offset :atomically-continuation))))
(:call-local-pf cons-non-pointer)
(:shll 16 :ecx)
(:orl ,(movitz:tag :bignum 0) :ecx)
(:movl :ecx (:eax ,movitz:+other-type-offset+))
(:shrl 16 :ecx)
(:leal ((:ecx ,movitz:+movitz-fixnum-factor+)
add 1 for header .
:ecx)
(:call-local-pf cons-commit-non-pointer)
(:locally (:movl 0 (:edi (:edi-offset atomically-continuation))))
(:leal (:esp 16) :esp)
Have fresh bignum in EAX , now fill it with ones .
fill-ones-loop
(:movl #xffffffff (:eax :ecx (:offset movitz-bignum bigit0)))
(:addl 4 :ecx)
(:cmpw :cx (:eax (:offset movitz-bignum length)))
(:jne 'fill-ones-loop)
(:sarl ,movitz:+movitz-fixnum-shift+ :ecx)
(:movl :ecx (:eax (:offset movitz-bignum bigit0)))
(:movl :eax :ebx)
Compute MSB bigit mask in EDX
(:compile-form (:result-mode :ecx) size)
(:shrl ,movitz:+movitz-fixnum-shift+ :ecx)
(:xorl :edx :edx)
(:andl 31 :ecx)
(:jz 'fixnum-mask-ok)
(:addl 1 :edx)
(:shll :cl :edx)
fixnum-mask-ok
(:subl 1 :edx)
(:movzxw (:ebx (:offset movitz-bignum length))
:ecx)
And EDX with the MSB bigit .
(:ebx :ecx (:offset movitz-bignum bigit0 -4)))
(:movl :edi :edx)
(:movl :edi :eax)
(:movl :ebx :eax)
(:jmp 'fixnum-done)
fixnum-result
(:shrl ,movitz:+movitz-fixnum-shift+ :ecx)
generate fixnum mask in EDX
(:shll :cl :edx)
(:subl ,movitz:+movitz-fixnum-factor+ :edx)
(:andl :edx :eax)
(:jmp 'fixnum-done)
fixnum-done
)))
(do-it)))
(positive-bignum
(cond
((= size 0) 0)
((<= size 32)
(macrolet
((do-it ()
`(with-inline-assembly (:returns :eax)
(:compile-form (:result-mode :ebx) integer)
(:compile-form (:result-mode :eax) position)
(:sarl 5 :ecx)
(:andl -4 :ecx)
(:addl 4 :ecx)
(:cmpl ,(* #x4000 movitz:+movitz-fixnum-factor+)
:ecx)
(:jae 'position-outside-integer)
(:cmpw :cx (:ebx (:offset movitz-bignum length)))
(:jc '(:sub-program (position-outside-integer)
(:movsxb (:ebx (:offset movitz-bignum sign)) :ecx)
(:leal ((:ecx ,movitz:+movitz-fixnum-factor+)) :eax)
(:jmp 'done-u32)))
(:std)
(:movl (:ebx :ecx (:offset movitz-bignum bigit0 -4))
:eax)
.. we must zero - extend rather than read top bigit .
(:movl (:ebx :ecx (:offset movitz-bignum bigit0))
Read top bigit into EDX
no-top-bigit
(:testl #xff00 (:ebx ,movitz:+other-type-offset+))
(:jnz '(:sub-program (negative-bignum)
We must negate the ..
(:break)
))
edx-eax-ok
EDX : EAX now holds the number that must be shifted and masked .
(:compile-form (:result-mode :ecx) position)
(:shrl ,movitz:+movitz-fixnum-shift+ :ecx)
Shifted value into EAX
(:compile-form (:result-mode :ecx) size)
Generate a mask in EDX
(:shrl ,movitz:+movitz-fixnum-shift+ :ecx)
(:testl 31 :ecx)
(:jz 'mask-ok-u32)
(:addl 1 :edx)
(:shll :cl :edx)
mask-ok-u32
(:subl 1 :edx)
(:andl :edx :eax)
(:movl :edi :eax)
(:movl :edi :edx)
(:cld)
(:cmpl ,(dpb movitz:+movitz-fixnum-factor+
(byte 16 16) (movitz:tag :bignum 0))
(:ebx ,movitz:+other-type-offset+))
(:jne 'cant-return-same)
(:cmpl :ecx (:ebx (:offset movitz-bignum bigit0)))
(:jne 'cant-return-same)
(:movl :ebx :eax)
(:jmp 'done-u32)
cant-return-same
(:call-local-pf box-u32-ecx)
done-u32
)))
(do-it)))
(t (macrolet
((do-it ()
`(let (new-size)
(with-inline-assembly (:returns :eax)
(:compile-form (:result-mode :ebx) integer)
(:compile-form (:result-mode :ecx) position)
(:cmpl ,(* #x4000 movitz:+movitz-fixnum-factor+)
:ecx)
(:jnc 'position-outside-integer)
(:cmpw :cx (:ebx (:offset movitz-bignum length)))
(:jbe '(:sub-program (position-outside-integer)
(:movsxb (:ebx (:offset movitz-bignum sign)) :ecx)
(:leal ((:ecx ,movitz:+movitz-fixnum-factor+)) :eax)
(:jmp 'done-u32)))
(:compile-two-forms (:edx :ecx) position size)
keep size / fixnum in EAX .
(:addl :edx :ecx)
compute msb bigit index / fixnum in ecx
(:addl 4 :ecx)
(:cmpw :cx (:ebx (:offset movitz-bignum length)))
(:je '(:sub-program (equal-size-maybe-return-same)
Can only return same if ( zerop position ) .
(:jnz 'adjust-size)
(:shrl ,movitz:+movitz-fixnum-shift+ :ecx)
(:andl 31 :ecx)
(:jz 'yes-return-same)
we know EDX=0 , now generate mask in EDX
(:addl 1 :edx)
(:shll :cl :edx)
(:movzxw (:ebx (:offset movitz-bignum length))
:ecx)
(:cmpl :edx (:ebx :ecx (:offset movitz-bignum bigit0 -4)))
yes-return-same
(:jmp 'ldb-done)))
(:jnc 'size-ok)
So , if ( zerop position ) , we can return the bignum as our result .
(:testl :edx :edx)
(:jz '(:sub-program ()
(:jmp 'ldb-done)))
adjust-size
The bytespec is ( partially ) outside source - integer , so we make the
(:movzxw (:ebx (:offset movitz-bignum length))
In case the new size is zero .
(:js '(:sub-program (should-not-happen)
(:break)))
New size was zero , so the result of ldb is zero .
New size into EAX .
size-ok
(:store-lexical (:lexical-binding new-size) :eax :type fixnum)
(:declare-label-set restart-ldb-jumper (restart-ldb))
(:locally (:pushl (:edi (:edi-offset :dynamic-env))))
(:pushl 'restart-ldb-jumper)
(:locally (:pushl (:edi (:edi-offset :atomically-continuation))))
(:pushl :ebp)
restart-ldb
(:movl (:esp) :ebp)
(:load-lexical (:lexical-binding new-size) :eax)
(:locally (:movl :esp (:edi (:edi-offset :atomically-continuation))))
( new ) Size is in EAX .
(:subl ,movitz:+movitz-fixnum-factor+ :eax)
(:andl ,(logxor #xffffffff
(mask-field (byte (+ 5 movitz:+movitz-fixnum-shift+) 0) -1))
:eax)
Divide ( size-1 ) by 32 to get number of bigits-1
Now add 1 for index->size , 1 for header , and 1 for tmp storage before shift .
(:addl ,(* 3 movitz:+movitz-fixnum-factor+) :eax)
(:pushl :eax)
(:call-local-pf cons-non-pointer)
(:popl :ecx)
(:shll 16 :ecx)
(:orl ,(movitz:tag :bignum 0) :ecx)
(:movl :ecx (:eax ,movitz:+other-type-offset+))
(:compile-form (:result-mode :ebx) integer)
(:xchgl :eax :ebx)
now : EAX = old integer , EBX = new result bignum
Edge case : When size(old)=size(new ) , the tail - tmp must be zero .
(:movzxw (:ebx (:offset movitz-bignum length))
Initialize tail - tmp to # xffffffff , meaning copy from source - integer .
(:movl #xffffffff (:ebx :ecx (:offset movitz-bignum bigit0)))
(:cmpw :cx (:eax (:offset movitz-bignum length)))
(:jc '(:sub-program (result-too-big-shouldnt-happen)
(:int 4)))
(:jne 'tail-tmp-ok)
Sizes was equal , so set tail - tmp to zero .
(:movl 0 (:ebx :ecx (:offset movitz-bignum bigit0)))
tail-tmp-ok
(:std)
(:compile-form (:result-mode :ecx) position)
(:leal (:eax (:ecx 4) (:offset movitz-bignum bigit0))
Use EAX as primitive pointer into source
copy-integer
(:movl (:eax) :edx)
(:addl 4 :eax)
(:movl :edx (:ebx :ecx (:offset movitz-bignum bigit0)))
(:addl 4 :ecx)
(:cmpw :cx (:ebx (:offset movitz-bignum length)))
(:jne 'copy-integer)
Copy one more than the length , namely the tmp at the end .
(:movl (:eax) :edx)
(:andl :edx (:ebx :ecx (:offset movitz-bignum bigit0)))
(:compile-form (:result-mode :ecx) position)
(:shrl ,movitz:+movitz-fixnum-shift+ :ecx)
(:andl 31 :ecx)
if ( zerop ( mod position 32 ) ) , no shift needed .
shift-loop
(:movl (:ebx :edx (:offset movitz-bignum bigit0 4))
Now shift bigit , with msbs from eax .
(:ebx :edx (:offset movitz-bignum bigit0)))
(:addl 4 :edx)
(:cmpw :dx (:ebx (:offset movitz-bignum length)))
(:jne 'shift-loop)
shift-done
Now we must mask MSB bigit .
(:movzxw (:ebx (:offset movitz-bignum length))
:edx)
(:load-lexical (:lexical-binding size) :ecx)
(:shrl 5 :ecx)
ECX = index of ( conceptual ) MSB
(:cmpl :ecx :edx)
(:jbe 'mask-done)
(:load-lexical (:lexical-binding size) :ecx)
(:shrl ,movitz:+movitz-fixnum-shift+ :ecx)
(:andl 31 :ecx)
(:jz 'mask-done)
Generate mask in EAX
(:shll :cl :eax)
(:subl 1 :eax)
(:andl :eax (:ebx :edx (:offset movitz-bignum bigit0 -4)))
mask-done
safe EAX
(:cld)
Now we must zero - truncate the result bignum in EBX .
(:movzxw (:ebx (:offset movitz-bignum length))
:ecx)
zero-truncate-loop
(:cmpl 0 (:ebx :ecx (:offset movitz-bignum bigit0 -4)))
(:jne 'zero-truncate-done)
(:subl 4 :ecx)
(:jnz 'zero-truncate-loop)
Zero bigits means the entire result collapsed to zero .
(:xorl :eax :eax)
zero-truncate-done
If result size is 1 , the result might have ..
(:cmpl ,movitz:+movitz-most-positive-fixnum+
(:ebx (:offset movitz-bignum bigit0)))
(:ja 'complete-bignum-allocation)
(:movl (:ebx (:offset movitz-bignum bigit0))
:ecx)
(:leal ((:ecx ,movitz:+movitz-fixnum-factor+)) :eax)
(:jmp 'return-fixnum)
complete-bignum-allocation
(:movw :cx (:ebx (:offset movitz-bignum length)))
(:movl :ebx :eax)
(:leal (:ecx ,movitz:+movitz-fixnum-factor+)
:ecx)
(:call-local-pf cons-commit-non-pointer)
return-fixnum
(:locally (:movl 0 (:edi (:edi-offset atomically-continuation))))
(:leal (:esp 16) :esp)
ldb-done))))
(do-it)))))))
(defun ldb (bytespec integer)
(ldb%byte (byte-size bytespec) (byte-position bytespec) integer))
(defun ldb-test (bytespec integer)
(case (byte-size bytespec)
(0 nil)
(1 (logbitp (byte-position bytespec) integer))
(t (/= 0 (ldb bytespec integer)))))
(defun logtest (integer-1 integer-2)
"=> generalized-boolean"
(not (= 0 (logand integer-1 integer-2))))
(defun logcount (integer)
(etypecase integer
(positive-fixnum
(with-inline-assembly (:returns :untagged-fixnum-ecx :type (integer 0 29))
(:load-lexical (:lexical-binding integer) :eax)
(:xorl :ecx :ecx)
count-loop
(:shll 1 :eax)
(:adcl 0 :ecx)
(:testl :eax :eax)
(:jnz 'count-loop)))
(positive-bignum
(bignum-logcount integer))))
(defun dpb (newbyte bytespec integer)
(logior (if (= 0 newbyte)
0
(mask-field bytespec (ash newbyte (byte-position bytespec))))
(if (= 0 integer)
0
(logandc2 integer (mask-field bytespec -1)))))
(defun mask-field (bytespec integer)
(ash (ldb bytespec integer) (byte-position bytespec)))
(defun deposit-field (newbyte bytespec integer)
(logior (mask-field bytespec newbyte)
(logandc2 integer (mask-field bytespec -1))))
(defun plus-if (x y)
(if (integerp x) (+ x y) x))
(defun minus-if (x y)
(if (integerp x) (- x y) x))
(defun gcd (&rest integers)
(numargs-case
(1 (u) u)
(2 (u v)
Code borrowed from CMUCL .
(cond
((= 0 u) v)
((= 0 v) u)
(t (do ((k 0 (1+ k))
(u (abs u) (truncate u 2))
(v (abs v) (truncate v 2)))
((or (oddp u) (oddp v))
(do ((temp (if (oddp u)
(- v)
(truncate u 2))
(truncate temp 2)))
(nil)
(when (oddp temp)
(if (plusp temp)
(setq u temp)
(setq v (- temp)))
(setq temp (- u v))
(when (zerop temp)
(return (ash u k))))))))))
(t (&rest integers)
(declare (dynamic-extent integers))
(do ((gcd (car integers)
(gcd gcd (car rest)))
(rest (cdr integers) (cdr rest)))
((null rest) gcd)))))
(defun lcm (&rest numbers)
"Returns the least common multiple of one or more integers. LCM of no
arguments is defined to be 1."
(numargs-case
(1 (n)
(abs n))
(2 (n m)
(abs (* (truncate (max n m) (gcd n m)) (min n m))))
(t (&rest numbers)
(declare (dynamic-extent numbers))
(reduce #'lcm numbers))))
(defun floor (n &optional (divisor 1))
"This is floor written in terms of truncate."
(numargs-case
(1 (n)
(if (not (typep n 'ratio))
(values n 0)
(multiple-value-bind (r q)
(floor (%ratio-numerator n) (%ratio-denominator n))
(values r (make-rational q (%ratio-denominator n))))))
(2 (n divisor)
(multiple-value-bind (q r)
(truncate n divisor)
(cond
((= 0 r)
(values q r))
((or (and (minusp r) (plusp divisor))
(and (plusp r) (minusp divisor)))
(values (1- q) (+ r divisor)))
(t (values q r)))))
(t (n &optional (divisor 1))
(floor n divisor))))
(defun isqrt (natural)
"=> natural-root"
(check-type natural (integer 0 *))
(if (= 0 natural)
0
(let ((r 1))
(do ((next-r (truncate (+ r (truncate natural r)) 2)
(truncate (+ r (truncate natural r)) 2)))
((typep (- next-r r) '(integer 0 1))
(let ((r+1 (1+ r)))
(if (<= (* r+1 r+1) natural)
r+1
r)))
(setf r next-r)))))
(defun rootn (x root)
(check-type root (integer 2 *))
(let ((root-1 (1- root))
(r (/ x root)))
(dotimes (i 10 r)
(let ((m (min (integer-length (numerator r))
(integer-length (denominator r)))))
(when (>= m 32)
(setf r (/ (ash (numerator r) (- 24 m))
(ash (denominator r) (- 24 m))))))
#+ignore (format t "~&~D: ~X~%~D: ~F [~D ~D]~%" i r i r
(integer-length (numerator r))
(integer-length (denominator r)))
(setf r (/ (+ (* root-1 r)
(/ x (expt r root-1)))
root)))))
(defun sqrt (x)
(rootn x 2))
(defun expt (base-number power-number)
"Take base-number to the power-number."
(etypecase power-number
(positive-fixnum
(do ((i 0 (1+ i))
(r 1 (* r base-number)))
((>= i power-number) r)
(declare (index i))))
(positive-bignum
(do ((i 0 (1+ i))
(r 1 (* r base-number)))
((>= i power-number) r)))
((number * -1)
(/ (expt base-number (- power-number))))
(ratio
(expt (rootn base-number (denominator power-number))
(numerator power-number)))))
(defun floatp (x)
(declare (ignore x))
nil)
(defun realpart (number)
number)
(defun imagpart (number)
(declare (ignore number))
0)
(defun rational (number)
number)
(defun realp (x)
(typep x 'real))
|
420ea172cc4c15bdf5d196805095eff77def862b7abcc874a57780ea09e564c5 | yuriy-chumak/ol | pick_random_element.scm | ;
(define *path* (cons "tests/rosettacode" *path*))
(import (otus random!))
(define x '("Monday" "Tuesday" "Wednesday" "Thursday" "Friday" "Saturday" "Sunday"))
(print (list-ref x (rand! (length x))))
| null | https://raw.githubusercontent.com/yuriy-chumak/ol/83dd03d311339763682eab02cbe0c1321daa25bc/tests/rosettacode/pick_random_element.scm | scheme | (define *path* (cons "tests/rosettacode" *path*))
(import (otus random!))
(define x '("Monday" "Tuesday" "Wednesday" "Thursday" "Friday" "Saturday" "Sunday"))
(print (list-ref x (rand! (length x))))
| |
7aa254a118f33539d2439fd67a3115cf78f3882b5b5f29d4eb5f49d12f84c5ef | namin/biohacker | timedb.lisp | ;; -*- Mode: Lisp; -*-
's temporal logic implemented in WALTZER
Last edited 1/29/93 , by KDF
Copyright ( c ) 1988 -- 1992 , Northwestern University ,
, Xerox Corporation .
;; All rights reserved.
;;; See the file legal.txt for a paragraph stating scope of permission
;;; and disclaimer of warranty. The above copyright notice and that
;;; paragraph must be included in any separate copy of this file.
(in-package :COMMON-LISP-USER)
(defstruct (timedb (:PREDICATE temporal-database?)
(:PRINT-FUNCTION
(lambda (st str ignore) (declare (ignore ignore))
(format str "<Temporal DB ~A>" (timedb-title st)))))
(title "") ;; String for printing
(debugging nil) ;; Debugging flag
(interval-id 0) ;; Unique ID
(intervals nil) ;; List of intervals
(relations nil) ;; Temporal relationships
(transitivity-table nil) ;; Transitivity table
network) ;; A constraint network
(defstruct (interval (:PREDICATE interval?)
(:PRINT-FUNCTION
(lambda (st str ignore) (declare (ignore ignore))
(format str "I-~A" (interval-name st)))))
name
index ; for ordering them
timedb ; backpointer
relations) ; ((<interval> . <relation-cell>))
(defun interval-order (x y)
(< (interval-index x) (interval-index y)))
(defvar *timedb* nil) ;; Current temporal database
(defvar *trels-file* (concatenate 'string (make-bps-path "relax") "allen.lisp"))
(defun in-timedb (new-one) (setq *timedb* new-one))
(defun with-timedb (timedb &rest forms)
`(let ((*timedb* ,timedb)) ,@ forms))
(defun create-timedb (title &optional
(t-file *trels-file*)
(debugging? nil))
(setq *timedb*
(make-timedb :TITLE title
:NETWORK
(create-network
(format nil "of ~A" title))
:DEBUGGING debugging?))
(load t-file)
*timedb*)
;;; Indexing relationships
(defun lookup-trel (i1 i2 &optional (virtual? nil)
(*timedb* *timedb*))
(let ((old (assoc i2 (interval-relations i1))))
(if old (cdr old)
(if virtual? (make-trel i1 i2) nil))))
(defun make-trel (i1 i2)
(cond ((interval-order i2 i1) (make-trel i2 i1))
(t (let ((tr (build-cell
(cons i1 i2) (timedb-network *timedb*)
(timedb-relations *timedb*))))
(push (cons i2 tr) (interval-relations i1))
(push (cons i1 tr) (interval-relations i2))
(clear-cell tr)
(find-transitive-relations tr)
tr))))
;;; Using transitivity
;; Simple version: installs all transitive relationships.
(defun find-transitive-relations (trel)
;; Any relationships in the interval's index
;; that have shared elements are fair game.
(let ((i1 (car (cell-name trel)))
(i2 (cdr (cell-name trel))))
(dolist (tpair1 (interval-relations i1))
(unless (eq (car tpair1) i2)
(let ((tpair2 (assoc (car tpair1)
(interval-relations i2))))
(when tpair2
;; Now must find which is which.
(let ((i3 (car tpair1)))
(cond ((interval-order i1 i3)
(cond ((interval-order i3 i2)
(build-transitive-constraint
(cdr tpair1) (cdr tpair2) trel))
(t (build-transitive-constraint
trel (cdr tpair2)(cdr tpair1)))))
(t (build-transitive-constraint
(cdr tpair1) trel (cdr tpair2)))))))))))
(defun build-transitive-constraint (tr1 tr2 tr3)
(let ((con (build-constraint
(list tr1 tr2 tr3)
(timedb-network *timedb*)
#'update-trel-transitivity)))
(add-constraint-cell tr1 con)
(add-constraint-cell tr2 con)
(add-constraint-cell tr3 con)
(setf (constraint-parts con) (list tr1 tr2 tr3))))
;;;; What the constraint does
(defun update-trel-transitivity (con &aux cells diffs possibles)
(setq cells (constraint-parts con))
(setq possibles
(update-possible-trel-values (cell-value (first cells))
(cell-value (second cells))))
(when possibles
(setq diffs (set-difference (cell-value (third cells))
possibles))
(when diffs
(dolist (d diffs)
(queue-cell (third cells) :EXCLUDE d con)))))
(defun update-possible-trel-values (vals1 vals2 &aux possibles)
(setq possibles nil)
(dolist (v1 vals1)
(dolist (v2 vals2)
(setq possibles (union possibles
(lookup-transitive-trels v1 v2)))))
possibles)
(defun lookup-transitive-trels (r1 r2)
(cdr (assoc r2
(cdr (assoc r1
(timedb-transitivity-table *timedb*))))))
;;;; User interface
(defmacro interval (i &optional (*timedb* *timedb*))
`(progn (let ((int (make-interval
:NAME ',i
:RELATIONS nil
:TIMEDB *timedb*
:INDEX (incf (timedb-interval-id *timedb*)))))
(push (cons ',i int) (timedb-intervals *timedb*)))))
(defun lookup-interval (iname &optional (*timedb* *timedb*))
(cdr (assoc iname (timedb-intervals *timedb*) :TEST #'equal)))
(defmacro tassert (int1 int2 &optional (rels :NOT-GIVEN)
(*timedb* *timedb*))
(when (eq rels :NOT-GIVEN)
(setq rels (timedb-relations *timedb*)))
`(temporal-relations (lookup-interval ',int1)
(lookup-interval ',int2) ',rels *timedb*))
(defun temporal-relations (a b &optional (possibles nil)
(*timedb* *timedb*) &aux trel)
(setq trel (lookup-trel a b t))
(when possibles
(dolist (rel possibles)
(unless (member rel (timedb-relations *timedb*))
(error "~A not legitmate temporal relation [~A, ~A, ~A]"
rel a b possibles)))
(dolist (rel (timedb-relations *timedb*))
(unless (member rel possibles)
(queue-cell trel :EXCLUDE rel 'USER))))
(fire-constraints (timedb-network *timedb*)))
(defun what-time (i1 i2 &aux rel)
(setq rel (lookup-trel i1 i2))
(if rel
(format t "~%~A {~A} ~A" (interval-name i1)
(make-relations-string (cell-value rel))
(interval-name i2))
(format t "~%No known relationship between ~A and ~A."
(interval-name i1)
(interval-name i2))))
(defun what-times (&optional (*timedb* *timedb*))
(dolist (c (reverse (network-cells
(timedb-network *timedb*))))
(what-time (car (cell-name (cdr c)))
(cdr (cell-name (cdr c))))))
(defun make-relations-string (rels)
(format nil "~{~<~% ~1:; ~S~>~^,~}" rels))
Defining a temporal logic , - style
(defmacro defTemporalRelation (sym)
`(push ',sym (timedb-relations *timedb*)))
(defmacro t-transitivity (r1 r2 &rest options)
(dolist (op (cons r1 (cons r2 options)))
(unless (member op (timedb-relations *timedb*))
(error "~A not a possible temporal relationship [~A, ~A]"
op r1 r2)))
`(let ((r1-entry (assoc ',r1
(timedb-transitivity-table *timedb*))))
(unless r1-entry
(setq r1-entry (list ',r1))
(push r1-entry (timedb-transitivity-table *timedb*)))
(push (cons ',r2 ',(copy-list options)) (cdr r1-entry))))
| null | https://raw.githubusercontent.com/namin/biohacker/6b5da4c51c9caa6b5e1a68b046af171708d1af64/BPS/relax/timedb.lisp | lisp | -*- Mode: Lisp; -*-
All rights reserved.
See the file legal.txt for a paragraph stating scope of permission
and disclaimer of warranty. The above copyright notice and that
paragraph must be included in any separate copy of this file.
String for printing
Debugging flag
Unique ID
List of intervals
Temporal relationships
Transitivity table
A constraint network
for ordering them
backpointer
((<interval> . <relation-cell>))
Current temporal database
Indexing relationships
Using transitivity
Simple version: installs all transitive relationships.
Any relationships in the interval's index
that have shared elements are fair game.
Now must find which is which.
What the constraint does
User interface |
's temporal logic implemented in WALTZER
Last edited 1/29/93 , by KDF
Copyright ( c ) 1988 -- 1992 , Northwestern University ,
, Xerox Corporation .
(in-package :COMMON-LISP-USER)
(defstruct (timedb (:PREDICATE temporal-database?)
(:PRINT-FUNCTION
(lambda (st str ignore) (declare (ignore ignore))
(format str "<Temporal DB ~A>" (timedb-title st)))))
(defstruct (interval (:PREDICATE interval?)
(:PRINT-FUNCTION
(lambda (st str ignore) (declare (ignore ignore))
(format str "I-~A" (interval-name st)))))
name
(defun interval-order (x y)
(< (interval-index x) (interval-index y)))
(defvar *trels-file* (concatenate 'string (make-bps-path "relax") "allen.lisp"))
(defun in-timedb (new-one) (setq *timedb* new-one))
(defun with-timedb (timedb &rest forms)
`(let ((*timedb* ,timedb)) ,@ forms))
(defun create-timedb (title &optional
(t-file *trels-file*)
(debugging? nil))
(setq *timedb*
(make-timedb :TITLE title
:NETWORK
(create-network
(format nil "of ~A" title))
:DEBUGGING debugging?))
(load t-file)
*timedb*)
(defun lookup-trel (i1 i2 &optional (virtual? nil)
(*timedb* *timedb*))
(let ((old (assoc i2 (interval-relations i1))))
(if old (cdr old)
(if virtual? (make-trel i1 i2) nil))))
(defun make-trel (i1 i2)
(cond ((interval-order i2 i1) (make-trel i2 i1))
(t (let ((tr (build-cell
(cons i1 i2) (timedb-network *timedb*)
(timedb-relations *timedb*))))
(push (cons i2 tr) (interval-relations i1))
(push (cons i1 tr) (interval-relations i2))
(clear-cell tr)
(find-transitive-relations tr)
tr))))
(defun find-transitive-relations (trel)
(let ((i1 (car (cell-name trel)))
(i2 (cdr (cell-name trel))))
(dolist (tpair1 (interval-relations i1))
(unless (eq (car tpair1) i2)
(let ((tpair2 (assoc (car tpair1)
(interval-relations i2))))
(when tpair2
(let ((i3 (car tpair1)))
(cond ((interval-order i1 i3)
(cond ((interval-order i3 i2)
(build-transitive-constraint
(cdr tpair1) (cdr tpair2) trel))
(t (build-transitive-constraint
trel (cdr tpair2)(cdr tpair1)))))
(t (build-transitive-constraint
(cdr tpair1) trel (cdr tpair2)))))))))))
(defun build-transitive-constraint (tr1 tr2 tr3)
(let ((con (build-constraint
(list tr1 tr2 tr3)
(timedb-network *timedb*)
#'update-trel-transitivity)))
(add-constraint-cell tr1 con)
(add-constraint-cell tr2 con)
(add-constraint-cell tr3 con)
(setf (constraint-parts con) (list tr1 tr2 tr3))))
(defun update-trel-transitivity (con &aux cells diffs possibles)
(setq cells (constraint-parts con))
(setq possibles
(update-possible-trel-values (cell-value (first cells))
(cell-value (second cells))))
(when possibles
(setq diffs (set-difference (cell-value (third cells))
possibles))
(when diffs
(dolist (d diffs)
(queue-cell (third cells) :EXCLUDE d con)))))
(defun update-possible-trel-values (vals1 vals2 &aux possibles)
(setq possibles nil)
(dolist (v1 vals1)
(dolist (v2 vals2)
(setq possibles (union possibles
(lookup-transitive-trels v1 v2)))))
possibles)
(defun lookup-transitive-trels (r1 r2)
(cdr (assoc r2
(cdr (assoc r1
(timedb-transitivity-table *timedb*))))))
(defmacro interval (i &optional (*timedb* *timedb*))
`(progn (let ((int (make-interval
:NAME ',i
:RELATIONS nil
:TIMEDB *timedb*
:INDEX (incf (timedb-interval-id *timedb*)))))
(push (cons ',i int) (timedb-intervals *timedb*)))))
(defun lookup-interval (iname &optional (*timedb* *timedb*))
(cdr (assoc iname (timedb-intervals *timedb*) :TEST #'equal)))
(defmacro tassert (int1 int2 &optional (rels :NOT-GIVEN)
(*timedb* *timedb*))
(when (eq rels :NOT-GIVEN)
(setq rels (timedb-relations *timedb*)))
`(temporal-relations (lookup-interval ',int1)
(lookup-interval ',int2) ',rels *timedb*))
(defun temporal-relations (a b &optional (possibles nil)
(*timedb* *timedb*) &aux trel)
(setq trel (lookup-trel a b t))
(when possibles
(dolist (rel possibles)
(unless (member rel (timedb-relations *timedb*))
(error "~A not legitmate temporal relation [~A, ~A, ~A]"
rel a b possibles)))
(dolist (rel (timedb-relations *timedb*))
(unless (member rel possibles)
(queue-cell trel :EXCLUDE rel 'USER))))
(fire-constraints (timedb-network *timedb*)))
(defun what-time (i1 i2 &aux rel)
(setq rel (lookup-trel i1 i2))
(if rel
(format t "~%~A {~A} ~A" (interval-name i1)
(make-relations-string (cell-value rel))
(interval-name i2))
(format t "~%No known relationship between ~A and ~A."
(interval-name i1)
(interval-name i2))))
(defun what-times (&optional (*timedb* *timedb*))
(dolist (c (reverse (network-cells
(timedb-network *timedb*))))
(what-time (car (cell-name (cdr c)))
(cdr (cell-name (cdr c))))))
(defun make-relations-string (rels)
(format nil "~{~<~% ~1:; ~S~>~^,~}" rels))
Defining a temporal logic , - style
(defmacro defTemporalRelation (sym)
`(push ',sym (timedb-relations *timedb*)))
(defmacro t-transitivity (r1 r2 &rest options)
(dolist (op (cons r1 (cons r2 options)))
(unless (member op (timedb-relations *timedb*))
(error "~A not a possible temporal relationship [~A, ~A]"
op r1 r2)))
`(let ((r1-entry (assoc ',r1
(timedb-transitivity-table *timedb*))))
(unless r1-entry
(setq r1-entry (list ',r1))
(push r1-entry (timedb-transitivity-table *timedb*)))
(push (cons ',r2 ',(copy-list options)) (cdr r1-entry))))
|
b3de97676c3680c97913a77a2036f6b36e925701d06e2adeb1d4634550dd897b | ocaml-ppx/cinaps | syntax.mli | type t =
{ comment_start_dollar : Re.re
; comment_end_or_dollar_comment_end_or_comment_start_if_rec_comment : Re.re
; comment_end_anchored : Re.re
}
val ocaml : t
val c : t
val sexp : t
| null | https://raw.githubusercontent.com/ocaml-ppx/cinaps/2791bce694bfea6ab077f13fc2987fb56fa5006f/src/syntax.mli | ocaml | type t =
{ comment_start_dollar : Re.re
; comment_end_or_dollar_comment_end_or_comment_start_if_rec_comment : Re.re
; comment_end_anchored : Re.re
}
val ocaml : t
val c : t
val sexp : t
| |
c0ff02341a018cf33ae3bbdd6e8aa618bd6d3c417fea1472513a692a28996d73 | rbkmoney/fistful-server | ff_withdrawal.erl | %%%
%%% Withdrawal
%%%
-module(ff_withdrawal).
-include_lib("damsel/include/dmsl_payment_processing_thrift.hrl").
-include_lib("damsel/include/dmsl_withdrawals_provider_adapter_thrift.hrl").
-type id() :: binary().
-type clock() :: ff_transaction:clock().
-define(ACTUAL_FORMAT_VERSION, 4).
-opaque withdrawal_state() :: #{
id := id(),
transfer_type := withdrawal,
body := body(),
params := transfer_params(),
created_at => ff_time:timestamp_ms(),
party_revision => party_revision(),
domain_revision => domain_revision(),
route => route(),
attempts => attempts(),
resource => destination_resource(),
adjustments => adjustments_index(),
status => status(),
metadata => metadata(),
external_id => id()
}.
-opaque withdrawal() :: #{
version := ?ACTUAL_FORMAT_VERSION,
id := id(),
transfer_type := withdrawal,
body := body(),
params := transfer_params(),
created_at => ff_time:timestamp_ms(),
party_revision => party_revision(),
domain_revision => domain_revision(),
route => route(),
metadata => metadata(),
external_id => id()
}.
-type params() :: #{
id := id(),
wallet_id := ff_wallet_machine:id(),
destination_id := ff_destination:id(),
body := body(),
external_id => id(),
quote => quote(),
metadata => metadata()
}.
-type status() ::
pending
| succeeded
| {failed, failure()}.
-type event() ::
{created, withdrawal()}
| {resource_got, destination_resource()}
| {route_changed, route()}
| {p_transfer, ff_postings_transfer:event()}
| {limit_check, limit_check_details()}
| {session_started, session_id()}
| {session_finished, {session_id(), session_result()}}
| {status_changed, status()}
| wrapped_adjustment_event().
-type create_error() ::
{wallet, notfound}
| {destination, notfound | unauthorized}
| {wallet, ff_wallet:inaccessibility()}
| {inconsistent_currency, {Withdrawal :: currency_id(), Wallet :: currency_id(), Destination :: currency_id()}}
| {terms, ff_party:validate_withdrawal_creation_error()}
| {identity_providers_mismatch, {ff_provider:id(), ff_provider:id()}}
| {destination_resource, {bin_data, ff_bin_data:bin_data_error()}}.
-type route() :: ff_withdrawal_routing:route().
-type attempts() :: ff_withdrawal_route_attempt_utils:attempts().
-type quote_params() :: #{
wallet_id := ff_wallet_machine:id(),
currency_from := ff_currency:id(),
currency_to := ff_currency:id(),
body := ff_transaction:body(),
destination_id => ff_destination:id(),
external_id => id()
}.
-type quote() :: #{
cash_from := cash(),
cash_to := cash(),
created_at := binary(),
expires_on := binary(),
quote_data := ff_adapter_withdrawal:quote_data(),
route := route(),
operation_timestamp := ff_time:timestamp_ms(),
resource_descriptor => resource_descriptor(),
domain_revision => party_revision(),
party_revision => domain_revision()
}.
-type quote_state() :: #{
cash_from := cash(),
cash_to := cash(),
created_at := binary(),
expires_on := binary(),
quote_data := ff_adapter_withdrawal:quote_data(),
route := route(),
resource_descriptor => resource_descriptor()
}.
-type session() :: #{
id := session_id(),
result => session_result()
}.
-type gen_args() :: #{
id := id(),
body := body(),
params := params(),
transfer_type := withdrawal,
status => status(),
route => route(),
external_id => external_id(),
created_at => ff_time:timestamp_ms(),
party_revision => party_revision(),
domain_revision => domain_revision(),
metadata => metadata()
}.
-type limit_check_details() ::
{wallet_sender, wallet_limit_check_details()}.
-type wallet_limit_check_details() ::
ok
| {failed, wallet_limit_check_error()}.
-type wallet_limit_check_error() :: #{
expected_range := cash_range(),
balance := cash()
}.
-type adjustment_params() :: #{
id := adjustment_id(),
change := adjustment_change(),
external_id => id()
}.
-type adjustment_change() ::
{change_status, status()}.
-type start_adjustment_error() ::
invalid_withdrawal_status_error()
| invalid_status_change_error()
| {another_adjustment_in_progress, adjustment_id()}
| ff_adjustment:create_error().
-type unknown_adjustment_error() :: ff_adjustment_utils:unknown_adjustment_error().
-type invalid_status_change_error() ::
{invalid_status_change, {unavailable_status, status()}}
| {invalid_status_change, {already_has_status, status()}}.
-type invalid_withdrawal_status_error() ::
{invalid_withdrawal_status, status()}.
-type action() :: sleep | continue | undefined.
-export_type([withdrawal/0]).
-export_type([withdrawal_state/0]).
-export_type([id/0]).
-export_type([params/0]).
-export_type([event/0]).
-export_type([route/0]).
-export_type([quote/0]).
-export_type([quote_params/0]).
-export_type([session/0]).
-export_type([gen_args/0]).
-export_type([create_error/0]).
-export_type([action/0]).
-export_type([adjustment_params/0]).
-export_type([start_adjustment_error/0]).
-export_type([limit_check_details/0]).
%% Transfer logic callbacks
-export([process_transfer/1]).
%%
-export([process_session_finished/3]).
Accessors
-export([wallet_id/1]).
-export([destination_id/1]).
-export([quote/1]).
-export([id/1]).
-export([body/1]).
-export([status/1]).
-export([route/1]).
-export([attempts/1]).
-export([external_id/1]).
-export([created_at/1]).
-export([party_revision/1]).
-export([domain_revision/1]).
-export([destination_resource/1]).
-export([metadata/1]).
%% API
-export([create/1]).
-export([gen/1]).
-export([get_quote/1]).
-export([is_finished/1]).
-export([start_adjustment/2]).
-export([find_adjustment/2]).
-export([adjustments/1]).
-export([effective_final_cash_flow/1]).
-export([sessions/1]).
-export([session_id/1]).
-export([get_current_session/1]).
-export([get_current_session_status/1]).
%% Event source
-export([apply_event/2]).
Pipeline
-import(ff_pipeline, [do/1, unwrap/1, unwrap/2]).
%% Internal types
-type body() :: ff_transaction:body().
-type identity() :: ff_identity:identity_state().
-type party_id() :: ff_party:id().
-type wallet_id() :: ff_wallet:id().
-type wallet() :: ff_wallet:wallet_state().
-type destination_id() :: ff_destination:id().
-type destination() :: ff_destination:destination_state().
-type process_result() :: {action(), [event()]}.
-type final_cash_flow() :: ff_cash_flow:final_cash_flow().
-type external_id() :: id() | undefined.
-type p_transfer() :: ff_postings_transfer:transfer().
-type session_id() :: id().
-type destination_resource() :: ff_destination:resource().
-type bin_data() :: ff_bin_data:bin_data().
-type cash() :: ff_cash:cash().
-type cash_range() :: ff_range:range(cash()).
-type failure() :: ff_failure:failure().
-type session_result() :: ff_withdrawal_session:session_result().
-type adjustment() :: ff_adjustment:adjustment().
-type adjustment_id() :: ff_adjustment:id().
-type adjustments_index() :: ff_adjustment_utils:index().
-type currency_id() :: ff_currency:id().
-type party_revision() :: ff_party:revision().
-type domain_revision() :: ff_domain_config:revision().
-type terms() :: ff_party:terms().
-type party_varset() :: ff_varset:varset().
-type metadata() :: ff_entity_context:md().
-type resource_descriptor() :: ff_resource:resource_descriptor().
-type wrapped_adjustment_event() :: ff_adjustment_utils:wrapped_event().
-type provider_id() :: ff_payouts_provider:id().
-type terminal_id() :: ff_payouts_terminal:id().
-type legacy_event() :: any().
-type transfer_params() :: #{
wallet_id := wallet_id(),
destination_id := destination_id(),
quote => quote_state()
}.
-type party_varset_params() :: #{
body := body(),
wallet_id := wallet_id(),
party_id := party_id(),
destination => destination(),
resource => destination_resource(),
bin_data := bin_data()
}.
-type activity() ::
routing
| p_transfer_start
| p_transfer_prepare
| session_starting
| session_sleeping
| p_transfer_commit
| p_transfer_cancel
| limit_check
| {fail, fail_type()}
| adjustment
% Legacy activity
| stop
| finish.
-type fail_type() ::
limit_check
| route_not_found
| {inconsistent_quote_route, {provider_id, provider_id()} | {terminal_id, terminal_id()}}
| session.
-type session_processing_status() :: undefined | pending | succeeded | failed.
Accessors
-spec wallet_id(withdrawal_state()) -> wallet_id().
wallet_id(T) ->
maps:get(wallet_id, params(T)).
-spec destination_id(withdrawal_state()) -> destination_id().
destination_id(T) ->
maps:get(destination_id, params(T)).
-spec destination_resource(withdrawal_state()) -> destination_resource().
destination_resource(#{resource := Resource}) ->
Resource;
destination_resource(Withdrawal) ->
DestinationID = destination_id(Withdrawal),
{ok, DestinationMachine} = ff_destination_machine:get(DestinationID),
Destination = ff_destination_machine:destination(DestinationMachine),
{ok, Resource} = ff_resource:create_resource(ff_destination:resource(Destination)),
Resource.
%%
-spec quote(withdrawal_state()) -> quote_state() | undefined.
quote(T) ->
maps:get(quote, params(T), undefined).
-spec id(withdrawal_state()) -> id().
id(#{id := V}) ->
V.
-spec body(withdrawal_state()) -> body().
body(#{body := V}) ->
V.
-spec status(withdrawal_state()) -> status() | undefined.
status(T) ->
maps:get(status, T, undefined).
-spec route(withdrawal_state()) -> route() | undefined.
route(T) ->
maps:get(route, T, undefined).
-spec attempts(withdrawal_state()) -> attempts().
attempts(#{attempts := Attempts}) ->
Attempts;
attempts(T) when not is_map_key(attempts, T) ->
ff_withdrawal_route_attempt_utils:new().
-spec external_id(withdrawal_state()) -> external_id() | undefined.
external_id(T) ->
maps:get(external_id, T, undefined).
-spec party_revision(withdrawal_state()) -> party_revision() | undefined.
party_revision(T) ->
maps:get(party_revision, T, undefined).
-spec domain_revision(withdrawal_state()) -> domain_revision() | undefined.
domain_revision(T) ->
maps:get(domain_revision, T, undefined).
-spec created_at(withdrawal_state()) -> ff_time:timestamp_ms() | undefined.
created_at(T) ->
maps:get(created_at, T, undefined).
-spec metadata(withdrawal_state()) -> metadata() | undefined.
metadata(T) ->
maps:get(metadata, T, undefined).
%% API
-spec gen(gen_args()) -> withdrawal().
gen(Args) ->
TypeKeys = [
id,
transfer_type,
body,
params,
external_id,
domain_revision,
party_revision,
created_at,
route,
metadata
],
Withdrawal = genlib_map:compact(maps:with(TypeKeys, Args)),
Withdrawal#{version => 4}.
-spec create(params()) ->
{ok, [event()]}
| {error, create_error()}.
create(Params) ->
do(fun() ->
#{id := ID, wallet_id := WalletID, destination_id := DestinationID, body := Body} = Params,
CreatedAt = ff_time:now(),
Quote = maps:get(quote, Params, undefined),
ResourceDescriptor = quote_resource_descriptor(Quote),
Timestamp = ff_maybe:get_defined(quote_timestamp(Quote), CreatedAt),
DomainRevision = ensure_domain_revision_defined(quote_domain_revision(Quote)),
Wallet = unwrap(wallet, get_wallet(WalletID)),
accessible = unwrap(wallet, ff_wallet:is_accessible(Wallet)),
Identity = get_wallet_identity(Wallet),
Destination = unwrap(destination, get_destination(DestinationID)),
ResourceParams = ff_destination:resource(Destination),
Resource = unwrap(
destination_resource,
create_resource(ResourceParams, ResourceDescriptor, Identity, DomainRevision)
),
PartyID = ff_identity:party(Identity),
VarsetParams = genlib_map:compact(#{
body => Body,
wallet_id => WalletID,
party_id => PartyID,
destination => Destination,
resource => Resource
}),
Varset = build_party_varset(VarsetParams),
PartyRevision = ensure_party_revision_defined(PartyID, quote_party_revision(Quote)),
ContractID = ff_identity:contract(Identity),
{ok, Terms} = ff_party:get_contract_terms(
PartyID,
ContractID,
Varset,
Timestamp,
PartyRevision,
DomainRevision
),
valid = unwrap(validate_withdrawal_creation(Terms, Body, Wallet, Destination)),
TransferParams = genlib_map:compact(#{
wallet_id => WalletID,
destination_id => DestinationID,
quote => Quote
}),
[
{created,
genlib_map:compact(#{
version => ?ACTUAL_FORMAT_VERSION,
id => ID,
transfer_type => withdrawal,
body => Body,
params => TransferParams,
created_at => CreatedAt,
party_revision => PartyRevision,
domain_revision => DomainRevision,
external_id => maps:get(external_id, Params, undefined),
metadata => maps:get(metadata, Params, undefined)
})},
{status_changed, pending},
{resource_got, Resource}
]
end).
create_resource(
{bank_card, #{bank_card := #{token := Token}} = ResourceBankCardParams},
ResourceDescriptor,
Identity,
DomainRevision
) ->
case ff_resource:get_bin_data(Token, ResourceDescriptor) of
{ok, BinData} ->
Varset = #{
bin_data => ff_dmsl_codec:marshal(bin_data, BinData)
},
{ok, PaymentInstitution} = get_payment_institution(Identity, Varset, DomainRevision),
PaymentSystem = unwrap(ff_payment_institution:payment_system(PaymentInstitution)),
ff_resource:create_bank_card_basic(ResourceBankCardParams, BinData, PaymentSystem);
{error, Error} ->
{error, {bin_data, Error}}
end;
create_resource(ResourceParams, ResourceDescriptor, _Identity, _DomainRevision) ->
ff_resource:create_resource(ResourceParams, ResourceDescriptor).
-spec start_adjustment(adjustment_params(), withdrawal_state()) ->
{ok, process_result()}
| {error, start_adjustment_error()}.
start_adjustment(Params, Withdrawal) ->
#{id := AdjustmentID} = Params,
case find_adjustment(AdjustmentID, Withdrawal) of
{error, {unknown_adjustment, _}} ->
do_start_adjustment(Params, Withdrawal);
{ok, _Adjustment} ->
{ok, {undefined, []}}
end.
-spec find_adjustment(adjustment_id(), withdrawal_state()) -> {ok, adjustment()} | {error, unknown_adjustment_error()}.
find_adjustment(AdjustmentID, Withdrawal) ->
ff_adjustment_utils:get_by_id(AdjustmentID, adjustments_index(Withdrawal)).
-spec adjustments(withdrawal_state()) -> [adjustment()].
adjustments(Withdrawal) ->
ff_adjustment_utils:adjustments(adjustments_index(Withdrawal)).
-spec effective_final_cash_flow(withdrawal_state()) -> final_cash_flow().
effective_final_cash_flow(Withdrawal) ->
case ff_adjustment_utils:cash_flow(adjustments_index(Withdrawal)) of
undefined ->
ff_cash_flow:make_empty_final();
CashFlow ->
CashFlow
end.
-spec sessions(withdrawal_state()) -> [session()].
sessions(Withdrawal) ->
ff_withdrawal_route_attempt_utils:get_sessions(attempts(Withdrawal)).
Сущность в каких - то действий
-spec is_active(withdrawal_state()) -> boolean().
is_active(#{status := succeeded} = Withdrawal) ->
is_childs_active(Withdrawal);
is_active(#{status := {failed, _}} = Withdrawal) ->
is_childs_active(Withdrawal);
is_active(#{status := pending}) ->
true.
Сущность завершила свою основную задачу по переводу денег . Дальше её состояние будет меняться только
изменением дочерних сущностей , например запуском adjustment .
-spec is_finished(withdrawal_state()) -> boolean().
is_finished(#{status := succeeded}) ->
true;
is_finished(#{status := {failed, _}}) ->
true;
is_finished(#{status := pending}) ->
false.
%% Transfer callbacks
-spec process_transfer(withdrawal_state()) -> process_result().
process_transfer(Withdrawal) ->
Activity = deduce_activity(Withdrawal),
do_process_transfer(Activity, Withdrawal).
%%
-spec process_session_finished(session_id(), session_result(), withdrawal_state()) ->
{ok, process_result()} | {error, session_not_found | old_session | result_mismatch}.
process_session_finished(SessionID, SessionResult, Withdrawal) ->
case get_session_by_id(SessionID, Withdrawal) of
#{id := SessionID, result := SessionResult} ->
{ok, {undefined, []}};
#{id := SessionID, result := _OtherSessionResult} ->
{error, result_mismatch};
#{id := SessionID} ->
try_finish_session(SessionID, SessionResult, Withdrawal);
undefined ->
{error, session_not_found}
end.
-spec get_session_by_id(session_id(), withdrawal_state()) -> session() | undefined.
get_session_by_id(SessionID, Withdrawal) ->
Sessions = ff_withdrawal_route_attempt_utils:get_sessions(attempts(Withdrawal)),
case lists:filter(fun(#{id := SessionID0}) -> SessionID0 =:= SessionID end, Sessions) of
[Session] -> Session;
[] -> undefined
end.
-spec try_finish_session(session_id(), session_result(), withdrawal_state()) ->
{ok, process_result()} | {error, old_session}.
try_finish_session(SessionID, SessionResult, Withdrawal) ->
case is_current_session(SessionID, Withdrawal) of
true ->
{ok, {continue, [{session_finished, {SessionID, SessionResult}}]}};
false ->
{error, old_session}
end.
-spec is_current_session(session_id(), withdrawal_state()) -> boolean().
is_current_session(SessionID, Withdrawal) ->
case session_id(Withdrawal) of
SessionID ->
true;
_ ->
false
end.
%% Internals
-spec do_start_adjustment(adjustment_params(), withdrawal_state()) ->
{ok, process_result()}
| {error, start_adjustment_error()}.
do_start_adjustment(Params, Withdrawal) ->
do(fun() ->
valid = unwrap(validate_adjustment_start(Params, Withdrawal)),
AdjustmentParams = make_adjustment_params(Params, Withdrawal),
#{id := AdjustmentID} = Params,
{Action, Events} = unwrap(ff_adjustment:create(AdjustmentParams)),
{Action, ff_adjustment_utils:wrap_events(AdjustmentID, Events)}
end).
%% Internal getters
-spec update_attempts(attempts(), withdrawal_state()) -> withdrawal_state().
update_attempts(Attempts, T) ->
maps:put(attempts, Attempts, T).
-spec params(withdrawal_state()) -> transfer_params().
params(#{params := V}) ->
V.
-spec p_transfer(withdrawal_state()) -> p_transfer() | undefined.
p_transfer(Withdrawal) ->
ff_withdrawal_route_attempt_utils:get_current_p_transfer(attempts(Withdrawal)).
p_transfer_status(Withdrawal) ->
case p_transfer(Withdrawal) of
undefined ->
undefined;
Transfer ->
ff_postings_transfer:status(Transfer)
end.
-spec route_selection_status(withdrawal_state()) -> unknown | found.
route_selection_status(Withdrawal) ->
case route(Withdrawal) of
undefined ->
unknown;
_Known ->
found
end.
-spec adjustments_index(withdrawal_state()) -> adjustments_index().
adjustments_index(Withdrawal) ->
case maps:find(adjustments, Withdrawal) of
{ok, Adjustments} ->
Adjustments;
error ->
ff_adjustment_utils:new_index()
end.
-spec set_adjustments_index(adjustments_index(), withdrawal_state()) -> withdrawal_state().
set_adjustments_index(Adjustments, Withdrawal) ->
Withdrawal#{adjustments => Adjustments}.
-spec operation_timestamp(withdrawal_state()) -> ff_time:timestamp_ms().
operation_timestamp(Withdrawal) ->
QuoteTimestamp = quote_timestamp(quote(Withdrawal)),
ff_maybe:get_defined([QuoteTimestamp, created_at(Withdrawal), ff_time:now()]).
-spec operation_party_revision(withdrawal_state()) -> domain_revision().
operation_party_revision(Withdrawal) ->
case party_revision(Withdrawal) of
undefined ->
{ok, Wallet} = get_wallet(wallet_id(Withdrawal)),
PartyID = ff_identity:party(get_wallet_identity(Wallet)),
{ok, Revision} = ff_party:get_revision(PartyID),
Revision;
Revision ->
Revision
end.
-spec operation_domain_revision(withdrawal_state()) -> domain_revision().
operation_domain_revision(Withdrawal) ->
case domain_revision(Withdrawal) of
undefined ->
ff_domain_config:head();
Revision ->
Revision
end.
%% Processing helpers
-spec deduce_activity(withdrawal_state()) -> activity().
deduce_activity(Withdrawal) ->
Params = #{
route => route_selection_status(Withdrawal),
p_transfer => p_transfer_status(Withdrawal),
session => get_current_session_status(Withdrawal),
status => status(Withdrawal),
limit_check => limit_check_processing_status(Withdrawal),
active_adjustment => ff_adjustment_utils:is_active(adjustments_index(Withdrawal))
},
do_deduce_activity(Params).
do_deduce_activity(#{status := pending} = Params) ->
do_pending_activity(Params);
do_deduce_activity(#{status := succeeded} = Params) ->
do_finished_activity(Params);
do_deduce_activity(#{status := {failed, _}} = Params) ->
do_finished_activity(Params).
do_pending_activity(#{route := unknown, p_transfer := undefined}) ->
routing;
do_pending_activity(#{route := found, p_transfer := undefined}) ->
p_transfer_start;
do_pending_activity(#{p_transfer := created}) ->
p_transfer_prepare;
do_pending_activity(#{p_transfer := prepared, limit_check := unknown}) ->
limit_check;
do_pending_activity(#{p_transfer := prepared, limit_check := ok, session := undefined}) ->
session_starting;
do_pending_activity(#{p_transfer := prepared, limit_check := failed}) ->
p_transfer_cancel;
do_pending_activity(#{p_transfer := cancelled, limit_check := failed}) ->
{fail, limit_check};
do_pending_activity(#{p_transfer := prepared, session := pending}) ->
session_sleeping;
do_pending_activity(#{p_transfer := prepared, session := succeeded}) ->
p_transfer_commit;
do_pending_activity(#{p_transfer := committed, session := succeeded}) ->
finish;
do_pending_activity(#{p_transfer := prepared, session := failed}) ->
p_transfer_cancel;
do_pending_activity(#{p_transfer := cancelled, session := failed}) ->
{fail, session}.
do_finished_activity(#{active_adjustment := true}) ->
adjustment;
Legacy activity . Remove after first deployment
do_finished_activity(#{status := {failed, _}, p_transfer := prepared}) ->
p_transfer_cancel;
do_finished_activity(#{status := succeeded, p_transfer := prepared}) ->
p_transfer_commit;
do_finished_activity(#{status := succeeded, p_transfer := committed}) ->
stop;
do_finished_activity(#{status := {failed, _}, p_transfer := cancelled}) ->
stop.
-spec do_process_transfer(activity(), withdrawal_state()) -> process_result().
do_process_transfer(routing, Withdrawal) ->
process_routing(Withdrawal);
do_process_transfer(p_transfer_start, Withdrawal) ->
process_p_transfer_creation(Withdrawal);
do_process_transfer(p_transfer_prepare, Withdrawal) ->
Tr = ff_withdrawal_route_attempt_utils:get_current_p_transfer(attempts(Withdrawal)),
{ok, Events} = ff_postings_transfer:prepare(Tr),
{continue, [{p_transfer, Ev} || Ev <- Events]};
do_process_transfer(p_transfer_commit, Withdrawal) ->
Tr = ff_withdrawal_route_attempt_utils:get_current_p_transfer(attempts(Withdrawal)),
{ok, Events} = ff_postings_transfer:commit(Tr),
{continue, [{p_transfer, Ev} || Ev <- Events]};
do_process_transfer(p_transfer_cancel, Withdrawal) ->
Tr = ff_withdrawal_route_attempt_utils:get_current_p_transfer(attempts(Withdrawal)),
{ok, Events} = ff_postings_transfer:cancel(Tr),
{continue, [{p_transfer, Ev} || Ev <- Events]};
do_process_transfer(limit_check, Withdrawal) ->
process_limit_check(Withdrawal);
do_process_transfer(session_starting, Withdrawal) ->
process_session_creation(Withdrawal);
do_process_transfer(session_sleeping, Withdrawal) ->
process_session_sleep(Withdrawal);
do_process_transfer({fail, Reason}, Withdrawal) ->
process_route_change(Withdrawal, Reason);
do_process_transfer(finish, Withdrawal) ->
process_transfer_finish(Withdrawal);
do_process_transfer(adjustment, Withdrawal) ->
process_adjustment(Withdrawal);
do_process_transfer(stop, _Withdrawal) ->
{undefined, []}.
-spec process_routing(withdrawal_state()) -> process_result().
process_routing(Withdrawal) ->
case do_process_routing(Withdrawal) of
{ok, [Route | _]} ->
{continue, [
{route_changed, Route}
]};
{error, route_not_found} ->
process_transfer_fail(route_not_found, Withdrawal);
{error, {inconsistent_quote_route, _Data} = Reason} ->
process_transfer_fail(Reason, Withdrawal)
end.
-spec do_process_routing(withdrawal_state()) -> {ok, [route()]} | {error, Reason} when
Reason :: route_not_found | InconsistentQuote,
InconsistentQuote :: {inconsistent_quote_route, {provider_id, provider_id()} | {terminal_id, terminal_id()}}.
do_process_routing(Withdrawal) ->
WalletID = wallet_id(Withdrawal),
{ok, Wallet} = get_wallet(WalletID),
DomainRevision = operation_domain_revision(Withdrawal),
{ok, Destination} = get_destination(destination_id(Withdrawal)),
Resource = destination_resource(Withdrawal),
Identity = get_wallet_identity(Wallet),
PartyID = ff_identity:party(get_wallet_identity(Wallet)),
VarsetParams = genlib_map:compact(#{
body => body(Withdrawal),
wallet_id => WalletID,
wallet => Wallet,
party_id => PartyID,
destination => Destination,
resource => Resource
}),
do(fun() ->
Varset = build_party_varset(VarsetParams),
Routes = unwrap(ff_withdrawal_routing:prepare_routes(Varset, Identity, DomainRevision)),
case quote(Withdrawal) of
undefined ->
Routes;
Quote ->
Route = hd(Routes),
valid = unwrap(validate_quote_route(Route, Quote)),
[Route]
end
end).
-spec validate_quote_route(route(), quote_state()) -> {ok, valid} | {error, InconsistentQuote} when
InconsistentQuote :: {inconsistent_quote_route, {provider_id, provider_id()} | {terminal_id, terminal_id()}}.
validate_quote_route(Route, #{route := QuoteRoute}) ->
do(fun() ->
valid = unwrap(validate_quote_provider(Route, QuoteRoute)),
valid = unwrap(validate_quote_terminal(Route, QuoteRoute))
end).
validate_quote_provider(#{provider_id := ProviderID}, #{provider_id := ProviderID}) ->
{ok, valid};
validate_quote_provider(#{provider_id := ProviderID}, _) ->
{error, {inconsistent_quote_route, {provider_id, ProviderID}}}.
validate_quote_terminal(#{terminal_id := TerminalID}, #{terminal_id := TerminalID}) ->
{ok, valid};
validate_quote_terminal(#{terminal_id := TerminalID}, _) ->
{error, {inconsistent_quote_route, {terminal_id, TerminalID}}}.
-spec process_limit_check(withdrawal_state()) -> process_result().
process_limit_check(Withdrawal) ->
WalletID = wallet_id(Withdrawal),
{ok, Wallet} = get_wallet(WalletID),
DomainRevision = operation_domain_revision(Withdrawal),
{ok, Destination} = get_destination(destination_id(Withdrawal)),
Resource = destination_resource(Withdrawal),
Identity = get_wallet_identity(Wallet),
PartyID = ff_identity:party(get_wallet_identity(Wallet)),
PartyRevision = operation_party_revision(Withdrawal),
ContractID = ff_identity:contract(Identity),
Timestamp = operation_timestamp(Withdrawal),
VarsetParams = genlib_map:compact(#{
body => body(Withdrawal),
wallet_id => WalletID,
wallet => Wallet,
party_id => PartyID,
destination => Destination,
resource => Resource
}),
PartyVarset = build_party_varset(VarsetParams),
{ok, Terms} = ff_party:get_contract_terms(
PartyID,
ContractID,
PartyVarset,
Timestamp,
PartyRevision,
DomainRevision
),
Clock = ff_postings_transfer:clock(p_transfer(Withdrawal)),
Events =
case validate_wallet_limits(Terms, Wallet, Clock) of
{ok, valid} ->
[{limit_check, {wallet_sender, ok}}];
{error, {terms_violation, {wallet_limit, {cash_range, {Cash, Range}}}}} ->
Details = #{
expected_range => Range,
balance => Cash
},
[{limit_check, {wallet_sender, {failed, Details}}}]
end,
{continue, Events}.
-spec process_p_transfer_creation(withdrawal_state()) -> process_result().
process_p_transfer_creation(Withdrawal) ->
FinalCashFlow = make_final_cash_flow(Withdrawal),
PTransferID = construct_p_transfer_id(Withdrawal),
{ok, PostingsTransferEvents} = ff_postings_transfer:create(PTransferID, FinalCashFlow),
{continue, [{p_transfer, Ev} || Ev <- PostingsTransferEvents]}.
-spec process_session_creation(withdrawal_state()) -> process_result().
process_session_creation(Withdrawal) ->
ID = construct_session_id(Withdrawal),
#{
wallet_id := WalletID,
destination_id := DestinationID
} = params(Withdrawal),
{ok, WalletMachine} = ff_wallet_machine:get(WalletID),
Wallet = ff_wallet_machine:wallet(WalletMachine),
WalletAccount = ff_wallet:account(Wallet),
{ok, DestinationMachine} = ff_destination_machine:get(DestinationID),
Destination = ff_destination_machine:destination(DestinationMachine),
DestinationAccount = ff_destination:account(Destination),
Route = route(Withdrawal),
{ok, SenderSt} = ff_identity_machine:get(ff_account:identity(WalletAccount)),
{ok, ReceiverSt} = ff_identity_machine:get(ff_account:identity(DestinationAccount)),
TransferData = genlib_map:compact(#{
id => ID,
cash => body(Withdrawal),
sender => ff_identity_machine:identity(SenderSt),
receiver => ff_identity_machine:identity(ReceiverSt),
quote => build_session_quote(quote(Withdrawal))
}),
SessionParams = #{
withdrawal_id => id(Withdrawal),
resource => destination_resource(Withdrawal),
route => Route
},
ok = create_session(ID, TransferData, SessionParams),
{continue, [{session_started, ID}]}.
-spec construct_session_id(withdrawal_state()) -> id().
construct_session_id(Withdrawal) ->
ID = id(Withdrawal),
Attempt = ff_withdrawal_route_attempt_utils:get_attempt(attempts(Withdrawal)),
SubID = integer_to_binary(Attempt),
<<ID/binary, "/", SubID/binary>>.
-spec construct_p_transfer_id(withdrawal_state()) -> id().
construct_p_transfer_id(Withdrawal) ->
ID = id(Withdrawal),
Attempt = ff_withdrawal_route_attempt_utils:get_attempt(attempts(Withdrawal)),
SubID = integer_to_binary(Attempt),
<<"ff/withdrawal/", ID/binary, "/", SubID/binary>>.
create_session(ID, TransferData, SessionParams) ->
case ff_withdrawal_session_machine:create(ID, TransferData, SessionParams) of
ok ->
ok;
{error, exists} ->
ok
end.
-spec process_session_sleep(withdrawal_state()) -> process_result().
process_session_sleep(Withdrawal) ->
SessionID = session_id(Withdrawal),
{ok, SessionMachine} = ff_withdrawal_session_machine:get(SessionID),
Session = ff_withdrawal_session_machine:session(SessionMachine),
case ff_withdrawal_session:status(Session) of
active ->
{sleep, []};
{finished, _} ->
Result = ff_withdrawal_session:result(Session),
{continue, [{session_finished, {SessionID, Result}}]}
end.
-spec process_transfer_finish(withdrawal_state()) -> process_result().
process_transfer_finish(_Withdrawal) ->
{undefined, [{status_changed, succeeded}]}.
-spec process_transfer_fail(fail_type(), withdrawal_state()) -> process_result().
process_transfer_fail(FailType, Withdrawal) ->
Failure = build_failure(FailType, Withdrawal),
{undefined, [{status_changed, {failed, Failure}}]}.
-spec handle_child_result(process_result(), withdrawal_state()) -> process_result().
handle_child_result({undefined, Events} = Result, Withdrawal) ->
NextWithdrawal = lists:foldl(fun(E, Acc) -> apply_event(E, Acc) end, Withdrawal, Events),
case is_active(NextWithdrawal) of
true ->
{continue, Events};
false ->
Result
end;
handle_child_result({_OtherAction, _Events} = Result, _Withdrawal) ->
Result.
-spec is_childs_active(withdrawal_state()) -> boolean().
is_childs_active(Withdrawal) ->
ff_adjustment_utils:is_active(adjustments_index(Withdrawal)).
-spec make_final_cash_flow(withdrawal_state()) -> final_cash_flow().
make_final_cash_flow(Withdrawal) ->
Body = body(Withdrawal),
WalletID = wallet_id(Withdrawal),
{ok, Wallet} = get_wallet(WalletID),
Route = route(Withdrawal),
DomainRevision = operation_domain_revision(Withdrawal),
{ok, Destination} = get_destination(destination_id(Withdrawal)),
Resource = destination_resource(Withdrawal),
Identity = get_wallet_identity(Wallet),
PartyID = ff_identity:party(get_wallet_identity(Wallet)),
PartyRevision = operation_party_revision(Withdrawal),
ContractID = ff_identity:contract(Identity),
Timestamp = operation_timestamp(Withdrawal),
VarsetParams = genlib_map:compact(#{
body => body(Withdrawal),
wallet_id => WalletID,
wallet => Wallet,
party_id => PartyID,
destination => Destination,
resource => Resource
}),
PartyVarset = build_party_varset(VarsetParams),
WalletAccount = ff_wallet:account(Wallet),
DestinationAccount = ff_destination:account(Destination),
{_Amount, CurrencyID} = Body,
#{provider_id := ProviderID} = Route,
{ok, Provider} = ff_payouts_provider:get(ProviderID, DomainRevision),
ProviderAccounts = ff_payouts_provider:accounts(Provider),
ProviderAccount = maps:get(CurrencyID, ProviderAccounts, undefined),
{ok, PaymentInstitution} = get_payment_institution(Identity, PartyVarset, DomainRevision),
{ok, SystemAccounts} = ff_payment_institution:system_accounts(PaymentInstitution, DomainRevision),
SystemAccount = maps:get(CurrencyID, SystemAccounts, #{}),
SettlementAccount = maps:get(settlement, SystemAccount, undefined),
SubagentAccount = maps:get(subagent, SystemAccount, undefined),
{ok, ProviderFee} = compute_fees(Route, PartyVarset, DomainRevision),
{ok, Terms} = ff_party:get_contract_terms(
PartyID,
ContractID,
PartyVarset,
Timestamp,
PartyRevision,
DomainRevision
),
{ok, WalletCashFlowPlan} = ff_party:get_withdrawal_cash_flow_plan(Terms),
{ok, CashFlowPlan} = ff_cash_flow:add_fee(WalletCashFlowPlan, ProviderFee),
Constants = #{
operation_amount => Body
},
Accounts = genlib_map:compact(#{
{wallet, sender_settlement} => WalletAccount,
{wallet, receiver_destination} => DestinationAccount,
{system, settlement} => SettlementAccount,
{system, subagent} => SubagentAccount,
{provider, settlement} => ProviderAccount
}),
{ok, FinalCashFlow} = ff_cash_flow:finalize(CashFlowPlan, Accounts, Constants),
FinalCashFlow.
-spec compute_fees(route(), party_varset(), domain_revision()) ->
{ok, ff_cash_flow:cash_flow_fee()}
| {error, term()}.
compute_fees(Route, VS, DomainRevision) ->
case compute_provider_terminal_terms(Route, VS, DomainRevision) of
{ok, #domain_ProvisionTermSet{
wallet = #domain_WalletProvisionTerms{
withdrawals = #domain_WithdrawalProvisionTerms{
cash_flow = CashFlowSelector
}
}
}} ->
cash_flow_postings(CashFlowSelector);
{error, Error} ->
{error, Error}
end.
-spec compute_provider_terminal_terms(route(), party_varset(), domain_revision()) ->
{ok, ff_party:provision_term_set()}
| {error, provider_not_found}
| {error, terminal_not_found}.
compute_provider_terminal_terms(#{provider_id := ProviderID, terminal_id := TerminalID}, VS, DomainRevision) ->
ProviderRef = ff_payouts_provider:ref(ProviderID),
TerminalRef = ff_payouts_terminal:ref(TerminalID),
ff_party:compute_provider_terminal_terms(ProviderRef, TerminalRef, VS, DomainRevision);
% Backward compatibility legacy case for old withrawals without terminals
compute_provider_terminal_terms(#{provider_id := ProviderID}, VS, DomainRevision) ->
ProviderRef = ff_payouts_provider:ref(ProviderID),
case ff_party:compute_provider(ProviderRef, VS, DomainRevision) of
{ok, #domain_Provider{
terms = Terms
}} ->
{ok, Terms};
{error, Error} ->
{error, Error}
end.
cash_flow_postings(CashFlowSelector) ->
case CashFlowSelector of
{value, CashFlow} ->
{ok, #{
postings => ff_cash_flow:decode_domain_postings(CashFlow)
}};
Ambiguous ->
error({misconfiguration, {'Could not reduce selector to a value', {cash_flow, Ambiguous}}})
end.
-spec ensure_domain_revision_defined(domain_revision() | undefined) -> domain_revision().
ensure_domain_revision_defined(undefined) ->
ff_domain_config:head();
ensure_domain_revision_defined(Revision) ->
Revision.
-spec ensure_party_revision_defined(party_id(), party_revision() | undefined) -> domain_revision().
ensure_party_revision_defined(PartyID, undefined) ->
{ok, Revision} = ff_party:get_revision(PartyID),
Revision;
ensure_party_revision_defined(_PartyID, Revision) ->
Revision.
-spec get_wallet(wallet_id()) -> {ok, wallet()} | {error, notfound}.
get_wallet(WalletID) ->
do(fun() ->
WalletMachine = unwrap(ff_wallet_machine:get(WalletID)),
ff_wallet_machine:wallet(WalletMachine)
end).
-spec get_destination(destination_id()) -> {ok, destination()} | {error, notfound}.
get_destination(DestinationID) ->
do(fun() ->
DestinationMachine = unwrap(ff_destination_machine:get(DestinationID)),
ff_destination_machine:destination(DestinationMachine)
end).
-spec get_wallet_identity(wallet()) -> identity().
get_wallet_identity(Wallet) ->
IdentityID = ff_wallet:identity(Wallet),
get_identity(IdentityID).
-spec get_destination_identity(destination()) -> identity().
get_destination_identity(Destination) ->
IdentityID = ff_destination:identity(Destination),
get_identity(IdentityID).
get_identity(IdentityID) ->
{ok, IdentityMachine} = ff_identity_machine:get(IdentityID),
ff_identity_machine:identity(IdentityMachine).
-spec get_payment_institution(identity(), party_varset(), domain_revision()) ->
{ok, ff_payment_institution:payment_institution()}.
get_payment_institution(Identity, PartyVarset, DomainRevision) ->
{ok, PaymentInstitutionID} = ff_party:get_identity_payment_institution_id(Identity),
ff_payment_institution:get(PaymentInstitutionID, PartyVarset, DomainRevision).
-spec build_party_varset(party_varset_params()) -> party_varset().
build_party_varset(#{body := Body, wallet_id := WalletID, party_id := PartyID} = Params) ->
{_, CurrencyID} = Body,
Destination = maps:get(destination, Params, undefined),
Resource = maps:get(resource, Params, undefined),
BinData = maps:get(bin_data, Params, undefined),
PaymentTool =
case {Destination, Resource} of
{undefined, _} ->
undefined;
{_, Resource} ->
construct_payment_tool(Resource)
end,
genlib_map:compact(#{
currency => ff_dmsl_codec:marshal(currency_ref, CurrencyID),
cost => ff_dmsl_codec:marshal(cash, Body),
party_id => PartyID,
wallet_id => WalletID,
payout_method => #domain_PayoutMethodRef{id = wallet_info},
TODO it 's not fair , because it 's PAYOUT not PAYMENT tool .
payment_tool => PaymentTool,
bin_data => ff_dmsl_codec:marshal(bin_data, BinData)
}).
-spec construct_payment_tool(ff_destination:resource() | ff_destination:resource_params()) ->
dmsl_domain_thrift:'PaymentTool'().
construct_payment_tool({bank_card, #{bank_card := ResourceBankCard}}) ->
PaymentSystem = maps:get(payment_system, ResourceBankCard, undefined),
{bank_card, #domain_BankCard{
token = maps:get(token, ResourceBankCard),
bin = maps:get(bin, ResourceBankCard),
last_digits = maps:get(masked_pan, ResourceBankCard),
payment_system = ff_dmsl_codec:marshal(payment_system, PaymentSystem),
payment_system_deprecated = maps:get(payment_system_deprecated, ResourceBankCard, undefined),
issuer_country = maps:get(issuer_country, ResourceBankCard, undefined),
bank_name = maps:get(bank_name, ResourceBankCard, undefined)
}};
construct_payment_tool({crypto_wallet, #{crypto_wallet := #{currency := {Currency, _}}}}) ->
{crypto_currency_deprecated, Currency};
construct_payment_tool({digital_wallet, #{digital_wallet := #{id := ID, data := {DigitalWalletType, _}}}}) ->
{digital_wallet, #domain_DigitalWallet{id = ID, provider_deprecated = DigitalWalletType}}.
%% Quote helpers
-spec get_quote(quote_params()) -> {ok, quote()} | {error, create_error() | {route, route_not_found}}.
get_quote(Params = #{destination_id := DestinationID, body := Body, wallet_id := WalletID}) ->
do(fun() ->
Destination = unwrap(destination, get_destination(DestinationID)),
Resource = unwrap(destination_resource, ff_resource:create_resource(ff_destination:resource(Destination))),
Wallet = unwrap(wallet, get_wallet(WalletID)),
Identity = get_wallet_identity(Wallet),
ContractID = ff_identity:contract(Identity),
PartyID = ff_identity:party(Identity),
DomainRevision = ff_domain_config:head(),
{ok, PartyRevision} = ff_party:get_revision(PartyID),
VarsetParams = genlib_map:compact(#{
body => Body,
wallet_id => WalletID,
wallet => Wallet,
party_id => PartyID,
destination => Destination,
resource => Resource
}),
PartyVarset = build_party_varset(VarsetParams),
Timestamp = ff_time:now(),
{ok, Terms} = ff_party:get_contract_terms(
PartyID,
ContractID,
PartyVarset,
Timestamp,
PartyRevision,
DomainRevision
),
valid = unwrap(validate_withdrawal_creation(Terms, Body, Wallet, Destination)),
GetQuoteParams = #{
base_params => Params,
identity => Identity,
party_varset => build_party_varset(VarsetParams),
timestamp => Timestamp,
domain_revision => DomainRevision,
party_revision => PartyRevision,
resource => Resource
},
unwrap(get_quote_(GetQuoteParams))
end);
get_quote(Params) ->
#{
wallet_id := WalletID,
body := Body
} = Params,
Wallet = unwrap(wallet, get_wallet(WalletID)),
Identity = get_wallet_identity(Wallet),
PartyID = ff_identity:party(Identity),
Timestamp = ff_time:now(),
DomainRevision = ff_domain_config:head(),
{ok, PartyRevision} = ff_party:get_revision(PartyID),
VarsetParams = genlib_map:compact(#{
body => Body,
wallet_id => WalletID,
wallet => Wallet,
party_id => PartyID
}),
GetQuoteParams = #{
base_params => Params,
identity => Identity,
party_varset => build_party_varset(VarsetParams),
timestamp => Timestamp,
domain_revision => DomainRevision,
party_revision => PartyRevision
},
get_quote_(GetQuoteParams).
get_quote_(Params) ->
do(fun() ->
#{
base_params := #{
body := Body,
currency_from := CurrencyFrom,
currency_to := CurrencyTo
},
identity := Identity,
party_varset := Varset,
timestamp := Timestamp,
domain_revision := DomainRevision,
party_revision := PartyRevision
} = Params,
Resource = maps:get(resource, Params, undefined),
[Route | _] = unwrap(route, ff_withdrawal_routing:prepare_routes(Varset, Identity, DomainRevision)),
{Adapter, AdapterOpts} = ff_withdrawal_session:get_adapter_with_opts(Route),
GetQuoteParams = #{
external_id => maps:get(external_id, Params, undefined),
currency_from => CurrencyFrom,
currency_to => CurrencyTo,
body => Body
},
{ok, Quote} = ff_adapter_withdrawal:get_quote(Adapter, GetQuoteParams, AdapterOpts),
genlib_map:compact(#{
cash_from => maps:get(cash_from, Quote),
cash_to => maps:get(cash_to, Quote),
created_at => maps:get(created_at, Quote),
expires_on => maps:get(expires_on, Quote),
quote_data => maps:get(quote_data, Quote),
route => Route,
operation_timestamp => Timestamp,
resource_descriptor => ff_resource:resource_descriptor(Resource),
domain_revision => DomainRevision,
party_revision => PartyRevision
})
end).
-spec build_session_quote(quote_state() | undefined) -> ff_adapter_withdrawal:quote_data() | undefined.
build_session_quote(undefined) ->
undefined;
build_session_quote(Quote) ->
maps:with([cash_from, cash_to, created_at, expires_on, quote_data], Quote).
-spec quote_resource_descriptor(quote() | undefined) -> resource_descriptor().
quote_resource_descriptor(undefined) ->
undefined;
quote_resource_descriptor(Quote) ->
maps:get(resource_descriptor, Quote, undefined).
-spec quote_timestamp(quote() | undefined) -> ff_time:timestamp_ms() | undefined.
quote_timestamp(undefined) ->
undefined;
quote_timestamp(Quote) ->
maps:get(operation_timestamp, Quote, undefined).
-spec quote_party_revision(quote() | undefined) -> party_revision() | undefined.
quote_party_revision(undefined) ->
undefined;
quote_party_revision(Quote) ->
maps:get(party_revision, Quote, undefined).
-spec quote_domain_revision(quote() | undefined) -> domain_revision() | undefined.
quote_domain_revision(undefined) ->
undefined;
quote_domain_revision(Quote) ->
maps:get(domain_revision, Quote, undefined).
%% Session management
-spec session_id(withdrawal_state()) -> session_id() | undefined.
session_id(T) ->
case get_current_session(T) of
undefined ->
undefined;
#{id := SessionID} ->
SessionID
end.
-spec get_current_session(withdrawal_state()) -> session() | undefined.
get_current_session(Withdrawal) ->
ff_withdrawal_route_attempt_utils:get_current_session(attempts(Withdrawal)).
-spec get_session_result(withdrawal_state()) -> session_result() | unknown | undefined.
get_session_result(Withdrawal) ->
case get_current_session(Withdrawal) of
undefined ->
undefined;
#{result := Result} ->
Result;
#{} ->
unknown
end.
-spec get_current_session_status(withdrawal_state()) -> session_processing_status().
get_current_session_status(Withdrawal) ->
Session = get_current_session(Withdrawal),
case Session of
undefined ->
undefined;
#{result := success} ->
succeeded;
#{result := {success, _}} ->
succeeded;
#{result := {failed, _}} ->
failed;
#{} ->
pending
end.
%% Withdrawal validators
-spec validate_withdrawal_creation(terms(), body(), wallet(), destination()) ->
{ok, valid}
| {error, create_error()}.
validate_withdrawal_creation(Terms, Body, Wallet, Destination) ->
do(fun() ->
valid = unwrap(terms, validate_withdrawal_creation_terms(Terms, Body)),
valid = unwrap(validate_withdrawal_currency(Body, Wallet, Destination)),
valid = unwrap(validate_destination_status(Destination)),
valid = unwrap(validate_withdrawal_providers(Wallet, Destination))
end).
validate_withdrawal_providers(Wallet, Destination) ->
WalletIdentity = get_wallet_identity(Wallet),
DestinationIdentity = get_destination_identity(Destination),
WalletProvider = ff_identity:provider(WalletIdentity),
DestinationProvider = ff_identity:provider(DestinationIdentity),
case WalletProvider =:= DestinationProvider of
true -> {ok, valid};
false -> {error, {identity_providers_mismatch, {WalletProvider, DestinationProvider}}}
end.
-spec validate_withdrawal_creation_terms(terms(), body()) ->
{ok, valid}
| {error, ff_party:validate_withdrawal_creation_error()}.
validate_withdrawal_creation_terms(Terms, Body) ->
ff_party:validate_withdrawal_creation(Terms, Body).
-spec validate_withdrawal_currency(body(), wallet(), destination()) ->
{ok, valid}
| {error, {inconsistent_currency, {currency_id(), currency_id(), currency_id()}}}.
validate_withdrawal_currency(Body, Wallet, Destination) ->
DestiantionCurrencyID = ff_account:currency(ff_destination:account(Destination)),
WalletCurrencyID = ff_account:currency(ff_wallet:account(Wallet)),
case Body of
{_Amount, WithdrawalCurencyID} when
WithdrawalCurencyID =:= DestiantionCurrencyID andalso
WithdrawalCurencyID =:= WalletCurrencyID
->
{ok, valid};
{_Amount, WithdrawalCurencyID} ->
{error, {inconsistent_currency, {WithdrawalCurencyID, WalletCurrencyID, DestiantionCurrencyID}}}
end.
-spec validate_destination_status(destination()) ->
{ok, valid}
| {error, {destination, ff_destination:status()}}.
validate_destination_status(Destination) ->
case ff_destination:status(Destination) of
authorized ->
{ok, valid};
unauthorized ->
{error, {destination, unauthorized}}
end.
%% Limit helpers
-spec add_limit_check(limit_check_details(), withdrawal_state()) -> withdrawal_state().
add_limit_check(Check, Withdrawal) ->
Attempts = attempts(Withdrawal),
Checks =
case ff_withdrawal_route_attempt_utils:get_current_limit_checks(Attempts) of
undefined ->
[Check];
C ->
[Check | C]
end,
R = ff_withdrawal_route_attempt_utils:update_current_limit_checks(Checks, Attempts),
update_attempts(R, Withdrawal).
-spec limit_check_status(withdrawal_state()) -> ok | {failed, limit_check_details()} | unknown.
limit_check_status(Withdrawal) ->
Attempts = attempts(Withdrawal),
Checks = ff_withdrawal_route_attempt_utils:get_current_limit_checks(Attempts),
limit_check_status_(Checks).
limit_check_status_(undefined) ->
unknown;
limit_check_status_(Checks) ->
case lists:dropwhile(fun is_limit_check_ok/1, Checks) of
[] ->
ok;
[H | _Tail] ->
{failed, H}
end.
-spec limit_check_processing_status(withdrawal_state()) -> ok | failed | unknown.
limit_check_processing_status(Withdrawal) ->
case limit_check_status(Withdrawal) of
ok ->
ok;
unknown ->
unknown;
{failed, _Details} ->
failed
end.
-spec is_limit_check_ok(limit_check_details()) -> boolean().
is_limit_check_ok({wallet_sender, ok}) ->
true;
is_limit_check_ok({wallet_sender, {failed, _Details}}) ->
false.
-spec validate_wallet_limits(terms(), wallet(), clock()) ->
{ok, valid}
| {error, {terms_violation, {wallet_limit, {cash_range, {cash(), cash_range()}}}}}.
validate_wallet_limits(Terms, Wallet, Clock) ->
case ff_party:validate_wallet_limits(Terms, Wallet, Clock) of
{ok, valid} = Result ->
Result;
{error, {terms_violation, {cash_range, {Cash, CashRange}}}} ->
{error, {terms_violation, {wallet_limit, {cash_range, {Cash, CashRange}}}}};
{error, {invalid_terms, _Details} = Reason} ->
erlang:error(Reason)
end.
%% Adjustment validators
-spec validate_adjustment_start(adjustment_params(), withdrawal_state()) ->
{ok, valid}
| {error, start_adjustment_error()}.
validate_adjustment_start(Params, Withdrawal) ->
do(fun() ->
valid = unwrap(validate_no_pending_adjustment(Withdrawal)),
valid = unwrap(validate_withdrawal_finish(Withdrawal)),
valid = unwrap(validate_status_change(Params, Withdrawal))
end).
-spec validate_withdrawal_finish(withdrawal_state()) ->
{ok, valid}
| {error, {invalid_withdrawal_status, status()}}.
validate_withdrawal_finish(Withdrawal) ->
case is_finished(Withdrawal) of
true ->
{ok, valid};
false ->
{error, {invalid_withdrawal_status, status(Withdrawal)}}
end.
-spec validate_no_pending_adjustment(withdrawal_state()) ->
{ok, valid}
| {error, {another_adjustment_in_progress, adjustment_id()}}.
validate_no_pending_adjustment(Withdrawal) ->
case ff_adjustment_utils:get_not_finished(adjustments_index(Withdrawal)) of
error ->
{ok, valid};
{ok, AdjustmentID} ->
{error, {another_adjustment_in_progress, AdjustmentID}}
end.
-spec validate_status_change(adjustment_params(), withdrawal_state()) ->
{ok, valid}
| {error, invalid_status_change_error()}.
validate_status_change(#{change := {change_status, Status}}, Withdrawal) ->
do(fun() ->
valid = unwrap(invalid_status_change, validate_target_status(Status)),
valid = unwrap(invalid_status_change, validate_change_same_status(Status, status(Withdrawal)))
end);
validate_status_change(_Params, _Withdrawal) ->
{ok, valid}.
-spec validate_target_status(status()) ->
{ok, valid}
| {error, {unavailable_status, status()}}.
validate_target_status(succeeded) ->
{ok, valid};
validate_target_status({failed, _Failure}) ->
{ok, valid};
validate_target_status(Status) ->
{error, {unavailable_status, Status}}.
-spec validate_change_same_status(status(), status()) ->
{ok, valid}
| {error, {already_has_status, status()}}.
validate_change_same_status(NewStatus, OldStatus) when NewStatus =/= OldStatus ->
{ok, valid};
validate_change_same_status(Status, Status) ->
{error, {already_has_status, Status}}.
%% Adjustment helpers
-spec apply_adjustment_event(wrapped_adjustment_event(), withdrawal_state()) -> withdrawal_state().
apply_adjustment_event(WrappedEvent, Withdrawal) ->
Adjustments0 = adjustments_index(Withdrawal),
Adjustments1 = ff_adjustment_utils:apply_event(WrappedEvent, Adjustments0),
set_adjustments_index(Adjustments1, Withdrawal).
-spec make_adjustment_params(adjustment_params(), withdrawal_state()) -> ff_adjustment:params().
make_adjustment_params(Params, Withdrawal) ->
#{id := ID, change := Change} = Params,
genlib_map:compact(#{
id => ID,
changes_plan => make_adjustment_change(Change, Withdrawal),
external_id => genlib_map:get(external_id, Params),
domain_revision => operation_domain_revision(Withdrawal),
party_revision => operation_party_revision(Withdrawal),
operation_timestamp => operation_timestamp(Withdrawal)
}).
-spec make_adjustment_change(adjustment_change(), withdrawal_state()) -> ff_adjustment:changes().
make_adjustment_change({change_status, NewStatus}, Withdrawal) ->
CurrentStatus = status(Withdrawal),
make_change_status_params(CurrentStatus, NewStatus, Withdrawal).
-spec make_change_status_params(status(), status(), withdrawal_state()) -> ff_adjustment:changes().
make_change_status_params(succeeded, {failed, _} = NewStatus, Withdrawal) ->
CurrentCashFlow = effective_final_cash_flow(Withdrawal),
NewCashFlow = ff_cash_flow:make_empty_final(),
#{
new_status => #{
new_status => NewStatus
},
new_cash_flow => #{
old_cash_flow_inverted => ff_cash_flow:inverse(CurrentCashFlow),
new_cash_flow => NewCashFlow
}
};
make_change_status_params({failed, _}, succeeded = NewStatus, Withdrawal) ->
CurrentCashFlow = effective_final_cash_flow(Withdrawal),
NewCashFlow = make_final_cash_flow(Withdrawal),
#{
new_status => #{
new_status => NewStatus
},
new_cash_flow => #{
old_cash_flow_inverted => ff_cash_flow:inverse(CurrentCashFlow),
new_cash_flow => NewCashFlow
}
};
make_change_status_params({failed, _}, {failed, _} = NewStatus, _Withdrawal) ->
#{
new_status => #{
new_status => NewStatus
}
}.
-spec process_adjustment(withdrawal_state()) -> process_result().
process_adjustment(Withdrawal) ->
#{
action := Action,
events := Events0,
changes := Changes
} = ff_adjustment_utils:process_adjustments(adjustments_index(Withdrawal)),
Events1 = Events0 ++ handle_adjustment_changes(Changes),
handle_child_result({Action, Events1}, Withdrawal).
-spec process_route_change(withdrawal_state(), fail_type()) -> process_result().
process_route_change(Withdrawal, Reason) ->
case is_failure_transient(Reason, Withdrawal) of
true ->
{ok, Providers} = do_process_routing(Withdrawal),
do_process_route_change(Providers, Withdrawal, Reason);
false ->
process_transfer_fail(Reason, Withdrawal)
end.
-spec is_failure_transient(fail_type(), withdrawal_state()) -> boolean().
is_failure_transient(Reason, Withdrawal) ->
{ok, Wallet} = get_wallet(wallet_id(Withdrawal)),
PartyID = ff_identity:party(get_wallet_identity(Wallet)),
RetryableErrors = get_retryable_error_list(PartyID),
ErrorTokens = to_error_token_list(Reason, Withdrawal),
match_error_whitelist(ErrorTokens, RetryableErrors).
-spec get_retryable_error_list(party_id()) -> list(list(binary())).
get_retryable_error_list(PartyID) ->
WithdrawalConfig = genlib_app:env(ff_transfer, withdrawal, #{}),
PartyRetryableErrors = maps:get(party_transient_errors, WithdrawalConfig, #{}),
Errors =
case maps:get(PartyID, PartyRetryableErrors, undefined) of
undefined ->
maps:get(default_transient_errors, WithdrawalConfig, []);
ErrorList ->
ErrorList
end,
binaries_to_error_tokens(Errors).
-spec binaries_to_error_tokens(list(binary())) -> list(list(binary())).
binaries_to_error_tokens(Errors) ->
lists:map(
fun(Error) ->
binary:split(Error, <<":">>, [global])
end,
Errors
).
-spec to_error_token_list(fail_type(), withdrawal_state()) -> list(binary()).
to_error_token_list(Reason, Withdrawal) ->
Failure = build_failure(Reason, Withdrawal),
failure_to_error_token_list(Failure).
-spec failure_to_error_token_list(ff_failure:failure()) -> list(binary()).
failure_to_error_token_list(#{code := Code, sub := SubFailure}) ->
SubFailureList = failure_to_error_token_list(SubFailure),
[Code | SubFailureList];
failure_to_error_token_list(#{code := Code}) ->
[Code].
-spec match_error_whitelist(list(binary()), list(list(binary()))) -> boolean().
match_error_whitelist(ErrorTokens, RetryableErrors) ->
lists:any(
fun(RetryableError) ->
error_tokens_match(ErrorTokens, RetryableError)
end,
RetryableErrors
).
-spec error_tokens_match(list(binary()), list(binary())) -> boolean().
error_tokens_match(_, []) ->
true;
error_tokens_match([], [_ | _]) ->
false;
error_tokens_match([Token0 | Rest0], [Token1 | Rest1]) when Token0 =:= Token1 ->
error_tokens_match(Rest0, Rest1);
error_tokens_match([Token0 | _], [Token1 | _]) when Token0 =/= Token1 ->
false.
-spec do_process_route_change([route()], withdrawal_state(), fail_type()) -> process_result().
do_process_route_change(Routes, Withdrawal, Reason) ->
Attempts = attempts(Withdrawal),
AttemptLimit = get_attempt_limit(Withdrawal),
case ff_withdrawal_route_attempt_utils:next_route(Routes, Attempts, AttemptLimit) of
{ok, Route} ->
{continue, [
{route_changed, Route}
]};
{error, route_not_found} ->
%% No more routes, return last error
process_transfer_fail(Reason, Withdrawal);
{error, attempt_limit_exceeded} ->
%% Attempt limit exceeded, return last error
process_transfer_fail(Reason, Withdrawal)
end.
-spec handle_adjustment_changes(ff_adjustment:changes()) -> [event()].
handle_adjustment_changes(Changes) ->
StatusChange = maps:get(new_status, Changes, undefined),
handle_adjustment_status_change(StatusChange).
-spec handle_adjustment_status_change(ff_adjustment:status_change() | undefined) -> [event()].
handle_adjustment_status_change(undefined) ->
[];
handle_adjustment_status_change(#{new_status := Status}) ->
[{status_changed, Status}].
-spec save_adjustable_info(event(), withdrawal_state()) -> withdrawal_state().
save_adjustable_info({p_transfer, {status_changed, committed}}, Withdrawal) ->
CashFlow = ff_postings_transfer:final_cash_flow(p_transfer(Withdrawal)),
update_adjusment_index(fun ff_adjustment_utils:set_cash_flow/2, CashFlow, Withdrawal);
save_adjustable_info(_Ev, Withdrawal) ->
Withdrawal.
-spec update_adjusment_index(Updater, Value, withdrawal_state()) -> withdrawal_state() when
Updater :: fun((Value, adjustments_index()) -> adjustments_index()),
Value :: any().
update_adjusment_index(Updater, Value, Withdrawal) ->
Index = adjustments_index(Withdrawal),
set_adjustments_index(Updater(Value, Index), Withdrawal).
%% Failure helpers
-spec build_failure(fail_type(), withdrawal_state()) -> failure().
build_failure(limit_check, Withdrawal) ->
{failed, Details} = limit_check_status(Withdrawal),
case Details of
{wallet_sender, _WalletLimitDetails} ->
#{
code => <<"account_limit_exceeded">>,
reason => genlib:format(Details),
sub => #{
code => <<"amount">>
}
}
end;
build_failure(route_not_found, _Withdrawal) ->
#{
code => <<"no_route_found">>
};
build_failure({inconsistent_quote_route, {Type, FoundID}}, Withdrawal) ->
Details =
{inconsistent_quote_route, #{
expected => {Type, FoundID},
found => get_quote_field(Type, quote(Withdrawal))
}},
#{
code => <<"unknown">>,
reason => genlib:format(Details)
};
build_failure(session, Withdrawal) ->
Result = get_session_result(Withdrawal),
{failed, Failure} = Result,
Failure.
get_quote_field(provider_id, #{route := Route}) ->
ff_withdrawal_routing:get_provider(Route);
get_quote_field(terminal_id, #{route := Route}) ->
ff_withdrawal_routing:get_terminal(Route).
%%
-spec apply_event(event() | legacy_event(), ff_maybe:maybe(withdrawal_state())) -> withdrawal_state().
apply_event(Ev, T0) ->
T1 = apply_event_(Ev, T0),
T2 = save_adjustable_info(Ev, T1),
T2.
-spec apply_event_(event(), ff_maybe:maybe(withdrawal_state())) -> withdrawal_state().
apply_event_({created, T}, undefined) ->
make_state(T);
apply_event_({status_changed, Status}, T) ->
maps:put(status, Status, T);
apply_event_({resource_got, Resource}, T) ->
maps:put(resource, Resource, T);
apply_event_({limit_check, Details}, T) ->
add_limit_check(Details, T);
apply_event_({p_transfer, Ev}, T) ->
Tr = ff_postings_transfer:apply_event(Ev, p_transfer(T)),
Attempts = attempts(T),
R = ff_withdrawal_route_attempt_utils:update_current_p_transfer(Tr, Attempts),
update_attempts(R, T);
apply_event_({session_started, SessionID}, T) ->
Session = #{id => SessionID},
Attempts = attempts(T),
R = ff_withdrawal_route_attempt_utils:update_current_session(Session, Attempts),
update_attempts(R, T);
apply_event_({session_finished, {SessionID, Result}}, T) ->
Attempts = attempts(T),
Session = ff_withdrawal_route_attempt_utils:get_current_session(Attempts),
SessionID = maps:get(id, Session),
UpdSession = Session#{result => Result},
R = ff_withdrawal_route_attempt_utils:update_current_session(UpdSession, Attempts),
update_attempts(R, T);
apply_event_({route_changed, Route}, T) ->
Attempts = attempts(T),
R = ff_withdrawal_route_attempt_utils:new_route(Route, Attempts),
T#{
route => Route,
attempts => R
};
apply_event_({adjustment, _Ev} = Event, T) ->
apply_adjustment_event(Event, T).
-spec make_state(withdrawal()) -> withdrawal_state().
make_state(#{route := Route} = T) ->
Attempts = ff_withdrawal_route_attempt_utils:new(),
T#{
attempts => ff_withdrawal_route_attempt_utils:new_route(Route, Attempts)
};
make_state(T) when not is_map_key(route, T) ->
T.
get_attempt_limit(Withdrawal) ->
#{
body := Body,
params := #{
wallet_id := WalletID,
destination_id := DestinationID
},
created_at := Timestamp,
party_revision := PartyRevision,
domain_revision := DomainRevision,
resource := Resource
} = Withdrawal,
{ok, Wallet} = get_wallet(WalletID),
{ok, Destination} = get_destination(DestinationID),
Identity = get_wallet_identity(Wallet),
PartyID = ff_identity:party(Identity),
ContractID = ff_identity:contract(Identity),
VarsetParams = genlib_map:compact(#{
body => Body,
wallet_id => WalletID,
party_id => PartyID,
destination => Destination,
resource => Resource
}),
{ok, Terms} = ff_party:get_contract_terms(
PartyID,
ContractID,
build_party_varset(VarsetParams),
Timestamp,
PartyRevision,
DomainRevision
),
#domain_TermSet{wallets = WalletTerms} = Terms,
#domain_WalletServiceTerms{withdrawals = WithdrawalTerms} = WalletTerms,
#domain_WithdrawalServiceTerms{attempt_limit = AttemptLimit} = WithdrawalTerms,
get_attempt_limit_(AttemptLimit).
get_attempt_limit_(undefined) ->
%% When attempt_limit is undefined
%% do not try all defined providers, if any
just stop after first one
1;
get_attempt_limit_({value, Limit}) ->
ff_dmsl_codec:unmarshal(attempt_limit, Limit).
%% Tests
-ifdef(TEST).
-include_lib("eunit/include/eunit.hrl").
-spec test() -> _.
-spec match_error_whitelist_test() -> _.
match_error_whitelist_test() ->
ErrorWhitelist = binaries_to_error_tokens([
<<"some:test:error">>,
<<"another:test:error">>,
<<"wide">>
]),
?assertEqual(
false,
match_error_whitelist(
[<<>>],
ErrorWhitelist
)
),
?assertEqual(
false,
match_error_whitelist(
[<<"some">>, <<"completely">>, <<"different">>, <<"error">>],
ErrorWhitelist
)
),
?assertEqual(
false,
match_error_whitelist(
[<<"some">>, <<"test">>],
ErrorWhitelist
)
),
?assertEqual(
false,
match_error_whitelist(
[<<"wider">>],
ErrorWhitelist
)
),
?assertEqual(
true,
match_error_whitelist(
[<<"some">>, <<"test">>, <<"error">>],
ErrorWhitelist
)
),
?assertEqual(
true,
match_error_whitelist(
[<<"another">>, <<"test">>, <<"error">>, <<"that">>, <<"is">>, <<"more">>, <<"specific">>],
ErrorWhitelist
)
).
-endif.
| null | https://raw.githubusercontent.com/rbkmoney/fistful-server/2be57c4e9fe1a2bf2b2143da158a0f43d4a96dfc/apps/ff_transfer/src/ff_withdrawal.erl | erlang |
Withdrawal
Transfer logic callbacks
API
Event source
Internal types
Legacy activity
API
Transfer callbacks
Internals
Internal getters
Processing helpers
Backward compatibility legacy case for old withrawals without terminals
Quote helpers
Session management
Withdrawal validators
Limit helpers
Adjustment validators
Adjustment helpers
No more routes, return last error
Attempt limit exceeded, return last error
Failure helpers
When attempt_limit is undefined
do not try all defined providers, if any
Tests |
-module(ff_withdrawal).
-include_lib("damsel/include/dmsl_payment_processing_thrift.hrl").
-include_lib("damsel/include/dmsl_withdrawals_provider_adapter_thrift.hrl").
-type id() :: binary().
-type clock() :: ff_transaction:clock().
-define(ACTUAL_FORMAT_VERSION, 4).
-opaque withdrawal_state() :: #{
id := id(),
transfer_type := withdrawal,
body := body(),
params := transfer_params(),
created_at => ff_time:timestamp_ms(),
party_revision => party_revision(),
domain_revision => domain_revision(),
route => route(),
attempts => attempts(),
resource => destination_resource(),
adjustments => adjustments_index(),
status => status(),
metadata => metadata(),
external_id => id()
}.
-opaque withdrawal() :: #{
version := ?ACTUAL_FORMAT_VERSION,
id := id(),
transfer_type := withdrawal,
body := body(),
params := transfer_params(),
created_at => ff_time:timestamp_ms(),
party_revision => party_revision(),
domain_revision => domain_revision(),
route => route(),
metadata => metadata(),
external_id => id()
}.
-type params() :: #{
id := id(),
wallet_id := ff_wallet_machine:id(),
destination_id := ff_destination:id(),
body := body(),
external_id => id(),
quote => quote(),
metadata => metadata()
}.
-type status() ::
pending
| succeeded
| {failed, failure()}.
-type event() ::
{created, withdrawal()}
| {resource_got, destination_resource()}
| {route_changed, route()}
| {p_transfer, ff_postings_transfer:event()}
| {limit_check, limit_check_details()}
| {session_started, session_id()}
| {session_finished, {session_id(), session_result()}}
| {status_changed, status()}
| wrapped_adjustment_event().
-type create_error() ::
{wallet, notfound}
| {destination, notfound | unauthorized}
| {wallet, ff_wallet:inaccessibility()}
| {inconsistent_currency, {Withdrawal :: currency_id(), Wallet :: currency_id(), Destination :: currency_id()}}
| {terms, ff_party:validate_withdrawal_creation_error()}
| {identity_providers_mismatch, {ff_provider:id(), ff_provider:id()}}
| {destination_resource, {bin_data, ff_bin_data:bin_data_error()}}.
-type route() :: ff_withdrawal_routing:route().
-type attempts() :: ff_withdrawal_route_attempt_utils:attempts().
-type quote_params() :: #{
wallet_id := ff_wallet_machine:id(),
currency_from := ff_currency:id(),
currency_to := ff_currency:id(),
body := ff_transaction:body(),
destination_id => ff_destination:id(),
external_id => id()
}.
-type quote() :: #{
cash_from := cash(),
cash_to := cash(),
created_at := binary(),
expires_on := binary(),
quote_data := ff_adapter_withdrawal:quote_data(),
route := route(),
operation_timestamp := ff_time:timestamp_ms(),
resource_descriptor => resource_descriptor(),
domain_revision => party_revision(),
party_revision => domain_revision()
}.
-type quote_state() :: #{
cash_from := cash(),
cash_to := cash(),
created_at := binary(),
expires_on := binary(),
quote_data := ff_adapter_withdrawal:quote_data(),
route := route(),
resource_descriptor => resource_descriptor()
}.
-type session() :: #{
id := session_id(),
result => session_result()
}.
-type gen_args() :: #{
id := id(),
body := body(),
params := params(),
transfer_type := withdrawal,
status => status(),
route => route(),
external_id => external_id(),
created_at => ff_time:timestamp_ms(),
party_revision => party_revision(),
domain_revision => domain_revision(),
metadata => metadata()
}.
-type limit_check_details() ::
{wallet_sender, wallet_limit_check_details()}.
-type wallet_limit_check_details() ::
ok
| {failed, wallet_limit_check_error()}.
-type wallet_limit_check_error() :: #{
expected_range := cash_range(),
balance := cash()
}.
-type adjustment_params() :: #{
id := adjustment_id(),
change := adjustment_change(),
external_id => id()
}.
-type adjustment_change() ::
{change_status, status()}.
-type start_adjustment_error() ::
invalid_withdrawal_status_error()
| invalid_status_change_error()
| {another_adjustment_in_progress, adjustment_id()}
| ff_adjustment:create_error().
-type unknown_adjustment_error() :: ff_adjustment_utils:unknown_adjustment_error().
-type invalid_status_change_error() ::
{invalid_status_change, {unavailable_status, status()}}
| {invalid_status_change, {already_has_status, status()}}.
-type invalid_withdrawal_status_error() ::
{invalid_withdrawal_status, status()}.
-type action() :: sleep | continue | undefined.
-export_type([withdrawal/0]).
-export_type([withdrawal_state/0]).
-export_type([id/0]).
-export_type([params/0]).
-export_type([event/0]).
-export_type([route/0]).
-export_type([quote/0]).
-export_type([quote_params/0]).
-export_type([session/0]).
-export_type([gen_args/0]).
-export_type([create_error/0]).
-export_type([action/0]).
-export_type([adjustment_params/0]).
-export_type([start_adjustment_error/0]).
-export_type([limit_check_details/0]).
-export([process_transfer/1]).
-export([process_session_finished/3]).
Accessors
-export([wallet_id/1]).
-export([destination_id/1]).
-export([quote/1]).
-export([id/1]).
-export([body/1]).
-export([status/1]).
-export([route/1]).
-export([attempts/1]).
-export([external_id/1]).
-export([created_at/1]).
-export([party_revision/1]).
-export([domain_revision/1]).
-export([destination_resource/1]).
-export([metadata/1]).
-export([create/1]).
-export([gen/1]).
-export([get_quote/1]).
-export([is_finished/1]).
-export([start_adjustment/2]).
-export([find_adjustment/2]).
-export([adjustments/1]).
-export([effective_final_cash_flow/1]).
-export([sessions/1]).
-export([session_id/1]).
-export([get_current_session/1]).
-export([get_current_session_status/1]).
-export([apply_event/2]).
Pipeline
-import(ff_pipeline, [do/1, unwrap/1, unwrap/2]).
-type body() :: ff_transaction:body().
-type identity() :: ff_identity:identity_state().
-type party_id() :: ff_party:id().
-type wallet_id() :: ff_wallet:id().
-type wallet() :: ff_wallet:wallet_state().
-type destination_id() :: ff_destination:id().
-type destination() :: ff_destination:destination_state().
-type process_result() :: {action(), [event()]}.
-type final_cash_flow() :: ff_cash_flow:final_cash_flow().
-type external_id() :: id() | undefined.
-type p_transfer() :: ff_postings_transfer:transfer().
-type session_id() :: id().
-type destination_resource() :: ff_destination:resource().
-type bin_data() :: ff_bin_data:bin_data().
-type cash() :: ff_cash:cash().
-type cash_range() :: ff_range:range(cash()).
-type failure() :: ff_failure:failure().
-type session_result() :: ff_withdrawal_session:session_result().
-type adjustment() :: ff_adjustment:adjustment().
-type adjustment_id() :: ff_adjustment:id().
-type adjustments_index() :: ff_adjustment_utils:index().
-type currency_id() :: ff_currency:id().
-type party_revision() :: ff_party:revision().
-type domain_revision() :: ff_domain_config:revision().
-type terms() :: ff_party:terms().
-type party_varset() :: ff_varset:varset().
-type metadata() :: ff_entity_context:md().
-type resource_descriptor() :: ff_resource:resource_descriptor().
-type wrapped_adjustment_event() :: ff_adjustment_utils:wrapped_event().
-type provider_id() :: ff_payouts_provider:id().
-type terminal_id() :: ff_payouts_terminal:id().
-type legacy_event() :: any().
-type transfer_params() :: #{
wallet_id := wallet_id(),
destination_id := destination_id(),
quote => quote_state()
}.
-type party_varset_params() :: #{
body := body(),
wallet_id := wallet_id(),
party_id := party_id(),
destination => destination(),
resource => destination_resource(),
bin_data := bin_data()
}.
-type activity() ::
routing
| p_transfer_start
| p_transfer_prepare
| session_starting
| session_sleeping
| p_transfer_commit
| p_transfer_cancel
| limit_check
| {fail, fail_type()}
| adjustment
| stop
| finish.
-type fail_type() ::
limit_check
| route_not_found
| {inconsistent_quote_route, {provider_id, provider_id()} | {terminal_id, terminal_id()}}
| session.
-type session_processing_status() :: undefined | pending | succeeded | failed.
Accessors
-spec wallet_id(withdrawal_state()) -> wallet_id().
wallet_id(T) ->
maps:get(wallet_id, params(T)).
-spec destination_id(withdrawal_state()) -> destination_id().
destination_id(T) ->
maps:get(destination_id, params(T)).
-spec destination_resource(withdrawal_state()) -> destination_resource().
destination_resource(#{resource := Resource}) ->
Resource;
destination_resource(Withdrawal) ->
DestinationID = destination_id(Withdrawal),
{ok, DestinationMachine} = ff_destination_machine:get(DestinationID),
Destination = ff_destination_machine:destination(DestinationMachine),
{ok, Resource} = ff_resource:create_resource(ff_destination:resource(Destination)),
Resource.
-spec quote(withdrawal_state()) -> quote_state() | undefined.
quote(T) ->
maps:get(quote, params(T), undefined).
-spec id(withdrawal_state()) -> id().
id(#{id := V}) ->
V.
-spec body(withdrawal_state()) -> body().
body(#{body := V}) ->
V.
-spec status(withdrawal_state()) -> status() | undefined.
status(T) ->
maps:get(status, T, undefined).
-spec route(withdrawal_state()) -> route() | undefined.
route(T) ->
maps:get(route, T, undefined).
-spec attempts(withdrawal_state()) -> attempts().
attempts(#{attempts := Attempts}) ->
Attempts;
attempts(T) when not is_map_key(attempts, T) ->
ff_withdrawal_route_attempt_utils:new().
-spec external_id(withdrawal_state()) -> external_id() | undefined.
external_id(T) ->
maps:get(external_id, T, undefined).
-spec party_revision(withdrawal_state()) -> party_revision() | undefined.
party_revision(T) ->
maps:get(party_revision, T, undefined).
-spec domain_revision(withdrawal_state()) -> domain_revision() | undefined.
domain_revision(T) ->
maps:get(domain_revision, T, undefined).
-spec created_at(withdrawal_state()) -> ff_time:timestamp_ms() | undefined.
created_at(T) ->
maps:get(created_at, T, undefined).
-spec metadata(withdrawal_state()) -> metadata() | undefined.
metadata(T) ->
maps:get(metadata, T, undefined).
-spec gen(gen_args()) -> withdrawal().
gen(Args) ->
TypeKeys = [
id,
transfer_type,
body,
params,
external_id,
domain_revision,
party_revision,
created_at,
route,
metadata
],
Withdrawal = genlib_map:compact(maps:with(TypeKeys, Args)),
Withdrawal#{version => 4}.
-spec create(params()) ->
{ok, [event()]}
| {error, create_error()}.
create(Params) ->
do(fun() ->
#{id := ID, wallet_id := WalletID, destination_id := DestinationID, body := Body} = Params,
CreatedAt = ff_time:now(),
Quote = maps:get(quote, Params, undefined),
ResourceDescriptor = quote_resource_descriptor(Quote),
Timestamp = ff_maybe:get_defined(quote_timestamp(Quote), CreatedAt),
DomainRevision = ensure_domain_revision_defined(quote_domain_revision(Quote)),
Wallet = unwrap(wallet, get_wallet(WalletID)),
accessible = unwrap(wallet, ff_wallet:is_accessible(Wallet)),
Identity = get_wallet_identity(Wallet),
Destination = unwrap(destination, get_destination(DestinationID)),
ResourceParams = ff_destination:resource(Destination),
Resource = unwrap(
destination_resource,
create_resource(ResourceParams, ResourceDescriptor, Identity, DomainRevision)
),
PartyID = ff_identity:party(Identity),
VarsetParams = genlib_map:compact(#{
body => Body,
wallet_id => WalletID,
party_id => PartyID,
destination => Destination,
resource => Resource
}),
Varset = build_party_varset(VarsetParams),
PartyRevision = ensure_party_revision_defined(PartyID, quote_party_revision(Quote)),
ContractID = ff_identity:contract(Identity),
{ok, Terms} = ff_party:get_contract_terms(
PartyID,
ContractID,
Varset,
Timestamp,
PartyRevision,
DomainRevision
),
valid = unwrap(validate_withdrawal_creation(Terms, Body, Wallet, Destination)),
TransferParams = genlib_map:compact(#{
wallet_id => WalletID,
destination_id => DestinationID,
quote => Quote
}),
[
{created,
genlib_map:compact(#{
version => ?ACTUAL_FORMAT_VERSION,
id => ID,
transfer_type => withdrawal,
body => Body,
params => TransferParams,
created_at => CreatedAt,
party_revision => PartyRevision,
domain_revision => DomainRevision,
external_id => maps:get(external_id, Params, undefined),
metadata => maps:get(metadata, Params, undefined)
})},
{status_changed, pending},
{resource_got, Resource}
]
end).
create_resource(
{bank_card, #{bank_card := #{token := Token}} = ResourceBankCardParams},
ResourceDescriptor,
Identity,
DomainRevision
) ->
case ff_resource:get_bin_data(Token, ResourceDescriptor) of
{ok, BinData} ->
Varset = #{
bin_data => ff_dmsl_codec:marshal(bin_data, BinData)
},
{ok, PaymentInstitution} = get_payment_institution(Identity, Varset, DomainRevision),
PaymentSystem = unwrap(ff_payment_institution:payment_system(PaymentInstitution)),
ff_resource:create_bank_card_basic(ResourceBankCardParams, BinData, PaymentSystem);
{error, Error} ->
{error, {bin_data, Error}}
end;
create_resource(ResourceParams, ResourceDescriptor, _Identity, _DomainRevision) ->
ff_resource:create_resource(ResourceParams, ResourceDescriptor).
-spec start_adjustment(adjustment_params(), withdrawal_state()) ->
{ok, process_result()}
| {error, start_adjustment_error()}.
start_adjustment(Params, Withdrawal) ->
#{id := AdjustmentID} = Params,
case find_adjustment(AdjustmentID, Withdrawal) of
{error, {unknown_adjustment, _}} ->
do_start_adjustment(Params, Withdrawal);
{ok, _Adjustment} ->
{ok, {undefined, []}}
end.
-spec find_adjustment(adjustment_id(), withdrawal_state()) -> {ok, adjustment()} | {error, unknown_adjustment_error()}.
find_adjustment(AdjustmentID, Withdrawal) ->
ff_adjustment_utils:get_by_id(AdjustmentID, adjustments_index(Withdrawal)).
-spec adjustments(withdrawal_state()) -> [adjustment()].
adjustments(Withdrawal) ->
ff_adjustment_utils:adjustments(adjustments_index(Withdrawal)).
-spec effective_final_cash_flow(withdrawal_state()) -> final_cash_flow().
effective_final_cash_flow(Withdrawal) ->
case ff_adjustment_utils:cash_flow(adjustments_index(Withdrawal)) of
undefined ->
ff_cash_flow:make_empty_final();
CashFlow ->
CashFlow
end.
-spec sessions(withdrawal_state()) -> [session()].
sessions(Withdrawal) ->
ff_withdrawal_route_attempt_utils:get_sessions(attempts(Withdrawal)).
Сущность в каких - то действий
-spec is_active(withdrawal_state()) -> boolean().
is_active(#{status := succeeded} = Withdrawal) ->
is_childs_active(Withdrawal);
is_active(#{status := {failed, _}} = Withdrawal) ->
is_childs_active(Withdrawal);
is_active(#{status := pending}) ->
true.
Сущность завершила свою основную задачу по переводу денег . Дальше её состояние будет меняться только
изменением дочерних сущностей , например запуском adjustment .
-spec is_finished(withdrawal_state()) -> boolean().
is_finished(#{status := succeeded}) ->
true;
is_finished(#{status := {failed, _}}) ->
true;
is_finished(#{status := pending}) ->
false.
-spec process_transfer(withdrawal_state()) -> process_result().
process_transfer(Withdrawal) ->
Activity = deduce_activity(Withdrawal),
do_process_transfer(Activity, Withdrawal).
-spec process_session_finished(session_id(), session_result(), withdrawal_state()) ->
{ok, process_result()} | {error, session_not_found | old_session | result_mismatch}.
process_session_finished(SessionID, SessionResult, Withdrawal) ->
case get_session_by_id(SessionID, Withdrawal) of
#{id := SessionID, result := SessionResult} ->
{ok, {undefined, []}};
#{id := SessionID, result := _OtherSessionResult} ->
{error, result_mismatch};
#{id := SessionID} ->
try_finish_session(SessionID, SessionResult, Withdrawal);
undefined ->
{error, session_not_found}
end.
-spec get_session_by_id(session_id(), withdrawal_state()) -> session() | undefined.
get_session_by_id(SessionID, Withdrawal) ->
Sessions = ff_withdrawal_route_attempt_utils:get_sessions(attempts(Withdrawal)),
case lists:filter(fun(#{id := SessionID0}) -> SessionID0 =:= SessionID end, Sessions) of
[Session] -> Session;
[] -> undefined
end.
-spec try_finish_session(session_id(), session_result(), withdrawal_state()) ->
{ok, process_result()} | {error, old_session}.
try_finish_session(SessionID, SessionResult, Withdrawal) ->
case is_current_session(SessionID, Withdrawal) of
true ->
{ok, {continue, [{session_finished, {SessionID, SessionResult}}]}};
false ->
{error, old_session}
end.
-spec is_current_session(session_id(), withdrawal_state()) -> boolean().
is_current_session(SessionID, Withdrawal) ->
case session_id(Withdrawal) of
SessionID ->
true;
_ ->
false
end.
-spec do_start_adjustment(adjustment_params(), withdrawal_state()) ->
{ok, process_result()}
| {error, start_adjustment_error()}.
do_start_adjustment(Params, Withdrawal) ->
do(fun() ->
valid = unwrap(validate_adjustment_start(Params, Withdrawal)),
AdjustmentParams = make_adjustment_params(Params, Withdrawal),
#{id := AdjustmentID} = Params,
{Action, Events} = unwrap(ff_adjustment:create(AdjustmentParams)),
{Action, ff_adjustment_utils:wrap_events(AdjustmentID, Events)}
end).
-spec update_attempts(attempts(), withdrawal_state()) -> withdrawal_state().
update_attempts(Attempts, T) ->
maps:put(attempts, Attempts, T).
-spec params(withdrawal_state()) -> transfer_params().
params(#{params := V}) ->
V.
-spec p_transfer(withdrawal_state()) -> p_transfer() | undefined.
p_transfer(Withdrawal) ->
ff_withdrawal_route_attempt_utils:get_current_p_transfer(attempts(Withdrawal)).
p_transfer_status(Withdrawal) ->
case p_transfer(Withdrawal) of
undefined ->
undefined;
Transfer ->
ff_postings_transfer:status(Transfer)
end.
-spec route_selection_status(withdrawal_state()) -> unknown | found.
route_selection_status(Withdrawal) ->
case route(Withdrawal) of
undefined ->
unknown;
_Known ->
found
end.
-spec adjustments_index(withdrawal_state()) -> adjustments_index().
adjustments_index(Withdrawal) ->
case maps:find(adjustments, Withdrawal) of
{ok, Adjustments} ->
Adjustments;
error ->
ff_adjustment_utils:new_index()
end.
-spec set_adjustments_index(adjustments_index(), withdrawal_state()) -> withdrawal_state().
set_adjustments_index(Adjustments, Withdrawal) ->
Withdrawal#{adjustments => Adjustments}.
-spec operation_timestamp(withdrawal_state()) -> ff_time:timestamp_ms().
operation_timestamp(Withdrawal) ->
QuoteTimestamp = quote_timestamp(quote(Withdrawal)),
ff_maybe:get_defined([QuoteTimestamp, created_at(Withdrawal), ff_time:now()]).
-spec operation_party_revision(withdrawal_state()) -> domain_revision().
operation_party_revision(Withdrawal) ->
case party_revision(Withdrawal) of
undefined ->
{ok, Wallet} = get_wallet(wallet_id(Withdrawal)),
PartyID = ff_identity:party(get_wallet_identity(Wallet)),
{ok, Revision} = ff_party:get_revision(PartyID),
Revision;
Revision ->
Revision
end.
-spec operation_domain_revision(withdrawal_state()) -> domain_revision().
operation_domain_revision(Withdrawal) ->
case domain_revision(Withdrawal) of
undefined ->
ff_domain_config:head();
Revision ->
Revision
end.
-spec deduce_activity(withdrawal_state()) -> activity().
deduce_activity(Withdrawal) ->
Params = #{
route => route_selection_status(Withdrawal),
p_transfer => p_transfer_status(Withdrawal),
session => get_current_session_status(Withdrawal),
status => status(Withdrawal),
limit_check => limit_check_processing_status(Withdrawal),
active_adjustment => ff_adjustment_utils:is_active(adjustments_index(Withdrawal))
},
do_deduce_activity(Params).
do_deduce_activity(#{status := pending} = Params) ->
do_pending_activity(Params);
do_deduce_activity(#{status := succeeded} = Params) ->
do_finished_activity(Params);
do_deduce_activity(#{status := {failed, _}} = Params) ->
do_finished_activity(Params).
do_pending_activity(#{route := unknown, p_transfer := undefined}) ->
routing;
do_pending_activity(#{route := found, p_transfer := undefined}) ->
p_transfer_start;
do_pending_activity(#{p_transfer := created}) ->
p_transfer_prepare;
do_pending_activity(#{p_transfer := prepared, limit_check := unknown}) ->
limit_check;
do_pending_activity(#{p_transfer := prepared, limit_check := ok, session := undefined}) ->
session_starting;
do_pending_activity(#{p_transfer := prepared, limit_check := failed}) ->
p_transfer_cancel;
do_pending_activity(#{p_transfer := cancelled, limit_check := failed}) ->
{fail, limit_check};
do_pending_activity(#{p_transfer := prepared, session := pending}) ->
session_sleeping;
do_pending_activity(#{p_transfer := prepared, session := succeeded}) ->
p_transfer_commit;
do_pending_activity(#{p_transfer := committed, session := succeeded}) ->
finish;
do_pending_activity(#{p_transfer := prepared, session := failed}) ->
p_transfer_cancel;
do_pending_activity(#{p_transfer := cancelled, session := failed}) ->
{fail, session}.
do_finished_activity(#{active_adjustment := true}) ->
adjustment;
Legacy activity . Remove after first deployment
do_finished_activity(#{status := {failed, _}, p_transfer := prepared}) ->
p_transfer_cancel;
do_finished_activity(#{status := succeeded, p_transfer := prepared}) ->
p_transfer_commit;
do_finished_activity(#{status := succeeded, p_transfer := committed}) ->
stop;
do_finished_activity(#{status := {failed, _}, p_transfer := cancelled}) ->
stop.
-spec do_process_transfer(activity(), withdrawal_state()) -> process_result().
do_process_transfer(routing, Withdrawal) ->
process_routing(Withdrawal);
do_process_transfer(p_transfer_start, Withdrawal) ->
process_p_transfer_creation(Withdrawal);
do_process_transfer(p_transfer_prepare, Withdrawal) ->
Tr = ff_withdrawal_route_attempt_utils:get_current_p_transfer(attempts(Withdrawal)),
{ok, Events} = ff_postings_transfer:prepare(Tr),
{continue, [{p_transfer, Ev} || Ev <- Events]};
do_process_transfer(p_transfer_commit, Withdrawal) ->
Tr = ff_withdrawal_route_attempt_utils:get_current_p_transfer(attempts(Withdrawal)),
{ok, Events} = ff_postings_transfer:commit(Tr),
{continue, [{p_transfer, Ev} || Ev <- Events]};
do_process_transfer(p_transfer_cancel, Withdrawal) ->
Tr = ff_withdrawal_route_attempt_utils:get_current_p_transfer(attempts(Withdrawal)),
{ok, Events} = ff_postings_transfer:cancel(Tr),
{continue, [{p_transfer, Ev} || Ev <- Events]};
do_process_transfer(limit_check, Withdrawal) ->
process_limit_check(Withdrawal);
do_process_transfer(session_starting, Withdrawal) ->
process_session_creation(Withdrawal);
do_process_transfer(session_sleeping, Withdrawal) ->
process_session_sleep(Withdrawal);
do_process_transfer({fail, Reason}, Withdrawal) ->
process_route_change(Withdrawal, Reason);
do_process_transfer(finish, Withdrawal) ->
process_transfer_finish(Withdrawal);
do_process_transfer(adjustment, Withdrawal) ->
process_adjustment(Withdrawal);
do_process_transfer(stop, _Withdrawal) ->
{undefined, []}.
-spec process_routing(withdrawal_state()) -> process_result().
process_routing(Withdrawal) ->
case do_process_routing(Withdrawal) of
{ok, [Route | _]} ->
{continue, [
{route_changed, Route}
]};
{error, route_not_found} ->
process_transfer_fail(route_not_found, Withdrawal);
{error, {inconsistent_quote_route, _Data} = Reason} ->
process_transfer_fail(Reason, Withdrawal)
end.
-spec do_process_routing(withdrawal_state()) -> {ok, [route()]} | {error, Reason} when
Reason :: route_not_found | InconsistentQuote,
InconsistentQuote :: {inconsistent_quote_route, {provider_id, provider_id()} | {terminal_id, terminal_id()}}.
do_process_routing(Withdrawal) ->
WalletID = wallet_id(Withdrawal),
{ok, Wallet} = get_wallet(WalletID),
DomainRevision = operation_domain_revision(Withdrawal),
{ok, Destination} = get_destination(destination_id(Withdrawal)),
Resource = destination_resource(Withdrawal),
Identity = get_wallet_identity(Wallet),
PartyID = ff_identity:party(get_wallet_identity(Wallet)),
VarsetParams = genlib_map:compact(#{
body => body(Withdrawal),
wallet_id => WalletID,
wallet => Wallet,
party_id => PartyID,
destination => Destination,
resource => Resource
}),
do(fun() ->
Varset = build_party_varset(VarsetParams),
Routes = unwrap(ff_withdrawal_routing:prepare_routes(Varset, Identity, DomainRevision)),
case quote(Withdrawal) of
undefined ->
Routes;
Quote ->
Route = hd(Routes),
valid = unwrap(validate_quote_route(Route, Quote)),
[Route]
end
end).
-spec validate_quote_route(route(), quote_state()) -> {ok, valid} | {error, InconsistentQuote} when
InconsistentQuote :: {inconsistent_quote_route, {provider_id, provider_id()} | {terminal_id, terminal_id()}}.
validate_quote_route(Route, #{route := QuoteRoute}) ->
do(fun() ->
valid = unwrap(validate_quote_provider(Route, QuoteRoute)),
valid = unwrap(validate_quote_terminal(Route, QuoteRoute))
end).
validate_quote_provider(#{provider_id := ProviderID}, #{provider_id := ProviderID}) ->
{ok, valid};
validate_quote_provider(#{provider_id := ProviderID}, _) ->
{error, {inconsistent_quote_route, {provider_id, ProviderID}}}.
validate_quote_terminal(#{terminal_id := TerminalID}, #{terminal_id := TerminalID}) ->
{ok, valid};
validate_quote_terminal(#{terminal_id := TerminalID}, _) ->
{error, {inconsistent_quote_route, {terminal_id, TerminalID}}}.
-spec process_limit_check(withdrawal_state()) -> process_result().
process_limit_check(Withdrawal) ->
WalletID = wallet_id(Withdrawal),
{ok, Wallet} = get_wallet(WalletID),
DomainRevision = operation_domain_revision(Withdrawal),
{ok, Destination} = get_destination(destination_id(Withdrawal)),
Resource = destination_resource(Withdrawal),
Identity = get_wallet_identity(Wallet),
PartyID = ff_identity:party(get_wallet_identity(Wallet)),
PartyRevision = operation_party_revision(Withdrawal),
ContractID = ff_identity:contract(Identity),
Timestamp = operation_timestamp(Withdrawal),
VarsetParams = genlib_map:compact(#{
body => body(Withdrawal),
wallet_id => WalletID,
wallet => Wallet,
party_id => PartyID,
destination => Destination,
resource => Resource
}),
PartyVarset = build_party_varset(VarsetParams),
{ok, Terms} = ff_party:get_contract_terms(
PartyID,
ContractID,
PartyVarset,
Timestamp,
PartyRevision,
DomainRevision
),
Clock = ff_postings_transfer:clock(p_transfer(Withdrawal)),
Events =
case validate_wallet_limits(Terms, Wallet, Clock) of
{ok, valid} ->
[{limit_check, {wallet_sender, ok}}];
{error, {terms_violation, {wallet_limit, {cash_range, {Cash, Range}}}}} ->
Details = #{
expected_range => Range,
balance => Cash
},
[{limit_check, {wallet_sender, {failed, Details}}}]
end,
{continue, Events}.
-spec process_p_transfer_creation(withdrawal_state()) -> process_result().
process_p_transfer_creation(Withdrawal) ->
FinalCashFlow = make_final_cash_flow(Withdrawal),
PTransferID = construct_p_transfer_id(Withdrawal),
{ok, PostingsTransferEvents} = ff_postings_transfer:create(PTransferID, FinalCashFlow),
{continue, [{p_transfer, Ev} || Ev <- PostingsTransferEvents]}.
-spec process_session_creation(withdrawal_state()) -> process_result().
process_session_creation(Withdrawal) ->
ID = construct_session_id(Withdrawal),
#{
wallet_id := WalletID,
destination_id := DestinationID
} = params(Withdrawal),
{ok, WalletMachine} = ff_wallet_machine:get(WalletID),
Wallet = ff_wallet_machine:wallet(WalletMachine),
WalletAccount = ff_wallet:account(Wallet),
{ok, DestinationMachine} = ff_destination_machine:get(DestinationID),
Destination = ff_destination_machine:destination(DestinationMachine),
DestinationAccount = ff_destination:account(Destination),
Route = route(Withdrawal),
{ok, SenderSt} = ff_identity_machine:get(ff_account:identity(WalletAccount)),
{ok, ReceiverSt} = ff_identity_machine:get(ff_account:identity(DestinationAccount)),
TransferData = genlib_map:compact(#{
id => ID,
cash => body(Withdrawal),
sender => ff_identity_machine:identity(SenderSt),
receiver => ff_identity_machine:identity(ReceiverSt),
quote => build_session_quote(quote(Withdrawal))
}),
SessionParams = #{
withdrawal_id => id(Withdrawal),
resource => destination_resource(Withdrawal),
route => Route
},
ok = create_session(ID, TransferData, SessionParams),
{continue, [{session_started, ID}]}.
-spec construct_session_id(withdrawal_state()) -> id().
construct_session_id(Withdrawal) ->
ID = id(Withdrawal),
Attempt = ff_withdrawal_route_attempt_utils:get_attempt(attempts(Withdrawal)),
SubID = integer_to_binary(Attempt),
<<ID/binary, "/", SubID/binary>>.
-spec construct_p_transfer_id(withdrawal_state()) -> id().
construct_p_transfer_id(Withdrawal) ->
ID = id(Withdrawal),
Attempt = ff_withdrawal_route_attempt_utils:get_attempt(attempts(Withdrawal)),
SubID = integer_to_binary(Attempt),
<<"ff/withdrawal/", ID/binary, "/", SubID/binary>>.
create_session(ID, TransferData, SessionParams) ->
case ff_withdrawal_session_machine:create(ID, TransferData, SessionParams) of
ok ->
ok;
{error, exists} ->
ok
end.
-spec process_session_sleep(withdrawal_state()) -> process_result().
process_session_sleep(Withdrawal) ->
SessionID = session_id(Withdrawal),
{ok, SessionMachine} = ff_withdrawal_session_machine:get(SessionID),
Session = ff_withdrawal_session_machine:session(SessionMachine),
case ff_withdrawal_session:status(Session) of
active ->
{sleep, []};
{finished, _} ->
Result = ff_withdrawal_session:result(Session),
{continue, [{session_finished, {SessionID, Result}}]}
end.
-spec process_transfer_finish(withdrawal_state()) -> process_result().
process_transfer_finish(_Withdrawal) ->
{undefined, [{status_changed, succeeded}]}.
-spec process_transfer_fail(fail_type(), withdrawal_state()) -> process_result().
process_transfer_fail(FailType, Withdrawal) ->
Failure = build_failure(FailType, Withdrawal),
{undefined, [{status_changed, {failed, Failure}}]}.
-spec handle_child_result(process_result(), withdrawal_state()) -> process_result().
handle_child_result({undefined, Events} = Result, Withdrawal) ->
NextWithdrawal = lists:foldl(fun(E, Acc) -> apply_event(E, Acc) end, Withdrawal, Events),
case is_active(NextWithdrawal) of
true ->
{continue, Events};
false ->
Result
end;
handle_child_result({_OtherAction, _Events} = Result, _Withdrawal) ->
Result.
-spec is_childs_active(withdrawal_state()) -> boolean().
is_childs_active(Withdrawal) ->
ff_adjustment_utils:is_active(adjustments_index(Withdrawal)).
-spec make_final_cash_flow(withdrawal_state()) -> final_cash_flow().
make_final_cash_flow(Withdrawal) ->
Body = body(Withdrawal),
WalletID = wallet_id(Withdrawal),
{ok, Wallet} = get_wallet(WalletID),
Route = route(Withdrawal),
DomainRevision = operation_domain_revision(Withdrawal),
{ok, Destination} = get_destination(destination_id(Withdrawal)),
Resource = destination_resource(Withdrawal),
Identity = get_wallet_identity(Wallet),
PartyID = ff_identity:party(get_wallet_identity(Wallet)),
PartyRevision = operation_party_revision(Withdrawal),
ContractID = ff_identity:contract(Identity),
Timestamp = operation_timestamp(Withdrawal),
VarsetParams = genlib_map:compact(#{
body => body(Withdrawal),
wallet_id => WalletID,
wallet => Wallet,
party_id => PartyID,
destination => Destination,
resource => Resource
}),
PartyVarset = build_party_varset(VarsetParams),
WalletAccount = ff_wallet:account(Wallet),
DestinationAccount = ff_destination:account(Destination),
{_Amount, CurrencyID} = Body,
#{provider_id := ProviderID} = Route,
{ok, Provider} = ff_payouts_provider:get(ProviderID, DomainRevision),
ProviderAccounts = ff_payouts_provider:accounts(Provider),
ProviderAccount = maps:get(CurrencyID, ProviderAccounts, undefined),
{ok, PaymentInstitution} = get_payment_institution(Identity, PartyVarset, DomainRevision),
{ok, SystemAccounts} = ff_payment_institution:system_accounts(PaymentInstitution, DomainRevision),
SystemAccount = maps:get(CurrencyID, SystemAccounts, #{}),
SettlementAccount = maps:get(settlement, SystemAccount, undefined),
SubagentAccount = maps:get(subagent, SystemAccount, undefined),
{ok, ProviderFee} = compute_fees(Route, PartyVarset, DomainRevision),
{ok, Terms} = ff_party:get_contract_terms(
PartyID,
ContractID,
PartyVarset,
Timestamp,
PartyRevision,
DomainRevision
),
{ok, WalletCashFlowPlan} = ff_party:get_withdrawal_cash_flow_plan(Terms),
{ok, CashFlowPlan} = ff_cash_flow:add_fee(WalletCashFlowPlan, ProviderFee),
Constants = #{
operation_amount => Body
},
Accounts = genlib_map:compact(#{
{wallet, sender_settlement} => WalletAccount,
{wallet, receiver_destination} => DestinationAccount,
{system, settlement} => SettlementAccount,
{system, subagent} => SubagentAccount,
{provider, settlement} => ProviderAccount
}),
{ok, FinalCashFlow} = ff_cash_flow:finalize(CashFlowPlan, Accounts, Constants),
FinalCashFlow.
-spec compute_fees(route(), party_varset(), domain_revision()) ->
{ok, ff_cash_flow:cash_flow_fee()}
| {error, term()}.
compute_fees(Route, VS, DomainRevision) ->
case compute_provider_terminal_terms(Route, VS, DomainRevision) of
{ok, #domain_ProvisionTermSet{
wallet = #domain_WalletProvisionTerms{
withdrawals = #domain_WithdrawalProvisionTerms{
cash_flow = CashFlowSelector
}
}
}} ->
cash_flow_postings(CashFlowSelector);
{error, Error} ->
{error, Error}
end.
-spec compute_provider_terminal_terms(route(), party_varset(), domain_revision()) ->
{ok, ff_party:provision_term_set()}
| {error, provider_not_found}
| {error, terminal_not_found}.
compute_provider_terminal_terms(#{provider_id := ProviderID, terminal_id := TerminalID}, VS, DomainRevision) ->
ProviderRef = ff_payouts_provider:ref(ProviderID),
TerminalRef = ff_payouts_terminal:ref(TerminalID),
ff_party:compute_provider_terminal_terms(ProviderRef, TerminalRef, VS, DomainRevision);
compute_provider_terminal_terms(#{provider_id := ProviderID}, VS, DomainRevision) ->
ProviderRef = ff_payouts_provider:ref(ProviderID),
case ff_party:compute_provider(ProviderRef, VS, DomainRevision) of
{ok, #domain_Provider{
terms = Terms
}} ->
{ok, Terms};
{error, Error} ->
{error, Error}
end.
cash_flow_postings(CashFlowSelector) ->
case CashFlowSelector of
{value, CashFlow} ->
{ok, #{
postings => ff_cash_flow:decode_domain_postings(CashFlow)
}};
Ambiguous ->
error({misconfiguration, {'Could not reduce selector to a value', {cash_flow, Ambiguous}}})
end.
-spec ensure_domain_revision_defined(domain_revision() | undefined) -> domain_revision().
ensure_domain_revision_defined(undefined) ->
ff_domain_config:head();
ensure_domain_revision_defined(Revision) ->
Revision.
-spec ensure_party_revision_defined(party_id(), party_revision() | undefined) -> domain_revision().
ensure_party_revision_defined(PartyID, undefined) ->
{ok, Revision} = ff_party:get_revision(PartyID),
Revision;
ensure_party_revision_defined(_PartyID, Revision) ->
Revision.
-spec get_wallet(wallet_id()) -> {ok, wallet()} | {error, notfound}.
get_wallet(WalletID) ->
do(fun() ->
WalletMachine = unwrap(ff_wallet_machine:get(WalletID)),
ff_wallet_machine:wallet(WalletMachine)
end).
-spec get_destination(destination_id()) -> {ok, destination()} | {error, notfound}.
get_destination(DestinationID) ->
do(fun() ->
DestinationMachine = unwrap(ff_destination_machine:get(DestinationID)),
ff_destination_machine:destination(DestinationMachine)
end).
-spec get_wallet_identity(wallet()) -> identity().
get_wallet_identity(Wallet) ->
IdentityID = ff_wallet:identity(Wallet),
get_identity(IdentityID).
-spec get_destination_identity(destination()) -> identity().
get_destination_identity(Destination) ->
IdentityID = ff_destination:identity(Destination),
get_identity(IdentityID).
get_identity(IdentityID) ->
{ok, IdentityMachine} = ff_identity_machine:get(IdentityID),
ff_identity_machine:identity(IdentityMachine).
-spec get_payment_institution(identity(), party_varset(), domain_revision()) ->
{ok, ff_payment_institution:payment_institution()}.
get_payment_institution(Identity, PartyVarset, DomainRevision) ->
{ok, PaymentInstitutionID} = ff_party:get_identity_payment_institution_id(Identity),
ff_payment_institution:get(PaymentInstitutionID, PartyVarset, DomainRevision).
-spec build_party_varset(party_varset_params()) -> party_varset().
build_party_varset(#{body := Body, wallet_id := WalletID, party_id := PartyID} = Params) ->
{_, CurrencyID} = Body,
Destination = maps:get(destination, Params, undefined),
Resource = maps:get(resource, Params, undefined),
BinData = maps:get(bin_data, Params, undefined),
PaymentTool =
case {Destination, Resource} of
{undefined, _} ->
undefined;
{_, Resource} ->
construct_payment_tool(Resource)
end,
genlib_map:compact(#{
currency => ff_dmsl_codec:marshal(currency_ref, CurrencyID),
cost => ff_dmsl_codec:marshal(cash, Body),
party_id => PartyID,
wallet_id => WalletID,
payout_method => #domain_PayoutMethodRef{id = wallet_info},
TODO it 's not fair , because it 's PAYOUT not PAYMENT tool .
payment_tool => PaymentTool,
bin_data => ff_dmsl_codec:marshal(bin_data, BinData)
}).
-spec construct_payment_tool(ff_destination:resource() | ff_destination:resource_params()) ->
dmsl_domain_thrift:'PaymentTool'().
construct_payment_tool({bank_card, #{bank_card := ResourceBankCard}}) ->
PaymentSystem = maps:get(payment_system, ResourceBankCard, undefined),
{bank_card, #domain_BankCard{
token = maps:get(token, ResourceBankCard),
bin = maps:get(bin, ResourceBankCard),
last_digits = maps:get(masked_pan, ResourceBankCard),
payment_system = ff_dmsl_codec:marshal(payment_system, PaymentSystem),
payment_system_deprecated = maps:get(payment_system_deprecated, ResourceBankCard, undefined),
issuer_country = maps:get(issuer_country, ResourceBankCard, undefined),
bank_name = maps:get(bank_name, ResourceBankCard, undefined)
}};
construct_payment_tool({crypto_wallet, #{crypto_wallet := #{currency := {Currency, _}}}}) ->
{crypto_currency_deprecated, Currency};
construct_payment_tool({digital_wallet, #{digital_wallet := #{id := ID, data := {DigitalWalletType, _}}}}) ->
{digital_wallet, #domain_DigitalWallet{id = ID, provider_deprecated = DigitalWalletType}}.
-spec get_quote(quote_params()) -> {ok, quote()} | {error, create_error() | {route, route_not_found}}.
get_quote(Params = #{destination_id := DestinationID, body := Body, wallet_id := WalletID}) ->
do(fun() ->
Destination = unwrap(destination, get_destination(DestinationID)),
Resource = unwrap(destination_resource, ff_resource:create_resource(ff_destination:resource(Destination))),
Wallet = unwrap(wallet, get_wallet(WalletID)),
Identity = get_wallet_identity(Wallet),
ContractID = ff_identity:contract(Identity),
PartyID = ff_identity:party(Identity),
DomainRevision = ff_domain_config:head(),
{ok, PartyRevision} = ff_party:get_revision(PartyID),
VarsetParams = genlib_map:compact(#{
body => Body,
wallet_id => WalletID,
wallet => Wallet,
party_id => PartyID,
destination => Destination,
resource => Resource
}),
PartyVarset = build_party_varset(VarsetParams),
Timestamp = ff_time:now(),
{ok, Terms} = ff_party:get_contract_terms(
PartyID,
ContractID,
PartyVarset,
Timestamp,
PartyRevision,
DomainRevision
),
valid = unwrap(validate_withdrawal_creation(Terms, Body, Wallet, Destination)),
GetQuoteParams = #{
base_params => Params,
identity => Identity,
party_varset => build_party_varset(VarsetParams),
timestamp => Timestamp,
domain_revision => DomainRevision,
party_revision => PartyRevision,
resource => Resource
},
unwrap(get_quote_(GetQuoteParams))
end);
get_quote(Params) ->
#{
wallet_id := WalletID,
body := Body
} = Params,
Wallet = unwrap(wallet, get_wallet(WalletID)),
Identity = get_wallet_identity(Wallet),
PartyID = ff_identity:party(Identity),
Timestamp = ff_time:now(),
DomainRevision = ff_domain_config:head(),
{ok, PartyRevision} = ff_party:get_revision(PartyID),
VarsetParams = genlib_map:compact(#{
body => Body,
wallet_id => WalletID,
wallet => Wallet,
party_id => PartyID
}),
GetQuoteParams = #{
base_params => Params,
identity => Identity,
party_varset => build_party_varset(VarsetParams),
timestamp => Timestamp,
domain_revision => DomainRevision,
party_revision => PartyRevision
},
get_quote_(GetQuoteParams).
get_quote_(Params) ->
do(fun() ->
#{
base_params := #{
body := Body,
currency_from := CurrencyFrom,
currency_to := CurrencyTo
},
identity := Identity,
party_varset := Varset,
timestamp := Timestamp,
domain_revision := DomainRevision,
party_revision := PartyRevision
} = Params,
Resource = maps:get(resource, Params, undefined),
[Route | _] = unwrap(route, ff_withdrawal_routing:prepare_routes(Varset, Identity, DomainRevision)),
{Adapter, AdapterOpts} = ff_withdrawal_session:get_adapter_with_opts(Route),
GetQuoteParams = #{
external_id => maps:get(external_id, Params, undefined),
currency_from => CurrencyFrom,
currency_to => CurrencyTo,
body => Body
},
{ok, Quote} = ff_adapter_withdrawal:get_quote(Adapter, GetQuoteParams, AdapterOpts),
genlib_map:compact(#{
cash_from => maps:get(cash_from, Quote),
cash_to => maps:get(cash_to, Quote),
created_at => maps:get(created_at, Quote),
expires_on => maps:get(expires_on, Quote),
quote_data => maps:get(quote_data, Quote),
route => Route,
operation_timestamp => Timestamp,
resource_descriptor => ff_resource:resource_descriptor(Resource),
domain_revision => DomainRevision,
party_revision => PartyRevision
})
end).
-spec build_session_quote(quote_state() | undefined) -> ff_adapter_withdrawal:quote_data() | undefined.
build_session_quote(undefined) ->
undefined;
build_session_quote(Quote) ->
maps:with([cash_from, cash_to, created_at, expires_on, quote_data], Quote).
-spec quote_resource_descriptor(quote() | undefined) -> resource_descriptor().
quote_resource_descriptor(undefined) ->
undefined;
quote_resource_descriptor(Quote) ->
maps:get(resource_descriptor, Quote, undefined).
-spec quote_timestamp(quote() | undefined) -> ff_time:timestamp_ms() | undefined.
quote_timestamp(undefined) ->
undefined;
quote_timestamp(Quote) ->
maps:get(operation_timestamp, Quote, undefined).
-spec quote_party_revision(quote() | undefined) -> party_revision() | undefined.
quote_party_revision(undefined) ->
undefined;
quote_party_revision(Quote) ->
maps:get(party_revision, Quote, undefined).
-spec quote_domain_revision(quote() | undefined) -> domain_revision() | undefined.
quote_domain_revision(undefined) ->
undefined;
quote_domain_revision(Quote) ->
maps:get(domain_revision, Quote, undefined).
-spec session_id(withdrawal_state()) -> session_id() | undefined.
session_id(T) ->
case get_current_session(T) of
undefined ->
undefined;
#{id := SessionID} ->
SessionID
end.
-spec get_current_session(withdrawal_state()) -> session() | undefined.
get_current_session(Withdrawal) ->
ff_withdrawal_route_attempt_utils:get_current_session(attempts(Withdrawal)).
-spec get_session_result(withdrawal_state()) -> session_result() | unknown | undefined.
get_session_result(Withdrawal) ->
case get_current_session(Withdrawal) of
undefined ->
undefined;
#{result := Result} ->
Result;
#{} ->
unknown
end.
-spec get_current_session_status(withdrawal_state()) -> session_processing_status().
get_current_session_status(Withdrawal) ->
Session = get_current_session(Withdrawal),
case Session of
undefined ->
undefined;
#{result := success} ->
succeeded;
#{result := {success, _}} ->
succeeded;
#{result := {failed, _}} ->
failed;
#{} ->
pending
end.
-spec validate_withdrawal_creation(terms(), body(), wallet(), destination()) ->
{ok, valid}
| {error, create_error()}.
validate_withdrawal_creation(Terms, Body, Wallet, Destination) ->
do(fun() ->
valid = unwrap(terms, validate_withdrawal_creation_terms(Terms, Body)),
valid = unwrap(validate_withdrawal_currency(Body, Wallet, Destination)),
valid = unwrap(validate_destination_status(Destination)),
valid = unwrap(validate_withdrawal_providers(Wallet, Destination))
end).
validate_withdrawal_providers(Wallet, Destination) ->
WalletIdentity = get_wallet_identity(Wallet),
DestinationIdentity = get_destination_identity(Destination),
WalletProvider = ff_identity:provider(WalletIdentity),
DestinationProvider = ff_identity:provider(DestinationIdentity),
case WalletProvider =:= DestinationProvider of
true -> {ok, valid};
false -> {error, {identity_providers_mismatch, {WalletProvider, DestinationProvider}}}
end.
-spec validate_withdrawal_creation_terms(terms(), body()) ->
{ok, valid}
| {error, ff_party:validate_withdrawal_creation_error()}.
validate_withdrawal_creation_terms(Terms, Body) ->
ff_party:validate_withdrawal_creation(Terms, Body).
-spec validate_withdrawal_currency(body(), wallet(), destination()) ->
{ok, valid}
| {error, {inconsistent_currency, {currency_id(), currency_id(), currency_id()}}}.
validate_withdrawal_currency(Body, Wallet, Destination) ->
DestiantionCurrencyID = ff_account:currency(ff_destination:account(Destination)),
WalletCurrencyID = ff_account:currency(ff_wallet:account(Wallet)),
case Body of
{_Amount, WithdrawalCurencyID} when
WithdrawalCurencyID =:= DestiantionCurrencyID andalso
WithdrawalCurencyID =:= WalletCurrencyID
->
{ok, valid};
{_Amount, WithdrawalCurencyID} ->
{error, {inconsistent_currency, {WithdrawalCurencyID, WalletCurrencyID, DestiantionCurrencyID}}}
end.
-spec validate_destination_status(destination()) ->
{ok, valid}
| {error, {destination, ff_destination:status()}}.
validate_destination_status(Destination) ->
case ff_destination:status(Destination) of
authorized ->
{ok, valid};
unauthorized ->
{error, {destination, unauthorized}}
end.
-spec add_limit_check(limit_check_details(), withdrawal_state()) -> withdrawal_state().
add_limit_check(Check, Withdrawal) ->
Attempts = attempts(Withdrawal),
Checks =
case ff_withdrawal_route_attempt_utils:get_current_limit_checks(Attempts) of
undefined ->
[Check];
C ->
[Check | C]
end,
R = ff_withdrawal_route_attempt_utils:update_current_limit_checks(Checks, Attempts),
update_attempts(R, Withdrawal).
-spec limit_check_status(withdrawal_state()) -> ok | {failed, limit_check_details()} | unknown.
limit_check_status(Withdrawal) ->
Attempts = attempts(Withdrawal),
Checks = ff_withdrawal_route_attempt_utils:get_current_limit_checks(Attempts),
limit_check_status_(Checks).
limit_check_status_(undefined) ->
unknown;
limit_check_status_(Checks) ->
case lists:dropwhile(fun is_limit_check_ok/1, Checks) of
[] ->
ok;
[H | _Tail] ->
{failed, H}
end.
-spec limit_check_processing_status(withdrawal_state()) -> ok | failed | unknown.
limit_check_processing_status(Withdrawal) ->
case limit_check_status(Withdrawal) of
ok ->
ok;
unknown ->
unknown;
{failed, _Details} ->
failed
end.
-spec is_limit_check_ok(limit_check_details()) -> boolean().
is_limit_check_ok({wallet_sender, ok}) ->
true;
is_limit_check_ok({wallet_sender, {failed, _Details}}) ->
false.
-spec validate_wallet_limits(terms(), wallet(), clock()) ->
{ok, valid}
| {error, {terms_violation, {wallet_limit, {cash_range, {cash(), cash_range()}}}}}.
validate_wallet_limits(Terms, Wallet, Clock) ->
case ff_party:validate_wallet_limits(Terms, Wallet, Clock) of
{ok, valid} = Result ->
Result;
{error, {terms_violation, {cash_range, {Cash, CashRange}}}} ->
{error, {terms_violation, {wallet_limit, {cash_range, {Cash, CashRange}}}}};
{error, {invalid_terms, _Details} = Reason} ->
erlang:error(Reason)
end.
-spec validate_adjustment_start(adjustment_params(), withdrawal_state()) ->
{ok, valid}
| {error, start_adjustment_error()}.
validate_adjustment_start(Params, Withdrawal) ->
do(fun() ->
valid = unwrap(validate_no_pending_adjustment(Withdrawal)),
valid = unwrap(validate_withdrawal_finish(Withdrawal)),
valid = unwrap(validate_status_change(Params, Withdrawal))
end).
-spec validate_withdrawal_finish(withdrawal_state()) ->
{ok, valid}
| {error, {invalid_withdrawal_status, status()}}.
validate_withdrawal_finish(Withdrawal) ->
case is_finished(Withdrawal) of
true ->
{ok, valid};
false ->
{error, {invalid_withdrawal_status, status(Withdrawal)}}
end.
-spec validate_no_pending_adjustment(withdrawal_state()) ->
{ok, valid}
| {error, {another_adjustment_in_progress, adjustment_id()}}.
validate_no_pending_adjustment(Withdrawal) ->
case ff_adjustment_utils:get_not_finished(adjustments_index(Withdrawal)) of
error ->
{ok, valid};
{ok, AdjustmentID} ->
{error, {another_adjustment_in_progress, AdjustmentID}}
end.
-spec validate_status_change(adjustment_params(), withdrawal_state()) ->
{ok, valid}
| {error, invalid_status_change_error()}.
validate_status_change(#{change := {change_status, Status}}, Withdrawal) ->
do(fun() ->
valid = unwrap(invalid_status_change, validate_target_status(Status)),
valid = unwrap(invalid_status_change, validate_change_same_status(Status, status(Withdrawal)))
end);
validate_status_change(_Params, _Withdrawal) ->
{ok, valid}.
-spec validate_target_status(status()) ->
{ok, valid}
| {error, {unavailable_status, status()}}.
validate_target_status(succeeded) ->
{ok, valid};
validate_target_status({failed, _Failure}) ->
{ok, valid};
validate_target_status(Status) ->
{error, {unavailable_status, Status}}.
-spec validate_change_same_status(status(), status()) ->
{ok, valid}
| {error, {already_has_status, status()}}.
validate_change_same_status(NewStatus, OldStatus) when NewStatus =/= OldStatus ->
{ok, valid};
validate_change_same_status(Status, Status) ->
{error, {already_has_status, Status}}.
-spec apply_adjustment_event(wrapped_adjustment_event(), withdrawal_state()) -> withdrawal_state().
apply_adjustment_event(WrappedEvent, Withdrawal) ->
Adjustments0 = adjustments_index(Withdrawal),
Adjustments1 = ff_adjustment_utils:apply_event(WrappedEvent, Adjustments0),
set_adjustments_index(Adjustments1, Withdrawal).
-spec make_adjustment_params(adjustment_params(), withdrawal_state()) -> ff_adjustment:params().
make_adjustment_params(Params, Withdrawal) ->
#{id := ID, change := Change} = Params,
genlib_map:compact(#{
id => ID,
changes_plan => make_adjustment_change(Change, Withdrawal),
external_id => genlib_map:get(external_id, Params),
domain_revision => operation_domain_revision(Withdrawal),
party_revision => operation_party_revision(Withdrawal),
operation_timestamp => operation_timestamp(Withdrawal)
}).
-spec make_adjustment_change(adjustment_change(), withdrawal_state()) -> ff_adjustment:changes().
make_adjustment_change({change_status, NewStatus}, Withdrawal) ->
CurrentStatus = status(Withdrawal),
make_change_status_params(CurrentStatus, NewStatus, Withdrawal).
-spec make_change_status_params(status(), status(), withdrawal_state()) -> ff_adjustment:changes().
make_change_status_params(succeeded, {failed, _} = NewStatus, Withdrawal) ->
CurrentCashFlow = effective_final_cash_flow(Withdrawal),
NewCashFlow = ff_cash_flow:make_empty_final(),
#{
new_status => #{
new_status => NewStatus
},
new_cash_flow => #{
old_cash_flow_inverted => ff_cash_flow:inverse(CurrentCashFlow),
new_cash_flow => NewCashFlow
}
};
make_change_status_params({failed, _}, succeeded = NewStatus, Withdrawal) ->
CurrentCashFlow = effective_final_cash_flow(Withdrawal),
NewCashFlow = make_final_cash_flow(Withdrawal),
#{
new_status => #{
new_status => NewStatus
},
new_cash_flow => #{
old_cash_flow_inverted => ff_cash_flow:inverse(CurrentCashFlow),
new_cash_flow => NewCashFlow
}
};
make_change_status_params({failed, _}, {failed, _} = NewStatus, _Withdrawal) ->
#{
new_status => #{
new_status => NewStatus
}
}.
-spec process_adjustment(withdrawal_state()) -> process_result().
process_adjustment(Withdrawal) ->
#{
action := Action,
events := Events0,
changes := Changes
} = ff_adjustment_utils:process_adjustments(adjustments_index(Withdrawal)),
Events1 = Events0 ++ handle_adjustment_changes(Changes),
handle_child_result({Action, Events1}, Withdrawal).
-spec process_route_change(withdrawal_state(), fail_type()) -> process_result().
process_route_change(Withdrawal, Reason) ->
case is_failure_transient(Reason, Withdrawal) of
true ->
{ok, Providers} = do_process_routing(Withdrawal),
do_process_route_change(Providers, Withdrawal, Reason);
false ->
process_transfer_fail(Reason, Withdrawal)
end.
-spec is_failure_transient(fail_type(), withdrawal_state()) -> boolean().
is_failure_transient(Reason, Withdrawal) ->
{ok, Wallet} = get_wallet(wallet_id(Withdrawal)),
PartyID = ff_identity:party(get_wallet_identity(Wallet)),
RetryableErrors = get_retryable_error_list(PartyID),
ErrorTokens = to_error_token_list(Reason, Withdrawal),
match_error_whitelist(ErrorTokens, RetryableErrors).
-spec get_retryable_error_list(party_id()) -> list(list(binary())).
get_retryable_error_list(PartyID) ->
WithdrawalConfig = genlib_app:env(ff_transfer, withdrawal, #{}),
PartyRetryableErrors = maps:get(party_transient_errors, WithdrawalConfig, #{}),
Errors =
case maps:get(PartyID, PartyRetryableErrors, undefined) of
undefined ->
maps:get(default_transient_errors, WithdrawalConfig, []);
ErrorList ->
ErrorList
end,
binaries_to_error_tokens(Errors).
-spec binaries_to_error_tokens(list(binary())) -> list(list(binary())).
binaries_to_error_tokens(Errors) ->
lists:map(
fun(Error) ->
binary:split(Error, <<":">>, [global])
end,
Errors
).
-spec to_error_token_list(fail_type(), withdrawal_state()) -> list(binary()).
to_error_token_list(Reason, Withdrawal) ->
Failure = build_failure(Reason, Withdrawal),
failure_to_error_token_list(Failure).
-spec failure_to_error_token_list(ff_failure:failure()) -> list(binary()).
failure_to_error_token_list(#{code := Code, sub := SubFailure}) ->
SubFailureList = failure_to_error_token_list(SubFailure),
[Code | SubFailureList];
failure_to_error_token_list(#{code := Code}) ->
[Code].
-spec match_error_whitelist(list(binary()), list(list(binary()))) -> boolean().
match_error_whitelist(ErrorTokens, RetryableErrors) ->
lists:any(
fun(RetryableError) ->
error_tokens_match(ErrorTokens, RetryableError)
end,
RetryableErrors
).
-spec error_tokens_match(list(binary()), list(binary())) -> boolean().
error_tokens_match(_, []) ->
true;
error_tokens_match([], [_ | _]) ->
false;
error_tokens_match([Token0 | Rest0], [Token1 | Rest1]) when Token0 =:= Token1 ->
error_tokens_match(Rest0, Rest1);
error_tokens_match([Token0 | _], [Token1 | _]) when Token0 =/= Token1 ->
false.
-spec do_process_route_change([route()], withdrawal_state(), fail_type()) -> process_result().
do_process_route_change(Routes, Withdrawal, Reason) ->
Attempts = attempts(Withdrawal),
AttemptLimit = get_attempt_limit(Withdrawal),
case ff_withdrawal_route_attempt_utils:next_route(Routes, Attempts, AttemptLimit) of
{ok, Route} ->
{continue, [
{route_changed, Route}
]};
{error, route_not_found} ->
process_transfer_fail(Reason, Withdrawal);
{error, attempt_limit_exceeded} ->
process_transfer_fail(Reason, Withdrawal)
end.
-spec handle_adjustment_changes(ff_adjustment:changes()) -> [event()].
handle_adjustment_changes(Changes) ->
StatusChange = maps:get(new_status, Changes, undefined),
handle_adjustment_status_change(StatusChange).
-spec handle_adjustment_status_change(ff_adjustment:status_change() | undefined) -> [event()].
handle_adjustment_status_change(undefined) ->
[];
handle_adjustment_status_change(#{new_status := Status}) ->
[{status_changed, Status}].
-spec save_adjustable_info(event(), withdrawal_state()) -> withdrawal_state().
save_adjustable_info({p_transfer, {status_changed, committed}}, Withdrawal) ->
CashFlow = ff_postings_transfer:final_cash_flow(p_transfer(Withdrawal)),
update_adjusment_index(fun ff_adjustment_utils:set_cash_flow/2, CashFlow, Withdrawal);
save_adjustable_info(_Ev, Withdrawal) ->
Withdrawal.
-spec update_adjusment_index(Updater, Value, withdrawal_state()) -> withdrawal_state() when
Updater :: fun((Value, adjustments_index()) -> adjustments_index()),
Value :: any().
update_adjusment_index(Updater, Value, Withdrawal) ->
Index = adjustments_index(Withdrawal),
set_adjustments_index(Updater(Value, Index), Withdrawal).
-spec build_failure(fail_type(), withdrawal_state()) -> failure().
build_failure(limit_check, Withdrawal) ->
{failed, Details} = limit_check_status(Withdrawal),
case Details of
{wallet_sender, _WalletLimitDetails} ->
#{
code => <<"account_limit_exceeded">>,
reason => genlib:format(Details),
sub => #{
code => <<"amount">>
}
}
end;
build_failure(route_not_found, _Withdrawal) ->
#{
code => <<"no_route_found">>
};
build_failure({inconsistent_quote_route, {Type, FoundID}}, Withdrawal) ->
Details =
{inconsistent_quote_route, #{
expected => {Type, FoundID},
found => get_quote_field(Type, quote(Withdrawal))
}},
#{
code => <<"unknown">>,
reason => genlib:format(Details)
};
build_failure(session, Withdrawal) ->
Result = get_session_result(Withdrawal),
{failed, Failure} = Result,
Failure.
get_quote_field(provider_id, #{route := Route}) ->
ff_withdrawal_routing:get_provider(Route);
get_quote_field(terminal_id, #{route := Route}) ->
ff_withdrawal_routing:get_terminal(Route).
-spec apply_event(event() | legacy_event(), ff_maybe:maybe(withdrawal_state())) -> withdrawal_state().
apply_event(Ev, T0) ->
T1 = apply_event_(Ev, T0),
T2 = save_adjustable_info(Ev, T1),
T2.
-spec apply_event_(event(), ff_maybe:maybe(withdrawal_state())) -> withdrawal_state().
apply_event_({created, T}, undefined) ->
make_state(T);
apply_event_({status_changed, Status}, T) ->
maps:put(status, Status, T);
apply_event_({resource_got, Resource}, T) ->
maps:put(resource, Resource, T);
apply_event_({limit_check, Details}, T) ->
add_limit_check(Details, T);
apply_event_({p_transfer, Ev}, T) ->
Tr = ff_postings_transfer:apply_event(Ev, p_transfer(T)),
Attempts = attempts(T),
R = ff_withdrawal_route_attempt_utils:update_current_p_transfer(Tr, Attempts),
update_attempts(R, T);
apply_event_({session_started, SessionID}, T) ->
Session = #{id => SessionID},
Attempts = attempts(T),
R = ff_withdrawal_route_attempt_utils:update_current_session(Session, Attempts),
update_attempts(R, T);
apply_event_({session_finished, {SessionID, Result}}, T) ->
Attempts = attempts(T),
Session = ff_withdrawal_route_attempt_utils:get_current_session(Attempts),
SessionID = maps:get(id, Session),
UpdSession = Session#{result => Result},
R = ff_withdrawal_route_attempt_utils:update_current_session(UpdSession, Attempts),
update_attempts(R, T);
apply_event_({route_changed, Route}, T) ->
Attempts = attempts(T),
R = ff_withdrawal_route_attempt_utils:new_route(Route, Attempts),
T#{
route => Route,
attempts => R
};
apply_event_({adjustment, _Ev} = Event, T) ->
apply_adjustment_event(Event, T).
-spec make_state(withdrawal()) -> withdrawal_state().
make_state(#{route := Route} = T) ->
Attempts = ff_withdrawal_route_attempt_utils:new(),
T#{
attempts => ff_withdrawal_route_attempt_utils:new_route(Route, Attempts)
};
make_state(T) when not is_map_key(route, T) ->
T.
get_attempt_limit(Withdrawal) ->
#{
body := Body,
params := #{
wallet_id := WalletID,
destination_id := DestinationID
},
created_at := Timestamp,
party_revision := PartyRevision,
domain_revision := DomainRevision,
resource := Resource
} = Withdrawal,
{ok, Wallet} = get_wallet(WalletID),
{ok, Destination} = get_destination(DestinationID),
Identity = get_wallet_identity(Wallet),
PartyID = ff_identity:party(Identity),
ContractID = ff_identity:contract(Identity),
VarsetParams = genlib_map:compact(#{
body => Body,
wallet_id => WalletID,
party_id => PartyID,
destination => Destination,
resource => Resource
}),
{ok, Terms} = ff_party:get_contract_terms(
PartyID,
ContractID,
build_party_varset(VarsetParams),
Timestamp,
PartyRevision,
DomainRevision
),
#domain_TermSet{wallets = WalletTerms} = Terms,
#domain_WalletServiceTerms{withdrawals = WithdrawalTerms} = WalletTerms,
#domain_WithdrawalServiceTerms{attempt_limit = AttemptLimit} = WithdrawalTerms,
get_attempt_limit_(AttemptLimit).
get_attempt_limit_(undefined) ->
just stop after first one
1;
get_attempt_limit_({value, Limit}) ->
ff_dmsl_codec:unmarshal(attempt_limit, Limit).
-ifdef(TEST).
-include_lib("eunit/include/eunit.hrl").
-spec test() -> _.
-spec match_error_whitelist_test() -> _.
match_error_whitelist_test() ->
ErrorWhitelist = binaries_to_error_tokens([
<<"some:test:error">>,
<<"another:test:error">>,
<<"wide">>
]),
?assertEqual(
false,
match_error_whitelist(
[<<>>],
ErrorWhitelist
)
),
?assertEqual(
false,
match_error_whitelist(
[<<"some">>, <<"completely">>, <<"different">>, <<"error">>],
ErrorWhitelist
)
),
?assertEqual(
false,
match_error_whitelist(
[<<"some">>, <<"test">>],
ErrorWhitelist
)
),
?assertEqual(
false,
match_error_whitelist(
[<<"wider">>],
ErrorWhitelist
)
),
?assertEqual(
true,
match_error_whitelist(
[<<"some">>, <<"test">>, <<"error">>],
ErrorWhitelist
)
),
?assertEqual(
true,
match_error_whitelist(
[<<"another">>, <<"test">>, <<"error">>, <<"that">>, <<"is">>, <<"more">>, <<"specific">>],
ErrorWhitelist
)
).
-endif.
|
9ee14e6f64a21b55bf7e8d046fa583fbfc4abbb3fedd7b3b425b7dc44247a1db | realworldocaml/book | configuration.mli | open! Core
open! Import
(** Default amount of context shown around each change in the diff *)
val default_context : int
(** The following constants were all chosen empirically. *)
(** Default cutoff for line-level semantic cleanup. Any match of [default_line_big_enough]
or more will not be deleted, even if it's surrounded by large inserts and deletes.
Raising this quantity can only decrease the number of matches, and lowering it
can only increase the number of matches. *)
val default_line_big_enough : int
(** Analogous to {!default_line_big_enough}, but for word-level refinement *)
val default_word_big_enough : int
* Governs the behavior of [ split_for_readability ] . We will only split ranges around
matches of size greater than [ too_short_to_split ] . Note that this should always
be at least 1 , otherwise we will split on a single ` Newline token .
Raising this quantity will result in less ranges being split , and setting it to
infinity is the same as passing in [ ~interleave : false ] .
matches of size greater than [too_short_to_split]. Note that this should always
be at least 1, otherwise we will split on a single `Newline token.
Raising this quantity will result in less ranges being split, and setting it to
infinity is the same as passing in [~interleave:false]. *)
val too_short_to_split : int
val warn_if_no_trailing_newline_in_both_default : bool
type t = private
{ output : Output.t
; rules : Format.Rules.t
; float_tolerance : Percent.t option
; produce_unified_lines : bool
; unrefined : bool
; keep_ws : bool
; split_long_lines : bool
; interleave : bool
; assume_text : bool
; context : int
; line_big_enough : int
; word_big_enough : int
; shallow : bool
; quiet : bool
; double_check : bool
; mask_uniques : bool
; prev_alt : string option
; next_alt : string option
; location_style : Format.Location_style.t
; warn_if_no_trailing_newline_in_both : bool
}
[@@deriving compare, fields, sexp_of]
include Invariant.S with type t := t
(** Raises if [invariant t] fails. *)
val create_exn
: output:Output.t
-> rules:Format.Rules.t
-> float_tolerance:Percent.t option
-> produce_unified_lines:bool
-> unrefined:bool
-> keep_ws:bool
-> split_long_lines:bool
-> interleave:bool
-> assume_text:bool
-> context:int
-> line_big_enough:int
-> word_big_enough:int
-> shallow:bool
-> quiet:bool
-> double_check:bool
-> mask_uniques:bool
-> prev_alt:string option
-> next_alt:string option
-> location_style:Format.Location_style.t
-> warn_if_no_trailing_newline_in_both:bool
-> t
val override
: ?output:Output.t
-> ?rules:Format.Rules.t
-> ?float_tolerance:Percent.t option
-> ?produce_unified_lines:bool
-> ?unrefined:bool
-> ?keep_ws:bool
-> ?split_long_lines:bool
-> ?interleave:bool
-> ?assume_text:bool
-> ?context:int
-> ?line_big_enough:int
-> ?word_big_enough:int
-> ?shallow:bool
-> ?quiet:bool
-> ?double_check:bool
-> ?mask_uniques:bool
-> ?prev_alt:string option
-> ?next_alt:string option
-> ?location_style:Format.Location_style.t
-> ?warn_if_no_trailing_newline_in_both:bool
-> t
-> t
val default : t
| null | https://raw.githubusercontent.com/realworldocaml/book/d822fd065f19dbb6324bf83e0143bc73fd77dbf9/duniverse/patdiff/kernel/src/configuration.mli | ocaml | * Default amount of context shown around each change in the diff
* The following constants were all chosen empirically.
* Default cutoff for line-level semantic cleanup. Any match of [default_line_big_enough]
or more will not be deleted, even if it's surrounded by large inserts and deletes.
Raising this quantity can only decrease the number of matches, and lowering it
can only increase the number of matches.
* Analogous to {!default_line_big_enough}, but for word-level refinement
* Raises if [invariant t] fails. | open! Core
open! Import
val default_context : int
val default_line_big_enough : int
val default_word_big_enough : int
* Governs the behavior of [ split_for_readability ] . We will only split ranges around
matches of size greater than [ too_short_to_split ] . Note that this should always
be at least 1 , otherwise we will split on a single ` Newline token .
Raising this quantity will result in less ranges being split , and setting it to
infinity is the same as passing in [ ~interleave : false ] .
matches of size greater than [too_short_to_split]. Note that this should always
be at least 1, otherwise we will split on a single `Newline token.
Raising this quantity will result in less ranges being split, and setting it to
infinity is the same as passing in [~interleave:false]. *)
val too_short_to_split : int
val warn_if_no_trailing_newline_in_both_default : bool
type t = private
{ output : Output.t
; rules : Format.Rules.t
; float_tolerance : Percent.t option
; produce_unified_lines : bool
; unrefined : bool
; keep_ws : bool
; split_long_lines : bool
; interleave : bool
; assume_text : bool
; context : int
; line_big_enough : int
; word_big_enough : int
; shallow : bool
; quiet : bool
; double_check : bool
; mask_uniques : bool
; prev_alt : string option
; next_alt : string option
; location_style : Format.Location_style.t
; warn_if_no_trailing_newline_in_both : bool
}
[@@deriving compare, fields, sexp_of]
include Invariant.S with type t := t
val create_exn
: output:Output.t
-> rules:Format.Rules.t
-> float_tolerance:Percent.t option
-> produce_unified_lines:bool
-> unrefined:bool
-> keep_ws:bool
-> split_long_lines:bool
-> interleave:bool
-> assume_text:bool
-> context:int
-> line_big_enough:int
-> word_big_enough:int
-> shallow:bool
-> quiet:bool
-> double_check:bool
-> mask_uniques:bool
-> prev_alt:string option
-> next_alt:string option
-> location_style:Format.Location_style.t
-> warn_if_no_trailing_newline_in_both:bool
-> t
val override
: ?output:Output.t
-> ?rules:Format.Rules.t
-> ?float_tolerance:Percent.t option
-> ?produce_unified_lines:bool
-> ?unrefined:bool
-> ?keep_ws:bool
-> ?split_long_lines:bool
-> ?interleave:bool
-> ?assume_text:bool
-> ?context:int
-> ?line_big_enough:int
-> ?word_big_enough:int
-> ?shallow:bool
-> ?quiet:bool
-> ?double_check:bool
-> ?mask_uniques:bool
-> ?prev_alt:string option
-> ?next_alt:string option
-> ?location_style:Format.Location_style.t
-> ?warn_if_no_trailing_newline_in_both:bool
-> t
-> t
val default : t
|
5eac76be182cdc21cdd08e6da2e6d1c30ebce992f931aa0ffe32e7b8e62066e9 | MarchLiu/market | project.clj | (defproject sequences "0.2.2"
:description "FIXME: write description"
:url ""
:license {:name "Eclipse Public License"
:url "-v10.html"}
:source-paths ["src/main/clojure"]
:java-source-paths ["src/main/java"]
:plugins [[lein-junit "1.1.8"]]
:dependencies [[org.clojure/clojure "1.10.0"]
[com.typesafe.akka/akka-actor_2.12 "2.5.19"]
[com.typesafe.akka/akka-remote_2.12 "2.5.19"]
[liu.mars/jaskell "0.1.2"]
[liu.mars/market-messages "0.2"]
[org.postgresql/postgresql "42.2.5"]
[org.clojure/java.jdbc "0.7.8"]
[clj-postgresql "0.7.0"]
[org.clojure/core.specs.alpha "0.1.10" :exclusions [[org.clojure/clojure] [org.clojure/spec.alpha]]]
[org.clojure/spec.alpha "0.1.123" :exclusions [[org.clojure/clojure]]]
[com.fasterxml.jackson.core/jackson-core "2.9.6"]
[com.fasterxml.jackson.core/jackson-databind "2.9.6"]
[com.taoensso/nippy "2.14.0"]
[cheshire "5.8.1"]
[com.github.romix.akka/akka-kryo-serialization_2.12 "0.5.2"]]
:aot :all
:uberjar-merge-with {#"\.properties$" [slurp str spit] "reference.conf" [slurp str spit]}
:test-paths ["src/test/clojure" "src/test/java"]
:resource-paths ["resources/main"]
:junit ["src/test/java"]
:profiles {:server {:main liu.mars.market.SequencesApp
:jvm-opts ["-Dconfig.resource=server.conf"]
:resource-paths ["resources/server"]}
:test {:dependencies [[junit/junit "4.12"]
[com.typesafe.akka/akka-testkit_2.12 "2.5.19"]]
:resource-paths ["resources/test"]
:java-source-paths ["src/test/java"]
:jvm-opts ["-Dconfig.resource=test.conf"]}})
| null | https://raw.githubusercontent.com/MarchLiu/market/7a7daf6c04b41e0f8494be6740da8d54785c5e77/sequences/project.clj | clojure | (defproject sequences "0.2.2"
:description "FIXME: write description"
:url ""
:license {:name "Eclipse Public License"
:url "-v10.html"}
:source-paths ["src/main/clojure"]
:java-source-paths ["src/main/java"]
:plugins [[lein-junit "1.1.8"]]
:dependencies [[org.clojure/clojure "1.10.0"]
[com.typesafe.akka/akka-actor_2.12 "2.5.19"]
[com.typesafe.akka/akka-remote_2.12 "2.5.19"]
[liu.mars/jaskell "0.1.2"]
[liu.mars/market-messages "0.2"]
[org.postgresql/postgresql "42.2.5"]
[org.clojure/java.jdbc "0.7.8"]
[clj-postgresql "0.7.0"]
[org.clojure/core.specs.alpha "0.1.10" :exclusions [[org.clojure/clojure] [org.clojure/spec.alpha]]]
[org.clojure/spec.alpha "0.1.123" :exclusions [[org.clojure/clojure]]]
[com.fasterxml.jackson.core/jackson-core "2.9.6"]
[com.fasterxml.jackson.core/jackson-databind "2.9.6"]
[com.taoensso/nippy "2.14.0"]
[cheshire "5.8.1"]
[com.github.romix.akka/akka-kryo-serialization_2.12 "0.5.2"]]
:aot :all
:uberjar-merge-with {#"\.properties$" [slurp str spit] "reference.conf" [slurp str spit]}
:test-paths ["src/test/clojure" "src/test/java"]
:resource-paths ["resources/main"]
:junit ["src/test/java"]
:profiles {:server {:main liu.mars.market.SequencesApp
:jvm-opts ["-Dconfig.resource=server.conf"]
:resource-paths ["resources/server"]}
:test {:dependencies [[junit/junit "4.12"]
[com.typesafe.akka/akka-testkit_2.12 "2.5.19"]]
:resource-paths ["resources/test"]
:java-source-paths ["src/test/java"]
:jvm-opts ["-Dconfig.resource=test.conf"]}})
| |
58ab819bdbffe306a930f9f750e939526ece831e20fb035f55822a360d013027 | BinaryAnalysisPlatform/bap | regular_data_write.ml | open Core_kernel[@@warning "-D"]
open Regular_data_types
type bytes = Regular_bytes.t
type 'a t = {
size : 'a -> int;
copy : ('a,bytes) copy;
blit : ('a,bigstring) copy;
dump : Out_channel.t -> 'a -> unit;
pp : Format.formatter -> 'a -> unit;
to_bytes : 'a -> bytes;
to_bigstring : 'a -> bigstring;
} [@@deriving fields]
let not_sufficient () =
invalid_arg "Writable class definition is not complete"
let bytes_to_bytes ~dst ~src dst_pos =
Bytes.blito ~src ~dst ~dst_pos ()
let bytes_to_bigstring ~dst ~src dst_pos =
Bigstring.From_bytes.blito ~src ~dst ~dst_pos ()
let bigstring_to_bytes ~dst ~src dst_pos =
Bigstring.To_bytes.blito ~src ~dst ~dst_pos ()
let bigstring_to_bigstring ~dst ~src dst_pos =
Bigstring.blito ~dst ~src ~dst_pos ()
let copy_via_blit size blit ~dst x pos =
let buf = Bigstring.create (size x) in
blit buf x 0;
bigstring_to_bytes ~dst ~src:buf pos
let blit_via_copy size copy ~dst x pos =
let str = Bytes.create (size x) in
copy str x 0;
bytes_to_bigstring ~dst ~src:str pos
let bytes_via_copy size copy x =
let buf = Bytes.create (size x) in
copy buf x 0;
buf
let bigstring_via_blit size blit x =
let buf = Bigstring.create (size x) in
blit buf x;
buf
let pp_bytes f x = Format.asprintf "%a" f x |> Bytes.of_string
let create
?to_bytes ?to_bigstring
?dump ?pp ?size
?blit_to_string:copy ?blit_to_bigstring:(blit:('a,bigstring) copy option) () =
let to_bytes = match to_bytes,to_bigstring,pp with
| Some f,_,_ -> Some f
| None,Some f,_ -> Some (fun x -> Bigstring.to_bytes (f x))
| None,None,Some f -> Some (pp_bytes f)
| None,None,None -> None in
let size = match size, to_bytes, to_bigstring with
| None,None,None -> not_sufficient ()
| Some f,_,_ -> f
| _,Some f,_ -> fun x -> Bytes.length (f x)
| _,_,Some f -> fun x -> Bigstring.length (f x) in
let copy = match copy,to_bytes,blit,to_bigstring with
| None,None,None,None -> not_sufficient ()
| Some f,_,_,_ -> f
| _,Some f,_,_ -> fun dst x -> bytes_to_bytes ~dst ~src:(f x)
| _,_,Some f,_ -> fun dst x -> copy_via_blit size f ~dst x
| _,_,_,Some f -> fun dst x -> bigstring_to_bytes ~dst ~src:(f x) in
let blit : ('a,bigstring) copy = match blit,to_bytes,to_bigstring with
| Some f,_,_ -> f
| _,Some f,_ -> fun dst x -> bytes_to_bigstring ~dst ~src:(f x)
| _,_,Some f -> fun dst x -> bigstring_to_bigstring ~dst ~src:(f x)
| _ -> fun dst x -> blit_via_copy size copy ~dst x in
let to_bytes = match to_bytes with
| Some f -> f
| None -> bytes_via_copy size copy in
let pp = match pp with
| Some f -> f
| None -> fun ppf x -> Format.fprintf ppf "%s" (Bytes.to_string (to_bytes x)) in
let to_bigstring = match to_bigstring with
| Some f -> f
| None -> fun x -> Bigstring.of_bytes (to_bytes x) in
let dump = match dump with
| Some f -> f
| None -> fun c x ->
let ppf = Format.formatter_of_out_channel c in
pp ppf x;
Format.pp_print_flush ppf () in
{size; copy; blit; dump; pp; to_bytes; to_bigstring}
let blit_to_string = copy
let blit_to_bytes = copy
let blit_to_bigstring = blit
let to_channel = dump
let to_formatter = pp
| null | https://raw.githubusercontent.com/BinaryAnalysisPlatform/bap/7eb7cbfbed0a46d6511efe416e4bee32d6c39be8/lib/regular/regular_data_write.ml | ocaml | open Core_kernel[@@warning "-D"]
open Regular_data_types
type bytes = Regular_bytes.t
type 'a t = {
size : 'a -> int;
copy : ('a,bytes) copy;
blit : ('a,bigstring) copy;
dump : Out_channel.t -> 'a -> unit;
pp : Format.formatter -> 'a -> unit;
to_bytes : 'a -> bytes;
to_bigstring : 'a -> bigstring;
} [@@deriving fields]
let not_sufficient () =
invalid_arg "Writable class definition is not complete"
let bytes_to_bytes ~dst ~src dst_pos =
Bytes.blito ~src ~dst ~dst_pos ()
let bytes_to_bigstring ~dst ~src dst_pos =
Bigstring.From_bytes.blito ~src ~dst ~dst_pos ()
let bigstring_to_bytes ~dst ~src dst_pos =
Bigstring.To_bytes.blito ~src ~dst ~dst_pos ()
let bigstring_to_bigstring ~dst ~src dst_pos =
Bigstring.blito ~dst ~src ~dst_pos ()
let copy_via_blit size blit ~dst x pos =
let buf = Bigstring.create (size x) in
blit buf x 0;
bigstring_to_bytes ~dst ~src:buf pos
let blit_via_copy size copy ~dst x pos =
let str = Bytes.create (size x) in
copy str x 0;
bytes_to_bigstring ~dst ~src:str pos
let bytes_via_copy size copy x =
let buf = Bytes.create (size x) in
copy buf x 0;
buf
let bigstring_via_blit size blit x =
let buf = Bigstring.create (size x) in
blit buf x;
buf
let pp_bytes f x = Format.asprintf "%a" f x |> Bytes.of_string
let create
?to_bytes ?to_bigstring
?dump ?pp ?size
?blit_to_string:copy ?blit_to_bigstring:(blit:('a,bigstring) copy option) () =
let to_bytes = match to_bytes,to_bigstring,pp with
| Some f,_,_ -> Some f
| None,Some f,_ -> Some (fun x -> Bigstring.to_bytes (f x))
| None,None,Some f -> Some (pp_bytes f)
| None,None,None -> None in
let size = match size, to_bytes, to_bigstring with
| None,None,None -> not_sufficient ()
| Some f,_,_ -> f
| _,Some f,_ -> fun x -> Bytes.length (f x)
| _,_,Some f -> fun x -> Bigstring.length (f x) in
let copy = match copy,to_bytes,blit,to_bigstring with
| None,None,None,None -> not_sufficient ()
| Some f,_,_,_ -> f
| _,Some f,_,_ -> fun dst x -> bytes_to_bytes ~dst ~src:(f x)
| _,_,Some f,_ -> fun dst x -> copy_via_blit size f ~dst x
| _,_,_,Some f -> fun dst x -> bigstring_to_bytes ~dst ~src:(f x) in
let blit : ('a,bigstring) copy = match blit,to_bytes,to_bigstring with
| Some f,_,_ -> f
| _,Some f,_ -> fun dst x -> bytes_to_bigstring ~dst ~src:(f x)
| _,_,Some f -> fun dst x -> bigstring_to_bigstring ~dst ~src:(f x)
| _ -> fun dst x -> blit_via_copy size copy ~dst x in
let to_bytes = match to_bytes with
| Some f -> f
| None -> bytes_via_copy size copy in
let pp = match pp with
| Some f -> f
| None -> fun ppf x -> Format.fprintf ppf "%s" (Bytes.to_string (to_bytes x)) in
let to_bigstring = match to_bigstring with
| Some f -> f
| None -> fun x -> Bigstring.of_bytes (to_bytes x) in
let dump = match dump with
| Some f -> f
| None -> fun c x ->
let ppf = Format.formatter_of_out_channel c in
pp ppf x;
Format.pp_print_flush ppf () in
{size; copy; blit; dump; pp; to_bytes; to_bigstring}
let blit_to_string = copy
let blit_to_bytes = copy
let blit_to_bigstring = blit
let to_channel = dump
let to_formatter = pp
| |
5dbdb74ff36e4526a1b5a97782ad1ecee7d882ec90fa07b2b93add80e46a9c34 | aantron/luv | network.ml | This file is part of Luv , released under the MIT license . See LICENSE.md for
details , or visit .
details, or visit . *)
module Interface_address =
struct
type t = {
name : string;
is_internal : bool;
physical : string;
address : Sockaddr.t;
netmask : Sockaddr.t;
}
let c_sockaddr_length =
Ctypes.(max (sizeof C.Types.Sockaddr.in_) (sizeof C.Types.Sockaddr.in6))
end
let load_address value =
Ctypes.(coerce
(ptr C.Types.Sockaddr.in_) (ptr C.Types.Sockaddr.t) (addr value))
|> Sockaddr.copy_sockaddr Interface_address.c_sockaddr_length
let interface_addresses () =
let module IA = C.Types.Network.Interface_address in
let null = Ctypes.(from_voidp IA.t null) in
let interfaces = Ctypes.(allocate (ptr IA.t)) null in
let count = Ctypes.(allocate int) 0 in
C.Functions.Network.interface_addresses interfaces count
|> Error.to_result_lazy begin fun () ->
let interfaces = Ctypes.(!@) interfaces in
let count = Ctypes.(!@) count in
let rec convert index =
if index >= count then
[]
else begin
let c_interface = Ctypes.(!@ (interfaces +@ index)) in
let physical = Ctypes.getf c_interface IA.phys_addr in
let interface = Interface_address.{
name = Ctypes.getf c_interface IA.name;
is_internal = Ctypes.getf c_interface IA.is_internal;
physical = String.init 6 (Ctypes.CArray.get physical);
address = load_address (Ctypes.getf c_interface IA.address4);
netmask = load_address (Ctypes.getf c_interface IA.netmask4);
}
in
interface::(convert (index + 1))
end
in
let converted_interfaces = convert 0 in
C.Functions.Network.free_interface_addresses interfaces count;
converted_interfaces
end
let generic_toname c_function index =
let length = C.Types.Network.if_namesize in
let buffer = Bytes.create length in
c_function
(Unsigned.UInt.of_int index)
(Ctypes.ocaml_bytes_start buffer)
(Ctypes.(allocate size_t) (Unsigned.Size_t.of_int length))
|> Error.to_result_lazy begin fun () ->
let length = Bytes.index buffer '\000' in
Bytes.sub_string buffer 0 length
end
let if_indextoname = generic_toname C.Functions.Network.if_indextoname
let if_indextoiid = generic_toname C.Functions.Network.if_indextoiid
let gethostname () =
let length = C.Types.Network.maxhostnamesize in
let buffer = Bytes.create length in
C.Functions.Network.gethostname
(Ctypes.ocaml_bytes_start buffer)
(Ctypes.(allocate size_t) (Unsigned.Size_t.of_int length))
|> Error.to_result_lazy begin fun () ->
let length = Bytes.index buffer '\000' in
Bytes.sub_string buffer 0 length
end
| null | https://raw.githubusercontent.com/aantron/luv/4b49d3edad2179c76d685500edf1b44f61ec4be8/src/network.ml | ocaml | This file is part of Luv , released under the MIT license . See LICENSE.md for
details , or visit .
details, or visit . *)
module Interface_address =
struct
type t = {
name : string;
is_internal : bool;
physical : string;
address : Sockaddr.t;
netmask : Sockaddr.t;
}
let c_sockaddr_length =
Ctypes.(max (sizeof C.Types.Sockaddr.in_) (sizeof C.Types.Sockaddr.in6))
end
let load_address value =
Ctypes.(coerce
(ptr C.Types.Sockaddr.in_) (ptr C.Types.Sockaddr.t) (addr value))
|> Sockaddr.copy_sockaddr Interface_address.c_sockaddr_length
let interface_addresses () =
let module IA = C.Types.Network.Interface_address in
let null = Ctypes.(from_voidp IA.t null) in
let interfaces = Ctypes.(allocate (ptr IA.t)) null in
let count = Ctypes.(allocate int) 0 in
C.Functions.Network.interface_addresses interfaces count
|> Error.to_result_lazy begin fun () ->
let interfaces = Ctypes.(!@) interfaces in
let count = Ctypes.(!@) count in
let rec convert index =
if index >= count then
[]
else begin
let c_interface = Ctypes.(!@ (interfaces +@ index)) in
let physical = Ctypes.getf c_interface IA.phys_addr in
let interface = Interface_address.{
name = Ctypes.getf c_interface IA.name;
is_internal = Ctypes.getf c_interface IA.is_internal;
physical = String.init 6 (Ctypes.CArray.get physical);
address = load_address (Ctypes.getf c_interface IA.address4);
netmask = load_address (Ctypes.getf c_interface IA.netmask4);
}
in
interface::(convert (index + 1))
end
in
let converted_interfaces = convert 0 in
C.Functions.Network.free_interface_addresses interfaces count;
converted_interfaces
end
let generic_toname c_function index =
let length = C.Types.Network.if_namesize in
let buffer = Bytes.create length in
c_function
(Unsigned.UInt.of_int index)
(Ctypes.ocaml_bytes_start buffer)
(Ctypes.(allocate size_t) (Unsigned.Size_t.of_int length))
|> Error.to_result_lazy begin fun () ->
let length = Bytes.index buffer '\000' in
Bytes.sub_string buffer 0 length
end
let if_indextoname = generic_toname C.Functions.Network.if_indextoname
let if_indextoiid = generic_toname C.Functions.Network.if_indextoiid
let gethostname () =
let length = C.Types.Network.maxhostnamesize in
let buffer = Bytes.create length in
C.Functions.Network.gethostname
(Ctypes.ocaml_bytes_start buffer)
(Ctypes.(allocate size_t) (Unsigned.Size_t.of_int length))
|> Error.to_result_lazy begin fun () ->
let length = Bytes.index buffer '\000' in
Bytes.sub_string buffer 0 length
end
| |
9b6ad8a6fd1eb0481eab2c75b84fcb2144aebe0c1c561873b74a3f61a49f1a1a | ghcjs/jsaddle-dom | Headers.hs | # LANGUAGE PatternSynonyms #
-- For HasCallStack compatibility
{-# LANGUAGE ImplicitParams, ConstraintKinds, KindSignatures #-}
# OPTIONS_GHC -fno - warn - unused - imports #
module JSDOM.Generated.Headers
(append, delete, get, get_, getUnsafe, getUnchecked, has, has_,
set, Headers(..), gTypeHeaders)
where
import Prelude ((.), (==), (>>=), return, IO, Int, Float, Double, Bool(..), Maybe, maybe, fromIntegral, round, realToFrac, fmap, Show, Read, Eq, Ord, Maybe(..))
import qualified Prelude (error)
import Data.Typeable (Typeable)
import Data.Traversable (mapM)
import Language.Javascript.JSaddle (JSM(..), JSVal(..), JSString, strictEqual, toJSVal, valToStr, valToNumber, valToBool, js, jss, jsf, jsg, function, asyncFunction, new, array, jsUndefined, (!), (!!))
import Data.Int (Int64)
import Data.Word (Word, Word64)
import JSDOM.Types
import Control.Applicative ((<$>))
import Control.Monad (void)
import Control.Lens.Operators ((^.))
import JSDOM.EventTargetClosures (EventName, unsafeEventName, unsafeEventNameAsync)
import JSDOM.Enums
| < -US/docs/Web/API/Headers.append Mozilla Headers.append documentation >
append ::
(MonadDOM m, ToJSString name, ToJSString value) =>
Headers -> name -> value -> m ()
append self name value
= liftDOM
(void (self ^. jsf "append" [toJSVal name, toJSVal value]))
| < -US/docs/Web/API/Headers.delete Mozilla Headers.delete documentation >
delete :: (MonadDOM m, ToJSString name) => Headers -> name -> m ()
delete self name
= liftDOM (void (self ^. jsf "delete" [toJSVal name]))
| < -US/docs/Web/API/Headers.get Mozilla Headers.get documentation >
get ::
(MonadDOM m, ToJSString name, FromJSString result) =>
Headers -> name -> m (Maybe result)
get self name
= liftDOM
((self ^. jsf "get" [toJSVal name]) >>= fromMaybeJSString)
| < -US/docs/Web/API/Headers.get Mozilla Headers.get documentation >
get_ :: (MonadDOM m, ToJSString name) => Headers -> name -> m ()
get_ self name = liftDOM (void (self ^. jsf "get" [toJSVal name]))
| < -US/docs/Web/API/Headers.get Mozilla Headers.get documentation >
getUnsafe ::
(MonadDOM m, ToJSString name, HasCallStack, FromJSString result) =>
Headers -> name -> m result
getUnsafe self name
= liftDOM
(((self ^. jsf "get" [toJSVal name]) >>= fromMaybeJSString) >>=
maybe (Prelude.error "Nothing to return") return)
| < -US/docs/Web/API/Headers.get Mozilla Headers.get documentation >
getUnchecked ::
(MonadDOM m, ToJSString name, FromJSString result) =>
Headers -> name -> m result
getUnchecked self name
= liftDOM
((self ^. jsf "get" [toJSVal name]) >>= fromJSValUnchecked)
| < -US/docs/Web/API/Headers.has Mozilla Headers.has documentation >
has :: (MonadDOM m, ToJSString name) => Headers -> name -> m Bool
has self name
= liftDOM ((self ^. jsf "has" [toJSVal name]) >>= valToBool)
| < -US/docs/Web/API/Headers.has Mozilla Headers.has documentation >
has_ :: (MonadDOM m, ToJSString name) => Headers -> name -> m ()
has_ self name = liftDOM (void (self ^. jsf "has" [toJSVal name]))
| < -US/docs/Web/API/Headers.set Mozilla Headers.set documentation >
set ::
(MonadDOM m, ToJSString name, ToJSString value) =>
Headers -> name -> value -> m ()
set self name value
= liftDOM (void (self ^. jsf "set" [toJSVal name, toJSVal value]))
| null | https://raw.githubusercontent.com/ghcjs/jsaddle-dom/5f5094277d4b11f3dc3e2df6bb437b75712d268f/src/JSDOM/Generated/Headers.hs | haskell | For HasCallStack compatibility
# LANGUAGE ImplicitParams, ConstraintKinds, KindSignatures # | # LANGUAGE PatternSynonyms #
# OPTIONS_GHC -fno - warn - unused - imports #
module JSDOM.Generated.Headers
(append, delete, get, get_, getUnsafe, getUnchecked, has, has_,
set, Headers(..), gTypeHeaders)
where
import Prelude ((.), (==), (>>=), return, IO, Int, Float, Double, Bool(..), Maybe, maybe, fromIntegral, round, realToFrac, fmap, Show, Read, Eq, Ord, Maybe(..))
import qualified Prelude (error)
import Data.Typeable (Typeable)
import Data.Traversable (mapM)
import Language.Javascript.JSaddle (JSM(..), JSVal(..), JSString, strictEqual, toJSVal, valToStr, valToNumber, valToBool, js, jss, jsf, jsg, function, asyncFunction, new, array, jsUndefined, (!), (!!))
import Data.Int (Int64)
import Data.Word (Word, Word64)
import JSDOM.Types
import Control.Applicative ((<$>))
import Control.Monad (void)
import Control.Lens.Operators ((^.))
import JSDOM.EventTargetClosures (EventName, unsafeEventName, unsafeEventNameAsync)
import JSDOM.Enums
| < -US/docs/Web/API/Headers.append Mozilla Headers.append documentation >
append ::
(MonadDOM m, ToJSString name, ToJSString value) =>
Headers -> name -> value -> m ()
append self name value
= liftDOM
(void (self ^. jsf "append" [toJSVal name, toJSVal value]))
| < -US/docs/Web/API/Headers.delete Mozilla Headers.delete documentation >
delete :: (MonadDOM m, ToJSString name) => Headers -> name -> m ()
delete self name
= liftDOM (void (self ^. jsf "delete" [toJSVal name]))
| < -US/docs/Web/API/Headers.get Mozilla Headers.get documentation >
get ::
(MonadDOM m, ToJSString name, FromJSString result) =>
Headers -> name -> m (Maybe result)
get self name
= liftDOM
((self ^. jsf "get" [toJSVal name]) >>= fromMaybeJSString)
| < -US/docs/Web/API/Headers.get Mozilla Headers.get documentation >
get_ :: (MonadDOM m, ToJSString name) => Headers -> name -> m ()
get_ self name = liftDOM (void (self ^. jsf "get" [toJSVal name]))
| < -US/docs/Web/API/Headers.get Mozilla Headers.get documentation >
getUnsafe ::
(MonadDOM m, ToJSString name, HasCallStack, FromJSString result) =>
Headers -> name -> m result
getUnsafe self name
= liftDOM
(((self ^. jsf "get" [toJSVal name]) >>= fromMaybeJSString) >>=
maybe (Prelude.error "Nothing to return") return)
| < -US/docs/Web/API/Headers.get Mozilla Headers.get documentation >
getUnchecked ::
(MonadDOM m, ToJSString name, FromJSString result) =>
Headers -> name -> m result
getUnchecked self name
= liftDOM
((self ^. jsf "get" [toJSVal name]) >>= fromJSValUnchecked)
| < -US/docs/Web/API/Headers.has Mozilla Headers.has documentation >
has :: (MonadDOM m, ToJSString name) => Headers -> name -> m Bool
has self name
= liftDOM ((self ^. jsf "has" [toJSVal name]) >>= valToBool)
| < -US/docs/Web/API/Headers.has Mozilla Headers.has documentation >
has_ :: (MonadDOM m, ToJSString name) => Headers -> name -> m ()
has_ self name = liftDOM (void (self ^. jsf "has" [toJSVal name]))
| < -US/docs/Web/API/Headers.set Mozilla Headers.set documentation >
set ::
(MonadDOM m, ToJSString name, ToJSString value) =>
Headers -> name -> value -> m ()
set self name value
= liftDOM (void (self ^. jsf "set" [toJSVal name, toJSVal value]))
|
af5a2ff93627befac84e3a8939a1ee2b47e5645437f1d2962ac7720c6b54577b | lamdu/lamdu | Code.hs | -- | Code texts
{-# OPTIONS -O0 #-}
# LANGUAGE TemplateHaskell , DerivingVia #
module Lamdu.I18N.Code where
import qualified Control.Lens as Lens
import qualified Data.Aeson.TH.Extended as JsonTH
import GUI.Momentu.Element.Id (ElemIds)
import Lamdu.Prelude
-- All words here are reserved (conflicted when used as user names)
data Code a = Code
{ _assign :: a -- Assignment
, _punnedFields :: a -- Apply
, _let_ :: a
, _repl :: a
, -- Case
_case_ :: a
, -- If:
_if_ :: a
, _else_ :: a
shorthand for else - if , " elif " a la Python
, -- Inject
_injectSymbol :: a
, -- Lambda:
_defer :: a
, _lam :: a
, _arrow :: a
, -- Literal a:
_textOpener :: a
, _textCloser :: a
, -- Record:
_recordOpener :: a
, _caseOpener :: a
, _compositeSeparator :: a
, _compositeExtendTail :: a
, _recordCloser :: a
, _caseCloser :: a
-- Kinds
, _typ :: a
, _row :: a
}
deriving stock (Generic, Generic1, Eq, Functor, Foldable, Traversable)
deriving anyclass ElemIds
deriving Applicative via (Generically1 Code)
Lens.makeLenses ''Code
JsonTH.derivePrefixed "_" ''Code
| null | https://raw.githubusercontent.com/lamdu/lamdu/5b15688e53ccbf7448ff11134b3e51ed082c6b6c/src/Lamdu/I18N/Code.hs | haskell | | Code texts
# OPTIONS -O0 #
All words here are reserved (conflicted when used as user names)
Assignment
Apply
Case
If:
Inject
Lambda:
Literal a:
Record:
Kinds | # LANGUAGE TemplateHaskell , DerivingVia #
module Lamdu.I18N.Code where
import qualified Control.Lens as Lens
import qualified Data.Aeson.TH.Extended as JsonTH
import GUI.Momentu.Element.Id (ElemIds)
import Lamdu.Prelude
data Code a = Code
, _let_ :: a
, _repl :: a
_case_ :: a
_if_ :: a
, _else_ :: a
shorthand for else - if , " elif " a la Python
_injectSymbol :: a
_defer :: a
, _lam :: a
, _arrow :: a
_textOpener :: a
, _textCloser :: a
_recordOpener :: a
, _caseOpener :: a
, _compositeSeparator :: a
, _compositeExtendTail :: a
, _recordCloser :: a
, _caseCloser :: a
, _typ :: a
, _row :: a
}
deriving stock (Generic, Generic1, Eq, Functor, Foldable, Traversable)
deriving anyclass ElemIds
deriving Applicative via (Generically1 Code)
Lens.makeLenses ''Code
JsonTH.derivePrefixed "_" ''Code
|
0c0062d3dd15e861c23ed1be11ad0f30633ee1f9ffc4e9b3da0dd894348c9a38 | robert-strandh/Clump | test-2-3-tree.lisp | (cl:in-package #:clump-test)
(defclass size-mixin ()
((%size :initarg :size :accessor size)))
(defmethod clump-2-3-tree:replace :after
((node size-mixin) old-child new-child)
(declare (ignore old-child new-child))
(recompute-size node))
(defmethod clump-2-3-tree:split :after
((node size-mixin) old-child new-child-1 new-child-2)
(declare (ignore old-child new-child-1 new-child-2))
(recompute-size node))
(defmethod clump-2-3-tree:replace-and-shrink :after
((node size-mixin) old-child new-child)
(declare (ignore old-child new-child))
(recompute-size node))
(defclass leaf-size (size-mixin clump-2-3-tree:leaf)
()
(:default-initargs :size 1))
(defclass 2-node-size (size-mixin clump-2-3-tree:2-node)
())
(defgeneric recompute-size (node))
(defmethod recompute-size ((node 2-node-size))
(setf (size node)
(+ (size (clump-2-3-tree:left node))
(size (clump-2-3-tree:right node))))
(recompute-size (clump-2-3-tree:parent node)))
(defmethod initialize-instance :after ((object 2-node-size) &key)
(setf (size object)
(+ (size (clump-2-3-tree:left object))
(size (clump-2-3-tree:right object)))))
(defclass 3-node-size (size-mixin clump-2-3-tree:3-node)
())
(defmethod recompute-size ((node 3-node-size))
(setf (size node)
(+ (size (clump-2-3-tree:left node))
(size (clump-2-3-tree:middle node))
(size (clump-2-3-tree:right node))))
(recompute-size (clump-2-3-tree:parent node)))
(defmethod initialize-instance :after ((object 3-node-size) &key)
(setf (size object)
(+ (size (clump-2-3-tree:left object))
(size (clump-2-3-tree:middle object))
(size (clump-2-3-tree:right object)))))
(defclass size-tree (clump-2-3-tree:tree)
()
(:default-initargs
:leaf-class 'leaf-size
:2-node-class '2-node-size
:3-node-class '3-node-size))
(defmethod recompute-size ((tree size-tree))
nil)
(defgeneric find-leaf (node-or-tree leaf-number))
(defmethod find-leaf ((tree size-tree) leaf-number)
(let ((contents (clump-2-3-tree:contents tree)))
(assert (not (null contents)))
(find-leaf contents leaf-number)))
(defmethod find-leaf ((node leaf-size) leaf-number)
(assert (zerop leaf-number))
node)
(defmethod find-leaf ((node 2-node-size) leaf-number)
(let ((left (clump-2-3-tree:left node))
(right (clump-2-3-tree:right node)))
(if (< leaf-number (size left))
(find-leaf left leaf-number)
(find-leaf right (- leaf-number (size left))))))
(defmethod find-leaf ((node 3-node-size) leaf-number)
(let ((left (clump-2-3-tree:left node))
(middle (clump-2-3-tree:middle node))
(right (clump-2-3-tree:right node)))
(cond ((< leaf-number (size left))
(find-leaf left leaf-number))
((< leaf-number (+ (size left) (size middle)))
(find-leaf middle (- leaf-number (size left))))
(t
(find-leaf right (- leaf-number (+ (size left) (size middle))))))))
(defgeneric to-list (node-or-tree))
(defmethod to-list ((tree size-tree))
(let ((contents (clump-2-3-tree:contents tree)))
(if (null contents)
'()
(to-list contents))))
(defmethod to-list ((node leaf-size))
(list (clump-2-3-tree:contents node)))
(defmethod to-list ((node 2-node-size))
(append (to-list (clump-2-3-tree:left node))
(to-list (clump-2-3-tree:right node))))
(defmethod to-list ((node 3-node-size))
(append (to-list (clump-2-3-tree:left node))
(to-list (clump-2-3-tree:middle node))
(to-list (clump-2-3-tree:right node))))
(defun check-result (tree list)
(assert (or (and (null list)
(null (clump-2-3-tree:contents tree)))
(= (length list)
(size (clump-2-3-tree:contents tree)))))
(assert (equal (to-list tree) list)))
(defun test-2-3-tree-1 (n)
(let ((operation :insert)
(list '())
(tree (make-instance 'size-tree)))
(flet ((insert-before (position)
(let ((neighbor (find-leaf tree position))
(element (random 1000000000)))
(clump-2-3-tree:insert-before element neighbor)
(setf list
(append (subseq list 0 position)
(list element)
(subseq list position)))))
(insert-after (position)
(let ((neighbor (find-leaf tree position))
(element (random 1000000000)))
(clump-2-3-tree:insert-after element neighbor)
(setf list
(append (subseq list 0 (1+ position))
(list element)
(subseq list (1+ position)))))))
(loop repeat n
do (when (< (random 1d0) 1d-1)
(setf operation
(if (eq operation :insert)
:delete
:insert)))
(if (or (eq operation :insert) (null list))
(if (null list)
(let ((element (random 1000000000)))
(setf list (list element))
(clump-2-3-tree:insert element tree))
(let ((position (random (1+ (length list)))))
(cond ((zerop position)
(insert-before 0))
((= position (length list))
(insert-after (1- (length list))))
((< (random 1d0) 0.5d0)
(insert-before position))
(t
(insert-after (1- position))))))
(let* ((position (random (length list)))
(leaf (find-leaf tree position)))
(clump-2-3-tree:delete leaf)
(setf list
(append (subseq list 0 position)
(subseq list (1+ position))))))
(check-result tree list)))))
| null | https://raw.githubusercontent.com/robert-strandh/Clump/1ea4dbac1cb86713acff9ae58727dd187d21048a/Test/test-2-3-tree.lisp | lisp | (cl:in-package #:clump-test)
(defclass size-mixin ()
((%size :initarg :size :accessor size)))
(defmethod clump-2-3-tree:replace :after
((node size-mixin) old-child new-child)
(declare (ignore old-child new-child))
(recompute-size node))
(defmethod clump-2-3-tree:split :after
((node size-mixin) old-child new-child-1 new-child-2)
(declare (ignore old-child new-child-1 new-child-2))
(recompute-size node))
(defmethod clump-2-3-tree:replace-and-shrink :after
((node size-mixin) old-child new-child)
(declare (ignore old-child new-child))
(recompute-size node))
(defclass leaf-size (size-mixin clump-2-3-tree:leaf)
()
(:default-initargs :size 1))
(defclass 2-node-size (size-mixin clump-2-3-tree:2-node)
())
(defgeneric recompute-size (node))
(defmethod recompute-size ((node 2-node-size))
(setf (size node)
(+ (size (clump-2-3-tree:left node))
(size (clump-2-3-tree:right node))))
(recompute-size (clump-2-3-tree:parent node)))
(defmethod initialize-instance :after ((object 2-node-size) &key)
(setf (size object)
(+ (size (clump-2-3-tree:left object))
(size (clump-2-3-tree:right object)))))
(defclass 3-node-size (size-mixin clump-2-3-tree:3-node)
())
(defmethod recompute-size ((node 3-node-size))
(setf (size node)
(+ (size (clump-2-3-tree:left node))
(size (clump-2-3-tree:middle node))
(size (clump-2-3-tree:right node))))
(recompute-size (clump-2-3-tree:parent node)))
(defmethod initialize-instance :after ((object 3-node-size) &key)
(setf (size object)
(+ (size (clump-2-3-tree:left object))
(size (clump-2-3-tree:middle object))
(size (clump-2-3-tree:right object)))))
(defclass size-tree (clump-2-3-tree:tree)
()
(:default-initargs
:leaf-class 'leaf-size
:2-node-class '2-node-size
:3-node-class '3-node-size))
(defmethod recompute-size ((tree size-tree))
nil)
(defgeneric find-leaf (node-or-tree leaf-number))
(defmethod find-leaf ((tree size-tree) leaf-number)
(let ((contents (clump-2-3-tree:contents tree)))
(assert (not (null contents)))
(find-leaf contents leaf-number)))
(defmethod find-leaf ((node leaf-size) leaf-number)
(assert (zerop leaf-number))
node)
(defmethod find-leaf ((node 2-node-size) leaf-number)
(let ((left (clump-2-3-tree:left node))
(right (clump-2-3-tree:right node)))
(if (< leaf-number (size left))
(find-leaf left leaf-number)
(find-leaf right (- leaf-number (size left))))))
(defmethod find-leaf ((node 3-node-size) leaf-number)
(let ((left (clump-2-3-tree:left node))
(middle (clump-2-3-tree:middle node))
(right (clump-2-3-tree:right node)))
(cond ((< leaf-number (size left))
(find-leaf left leaf-number))
((< leaf-number (+ (size left) (size middle)))
(find-leaf middle (- leaf-number (size left))))
(t
(find-leaf right (- leaf-number (+ (size left) (size middle))))))))
(defgeneric to-list (node-or-tree))
(defmethod to-list ((tree size-tree))
(let ((contents (clump-2-3-tree:contents tree)))
(if (null contents)
'()
(to-list contents))))
(defmethod to-list ((node leaf-size))
(list (clump-2-3-tree:contents node)))
(defmethod to-list ((node 2-node-size))
(append (to-list (clump-2-3-tree:left node))
(to-list (clump-2-3-tree:right node))))
(defmethod to-list ((node 3-node-size))
(append (to-list (clump-2-3-tree:left node))
(to-list (clump-2-3-tree:middle node))
(to-list (clump-2-3-tree:right node))))
(defun check-result (tree list)
(assert (or (and (null list)
(null (clump-2-3-tree:contents tree)))
(= (length list)
(size (clump-2-3-tree:contents tree)))))
(assert (equal (to-list tree) list)))
(defun test-2-3-tree-1 (n)
(let ((operation :insert)
(list '())
(tree (make-instance 'size-tree)))
(flet ((insert-before (position)
(let ((neighbor (find-leaf tree position))
(element (random 1000000000)))
(clump-2-3-tree:insert-before element neighbor)
(setf list
(append (subseq list 0 position)
(list element)
(subseq list position)))))
(insert-after (position)
(let ((neighbor (find-leaf tree position))
(element (random 1000000000)))
(clump-2-3-tree:insert-after element neighbor)
(setf list
(append (subseq list 0 (1+ position))
(list element)
(subseq list (1+ position)))))))
(loop repeat n
do (when (< (random 1d0) 1d-1)
(setf operation
(if (eq operation :insert)
:delete
:insert)))
(if (or (eq operation :insert) (null list))
(if (null list)
(let ((element (random 1000000000)))
(setf list (list element))
(clump-2-3-tree:insert element tree))
(let ((position (random (1+ (length list)))))
(cond ((zerop position)
(insert-before 0))
((= position (length list))
(insert-after (1- (length list))))
((< (random 1d0) 0.5d0)
(insert-before position))
(t
(insert-after (1- position))))))
(let* ((position (random (length list)))
(leaf (find-leaf tree position)))
(clump-2-3-tree:delete leaf)
(setf list
(append (subseq list 0 position)
(subseq list (1+ position))))))
(check-result tree list)))))
| |
91805a5eeee4d43cf478db201de4d253c8878d40f988cb0a915f44b8294c5281 | toschoo/mom | Balancer.hs | {-# Language BangPatterns #-}
-------------------------------------------------------------------------------
-- |
Module : Network / Mom / Stompl / Patterns / Balancer.hs
Copyright : ( c )
-- License : LGPL
-- Stability : experimental
-- Portability: portable
--
-- This module provides a balancer for services and tasks
-- and a topic router.
-- Balancers for services and tasks improve scalability and reliability
-- of servers and workers. Workers should always be used with a balancer
-- (since balancing workload is the main idea of workers);
-- servers can very well be used without a balancer, but won't scale
-- with increasing numbers of clients.
--
-- A balancer consists of a registry to which
-- servers and workers connect;
-- servers and workers are maintained in lists
-- according to the job they provide.
-- Clients and pushers send requests to the balancer,
-- which then forwards the request to a server or worker.
-- The client will receive the reply not through the balancer,
-- but directly from the server (to which the reply queue
-- was forwarded as part of the request message --
-- see 'ClientA' for details).
--
-- With servers and workers sending heartbeats,
-- a balancer also improves reliability
-- in contrast to a topology
-- where a task is pushed to a single worker or
a request is sent to only one server .
--
-- A router is a forwarder of a topic.
-- A router is very similar to a publisher ('PubA')
-- with the difference that the router
-- does not create new topic data,
-- but uses topic data received from a publisher
-- (a router, hence, is a subscriber and a publisher).
Routers can be used to balance the workload of publishers :
Instead of one publisher serving thousands of subscribers ,
the initial publisher would serve thousands of routers ,
which , in their turn , serve thousands of subscribers
-- (or even other routers).
-------------------------------------------------------------------------------
module Network.Mom.Stompl.Patterns.Balancer (
-- * Balancer
withBalancer,
-- * Router
withRouter)
where
import Registry
import Types
import Network.Mom.Stompl.Client.Queue
import Network.Mom.Stompl.Patterns.Basic
import Codec.MIME.Type (nullType)
import Control.Exception (throwIO, catches)
import Control.Monad (forever, unless)
-----------------------------------------------------------------------
| Create a Service and Task Balancer with the lifetime
-- of the application-defined action passed in
-- and start it in a background thread:
--
-- * 'Con': Connection to a Stomp broker;
--
-- * String: Name of the balancer, used for error handling;
--
-- * 'QName': Registration queue -- this queue is used
-- by providers to connect to the registry,
-- it is not used for consumer requests;
--
* ( Int , Int ): Heartbeat range of the ' Registry '
( see ' ' for details ) ;
--
-- * 'QName': Request queue -- this queue is used
-- for consumer requests;
--
-- * 'OnError': Error handling;
--
-- * IO r: Action that defines the lifetime of the balancer;
the result /r/ is also the result of /withBalancer/.
-----------------------------------------------------------------------
withBalancer :: Con -> String -> QName -> (Int, Int) ->
QName -> OnError -> IO r -> IO r
withBalancer c n qn (mn,mx) rq onErr action =
withRegistry c n qn (mn,mx) onErr $ \reg ->
withPair c n (rq, [], [], bytesIn)
("unknown", [], [], bytesOut) $ \(r,w) ->
withThread (balance reg r w) action
where balance reg r w =
forever $ catches (do
m <- readQ r
jn <- getJobName m
t <- mapR reg jn (send2Prov w m)
unless t $ throwIO $ NoProviderX jn)
(ignoreHandler n onErr)
send2Prov w m p = writeAdHoc w (prvQ p) nullType
(msgHdrs m) $ msgContent m
-----------------------------------------------------------------------
-- | Create a router with the lifetime of the
-- application-defined action passed in
-- and start it in a background thread:
--
-- * 'Con': Connection to a Stomp broker;
--
-- * String: Name of the router, used for error handling;
--
* ' JobName ' : Routed topic ;
--
-- * 'QName': Registration queue of the source publisher;
--
-- * 'QName': Queue through which the internal subscriber
-- will receive the topic data from the source publisher;
--
-- * 'QName': Registration queue of the target publisher
-- to which subscribers will connect;
--
-- * Int: Registration timeout
-- (timeout to register at the source publisher);
--
-- * 'QName': Request queue -- this queue is used
-- for consumer requests;
--
-- * 'OnError': Error handling;
--
-- * IO r: Action that defines the lifetime of the router;
the result /r/ is also the result of /withRouter/.
-----------------------------------------------------------------------
withRouter :: Con -> String -> JobName ->
QName -> QName -> QName ->
Int -> OnError -> IO r -> IO r
withRouter c n jn srq ssq trq tmo onErr action =
withPub c n jn trq onErr
("unknown", [], [], bytesOut) $ \p ->
withSubThread c n jn srq tmo
(ssq, [], [], bytesIn) (pub p) onErr action
where pub p m = publish p nullType (msgHdrs m) $ msgContent m
| null | https://raw.githubusercontent.com/toschoo/mom/b58ca23d05c98ab50d9e981bd4ad2cdb76846399/src/stomp-patterns/Network/Mom/Stompl/Patterns/Balancer.hs | haskell | # Language BangPatterns #
-----------------------------------------------------------------------------
|
License : LGPL
Stability : experimental
Portability: portable
This module provides a balancer for services and tasks
and a topic router.
Balancers for services and tasks improve scalability and reliability
of servers and workers. Workers should always be used with a balancer
(since balancing workload is the main idea of workers);
servers can very well be used without a balancer, but won't scale
with increasing numbers of clients.
A balancer consists of a registry to which
servers and workers connect;
servers and workers are maintained in lists
according to the job they provide.
Clients and pushers send requests to the balancer,
which then forwards the request to a server or worker.
The client will receive the reply not through the balancer,
but directly from the server (to which the reply queue
was forwarded as part of the request message --
see 'ClientA' for details).
With servers and workers sending heartbeats,
a balancer also improves reliability
in contrast to a topology
where a task is pushed to a single worker or
A router is a forwarder of a topic.
A router is very similar to a publisher ('PubA')
with the difference that the router
does not create new topic data,
but uses topic data received from a publisher
(a router, hence, is a subscriber and a publisher).
(or even other routers).
-----------------------------------------------------------------------------
* Balancer
* Router
---------------------------------------------------------------------
of the application-defined action passed in
and start it in a background thread:
* 'Con': Connection to a Stomp broker;
* String: Name of the balancer, used for error handling;
* 'QName': Registration queue -- this queue is used
by providers to connect to the registry,
it is not used for consumer requests;
* 'QName': Request queue -- this queue is used
for consumer requests;
* 'OnError': Error handling;
* IO r: Action that defines the lifetime of the balancer;
---------------------------------------------------------------------
---------------------------------------------------------------------
| Create a router with the lifetime of the
application-defined action passed in
and start it in a background thread:
* 'Con': Connection to a Stomp broker;
* String: Name of the router, used for error handling;
* 'QName': Registration queue of the source publisher;
* 'QName': Queue through which the internal subscriber
will receive the topic data from the source publisher;
* 'QName': Registration queue of the target publisher
to which subscribers will connect;
* Int: Registration timeout
(timeout to register at the source publisher);
* 'QName': Request queue -- this queue is used
for consumer requests;
* 'OnError': Error handling;
* IO r: Action that defines the lifetime of the router;
--------------------------------------------------------------------- | Module : Network / Mom / Stompl / Patterns / Balancer.hs
Copyright : ( c )
a request is sent to only one server .
Routers can be used to balance the workload of publishers :
Instead of one publisher serving thousands of subscribers ,
the initial publisher would serve thousands of routers ,
which , in their turn , serve thousands of subscribers
module Network.Mom.Stompl.Patterns.Balancer (
withBalancer,
withRouter)
where
import Registry
import Types
import Network.Mom.Stompl.Client.Queue
import Network.Mom.Stompl.Patterns.Basic
import Codec.MIME.Type (nullType)
import Control.Exception (throwIO, catches)
import Control.Monad (forever, unless)
| Create a Service and Task Balancer with the lifetime
* ( Int , Int ): Heartbeat range of the ' Registry '
( see ' ' for details ) ;
the result /r/ is also the result of /withBalancer/.
withBalancer :: Con -> String -> QName -> (Int, Int) ->
QName -> OnError -> IO r -> IO r
withBalancer c n qn (mn,mx) rq onErr action =
withRegistry c n qn (mn,mx) onErr $ \reg ->
withPair c n (rq, [], [], bytesIn)
("unknown", [], [], bytesOut) $ \(r,w) ->
withThread (balance reg r w) action
where balance reg r w =
forever $ catches (do
m <- readQ r
jn <- getJobName m
t <- mapR reg jn (send2Prov w m)
unless t $ throwIO $ NoProviderX jn)
(ignoreHandler n onErr)
send2Prov w m p = writeAdHoc w (prvQ p) nullType
(msgHdrs m) $ msgContent m
* ' JobName ' : Routed topic ;
the result /r/ is also the result of /withRouter/.
withRouter :: Con -> String -> JobName ->
QName -> QName -> QName ->
Int -> OnError -> IO r -> IO r
withRouter c n jn srq ssq trq tmo onErr action =
withPub c n jn trq onErr
("unknown", [], [], bytesOut) $ \p ->
withSubThread c n jn srq tmo
(ssq, [], [], bytesIn) (pub p) onErr action
where pub p m = publish p nullType (msgHdrs m) $ msgContent m
|
841330e76f7217e0d88a115a8288f5108668eba87ae5c49a9755d62f0cd1d162 | tallaproject/onion | prop_dh.erl | %%%
Copyright ( c ) 2016 The Talla Authors . All rights reserved .
%%% Use of this source code is governed by a BSD-style
%%% license that can be found in the LICENSE file.
%%%
%%% -----------------------------------------------------------
@author < >
%%% @doc Property Tests for onion_dh.
%%% @end
%%% -----------------------------------------------------------
-module(prop_dh).
%% Properties.
-export([prop_shared_secret/0,
prop_degenerate/0,
prop_public_key_not_degenerate/0
]).
-include_lib("onion/include/onion_test.hrl").
-spec prop_shared_secret() -> term().
prop_shared_secret() ->
?FORALL({{AS, AP}, {BS, BP}}, {test_keypair(), test_keypair()},
begin
{ok, SharedA} = onion_dh:shared_secret(AS, BP),
{ok, SharedB} = onion_dh:shared_secret(BS, AP),
SharedA =:= SharedB
end).
-spec prop_degenerate() -> term().
prop_degenerate() ->
?FORALL(BadPublicKey, bad_public_key(),
begin
onion_dh:is_degenerate(BadPublicKey)
end).
-spec prop_public_key_not_degenerate() -> term().
prop_public_key_not_degenerate() ->
?FORALL({_, P}, test_keypair(),
begin
not onion_dh:is_degenerate(P)
end).
@private
-spec bad_public_key() -> term().
bad_public_key() ->
?LET(P, p(),
?LET(G, g(),
begin
oneof([
%% All negative numbers.
neg_integer(),
0 and 1 .
integer(0, 1),
%% The generator.
G,
%% P - 1 towards infinity.
integer(P - 1, inf)
])
end)).
@private
-spec p() -> term().
p() ->
?LET(L, onion_dh:params(), hd(L)).
@private
-spec g() -> term().
g() ->
?LET(L, onion_dh:params(), lists:last(L)).
@private
-spec test_keypair() -> term().
test_keypair() ->
#{ secret := SecretKey, public := PublicKey } = onion_dh:keypair(),
{SecretKey, PublicKey}.
| null | https://raw.githubusercontent.com/tallaproject/onion/d0c3f86c726c302744d3cfffa2de21f85c190cf0/test/prop_dh.erl | erlang |
Use of this source code is governed by a BSD-style
license that can be found in the LICENSE file.
-----------------------------------------------------------
@doc Property Tests for onion_dh.
@end
-----------------------------------------------------------
Properties.
All negative numbers.
The generator.
P - 1 towards infinity. | Copyright ( c ) 2016 The Talla Authors . All rights reserved .
@author < >
-module(prop_dh).
-export([prop_shared_secret/0,
prop_degenerate/0,
prop_public_key_not_degenerate/0
]).
-include_lib("onion/include/onion_test.hrl").
-spec prop_shared_secret() -> term().
prop_shared_secret() ->
?FORALL({{AS, AP}, {BS, BP}}, {test_keypair(), test_keypair()},
begin
{ok, SharedA} = onion_dh:shared_secret(AS, BP),
{ok, SharedB} = onion_dh:shared_secret(BS, AP),
SharedA =:= SharedB
end).
-spec prop_degenerate() -> term().
prop_degenerate() ->
?FORALL(BadPublicKey, bad_public_key(),
begin
onion_dh:is_degenerate(BadPublicKey)
end).
-spec prop_public_key_not_degenerate() -> term().
prop_public_key_not_degenerate() ->
?FORALL({_, P}, test_keypair(),
begin
not onion_dh:is_degenerate(P)
end).
@private
-spec bad_public_key() -> term().
bad_public_key() ->
?LET(P, p(),
?LET(G, g(),
begin
oneof([
neg_integer(),
0 and 1 .
integer(0, 1),
G,
integer(P - 1, inf)
])
end)).
@private
-spec p() -> term().
p() ->
?LET(L, onion_dh:params(), hd(L)).
@private
-spec g() -> term().
g() ->
?LET(L, onion_dh:params(), lists:last(L)).
@private
-spec test_keypair() -> term().
test_keypair() ->
#{ secret := SecretKey, public := PublicKey } = onion_dh:keypair(),
{SecretKey, PublicKey}.
|
0f9a97e624d5c7a85fd0b24b8aa64e2c0ba9f13e32bb90a34077dd4099e2a0d3 | GlideAngle/flare-timing | HLint.hs | module Main (main) where
import Language.Haskell.HLint (hlint)
import System.Exit (exitFailure, exitSuccess)
arguments :: [String]
arguments =
[ "library"
, "test-suite-hlint"
, "test-suite-parse"
-- WARNING: HLint turns off QuasiQuotes even if turned on in
default - extensions in the cabal file , # 55 .
-- SEE:
, "-XQuasiQuotes"
]
main :: IO ()
main = do
hints <- hlint arguments
if null hints then exitSuccess else exitFailure
| null | https://raw.githubusercontent.com/GlideAngle/flare-timing/27bd34c1943496987382091441a1c2516c169263/lang-haskell/kml/test-suite-hlint/HLint.hs | haskell | WARNING: HLint turns off QuasiQuotes even if turned on in
SEE: | module Main (main) where
import Language.Haskell.HLint (hlint)
import System.Exit (exitFailure, exitSuccess)
arguments :: [String]
arguments =
[ "library"
, "test-suite-hlint"
, "test-suite-parse"
default - extensions in the cabal file , # 55 .
, "-XQuasiQuotes"
]
main :: IO ()
main = do
hints <- hlint arguments
if null hints then exitSuccess else exitFailure
|
1f6cb88fc2f50ade2d90b110d366b5605d728c59c9d9f113e4ae084d21fe6814 | UU-ComputerScience/uhc | CString.hs | # EXCLUDE_IF_TARGET js #
{-# EXCLUDE_IF_TARGET cr #-}
module CString (module Foreign.C.String) where
import Foreign.C.String
| null | https://raw.githubusercontent.com/UU-ComputerScience/uhc/f2b94a90d26e2093d84044b3832a9a3e3c36b129/EHC/ehclib/haskell98/CString.hs | haskell | # EXCLUDE_IF_TARGET cr # | # EXCLUDE_IF_TARGET js #
module CString (module Foreign.C.String) where
import Foreign.C.String
|
91c64add592b401f645db95de6060b52f5a290795ce3d99f0ecd87d14365df99 | uswitch/blueshift | main.clj | (ns uswitch.blueshift.main
(:require [clojure.tools.logging :refer (info)]
[clojure.tools.cli :refer (parse-opts)]
[uswitch.blueshift.system :refer (build-system)]
[com.stuartsierra.component :refer (start stop)])
(:gen-class))
(def cli-options
[["-c" "--config CONFIG" "Path to EDN configuration file"
:default "./etc/config.edn"
:validate [string?]]
["-h" "--help"]])
(defn wait! []
(let [s (java.util.concurrent.Semaphore. 0)]
(.acquire s)))
(defn -main [& args]
(let [{:keys [options summary]} (parse-opts args cli-options)]
(when (:help options)
(println summary)
(System/exit 0))
(let [{:keys [config]} options]
(info "Starting Blueshift with configuration" config)
(let [system (build-system (read-string (slurp config)))]
(start system)
(wait!)))))
(comment
(def system
(atom
(build-system {:s3 {:bucket "uswitch-blueshift"
:key-pattern "production/insight-load/.*"
:poll-interval {:seconds 10}}})))
(prn system)
(swap! system start)
)
| null | https://raw.githubusercontent.com/uswitch/blueshift/98c4345c8145158247c8c88637ae7c01d9df7a83/src/uswitch/blueshift/main.clj | clojure | (ns uswitch.blueshift.main
(:require [clojure.tools.logging :refer (info)]
[clojure.tools.cli :refer (parse-opts)]
[uswitch.blueshift.system :refer (build-system)]
[com.stuartsierra.component :refer (start stop)])
(:gen-class))
(def cli-options
[["-c" "--config CONFIG" "Path to EDN configuration file"
:default "./etc/config.edn"
:validate [string?]]
["-h" "--help"]])
(defn wait! []
(let [s (java.util.concurrent.Semaphore. 0)]
(.acquire s)))
(defn -main [& args]
(let [{:keys [options summary]} (parse-opts args cli-options)]
(when (:help options)
(println summary)
(System/exit 0))
(let [{:keys [config]} options]
(info "Starting Blueshift with configuration" config)
(let [system (build-system (read-string (slurp config)))]
(start system)
(wait!)))))
(comment
(def system
(atom
(build-system {:s3 {:bucket "uswitch-blueshift"
:key-pattern "production/insight-load/.*"
:poll-interval {:seconds 10}}})))
(prn system)
(swap! system start)
)
| |
136d4712c5e0f2d6dd08f2ed5365e5e9a59a9def5911062ea507efc0574585bf | fukamachi/lack | csrf.lisp | (in-package :cl-user)
(defpackage lack.middleware.csrf
(:use :cl)
(:import-from :lack.request
:make-request
:request-body-parameters)
(:import-from :lack.util
:generate-random-id)
(:export :*lack-middleware-csrf*
:csrf-token
:csrf-html-tag))
(in-package :lack.middleware.csrf)
(defvar *csrf-session-key*)
(defvar *csrf-middleware-token*)
(defparameter *lack-middleware-csrf*
(lambda (app &key (block-app #'return-400) one-time
(session-key "_csrf_token")
(form-token "_csrf_token"))
(lambda (env)
(let ((*csrf-session-key* session-key)
(*csrf-middleware-token* form-token))
(block nil
(unless (danger-method-p (getf env :request-method))
(return (funcall app env)))
(let ((session (getf env :lack.session)))
(unless session
(error ":lack.session is missing in ENV. Wrap this app up with lack.middleware.session"))
(if (valid-token-p env)
(progn
(when one-time
(remhash *csrf-session-key* session))
(funcall app env))
(funcall block-app env)))))))
"Middleware for easy CSRF protection")
(defun return-400 (env)
(declare (ignore env))
'(400
(:content-type "text/plain"
:content-length 31)
("Bad Request: invalid CSRF token")))
(defun danger-method-p (request-method)
(member request-method
'(:POST :PUT :DELETE :PATCH)
:test #'eq))
(defun valid-token-p (env)
(let ((req (make-request env))
(csrf-token (gethash *csrf-session-key*
(getf env :lack.session))))
(and csrf-token
(let ((received-csrf-token
(cdr (assoc *csrf-middleware-token* (request-body-parameters req) :test #'string=))))
;; for multipart/form-data
(when (listp received-csrf-token)
(setf received-csrf-token (first received-csrf-token)))
(equal csrf-token received-csrf-token)))))
(defun csrf-token (session)
(unless (gethash *csrf-session-key* session)
(setf (gethash *csrf-session-key* session) (generate-random-id)))
(gethash *csrf-session-key* session))
(defun csrf-html-tag (session)
(format nil "<input type=\"hidden\" name=\"~A\" value=\"~A\">"
*csrf-middleware-token*
(csrf-token session)))
| null | https://raw.githubusercontent.com/fukamachi/lack/1f155216aeea36291b325c519f041e469262a399/src/middleware/csrf.lisp | lisp | for multipart/form-data | (in-package :cl-user)
(defpackage lack.middleware.csrf
(:use :cl)
(:import-from :lack.request
:make-request
:request-body-parameters)
(:import-from :lack.util
:generate-random-id)
(:export :*lack-middleware-csrf*
:csrf-token
:csrf-html-tag))
(in-package :lack.middleware.csrf)
(defvar *csrf-session-key*)
(defvar *csrf-middleware-token*)
(defparameter *lack-middleware-csrf*
(lambda (app &key (block-app #'return-400) one-time
(session-key "_csrf_token")
(form-token "_csrf_token"))
(lambda (env)
(let ((*csrf-session-key* session-key)
(*csrf-middleware-token* form-token))
(block nil
(unless (danger-method-p (getf env :request-method))
(return (funcall app env)))
(let ((session (getf env :lack.session)))
(unless session
(error ":lack.session is missing in ENV. Wrap this app up with lack.middleware.session"))
(if (valid-token-p env)
(progn
(when one-time
(remhash *csrf-session-key* session))
(funcall app env))
(funcall block-app env)))))))
"Middleware for easy CSRF protection")
(defun return-400 (env)
(declare (ignore env))
'(400
(:content-type "text/plain"
:content-length 31)
("Bad Request: invalid CSRF token")))
(defun danger-method-p (request-method)
(member request-method
'(:POST :PUT :DELETE :PATCH)
:test #'eq))
(defun valid-token-p (env)
(let ((req (make-request env))
(csrf-token (gethash *csrf-session-key*
(getf env :lack.session))))
(and csrf-token
(let ((received-csrf-token
(cdr (assoc *csrf-middleware-token* (request-body-parameters req) :test #'string=))))
(when (listp received-csrf-token)
(setf received-csrf-token (first received-csrf-token)))
(equal csrf-token received-csrf-token)))))
(defun csrf-token (session)
(unless (gethash *csrf-session-key* session)
(setf (gethash *csrf-session-key* session) (generate-random-id)))
(gethash *csrf-session-key* session))
(defun csrf-html-tag (session)
(format nil "<input type=\"hidden\" name=\"~A\" value=\"~A\">"
*csrf-middleware-token*
(csrf-token session)))
|
4fab03e5d15d0a2eed56df04ecf40303954903f47234b0e81aebd20d87f2faae | Mayvenn/storefront | contentful.clj | (ns storefront.system.contentful
(:require [clojure.walk :as walk]
[com.stuartsierra.component :as component]
[storefront.system.scheduler :as scheduler]
[storefront.utils :as utils]
[ring.util.response :as util.response]
[spice.date :as date]
[spice.maps :as maps]
[tugboat.core :as tugboat]
[clojure.string :as string]
[clojure.set :as set]))
(defn contentful-request
"Wrapper for the Content Delivery endpoint"
([contentful resource-type params]
(contentful-request contentful resource-type nil params))
([{:keys [endpoint api-key space-id]} resource-type content-id params]
(try
(tugboat/request {:endpoint endpoint}
:get (str "/spaces/" space-id "/" resource-type (when content-id (str "/" content-id)))
{:socket-timeout 30000
:conn-timeout 30000
:as :json
:query-params (merge {:access_token api-key} params)})
(catch java.io.IOException ioe
nil))))
(defn extract-fields
"Contentful resources are boxed.
We extract the fields, merging useful meta-data."
[{:keys [fields sys]}]
(merge (maps/kebabify fields)
{:content/updated-at (spice.date/to-millis (:updatedAt sys 0))
:content/type (or
(some-> sys :contentType :sys :id)
"Asset")
:content/id (-> sys :id)}))
(defn extract-latest-by
"Extract a resource (e.g. items), grouped by a key, and taking the latest"
[resource index-key]
(->> (map extract-fields resource)
(group-by index-key)
(maps/map-values (partial apply max-key :content/updated-at))))
(defn extract
"Extract resources in a response body"
[body]
(-> body
(update-in [:items]
extract-latest-by :content/type)
(update-in [:includes :Entry]
extract-latest-by :content/id)
(update-in [:includes :Asset]
extract-latest-by :content/id)))
(defn ^:private link->value [includes link]
(let [id (some-> link :sys :id)
link-type (some-> link :sys :link-type keyword)]
(get-in includes [link-type id] link)))
(defn resolve-link
"Resolves contentful links in field values by stitching included
resources in situ."
[includes [key value]]
[key (cond
(map? value) (link->value includes value)
(vector? value) (mapv (partial link->value includes) value)
:else value)])
(defn resolve-children
"Resolves child links in parent maps by lookup in includes."
[includes parent-map]
(maps/map-values (fn [child-map]
(into {}
(map (partial resolve-link includes))
child-map))
parent-map))
(defn resolve-all
"Resolves Assets under Entries within items."
[{:keys [items includes]}]
(-> includes
(update :Entry (partial resolve-children includes))
(resolve-children items)))
(defn resolve-all-collection
"Resolves Assets under Entries within items."
[{:keys [items includes]}]
(let [resolved-includes (-> includes
(update :Asset (partial mapv (partial resolve-children includes)))
(update :Asset (partial maps/index-by (comp :id :sys)))
(update :Entry (partial mapv (partial resolve-children includes)))
(update :Entry (partial maps/index-by (comp :id :sys))))]
(walk/postwalk
(fn [form]
(if (and (map? form)
(-> form :sys :type (= "Link")))
(if-let [resolved-include (or (get-in resolved-includes [:Entry (-> form :sys :id)])
(get-in resolved-includes [:Asset (-> form :sys :id)]))]
(extract-fields resolved-include)
form)
form))
items)))
;; Used for homepage
(defn ^:private condense
[data]
(->> data
(mapv (fn [asset-or-entry]
(let [id (-> asset-or-entry :sys :id)
type (-> asset-or-entry :sys :contentType :sys :id)]
[id (-> asset-or-entry
:fields
(assoc :content/id id)
(assoc :content/type type))])))
(into {})))
(defn ^:private replace-data [lookup-table]
(fn [form]
(if (and (map? form)
(-> form :sys :type (= "Link")))
(if-let [value (get lookup-table (-> form :sys :id))]
value
form)
form)))
(defn condense-items-with-includes
[{:keys [items includes]}]
(let [assets (condense (:Asset includes))
entries (condense (:Entry includes))]
(->> items
(mapv (fn [item]
(assoc-in item [:fields :content/id] (-> item :sys :id))))
(walk/postwalk (replace-data entries))
(walk/postwalk (replace-data assets))
(mapv (comp maps/kebabify :fields)))))
(defn format-answer [{:as answer :keys [content]}]
(mapv (fn [paragraph]
{:paragraph
(->> paragraph
:content
(map
(fn [{:keys [node-type content data value] :as node}]
(cond (= node-type "text")
{:text value}
(= node-type "hyperlink")
{:text (-> content first :value)
:url (-> data :uri)}))))})
content))
(defn fetch-all
[{:keys [logger exception-handler cache env-param] :as contentful}]
(let [limit 500]
(->> ["entries" "assets"]
(map
(fn [resource-type]
(loop [skip 0
acc {}
failures 0]
(when (> 2 failures)
(let [{:keys [status body]} (contentful-request contentful
resource-type
{:include 0
:limit limit
:skip skip})
merged-content (into acc (some->> body
:items
(map (fn [item] [(-> item :sys :id keyword) item]))))]
(cond (not (and status (<= 200 status 299)))
(recur skip acc (inc failures))
(> (:total body) (+ skip limit))
(recur (+ skip limit) merged-content failures)
:else
merged-content))))))
(apply merge))))
GROT : Deprecated in favor of full CMS DB pull , and query - side assembly
(defn do-fetch-entries
([contentful content-params]
(do-fetch-entries contentful content-params 1))
([{:keys [logger exception-handler cache env-param] :as contentful}
{:keys [content-type
latest?
select
exists
primary-key-fn
item-tx-fn
collection-tx-fn]
:or {item-tx-fn identity
collection-tx-fn identity}
:as content-params} attempt-number]
(when (<= attempt-number 2)
(let [{:keys [status body]} (contentful-request
contentful
"entries"
(merge
{"content_type" (name content-type)
"include" 10}
(when exists
(reduce
(fn [m field]
(assoc m (str field "[exists]") true))
{}
exists))
(when select
{"select" (string/join "," select)})
(when latest?
{"limit" 1
:order (str "-fields." env-param)
(str "fields." env-param "[lte]") (date/to-iso (date/now))})))]
(if (and status (<= 200 status 299))
(swap! cache merge
(cond
(contains? #{:mayvennMadePage :advertisedPromo} content-type)
(some-> body extract resolve-all walk/keywordize-keys (select-keys [content-type]))
(= :ugc-collection content-type)
(some->> body
resolve-all-collection
(mapv extract-fields)
walk/keywordize-keys
(mapv item-tx-fn)
(maps/index-by primary-key-fn)
collection-tx-fn
(assoc {} content-type))
(= :faq content-type)
(some->> body
resolve-all-collection
(mapv extract-fields)
walk/keywordize-keys
(mapv (juxt :faq-section :questions-answers))
(map (fn [[faq-section questions-answers]]
{:slug faq-section
:question-answers (map
(fn [{:keys [question answer]}]
{:question {:text question}
:answer (format-answer answer)})
questions-answers)}))
(maps/index-by primary-key-fn)
(assoc {} content-type))
:else
(some->> body
resolve-all-collection
(mapv extract-fields)
walk/keywordize-keys
(mapv item-tx-fn)
(maps/index-by primary-key-fn)
collection-tx-fn
(assoc {} content-type))))
(do-fetch-entries contentful content-params (inc attempt-number)))))))
(defprotocol CMSCache
GROT : deprecated in favor of separate retrieval and processing using the normalized cache
(read-normalized-cache [_] "Returns a map representing the normalized CMS cache")
(upsert-into-normalized-cache [_ _]))
(defrecord ContentfulContext [logger exception-handler environment cache-timeout api-key space-id endpoint scheduler]
component/Lifecycle
(start [c]
(let [production? (= environment "production")
cache (atom {})
normalized-cache (atom {})
env-param (if production?
"production"
"acceptance")
content-type-parameters [{:content-type :faq
:latest? false
:primary-key-fn (comp keyword :slug)
:exists ["fields.faqSection"]
:select ["fields.faqSection"
"fields.questionsAnswers"]}
{:content-type :advertisedPromo
:latest? true}
{:content-type :ugc-collection
:exists ["fields.slug"]
:primary-key-fn (comp keyword :slug)
:select [(if production?
"fields.looks"
"fields.acceptanceLooks")
"fields.slug"
"fields.name"
"sys.contentType"
"sys.updatedAt"
"sys.id"
"sys.type"]
:item-tx-fn (fn [u]
(let [u' (if production?
(dissoc u :acceptance-looks)
(set/rename-keys u {:acceptance-looks :looks}))]
(utils/?update u' :looks (partial remove :sys))))
:collection-tx-fn
(fn [m]
(->> (vals m)
(mapcat :looks)
(maps/index-by (comp keyword :content/id))
(assoc m :all-looks)))
:latest? false}]]
GROT : Deprecated in favor of using the normalized cache below .
(doseq [content-params content-type-parameters]
(scheduler/every scheduler (cache-timeout)
(str "poller for " (:content-type content-params))
#(do-fetch-entries (assoc c :cache cache :env-param env-param) content-params)))
(scheduler/every scheduler (cache-timeout)
"poller for normalized CMS cache"
#(reset! normalized-cache (fetch-all c)))
(assoc c
:cache cache
:normalized-cache normalized-cache)))
(stop [c]
(dissoc c :cache))
CMSCache
GROT : deprecated in favor of separate retrieval and processing using the normalized cache
(read-normalized-cache [c] (deref (:normalized-cache c)))
(upsert-into-normalized-cache [c node]
(let [content-id (-> node :sys :id)
resource-type (-> node :sys :type {"Entry" "entries"
"Asset" "assets"})
retrieved-entry (:body (contentful-request c resource-type content-id {}))]
(swap! (:normalized-cache c) #(assoc % (keyword content-id) retrieved-entry)))))
(defn derive-all-looks [cms-data]
(-> cms-data
(assoc-in [:ugc-collection :all-looks]
(->> (:ugc-collection cms-data)
vals
(mapcat :looks)
(maps/index-by (comp keyword :content/id))))))
| null | https://raw.githubusercontent.com/Mayvenn/storefront/246c6906e2152a55683d5e8bf642208d7d082513/src/storefront/system/contentful.clj | clojure | Used for homepage | (ns storefront.system.contentful
(:require [clojure.walk :as walk]
[com.stuartsierra.component :as component]
[storefront.system.scheduler :as scheduler]
[storefront.utils :as utils]
[ring.util.response :as util.response]
[spice.date :as date]
[spice.maps :as maps]
[tugboat.core :as tugboat]
[clojure.string :as string]
[clojure.set :as set]))
(defn contentful-request
"Wrapper for the Content Delivery endpoint"
([contentful resource-type params]
(contentful-request contentful resource-type nil params))
([{:keys [endpoint api-key space-id]} resource-type content-id params]
(try
(tugboat/request {:endpoint endpoint}
:get (str "/spaces/" space-id "/" resource-type (when content-id (str "/" content-id)))
{:socket-timeout 30000
:conn-timeout 30000
:as :json
:query-params (merge {:access_token api-key} params)})
(catch java.io.IOException ioe
nil))))
(defn extract-fields
"Contentful resources are boxed.
We extract the fields, merging useful meta-data."
[{:keys [fields sys]}]
(merge (maps/kebabify fields)
{:content/updated-at (spice.date/to-millis (:updatedAt sys 0))
:content/type (or
(some-> sys :contentType :sys :id)
"Asset")
:content/id (-> sys :id)}))
(defn extract-latest-by
"Extract a resource (e.g. items), grouped by a key, and taking the latest"
[resource index-key]
(->> (map extract-fields resource)
(group-by index-key)
(maps/map-values (partial apply max-key :content/updated-at))))
(defn extract
"Extract resources in a response body"
[body]
(-> body
(update-in [:items]
extract-latest-by :content/type)
(update-in [:includes :Entry]
extract-latest-by :content/id)
(update-in [:includes :Asset]
extract-latest-by :content/id)))
(defn ^:private link->value [includes link]
(let [id (some-> link :sys :id)
link-type (some-> link :sys :link-type keyword)]
(get-in includes [link-type id] link)))
(defn resolve-link
"Resolves contentful links in field values by stitching included
resources in situ."
[includes [key value]]
[key (cond
(map? value) (link->value includes value)
(vector? value) (mapv (partial link->value includes) value)
:else value)])
(defn resolve-children
"Resolves child links in parent maps by lookup in includes."
[includes parent-map]
(maps/map-values (fn [child-map]
(into {}
(map (partial resolve-link includes))
child-map))
parent-map))
(defn resolve-all
"Resolves Assets under Entries within items."
[{:keys [items includes]}]
(-> includes
(update :Entry (partial resolve-children includes))
(resolve-children items)))
(defn resolve-all-collection
"Resolves Assets under Entries within items."
[{:keys [items includes]}]
(let [resolved-includes (-> includes
(update :Asset (partial mapv (partial resolve-children includes)))
(update :Asset (partial maps/index-by (comp :id :sys)))
(update :Entry (partial mapv (partial resolve-children includes)))
(update :Entry (partial maps/index-by (comp :id :sys))))]
(walk/postwalk
(fn [form]
(if (and (map? form)
(-> form :sys :type (= "Link")))
(if-let [resolved-include (or (get-in resolved-includes [:Entry (-> form :sys :id)])
(get-in resolved-includes [:Asset (-> form :sys :id)]))]
(extract-fields resolved-include)
form)
form))
items)))
(defn ^:private condense
[data]
(->> data
(mapv (fn [asset-or-entry]
(let [id (-> asset-or-entry :sys :id)
type (-> asset-or-entry :sys :contentType :sys :id)]
[id (-> asset-or-entry
:fields
(assoc :content/id id)
(assoc :content/type type))])))
(into {})))
(defn ^:private replace-data [lookup-table]
(fn [form]
(if (and (map? form)
(-> form :sys :type (= "Link")))
(if-let [value (get lookup-table (-> form :sys :id))]
value
form)
form)))
(defn condense-items-with-includes
[{:keys [items includes]}]
(let [assets (condense (:Asset includes))
entries (condense (:Entry includes))]
(->> items
(mapv (fn [item]
(assoc-in item [:fields :content/id] (-> item :sys :id))))
(walk/postwalk (replace-data entries))
(walk/postwalk (replace-data assets))
(mapv (comp maps/kebabify :fields)))))
(defn format-answer [{:as answer :keys [content]}]
(mapv (fn [paragraph]
{:paragraph
(->> paragraph
:content
(map
(fn [{:keys [node-type content data value] :as node}]
(cond (= node-type "text")
{:text value}
(= node-type "hyperlink")
{:text (-> content first :value)
:url (-> data :uri)}))))})
content))
(defn fetch-all
[{:keys [logger exception-handler cache env-param] :as contentful}]
(let [limit 500]
(->> ["entries" "assets"]
(map
(fn [resource-type]
(loop [skip 0
acc {}
failures 0]
(when (> 2 failures)
(let [{:keys [status body]} (contentful-request contentful
resource-type
{:include 0
:limit limit
:skip skip})
merged-content (into acc (some->> body
:items
(map (fn [item] [(-> item :sys :id keyword) item]))))]
(cond (not (and status (<= 200 status 299)))
(recur skip acc (inc failures))
(> (:total body) (+ skip limit))
(recur (+ skip limit) merged-content failures)
:else
merged-content))))))
(apply merge))))
GROT : Deprecated in favor of full CMS DB pull , and query - side assembly
(defn do-fetch-entries
([contentful content-params]
(do-fetch-entries contentful content-params 1))
([{:keys [logger exception-handler cache env-param] :as contentful}
{:keys [content-type
latest?
select
exists
primary-key-fn
item-tx-fn
collection-tx-fn]
:or {item-tx-fn identity
collection-tx-fn identity}
:as content-params} attempt-number]
(when (<= attempt-number 2)
(let [{:keys [status body]} (contentful-request
contentful
"entries"
(merge
{"content_type" (name content-type)
"include" 10}
(when exists
(reduce
(fn [m field]
(assoc m (str field "[exists]") true))
{}
exists))
(when select
{"select" (string/join "," select)})
(when latest?
{"limit" 1
:order (str "-fields." env-param)
(str "fields." env-param "[lte]") (date/to-iso (date/now))})))]
(if (and status (<= 200 status 299))
(swap! cache merge
(cond
(contains? #{:mayvennMadePage :advertisedPromo} content-type)
(some-> body extract resolve-all walk/keywordize-keys (select-keys [content-type]))
(= :ugc-collection content-type)
(some->> body
resolve-all-collection
(mapv extract-fields)
walk/keywordize-keys
(mapv item-tx-fn)
(maps/index-by primary-key-fn)
collection-tx-fn
(assoc {} content-type))
(= :faq content-type)
(some->> body
resolve-all-collection
(mapv extract-fields)
walk/keywordize-keys
(mapv (juxt :faq-section :questions-answers))
(map (fn [[faq-section questions-answers]]
{:slug faq-section
:question-answers (map
(fn [{:keys [question answer]}]
{:question {:text question}
:answer (format-answer answer)})
questions-answers)}))
(maps/index-by primary-key-fn)
(assoc {} content-type))
:else
(some->> body
resolve-all-collection
(mapv extract-fields)
walk/keywordize-keys
(mapv item-tx-fn)
(maps/index-by primary-key-fn)
collection-tx-fn
(assoc {} content-type))))
(do-fetch-entries contentful content-params (inc attempt-number)))))))
(defprotocol CMSCache
GROT : deprecated in favor of separate retrieval and processing using the normalized cache
(read-normalized-cache [_] "Returns a map representing the normalized CMS cache")
(upsert-into-normalized-cache [_ _]))
(defrecord ContentfulContext [logger exception-handler environment cache-timeout api-key space-id endpoint scheduler]
component/Lifecycle
(start [c]
(let [production? (= environment "production")
cache (atom {})
normalized-cache (atom {})
env-param (if production?
"production"
"acceptance")
content-type-parameters [{:content-type :faq
:latest? false
:primary-key-fn (comp keyword :slug)
:exists ["fields.faqSection"]
:select ["fields.faqSection"
"fields.questionsAnswers"]}
{:content-type :advertisedPromo
:latest? true}
{:content-type :ugc-collection
:exists ["fields.slug"]
:primary-key-fn (comp keyword :slug)
:select [(if production?
"fields.looks"
"fields.acceptanceLooks")
"fields.slug"
"fields.name"
"sys.contentType"
"sys.updatedAt"
"sys.id"
"sys.type"]
:item-tx-fn (fn [u]
(let [u' (if production?
(dissoc u :acceptance-looks)
(set/rename-keys u {:acceptance-looks :looks}))]
(utils/?update u' :looks (partial remove :sys))))
:collection-tx-fn
(fn [m]
(->> (vals m)
(mapcat :looks)
(maps/index-by (comp keyword :content/id))
(assoc m :all-looks)))
:latest? false}]]
GROT : Deprecated in favor of using the normalized cache below .
(doseq [content-params content-type-parameters]
(scheduler/every scheduler (cache-timeout)
(str "poller for " (:content-type content-params))
#(do-fetch-entries (assoc c :cache cache :env-param env-param) content-params)))
(scheduler/every scheduler (cache-timeout)
"poller for normalized CMS cache"
#(reset! normalized-cache (fetch-all c)))
(assoc c
:cache cache
:normalized-cache normalized-cache)))
(stop [c]
(dissoc c :cache))
CMSCache
GROT : deprecated in favor of separate retrieval and processing using the normalized cache
(read-normalized-cache [c] (deref (:normalized-cache c)))
(upsert-into-normalized-cache [c node]
(let [content-id (-> node :sys :id)
resource-type (-> node :sys :type {"Entry" "entries"
"Asset" "assets"})
retrieved-entry (:body (contentful-request c resource-type content-id {}))]
(swap! (:normalized-cache c) #(assoc % (keyword content-id) retrieved-entry)))))
(defn derive-all-looks [cms-data]
(-> cms-data
(assoc-in [:ugc-collection :all-looks]
(->> (:ugc-collection cms-data)
vals
(mapcat :looks)
(maps/index-by (comp keyword :content/id))))))
|
002b779fa4ba4bb0043d061f2a3e9de207243bf34332151c2dbeb560015c94cb | RunOrg/RunOrg | eventStream.mli | open Common
type ('ctx, 'a) event_writer = 'a list -> ( 'ctx, Clock.t ) Run.t
module type STREAM = sig
type event
val name : string
val append : ( #ctx, event ) event_writer
val count : unit -> ( #ctx, int ) Run.t
val clock : unit -> ( #ctx, Clock.t ) Run.t
val track : Projection.view -> (event -> ctx Run.effect) -> unit
val track_full : Projection.view -> (< clock : Clock.t ; event : event > -> ctx Run.effect) -> unit
end
module Stream : functor(Event:sig
include Fmt.FMT
val name : string
end) -> STREAM with type event = Event.t
| null | https://raw.githubusercontent.com/RunOrg/RunOrg/b53ee2357f4bcb919ac48577426d632dffc25062/server/cqrsLib/eventStream.mli | ocaml | open Common
type ('ctx, 'a) event_writer = 'a list -> ( 'ctx, Clock.t ) Run.t
module type STREAM = sig
type event
val name : string
val append : ( #ctx, event ) event_writer
val count : unit -> ( #ctx, int ) Run.t
val clock : unit -> ( #ctx, Clock.t ) Run.t
val track : Projection.view -> (event -> ctx Run.effect) -> unit
val track_full : Projection.view -> (< clock : Clock.t ; event : event > -> ctx Run.effect) -> unit
end
module Stream : functor(Event:sig
include Fmt.FMT
val name : string
end) -> STREAM with type event = Event.t
| |
68c7e76888cff151c298bee4c768f7bfbc728d20db08c19abb5fd47ccf6fd139 | zhuangxm/clj-rpc | server.clj | Server for simple RPC(http )
;;
;; example usage:
;; (export-commands 'clojure.core)
;; to export all functions of clojure.core to outside world.
;; (start)
to start the http server on the default rpc port 9876
;; (stop)
;; to stop the server.
;;
;; Server urls:
The server supports different wire format ( currently clj , json ) .
First part of URL specify it :
;; e.g. :9876/json json format
For each format , the server support 2 commands :
;; help -- GET/POST returns the list of the functions
;; invoke -- POST (parameters: method, args) invoke the function (by
;;"method")
(ns clj-rpc.server
(:use compojure.core, ring.adapter.jetty)
(:require [compojure.route :as route]
[compojure.handler :as handler]
[clj-rpc.command :as command]
[clojure.tools.logging :as logging]
[cheshire.core :as json]
[clj-rpc.wire-format :as protocol]
[clj-rpc.rpc :as rpc]
[clj-rpc.context :as context]))
(def rpc-default-port 9876)
;;TODO add the ability to dynamic add wrap-context middleware
;;use dynamic method to export commands
(defonce ^:dynamic *commands* (atom {}))
(defn export-commands
"export all functions (fn-names is null or empty)
or specify functions in the namespace ns
invoker of this method must notice the order of the options
options: options is a collection include several keys
like [ [:requre-context true] [:params-checks ...] [... ...] ]
the meaning of option:
:require-context (true or false default false)
whether this command must have context
:params-checks
check parameters of the method be invoked statisfy the sepcific requirements
example :
{0 [:username]} -->
the first parameter must equals (get-in context [:username])
for example :
(export-commands 'clojure.core nil)
(export-commands \"clojure.core\" nil)
(export-commands 'clojure.core ['+])
(export-commands 'clojure.core [\"+\"]
[ [:require-context true] [:params-check {0 [:id]}] ])"
[ns fn-names & [options]]
(let [ns (symbol ns)]
(require ns)
(let [var-fns (map #(find-var (symbol (str ns "/" %))) fn-names)]
(swap! *commands* merge
(context/add-context-to-command-map
(apply command/get-commands ns var-fns)
options)))))
(defn execute-command
"get the function from the command-map according the method-name and
execute this function with args
return the execute result"
[command-map request method-request]
(let [request (assoc request :commands command-map
:method-request method-request)
cmd (command-map (:method method-request))
f (and cmd (command/.func cmd))
new-method-request (context/adjust-method-request
cmd request method-request)
response (rpc/execute-method f new-method-request)]
(context/adjust-response cmd request response)))
(defn help-commands
"return the command list"
[commands]
(->> (vals commands)
(map #(dissoc % :func))
(sort-by #(:title %))))
(defn change-str->keyword
[m]
(into {} (map (fn [[key value]] [(keyword key) value]) m)))
(defn rpc-invoke
"invoke rpc method
rpc-request can a map (one invoke) or a collection of map (multi invokes)"
[command-map request rpc-request]
(letfn [(fn-execute [r]
(execute-command command-map request
(change-str->keyword r)))]
(if (map? rpc-request)
(fn-execute rpc-request)
(map fn-execute rpc-request))))
(defroutes main-routes
(ANY "/:s-method/help" [s-method]
(when-let [[f-encode] (protocol/serialization s-method)]
(f-encode (help-commands @*commands*))))
(POST "/:s-method/invoke" [s-method :as reqeust]
(let [rpc-request (:body reqeust)]
(logging/debug "invoking (" s-method ") request: " rpc-request)
(let [[f-encode f-decode] (protocol/serialization s-method)]
(f-encode (rpc-invoke @*commands* reqeust (f-decode rpc-request))))))
(route/not-found "invalid url"))
;;define a jetty-instance used to start or stop
(defonce jetty-instance (atom nil))
(defn stop
"stop jetty server"
([]
(stop @jetty-instance)
(reset! jetty-instance nil))
([instance]
(when instance
(.stop instance))))
(defn wrap-commands
"enable binding a custom commands map
new-commands must be a atom of map"
[handler new-commands]
(fn [request]
(if new-commands
(binding [*commands* new-commands]
(handler request))
(handler request))))
(defn build-hander [options]
(-> main-routes
(context/wrap-context (:fn-get-context options)
(:cookie-attrs options)
(:token-cookie-key options))
(context/wrap-client-ip)
(wrap-commands (:commands options))
(context/wrap-cost)
(context/wrap-body)
handler/site))
(defn start
"start jetty server
options :
base on options of run-jetty of ring jetty adaptor
and add several more
:fn-get-context => function to get the context (fn-get-context token)
:token-cookie-key => the cookie name according to the token
:cookie-attrs => the cookie default attributes, include domain or others
reference ring wrap-session
:commands => the custom commands (atom of map) to be exported. (optional) "
([]
(start {:join? false :port rpc-default-port :host "127.0.0.1"} ))
([options]
(let [jetty (run-jetty (build-hander options) options)]
(if-not (:command options)
(reset! jetty-instance jetty)
jetty))))
(defmacro with-commands
"if you want to define another commands, using this macro,
and in it invoke export-commands function lile:"
;;define another command map.
[a-commands & body]
`(binding [*commands* ~a-commands]
~@body))
(comment
"an example of how to start another server with different commands"
;;main server.
(export-commands ... )
(export-commands ... )
(start {:join? false :port 9876})
;;if you want to stop default server
(stop)
;;another server with differenct command
(let [new-commands (atom {})]
(with-commands new-commands
(export-commands ...)
(export-commands ...)))
;;start another server
(def another-server (start {:join? false :commands new-commands :port 1980}))
;;if you want to stop another server
(stop another-server))
| null | https://raw.githubusercontent.com/zhuangxm/clj-rpc/73a2f66b5ed0cce865d102acb49ba229203343ad/src/clj_rpc/server.clj | clojure |
example usage:
(export-commands 'clojure.core)
to export all functions of clojure.core to outside world.
(start)
(stop)
to stop the server.
Server urls:
e.g. :9876/json json format
help -- GET/POST returns the list of the functions
invoke -- POST (parameters: method, args) invoke the function (by
"method")
TODO add the ability to dynamic add wrap-context middleware
use dynamic method to export commands
define a jetty-instance used to start or stop
define another command map.
main server.
if you want to stop default server
another server with differenct command
start another server
if you want to stop another server | Server for simple RPC(http )
to start the http server on the default rpc port 9876
The server supports different wire format ( currently clj , json ) .
First part of URL specify it :
For each format , the server support 2 commands :
(ns clj-rpc.server
(:use compojure.core, ring.adapter.jetty)
(:require [compojure.route :as route]
[compojure.handler :as handler]
[clj-rpc.command :as command]
[clojure.tools.logging :as logging]
[cheshire.core :as json]
[clj-rpc.wire-format :as protocol]
[clj-rpc.rpc :as rpc]
[clj-rpc.context :as context]))
(def rpc-default-port 9876)
(defonce ^:dynamic *commands* (atom {}))
(defn export-commands
"export all functions (fn-names is null or empty)
or specify functions in the namespace ns
invoker of this method must notice the order of the options
options: options is a collection include several keys
like [ [:requre-context true] [:params-checks ...] [... ...] ]
the meaning of option:
:require-context (true or false default false)
whether this command must have context
:params-checks
check parameters of the method be invoked statisfy the sepcific requirements
example :
{0 [:username]} -->
the first parameter must equals (get-in context [:username])
for example :
(export-commands 'clojure.core nil)
(export-commands \"clojure.core\" nil)
(export-commands 'clojure.core ['+])
(export-commands 'clojure.core [\"+\"]
[ [:require-context true] [:params-check {0 [:id]}] ])"
[ns fn-names & [options]]
(let [ns (symbol ns)]
(require ns)
(let [var-fns (map #(find-var (symbol (str ns "/" %))) fn-names)]
(swap! *commands* merge
(context/add-context-to-command-map
(apply command/get-commands ns var-fns)
options)))))
(defn execute-command
"get the function from the command-map according the method-name and
execute this function with args
return the execute result"
[command-map request method-request]
(let [request (assoc request :commands command-map
:method-request method-request)
cmd (command-map (:method method-request))
f (and cmd (command/.func cmd))
new-method-request (context/adjust-method-request
cmd request method-request)
response (rpc/execute-method f new-method-request)]
(context/adjust-response cmd request response)))
(defn help-commands
"return the command list"
[commands]
(->> (vals commands)
(map #(dissoc % :func))
(sort-by #(:title %))))
(defn change-str->keyword
[m]
(into {} (map (fn [[key value]] [(keyword key) value]) m)))
(defn rpc-invoke
"invoke rpc method
rpc-request can a map (one invoke) or a collection of map (multi invokes)"
[command-map request rpc-request]
(letfn [(fn-execute [r]
(execute-command command-map request
(change-str->keyword r)))]
(if (map? rpc-request)
(fn-execute rpc-request)
(map fn-execute rpc-request))))
(defroutes main-routes
(ANY "/:s-method/help" [s-method]
(when-let [[f-encode] (protocol/serialization s-method)]
(f-encode (help-commands @*commands*))))
(POST "/:s-method/invoke" [s-method :as reqeust]
(let [rpc-request (:body reqeust)]
(logging/debug "invoking (" s-method ") request: " rpc-request)
(let [[f-encode f-decode] (protocol/serialization s-method)]
(f-encode (rpc-invoke @*commands* reqeust (f-decode rpc-request))))))
(route/not-found "invalid url"))
(defonce jetty-instance (atom nil))
(defn stop
"stop jetty server"
([]
(stop @jetty-instance)
(reset! jetty-instance nil))
([instance]
(when instance
(.stop instance))))
(defn wrap-commands
"enable binding a custom commands map
new-commands must be a atom of map"
[handler new-commands]
(fn [request]
(if new-commands
(binding [*commands* new-commands]
(handler request))
(handler request))))
(defn build-hander [options]
(-> main-routes
(context/wrap-context (:fn-get-context options)
(:cookie-attrs options)
(:token-cookie-key options))
(context/wrap-client-ip)
(wrap-commands (:commands options))
(context/wrap-cost)
(context/wrap-body)
handler/site))
(defn start
"start jetty server
options :
base on options of run-jetty of ring jetty adaptor
and add several more
:fn-get-context => function to get the context (fn-get-context token)
:token-cookie-key => the cookie name according to the token
:cookie-attrs => the cookie default attributes, include domain or others
reference ring wrap-session
:commands => the custom commands (atom of map) to be exported. (optional) "
([]
(start {:join? false :port rpc-default-port :host "127.0.0.1"} ))
([options]
(let [jetty (run-jetty (build-hander options) options)]
(if-not (:command options)
(reset! jetty-instance jetty)
jetty))))
(defmacro with-commands
"if you want to define another commands, using this macro,
and in it invoke export-commands function lile:"
[a-commands & body]
`(binding [*commands* ~a-commands]
~@body))
(comment
"an example of how to start another server with different commands"
(export-commands ... )
(export-commands ... )
(start {:join? false :port 9876})
(stop)
(let [new-commands (atom {})]
(with-commands new-commands
(export-commands ...)
(export-commands ...)))
(def another-server (start {:join? false :commands new-commands :port 1980}))
(stop another-server))
|
5007b967b7a23a8f43ecf53c3ef3bfd9c8299e65b3072a7a8ca3703754ce61cd | kindista/kindista | facebook.lisp | Copyright 2015 - 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)
(defparameter *fb-graph-url* "/")
(defvar *facebook-app-token* nil)
(defvar *facebook-user-token* nil)
(defvar *facebook-user-token-expiration* nil)
(defvar *fb-id* nil)
(defparameter *fb-share-dialog-on-page-load*
"(function() {
FB.ui(
{
method: 'share',
link: '/',
},
function(response) {
if (response && response.post_id) {
alert('Post was published.');
} else {
alert('Post was not published.');
}
}
);
});
"
)
(defun find-nil-fb-actions (&aux items)
(dolist (result *recent-activity-index*)
(when (find (result-type result) '(:gratitude :offer :request))
(let* ((id (result-id result))
(data (db id)))
(when (and (getf data :fb-actions)
(not (getf (first (getf data :fb-actions))
:fb-action-id)))
(push (list :userid (or (getf data :author)
(getf data :by))
:item-id id)
items)
(modify-db id :fb-actions nil)))))
(values items
(mapcar (lambda (item) (db (getf item :userid) :name)) items)))
(defun fix-fb-publishing-error-time-data ()
(dolist (id (hash-table-keys *db*))
(let* ((data (db id))
(fb-errors (getf data :fb-publishing-error))
(new-error-data)
(modify-data nil))
(when fb-errors
(dolist (fb-error fb-errors)
(push
(if (and (getf fb-error :time)
(eql (type-of (getf fb-error :time))
'local-time:timestamp))
(progn
(setf modify-data t)
(list :time (local-time:timestamp-to-universal
(getf fb-error :time))
:userid (getf fb-error :userid)))
fb-error)
new-error-data))
(when modify-data
(modify-db id :fb-publishing-error new-error-data))))))
(defun show-fb-p (&key (userid *userid*) (user *user*))
(and (getf user :fb-id)
(getf user :fb-link-active)
(getf user :fb-token)
;(or *enable-facebook-posting*
; (find userid *alpha-testers*)
( getf user : test - user ) )
*enable-facebook-posting*))
(defun fix-fb-link-active-error ()
(dolist (id *active-people-index*)
(let ((person (db id)))
(when (and (getf person :fb-link-active)
(not (getf person :fb-id)))
(modify-db id :fb-link-active nil)))))
(defun get-facebook-app-token ()
(getf
(alist-plist
(decode-json-octets
(http-request
(url-compose ""
"client_id" *facebook-app-id*
"client_secret" *facebook-secret*
"grant_type" "client_credentials"))))
:access--token))
(defun current-fb-token-p (&optional permission)
(with-user (and (integerp *facebook-user-token-expiration*)
(> *facebook-user-token-expiration*
(+ (get-universal-time) +day-in-seconds+))
(not (facebook-token-validation-error-p *userid*))
(or (not permission)
(check-facebook-permission permission)))))
(defun renew-fb-token
(&key item-to-publish
(next "/home")
fb-permission-requested)
(setf (getf (token-session-data *token*) :fb-permission-requested)
fb-permission-requested)
(setf (getf (token-session-data *token*) :publish-to-fb)
item-to-publish)
(setf (getf (token-session-data *token*) :login-redirect)
(url-decode next))
(see-other (url-compose "/renew-fb-token")))
(defun facebook-item-meta-content
(id
typestring
title
&key description
url
image)
(html
(:meta :property "fb:app_id"
:content *facebook-app-id*)
(:meta :property "og:url"
:content (or url
(strcat* +base-url+
typestring
(when (or (string= typestring "offer")
(string= typestring "request"))
"s")
"/"
id)))
(:meta :property "og:title"
:content (escape-for-html
(or title (s+ "Kindista " (string-capitalize typestring)))))
(awhen description
(htm (:meta :property "og:description"
:content (escape-for-html it))))
(:meta :property "og:image:secure_url"
:content (s+ "" (or image "/media/biglogo4fb.jpg")))
(:meta :property "og:image"
:content (s+ ""
(aif image
(regex-replace "/media" it "")
"/biglogo4fb.jpg")))))
(defun facebook-share-button (url &optional text)
(html
(:a :href (s+ "="
+base-url+
(url-encode
(if (eql (char url 0) #\/)
(subseq url 1)
url)))
(str (or text "Share on Facebook"))))
;(:div
; :class "fb-share-button"
; :data-href url
; :data-layout "button"
; :data-size "small"
; :data-mobile-iframe "true"
; (:a :class "fb-xfbml-parse-ignore"
; :target "_blank"
: ( s+ " = "
; (url-encode url)
" & amp;src = " )
( or text " Share on Facebook " ) ) )
)
(defun facebook-sign-in-button
(&key (redirect-uri "home")
(button-text "Sign in with Facebook")
re-request
state
scope)
(asetf scope
(strcat* (if (listp scope)
(format nil "~{~A,~}" scope)
(s+ scope ","))
" public_profile , publish_actions , email "
"public_profile,email"))
(html
(:a :class "blue facebook-button"
:href (apply #'url-compose
""
(remove nil
(append
(list "client_id" *facebook-app-id*
"scope" scope
"response_type" "code,granted_scopes"
"redirect_uri" (url-encode
(s+ +base-url+ redirect-uri)))
(when re-request
(list "auth_type" " rerequest"))
(when state
(list "state" state)))))
(str (icon "facebook-white")) (str button-text))))
(defun get-renew-fb-token
(&aux (next (or (get-parameter-string "next") "/home"))
(new-fb-item (getf (token-session-data *token*) :publish-to-fb))
(permission-requested (getf (token-session-data *token*) :fb-permission-requested))
(item-type (string-downcase (awhen new-fb-item (symbol-name (db it :type))))))
(standard-page
(if permission-requested
"Authorize Facebok App"
"Reauthorize Facebook App")
(html
(:h2
(str (aif permission-requested
(case it
(:publish-actions
"Kindista needs your permission to be able to publish items to Facebook")
(t "Kindista needs special permission for this action on Facebook"))
"Your Facebook session has expired on Kindista")))
(str (facebook-sign-in-button
:redirect-uri "/login"
:button-text (if permission-requested
"Authorize Facebook"
"Reauthorize Facebook")
:re-request permission-requested
:scope (mapcar (lambda (permission)
(regex-replace-all
"-"
(string-downcase (symbol-name permission))
"_"))
(cons permission-requested (getf *user* :fb-permissions)))))
(:p (:strong "Please note: ")
(awhen item-type
(htm "We will publish your " (str it) " to Facebook after you reauthorize Kindista's access to your Facebook account. "))
"We are unable to publish "
(str (if new-fb-item
"this or any other"
"any"))
" items to Facebook on your behalf until you reauthorize your account. ")
(:div :class "small"
(:span "No longer want to use Facebook with Kindista?")
(:form :method "post"
:action "/settings/social"
:class "inline-block"
(:input :type "hidden" :name "next" :value next)
(:button :class "simple-link red bold"
:type "submit"
:name "fb-logout"
"Deactivate Facebook App"))))
:class "fb-reauth"))
(defun facebook-debugging-log (userid response-code &rest messages)
(with-open-file (s (s+ +db-path+ "facebook-log")
:direction :output
:if-does-not-exist :create
:if-exists :append)
(let ((*print-readably* nil))
(format s "USERID:~A STATUS:~A TIME:~A~%~{~S~%~}"
userid
response-code
(local-time:now)
messages))
(fsync s)))
(defun register-facebook-user
(&optional (redirect-uri "home")
&aux (request (url-compose
""
"client_id" *facebook-app-id*
"redirect_uri" (s+ +base-url+ redirect-uri)
"client_secret" *facebook-secret*
"code" (get-parameter "code")))
reply)
(when (and *token* (get-parameter "code"))
(setf reply (multiple-value-list (http-request request :force-binary t)))
(let* ((token-data (when (<= (second reply) 200)
(alist-plist (decode-json-octets (first reply))))))
(facebook-debugging-log
*userid*
(second reply)
(or token-data
(cdr (assoc :message
(cdr (assoc :error (decode-json-octets (first reply)))))))
token-data)
token-data)))
(defun check-facebook-user-token
(&optional (userid *userid*)
(fb-token (or *facebook-user-token* (db userid :fb-token)))
&aux (*user* (or *user* (db userid)))
reply
data)
(setf reply
(multiple-value-list
(http-request
(s+ *fb-graph-url* "debug_token")
:parameters (list (cons "input_token" fb-token)
(cons "access_token" *facebook-app-token*)
(cons "appsecret_proof" (fb-app-secret-proof))
))))
(when (= (second reply) 200)
(setf data
(alist-plist
(cdr (find :data
(decode-json-octets (first reply))
:key #'car)))))
(facebook-debugging-log userid (second reply) fb-token data)
(when (and (string= (getf data :app--id) *facebook-app-id*)
(eql (safe-parse-integer (getf data :user--id))
(getf *user* :fb-id)))
data))
(defun facebook-token-validation-error-p
(&optional (userid *userid*)
&aux (fb-response (check-facebook-user-token userid)))
(or (not (getf fb-response :is--valid))
(eql (getf fb-response :expires--at) 0)
(eql 190 (getf (alist-plist (getf fb-response :error)) :code))))
(defun get-facebook-user-data
(fb-token
&aux initial-response
user-data)
(setf initial-response
(alist-plist (decode-json-octets
(http-request
(strcat *fb-graph-url* "me")
:parameters (list (cons "access_token" fb-token)
(cons "method" "get"))))))
(setf user-data (flatten
(decode-json-octets
(http-request (strcat *fb-graph-url* "v12.0/" (getf initial-response :id))
:parameters (list (cons "access_token" fb-token)
(cons "fields" "id,name,email")
(cons "method" "get"))))))
(facebook-debugging-log *userid* user-data)
user-data)
(defun get-facebook-user-id (fb-token)
(safe-parse-integer (getf (get-facebook-user-data fb-token) :id)))
(defun fb-k-id (fb-id)
(gethash fb-id *facebook-id-index*))
(defun get-facebook-profile-picture
(k-user-id
&aux (user (db k-user-id))
(fb-token (getf user :fb-token))
(fb-user-id (getf user :fb-id))
(response))
(when (and fb-token fb-user-id (getf user :fb-link-active))
(setf response
(multiple-value-list
(http-request (strcat *fb-graph-url* "v12.0/" fb-user-id "/picture")
:parameters (list (cons "access_token" fb-token)
(cons "appsecret_proof" (fb-app-secret-proof fb-token))
(cons "type" "large")
(cons "method" "get")))))
(facebook-debugging-log (or k-user-id
*userid*
(token-userid *token*))
(second response)
(unless (eql (second response) 200)
(decode-json-octets (first response)))
(fourth response))
(values (first response)
(second response)
(cdr (assoc :content-type (third response)))
(fourth response))))
(defun save-facebook-profile-picture-to-avatar (k-userid)
(multiple-value-bind
(octet-array status-code content-type image-url)
(get-facebook-profile-picture k-userid)
(declare (ignore image-url))
(when (eql status-code 200)
(create-image octet-array content-type))))
(defun facebook-image-identifyier (k-userid)
(multiple-value-bind
(octet-array status-code content-type image-url)
(get-facebook-profile-picture k-userid)
(declare (ignore octet-array content-type))
(case status-code
(200 (awhen image-url (car (last (puri:uri-parsed-path it)))))
(t :authentication-error))))
(defun get-facebook-user-permissions
(k-id
&optional (user (db k-id))
&aux (fb-id (getf user :fb-id))
(user-token (getf user :fb-token))
response
fb-permissions
current-permissions)
(when (and fb-id (getf user :fb-link-active))
(setf response
(multiple-value-list
(http-request
(strcat *fb-graph-url*
"v12.0/"
fb-id "/permissions")
:parameters (list (cons "access_token" *facebook-app-token*)
(cons "access_token" user-token)
(cons "appsecret_proof" (fb-app-secret-proof user-token))
(cons "method" "get")))))
(setf fb-permissions (getf (alist-plist (decode-json-octets
(first response)))
:data)))
(mapcar
(lambda (pair)
(push (string-to-keyword (car pair))
(getf current-permissions (cdr pair))))
(loop for permission in fb-permissions
collect (cons (cdar permission)
(cond
((string= (cdadr permission) "granted") :granted)
((string= (cdadr permission) "declined") :declined)
((string= (cdadr permission) "expired") :expired)
(t :error)))))
;(facebook-debugging-log k-id
( second response )
( strcat * " FB Permissions : " current - permissions ) )
current-permissions)
(defun check-facebook-permission
(permission
&optional (userid *userid*)
&aux (user (db userid))
(saved-fb-permissions (getf user :fb-permissions))
(current-fb-permissions (get-facebook-user-permissions userid user))
(granted-fb-permissions (getf current-fb-permissions :granted)))
(when (set-exclusive-or saved-fb-permissions granted-fb-permissions)
(modify-db userid :fb-permissions granted-fb-permissions))
(values (find permission granted-fb-permissions)
(cond
((find permission (getf current-fb-permissions :declined))
:declined)
((find permission (getf current-fb-permissions :expired))
:expired)
(t nil))))
(defun get-facebook-kindista-friends
(&optional (k-id *userid*)
&aux (user (db k-id))
(user-token (getf user :fb-token))
(fb-id (getf user :fb-id))
(response)
friends)
(when (and fb-id (getf user :fb-link-active))
(setf response
(multiple-value-list
(http-request
(strcat *fb-graph-url*
"v3.0/"
fb-id "/friends")
:parameters (list (cons "access_token" *facebook-app-token*)
(cons "access_token" user-token)
(cons "appsecret_proof" (fb-app-secret-proof user-token))
(cons "method" "get"))))))
(pprint (find :data
(decode-json-octets (first response))
:key 'car))
(terpri)
(when (= (second response) 200)
(setf friends
(mapcar (lambda (friend)
(gethash (safe-parse-integer
(cdr (find :id friend :key 'car)))
*facebook-id-index*))
(cdr (find :data
(decode-json-octets (first response))
:key 'car)))))
(facebook-debugging-log k-id
(second response)
(strcat* "K-FB-Friends: " friends))
friends)
(defun active-facebook-user-p
(&optional (userid *userid*)
(user (if (eql userid *userid*) *user* (db userid))))
(and (getf user :fb-id) (getf user :fb-link-active) ))
(defun get-facebook-location-data (fb-location-id fb-token)
(alist-plist
(cdr
(assoc :location
(decode-json-octets
(http-request (strcat *fb-graph-url*
"v12.0/"
fb-location-id)
:parameters (list (cons "access_token" fb-token)
(cons "access_token" *facebook-app-token*)
(cons "appsecret_proof" (fb-app-secret-proof fb-token))
(cons "fields" "location")
(cons "method" "get"))))))))
(defun new-facebook-action-notice-handler
(&aux (notice-data (notice-data))
(userid (getf notice-data :userid))
(item-id (getf notice-data :item-id))
(item (db item-id))
(action-type (case (getf item :type)
(:gratitude "express")
(t "post")))
(fb-action-id)
(fb-object-id))
;; userid is included w/ new publish request but not scraping new data
(when (and userid (not (first (fb-object-actions-by-user item-id
:userid userid))))
(setf fb-action-id
(publish-facebook-action item-id
:userid userid
:item item
:action-type action-type))
(setf fb-object-id (get-facebook-object-id item-id)))
(cond
((getf notice-data :object-modified)
(scrape-facebook-item (getf notice-data :fb-object-id)))
(userid
update kindista DB with new facebook object / action ids
(http-request
(s+ +base-url+ "publish-facebook")
:parameters (list (cons "item-id" (strcat item-id))
(cons "userid" (strcat userid))
(cons "fb-action-id" (strcat fb-action-id))
(cons "fb-action-type" action-type)
(cons "fb-object-id" (strcat fb-object-id))
(cons "fb-id" (strcat (db userid :fb-id))))
:method :post))))
(defun post-new-facebook-data
(&aux (item-id (post-parameter-integer "item-id"))
(userid (post-parameter-integer "userid"))
(fb-action-id (post-parameter-integer "fb-action-id"))
(fb-object-id (post-parameter-integer "fb-object-id"))
(fb-id (post-parameter-integer "fb-id"))
(fb-action-type (post-parameter-string "fb-action-type")))
(if (server-side-request-p)
(progn
(facebook-debugging-log
userid
nil
"modifying the DB"
(post-parameters*)
(strcat* "fb-object-id: " fb-object-id)
(amodify-db item-id :fb-object-id fb-object-id
:fb-publishing-in-process nil
:fb-publishing-error (unless fb-action-id
(cons (list :time (get-universal-time)
:userid userid)
it))
:fb-actions (if fb-action-id
(cons (list :fb-id fb-id
:fb-action-type fb-action-type
:fb-action-id fb-action-id)
it)
it)))
(setf (return-code*) +http-no-content+)
nil)
(progn
(setf (return-code*) +http-forbidden+)
nil)))
(defun publish-facebook-action
(id
&key (item (db id))
(action-type (case (getf item :type)
(:gratitude "express")
(t "post")))
(userid *userid*)
&aux (object-type (string-downcase (symbol-name (getf item :type))))
(user (db userid))
(user-token (getf user :fb-token))
(reply
(multiple-value-list
(http-request
(strcat *fb-graph-url*
"v3.0/me"
"/kindistadotorg:"
action-type)
:parameters (list (cons "access_token" user-token)
(cons "method" "post")
(cons "appsecret_proof" (fb-app-secret-proof user-token))
(cons object-type
(s+ ""
(resource-url id item)))
(cons "debug" "all")
(cons "fb:explicitly_shared" "true"))))))
(let ((data (when (= (second reply) 200)
(alist-plist (decode-json-octets (first reply))))))
(facebook-debugging-log userid
(second reply)
(strcat* "ITEM-PUBLISHED-TO-FB:" id)
(list :fb-id (getf user :fb-id)
:fb-token user-token)
(or data
(if (stringp (first reply))
(first reply)
(decode-json-octets (first reply)))))
(awhen (getf data :id) (safe-parse-integer it))))
(defun get-facebook-object-id
(k-id
&aux (item (db k-id))
(reply
(multiple-value-list
(http-request
(strcat *fb-graph-url*)
:parameters (list (cons "access_token" *facebook-app-token*)
(cons "id" (s+ "" (resource-url k-id item)))
)))))
;; data and object are usefull for debugging
(let* ((data (when (= (second reply) 200)
(alist-plist (decode-json-octets (first reply)))))
(object (alist-plist (getf data :og--object))))
(facebook-debugging-log *userid*
(second reply)
(strcat* "ITEM-ID:" k-id)
data)
(when object (safe-parse-integer (getf object :id)))))
(defun get-user-facebook-objects-of-type
(typestring
&optional (userid *userid*)
&aux (user (db userid))
(reply
(multiple-value-list
(http-request
(strcat *fb-graph-url*
"me"
( or * fb - id * ( getf user : fb - id ) )
"/kindistadotorg:post/"
typestring)
:parameters (list (cons "access_token" (getf user :fb-token))
(cons "method" "get"))))))
(when (= (second reply) 200)
(decode-json-octets (first reply))))
(defun fb-object-actions-by-user
(k-item-id
&key (data (db k-item-id))
(userid *userid*)
(fb-id (if (eql *userid* userid)
(getf *user* :fb-id)
(db userid :fb-id)))
&aux (actions))
(when userid
(dolist (action (getf data :fb-actions))
(when (eql (getf action :fb-id) fb-id)
(push (getf action :fb-action-id) actions))))
actions)
(defun update-facebook-object
(k-id
&aux (item (db k-id))
(facebook-id (getf item :fb-object-id))
(typestring (string-downcase (symbol-name (getf item :type))))
(reply (multiple-value-list
(http-request
(strcat "/" facebook-id)
:parameters (list (cons "access_token"
*facebook-app-token*)
'("method" . "POST")
(cons typestring
(strcat ""
(resource-url k-id item))))))))
"Works the same as (scrape-facebook-item)"
(when (= (second reply) 200)
(decode-json-octets (first reply))))
(defun scrape-facebook-item
(url-or-fb-id
&aux (reply (multiple-value-list
(http-request
"/"
:parameters (list (cons "id"
(if (integerp url-or-fb-id)
(write-to-string url-or-fb-id)
url-or-fb-id))
(cons "access_token"
*facebook-app-token*)
'("scrape" . "true"))
:method :post)))
(data (when (= (second reply) 200)
(decode-json-octets (first reply)))))
"Works the same as (update-facebook-object)"
(facebook-debugging-log *userid*
(second reply)
url-or-fb-id
(or data (when (stringp (first reply))
(first reply))))
data)
(defun get-facebook-action
(k-id
&optional (k-userid *userid*)
(user (or *user* (db k-userid)))
&aux (k-item (db k-id))
(action-id (cdr (assoc (getf user :fb-id)
(getf k-item :fb-actions))))
(reply (multiple-value-list
(http-request
(strcat "/" action-id)
:parameters (list (cons "access_token"
*facebook-app-token*)
(cons "access_token"
(getf user :fb-token))
'("method" . "GET")))))
(data))
(unless (stringp (first reply))
(setf data (decode-json-octets (first reply))))
(facebook-debugging-log k-userid
(second reply)
(if (stringp (first reply))
(first reply)
data))
(values data (second reply)))
(defun delete-facebook-action
(facebook-action-id
&aux (reply (multiple-value-list
(http-request
(strcat "/" facebook-action-id)
:parameters (list (cons "access_token"
*facebook-app-token*)
'("method" . "DELETE"))))))
(values
(decode-json-octets (first reply))
(second reply)))
(defun get-taggable-fb-friends
(&optional (userid *userid*)
(user (if (eql userid *userid*) *user* (db userid)))
(url (strcat *fb-graph-url*
"v3.0/"
(getf user :fb-id)
"/taggable_friends"))
&aux (response)
(user-token (getf user :fb-token)))
"Performs a call to the FB graph taggable_friends endpoint to get a list of all taggable friends."
(when (active-facebook-user-p userid user)
(setf response
(multiple-value-list
(http-request
url
:parameters (list (cons "access_token" *facebook-app-token*)
(cons "access_token" user-token)
(cons "appsecret_proof" (fb-app-secret-proof user-token))
(cons "limit" "5000")
(cons "method" "get"))))))
(case (second response)
(200 (decode-json-octets (first response)))
(t (facebook-debugging-log *userid*
(second response)
(if (stringp (first response))
(first response)
(decode-json-octets (first response)))))))
(defun get-all-taggable-fb-friends
(&optional (userid *userid*)
(user (if (eql userid *userid*) *user* (db userid)))
&aux (all-results)
(current-results)
(next)
(requests 0))
"Performs multiple calls to the FB graph taggable_friends endpoint to accumulate a list of all taggable friends. Not currently needed because that endpoint allows a 'limit' get parameter to get a list of all taggable friends."
(labels ((request-loop ()
(setf current-results
(apply #'get-taggable-fb-friends (remove nil (list userid user next))))
(setf next (cdr (find :next
(cdr (find :paging current-results :key 'car))
:key 'car)))
(incf requests)
(if all-results
(asetf all-results (append it (cdr (find :data current-results :key 'car))))
(setf all-results (cdr (find :data current-results :key 'car))))
;; don't let it loop indefinitely
(when (and (< requests 5)
(stringp next))
(request-loop))))
(request-loop))
all-results)
(defun find-taggable-fb-friend-by-name (k-id name)
(find name
(get-all-taggable-fb-friends k-id)
:key (lambda (item)
(cdr (find :name item :key 'car)))
:test #'string=))
(defun facebook-taggable-friend-tokens
(k-user-ids-to-test
&optional (userid *userid*)
&aux (image-identifiers (mapcar (lambda (id)
(cons id (facebook-image-identifyier id)))
k-user-ids-to-test))
(logged-out-of-fb)
(taggable-fb-friends (get-all-taggable-fb-friends userid))
(taggable-k-users))
"Returns and a-list of (k-userid . fb-taggable-token)"
(flet ((get-pic-url-identifier (fb-data)
(car
(split "\\?"
(car
(last
(url-parts
(cdr (find :url
(cdr (find :data
(cdr (find :picture fb-data :key 'car))
:key 'car))
:key 'car)))))))))
(dolist (pair image-identifiers)
(if (eql (cdr pair) :authentication-error)
(push (car pair) logged-out-of-fb)
(awhen (find (cdr pair)
taggable-fb-friends
:key #'get-pic-url-identifier
:test #'string=)
(push (cons (car pair) (getf (alist-plist it) :id))
taggable-k-users)))))
(facebook-debugging-log *userid* nil "Facebook Taggable Friend Tokens" taggable-k-users logged-out-of-fb)
(values taggable-k-users logged-out-of-fb))
(defun fb-taggable-friends-auth-warning (id-list)
(when id-list
(flash (s+ (name-list-all id-list)
(if (> (length id-list) 1)
" are" " is")
" not logged into Facebook through Kindista. You can tag them in this statement of gratitude after they authorize their Facebook account through Kindista.")
:error t)))
(defun facebook-friends-permission-html
(&key redirect-uri
fb-gratitude-subjects
(cancel-link "home")
re-request
(page-title "Tag your Facebook friends"))
(standard-page
page-title
(html
(:div :id "tag-fb-friends-auth"
(:p :class "large"
"Would you like to tag "
(:strong (str (name-list-all fb-gratitude-subjects :stringp t
:conjunction :or)))
" in the gratitude you published to Facebook?")
(:p :class "small"
"To enable tagging, Facebook requires that you give Kindista access to your Facebook friends list. We respect your privacy and your relationships; we will not spam your friends.")
(str (facebook-sign-in-button :redirect-uri redirect-uri
:scope "user_friends"
:state "user_friends_scope_granted"
:re-request re-request
:button-text "Allow Kindista to see my list of Facebook friends"))
(:a :href cancel-link :class "gray-text cancel" "Not now")))
:selected "people"))
(defun tag-facebook-friends-html
(&key gratitude-id
fb-gratitude-subjects
(page-title "Tag your Facebook friends")
&aux (gratitude (when gratitude-id (db gratitude-id)))
(fb-g-subject-ids (mapcar #'cdr fb-gratitude-subjects)))
(awhen (set-difference (getf gratitude :subjects) fb-g-subject-ids)
(flash (s+ (name-list it :links nil :maximum-links 10)
" cannot be tagged. Either they have not linked their Facebook"
" accounts with Kindista or they have not given permission"
" for Kindista to see if you are friends on Facebook.")))
(standard-page
page-title
(html
(:div :id "tag-fb-friends"
(:h3 "You have published this Statement of Gratitude on your Facebook feed:")
(:blockquote
(str (gratitude-activity-item (gethash gratitude-id *db-results*)
:show-actions nil)))
(:form :method "post" :action (strcat "/gratitude/" gratitude-id)
(:fieldset
(:legend (str page-title))
(dolist (pair fb-gratitude-subjects)
(htm
(:div :class "friend-to-tag"
(:div :class "g-recipient item"
(:input :type "checkbox"
:name "tag-fb-friend"
:value (cdr pair)
:id (cdr pair)
:checked "")
(:label :for (cdr pair)
(:img :src (get-avatar-thumbnail (cdr pair) 70 70))
(str (car pair))))))))
(:p (:button :class "cancel" :type "submit" :class "cancel" :name "cancel" "Cancel")
(:button :class "yes" :type "submit" :class "submit" :name "tag-friends" "Tag Friends")))))
:selected "people"))
(defun tag-facebook-friends
(k-item-id
k-contacts-to-tag-on-fb
&optional (userid *userid*)
&aux (item (db k-item-id))
(user (if (eql userid *userid*) *user* (db userid)))
(user-token (getf user :fb-token))
(response)
(taggable-friend-tokens (facebook-taggable-friend-tokens
k-contacts-to-tag-on-fb
userid))
;; taggable-friend-tokens is an a-list of (k-userid . fb-taggable-token)
(friends-to-tag)
(tagged-friends)
(action-id (first (fb-object-actions-by-user k-item-id
:data item
:userid userid
:fb-id (getf user :fb-id)))))
;; Tagging is convoluted until Facebook changes it's API to allow apps to pass
;; FB user ids to tag an item. Now we have to associate taggable-tokens with known profile
;; pic urls associated with fb-ids.
(dolist (id k-contacts-to-tag-on-fb)
(awhen (assoc id taggable-friend-tokens)
(push (car it) tagged-friends)
(push (cdr it) friends-to-tag)))
(when (and friends-to-tag (active-facebook-user-p userid user))
(asetf friends-to-tag (separate-with-commas it :omit-spaces t))
(setf response
(multiple-value-list
(http-request
(strcat *fb-graph-url*
"v3.0/"
action-id)
:parameters (list (cons "access_token" user-token)
(cons "appsecret_proof" (fb-app-secret-proof user-token))
(cons "tags" friends-to-tag))
:method :post)))
(setf response (decode-json-octets (first response)))
(when (and (eql (caar response) :success)
(eql (cdar response) t))
(flash (s+ (name-list-all tagged-friends) " have been tagged in your statement of gratitude on Facebook."))
(amodify-db k-item-id :fb-tagged-friends (append tagged-friends it)))
(facebook-debugging-log userid
nil
action-id
(strcat* "Contacts to tag on fb: "
k-contacts-to-tag-on-fb)
taggable-friend-tokens
friends-to-tag
response)
response))
(defun fb-app-secret-proof
(&optional (access-token *facebook-app-token*)
&aux (hmac (ironclad:make-hmac (ironclad:ascii-string-to-byte-array *facebook-secret*) :sha256))
(hmac-hash (ironclad:update-hmac hmac (ironclad:ascii-string-to-byte-array access-token)))
(digest (ironclad:hmac-digest hmac-hash)))
(ironclad:byte-array-to-hex-string digest))
(defun post-uninstall-facebook
(&aux (signed-request (post-parameter "signed_request"))
(split-request (split "\\." signed-request))
(signature (substitute #\+ #\- (substitute #\/ #\_ (first split-request))))
(expected-sig)
(raw-data (second split-request))
(hmac (ironclad:make-hmac (string-to-octets *facebook-secret*) :sha256))
(json)
(fb-id)
(userid))
(ironclad:update-hmac hmac (string-to-octets raw-data))
(setf expected-sig
(remove #\= (base64:usb8-array-to-base64-string
(ironclad:hmac-digest hmac))))
(facebook-debugging-log nil
nil
"Uninstalling FB"
signed-request
expected-sig
signature)
(if (equalp expected-sig signature)
(progn
(setf json
(json:decode-json-from-string
(with-output-to-string (s)
(base64:base64-string-to-stream raw-data :uri t :stream s))))
(setf fb-id (safe-parse-integer (getf (alist-plist json) :user--id)))
(setf userid (gethash fb-id *facebook-id-index*))
(facebook-debugging-log userid nil json)
(when userid
;; testing environment may result in no userid if
;; user signed up on live server or vice versa.
(modify-db userid :fb-link-active nil
:fb-token nil
:fb-expires (get-universal-time)))
(setf (return-code*) +http-no-content+)
nil)
(progn (setf (return-code*) +http-forbidden+)
nil)))
| null | https://raw.githubusercontent.com/kindista/kindista/7d2be6d1bf2e8a8d027854998017f6cdcc70691a/src/shared/facebook.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.
(or *enable-facebook-posting*
(find userid *alpha-testers*)
(:div
:class "fb-share-button"
:data-href url
:data-layout "button"
:data-size "small"
:data-mobile-iframe "true"
(:a :class "fb-xfbml-parse-ignore"
:target "_blank"
(url-encode url)
(facebook-debugging-log k-id
userid is included w/ new publish request but not scraping new data
data and object are usefull for debugging
don't let it loop indefinitely
taggable-friend-tokens is an a-list of (k-userid . fb-taggable-token)
Tagging is convoluted until Facebook changes it's API to allow apps to pass
FB user ids to tag an item. Now we have to associate taggable-tokens with known profile
pic urls associated with fb-ids.
testing environment may result in no userid if
user signed up on live server or vice versa. | Copyright 2015 - 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)
(defparameter *fb-graph-url* "/")
(defvar *facebook-app-token* nil)
(defvar *facebook-user-token* nil)
(defvar *facebook-user-token-expiration* nil)
(defvar *fb-id* nil)
(defparameter *fb-share-dialog-on-page-load*
"(function() {
FB.ui(
{
method: 'share',
link: '/',
},
function(response) {
if (response && response.post_id) {
} else {
}
}
"
)
(defun find-nil-fb-actions (&aux items)
(dolist (result *recent-activity-index*)
(when (find (result-type result) '(:gratitude :offer :request))
(let* ((id (result-id result))
(data (db id)))
(when (and (getf data :fb-actions)
(not (getf (first (getf data :fb-actions))
:fb-action-id)))
(push (list :userid (or (getf data :author)
(getf data :by))
:item-id id)
items)
(modify-db id :fb-actions nil)))))
(values items
(mapcar (lambda (item) (db (getf item :userid) :name)) items)))
(defun fix-fb-publishing-error-time-data ()
(dolist (id (hash-table-keys *db*))
(let* ((data (db id))
(fb-errors (getf data :fb-publishing-error))
(new-error-data)
(modify-data nil))
(when fb-errors
(dolist (fb-error fb-errors)
(push
(if (and (getf fb-error :time)
(eql (type-of (getf fb-error :time))
'local-time:timestamp))
(progn
(setf modify-data t)
(list :time (local-time:timestamp-to-universal
(getf fb-error :time))
:userid (getf fb-error :userid)))
fb-error)
new-error-data))
(when modify-data
(modify-db id :fb-publishing-error new-error-data))))))
(defun show-fb-p (&key (userid *userid*) (user *user*))
(and (getf user :fb-id)
(getf user :fb-link-active)
(getf user :fb-token)
( getf user : test - user ) )
*enable-facebook-posting*))
(defun fix-fb-link-active-error ()
(dolist (id *active-people-index*)
(let ((person (db id)))
(when (and (getf person :fb-link-active)
(not (getf person :fb-id)))
(modify-db id :fb-link-active nil)))))
(defun get-facebook-app-token ()
(getf
(alist-plist
(decode-json-octets
(http-request
(url-compose ""
"client_id" *facebook-app-id*
"client_secret" *facebook-secret*
"grant_type" "client_credentials"))))
:access--token))
(defun current-fb-token-p (&optional permission)
(with-user (and (integerp *facebook-user-token-expiration*)
(> *facebook-user-token-expiration*
(+ (get-universal-time) +day-in-seconds+))
(not (facebook-token-validation-error-p *userid*))
(or (not permission)
(check-facebook-permission permission)))))
(defun renew-fb-token
(&key item-to-publish
(next "/home")
fb-permission-requested)
(setf (getf (token-session-data *token*) :fb-permission-requested)
fb-permission-requested)
(setf (getf (token-session-data *token*) :publish-to-fb)
item-to-publish)
(setf (getf (token-session-data *token*) :login-redirect)
(url-decode next))
(see-other (url-compose "/renew-fb-token")))
(defun facebook-item-meta-content
(id
typestring
title
&key description
url
image)
(html
(:meta :property "fb:app_id"
:content *facebook-app-id*)
(:meta :property "og:url"
:content (or url
(strcat* +base-url+
typestring
(when (or (string= typestring "offer")
(string= typestring "request"))
"s")
"/"
id)))
(:meta :property "og:title"
:content (escape-for-html
(or title (s+ "Kindista " (string-capitalize typestring)))))
(awhen description
(htm (:meta :property "og:description"
:content (escape-for-html it))))
(:meta :property "og:image:secure_url"
:content (s+ "" (or image "/media/biglogo4fb.jpg")))
(:meta :property "og:image"
:content (s+ ""
(aif image
(regex-replace "/media" it "")
"/biglogo4fb.jpg")))))
(defun facebook-share-button (url &optional text)
(html
(:a :href (s+ "="
+base-url+
(url-encode
(if (eql (char url 0) #\/)
(subseq url 1)
url)))
(str (or text "Share on Facebook"))))
: ( s+ " = "
" & amp;src = " )
( or text " Share on Facebook " ) ) )
)
(defun facebook-sign-in-button
(&key (redirect-uri "home")
(button-text "Sign in with Facebook")
re-request
state
scope)
(asetf scope
(strcat* (if (listp scope)
(format nil "~{~A,~}" scope)
(s+ scope ","))
" public_profile , publish_actions , email "
"public_profile,email"))
(html
(:a :class "blue facebook-button"
:href (apply #'url-compose
""
(remove nil
(append
(list "client_id" *facebook-app-id*
"scope" scope
"response_type" "code,granted_scopes"
"redirect_uri" (url-encode
(s+ +base-url+ redirect-uri)))
(when re-request
(list "auth_type" " rerequest"))
(when state
(list "state" state)))))
(str (icon "facebook-white")) (str button-text))))
(defun get-renew-fb-token
(&aux (next (or (get-parameter-string "next") "/home"))
(new-fb-item (getf (token-session-data *token*) :publish-to-fb))
(permission-requested (getf (token-session-data *token*) :fb-permission-requested))
(item-type (string-downcase (awhen new-fb-item (symbol-name (db it :type))))))
(standard-page
(if permission-requested
"Authorize Facebok App"
"Reauthorize Facebook App")
(html
(:h2
(str (aif permission-requested
(case it
(:publish-actions
"Kindista needs your permission to be able to publish items to Facebook")
(t "Kindista needs special permission for this action on Facebook"))
"Your Facebook session has expired on Kindista")))
(str (facebook-sign-in-button
:redirect-uri "/login"
:button-text (if permission-requested
"Authorize Facebook"
"Reauthorize Facebook")
:re-request permission-requested
:scope (mapcar (lambda (permission)
(regex-replace-all
"-"
(string-downcase (symbol-name permission))
"_"))
(cons permission-requested (getf *user* :fb-permissions)))))
(:p (:strong "Please note: ")
(awhen item-type
(htm "We will publish your " (str it) " to Facebook after you reauthorize Kindista's access to your Facebook account. "))
"We are unable to publish "
(str (if new-fb-item
"this or any other"
"any"))
" items to Facebook on your behalf until you reauthorize your account. ")
(:div :class "small"
(:span "No longer want to use Facebook with Kindista?")
(:form :method "post"
:action "/settings/social"
:class "inline-block"
(:input :type "hidden" :name "next" :value next)
(:button :class "simple-link red bold"
:type "submit"
:name "fb-logout"
"Deactivate Facebook App"))))
:class "fb-reauth"))
(defun facebook-debugging-log (userid response-code &rest messages)
(with-open-file (s (s+ +db-path+ "facebook-log")
:direction :output
:if-does-not-exist :create
:if-exists :append)
(let ((*print-readably* nil))
(format s "USERID:~A STATUS:~A TIME:~A~%~{~S~%~}"
userid
response-code
(local-time:now)
messages))
(fsync s)))
(defun register-facebook-user
(&optional (redirect-uri "home")
&aux (request (url-compose
""
"client_id" *facebook-app-id*
"redirect_uri" (s+ +base-url+ redirect-uri)
"client_secret" *facebook-secret*
"code" (get-parameter "code")))
reply)
(when (and *token* (get-parameter "code"))
(setf reply (multiple-value-list (http-request request :force-binary t)))
(let* ((token-data (when (<= (second reply) 200)
(alist-plist (decode-json-octets (first reply))))))
(facebook-debugging-log
*userid*
(second reply)
(or token-data
(cdr (assoc :message
(cdr (assoc :error (decode-json-octets (first reply)))))))
token-data)
token-data)))
(defun check-facebook-user-token
(&optional (userid *userid*)
(fb-token (or *facebook-user-token* (db userid :fb-token)))
&aux (*user* (or *user* (db userid)))
reply
data)
(setf reply
(multiple-value-list
(http-request
(s+ *fb-graph-url* "debug_token")
:parameters (list (cons "input_token" fb-token)
(cons "access_token" *facebook-app-token*)
(cons "appsecret_proof" (fb-app-secret-proof))
))))
(when (= (second reply) 200)
(setf data
(alist-plist
(cdr (find :data
(decode-json-octets (first reply))
:key #'car)))))
(facebook-debugging-log userid (second reply) fb-token data)
(when (and (string= (getf data :app--id) *facebook-app-id*)
(eql (safe-parse-integer (getf data :user--id))
(getf *user* :fb-id)))
data))
(defun facebook-token-validation-error-p
(&optional (userid *userid*)
&aux (fb-response (check-facebook-user-token userid)))
(or (not (getf fb-response :is--valid))
(eql (getf fb-response :expires--at) 0)
(eql 190 (getf (alist-plist (getf fb-response :error)) :code))))
(defun get-facebook-user-data
(fb-token
&aux initial-response
user-data)
(setf initial-response
(alist-plist (decode-json-octets
(http-request
(strcat *fb-graph-url* "me")
:parameters (list (cons "access_token" fb-token)
(cons "method" "get"))))))
(setf user-data (flatten
(decode-json-octets
(http-request (strcat *fb-graph-url* "v12.0/" (getf initial-response :id))
:parameters (list (cons "access_token" fb-token)
(cons "fields" "id,name,email")
(cons "method" "get"))))))
(facebook-debugging-log *userid* user-data)
user-data)
(defun get-facebook-user-id (fb-token)
(safe-parse-integer (getf (get-facebook-user-data fb-token) :id)))
(defun fb-k-id (fb-id)
(gethash fb-id *facebook-id-index*))
(defun get-facebook-profile-picture
(k-user-id
&aux (user (db k-user-id))
(fb-token (getf user :fb-token))
(fb-user-id (getf user :fb-id))
(response))
(when (and fb-token fb-user-id (getf user :fb-link-active))
(setf response
(multiple-value-list
(http-request (strcat *fb-graph-url* "v12.0/" fb-user-id "/picture")
:parameters (list (cons "access_token" fb-token)
(cons "appsecret_proof" (fb-app-secret-proof fb-token))
(cons "type" "large")
(cons "method" "get")))))
(facebook-debugging-log (or k-user-id
*userid*
(token-userid *token*))
(second response)
(unless (eql (second response) 200)
(decode-json-octets (first response)))
(fourth response))
(values (first response)
(second response)
(cdr (assoc :content-type (third response)))
(fourth response))))
(defun save-facebook-profile-picture-to-avatar (k-userid)
(multiple-value-bind
(octet-array status-code content-type image-url)
(get-facebook-profile-picture k-userid)
(declare (ignore image-url))
(when (eql status-code 200)
(create-image octet-array content-type))))
(defun facebook-image-identifyier (k-userid)
(multiple-value-bind
(octet-array status-code content-type image-url)
(get-facebook-profile-picture k-userid)
(declare (ignore octet-array content-type))
(case status-code
(200 (awhen image-url (car (last (puri:uri-parsed-path it)))))
(t :authentication-error))))
(defun get-facebook-user-permissions
(k-id
&optional (user (db k-id))
&aux (fb-id (getf user :fb-id))
(user-token (getf user :fb-token))
response
fb-permissions
current-permissions)
(when (and fb-id (getf user :fb-link-active))
(setf response
(multiple-value-list
(http-request
(strcat *fb-graph-url*
"v12.0/"
fb-id "/permissions")
:parameters (list (cons "access_token" *facebook-app-token*)
(cons "access_token" user-token)
(cons "appsecret_proof" (fb-app-secret-proof user-token))
(cons "method" "get")))))
(setf fb-permissions (getf (alist-plist (decode-json-octets
(first response)))
:data)))
(mapcar
(lambda (pair)
(push (string-to-keyword (car pair))
(getf current-permissions (cdr pair))))
(loop for permission in fb-permissions
collect (cons (cdar permission)
(cond
((string= (cdadr permission) "granted") :granted)
((string= (cdadr permission) "declined") :declined)
((string= (cdadr permission) "expired") :expired)
(t :error)))))
( second response )
( strcat * " FB Permissions : " current - permissions ) )
current-permissions)
(defun check-facebook-permission
(permission
&optional (userid *userid*)
&aux (user (db userid))
(saved-fb-permissions (getf user :fb-permissions))
(current-fb-permissions (get-facebook-user-permissions userid user))
(granted-fb-permissions (getf current-fb-permissions :granted)))
(when (set-exclusive-or saved-fb-permissions granted-fb-permissions)
(modify-db userid :fb-permissions granted-fb-permissions))
(values (find permission granted-fb-permissions)
(cond
((find permission (getf current-fb-permissions :declined))
:declined)
((find permission (getf current-fb-permissions :expired))
:expired)
(t nil))))
(defun get-facebook-kindista-friends
(&optional (k-id *userid*)
&aux (user (db k-id))
(user-token (getf user :fb-token))
(fb-id (getf user :fb-id))
(response)
friends)
(when (and fb-id (getf user :fb-link-active))
(setf response
(multiple-value-list
(http-request
(strcat *fb-graph-url*
"v3.0/"
fb-id "/friends")
:parameters (list (cons "access_token" *facebook-app-token*)
(cons "access_token" user-token)
(cons "appsecret_proof" (fb-app-secret-proof user-token))
(cons "method" "get"))))))
(pprint (find :data
(decode-json-octets (first response))
:key 'car))
(terpri)
(when (= (second response) 200)
(setf friends
(mapcar (lambda (friend)
(gethash (safe-parse-integer
(cdr (find :id friend :key 'car)))
*facebook-id-index*))
(cdr (find :data
(decode-json-octets (first response))
:key 'car)))))
(facebook-debugging-log k-id
(second response)
(strcat* "K-FB-Friends: " friends))
friends)
(defun active-facebook-user-p
(&optional (userid *userid*)
(user (if (eql userid *userid*) *user* (db userid))))
(and (getf user :fb-id) (getf user :fb-link-active) ))
(defun get-facebook-location-data (fb-location-id fb-token)
(alist-plist
(cdr
(assoc :location
(decode-json-octets
(http-request (strcat *fb-graph-url*
"v12.0/"
fb-location-id)
:parameters (list (cons "access_token" fb-token)
(cons "access_token" *facebook-app-token*)
(cons "appsecret_proof" (fb-app-secret-proof fb-token))
(cons "fields" "location")
(cons "method" "get"))))))))
(defun new-facebook-action-notice-handler
(&aux (notice-data (notice-data))
(userid (getf notice-data :userid))
(item-id (getf notice-data :item-id))
(item (db item-id))
(action-type (case (getf item :type)
(:gratitude "express")
(t "post")))
(fb-action-id)
(fb-object-id))
(when (and userid (not (first (fb-object-actions-by-user item-id
:userid userid))))
(setf fb-action-id
(publish-facebook-action item-id
:userid userid
:item item
:action-type action-type))
(setf fb-object-id (get-facebook-object-id item-id)))
(cond
((getf notice-data :object-modified)
(scrape-facebook-item (getf notice-data :fb-object-id)))
(userid
update kindista DB with new facebook object / action ids
(http-request
(s+ +base-url+ "publish-facebook")
:parameters (list (cons "item-id" (strcat item-id))
(cons "userid" (strcat userid))
(cons "fb-action-id" (strcat fb-action-id))
(cons "fb-action-type" action-type)
(cons "fb-object-id" (strcat fb-object-id))
(cons "fb-id" (strcat (db userid :fb-id))))
:method :post))))
(defun post-new-facebook-data
(&aux (item-id (post-parameter-integer "item-id"))
(userid (post-parameter-integer "userid"))
(fb-action-id (post-parameter-integer "fb-action-id"))
(fb-object-id (post-parameter-integer "fb-object-id"))
(fb-id (post-parameter-integer "fb-id"))
(fb-action-type (post-parameter-string "fb-action-type")))
(if (server-side-request-p)
(progn
(facebook-debugging-log
userid
nil
"modifying the DB"
(post-parameters*)
(strcat* "fb-object-id: " fb-object-id)
(amodify-db item-id :fb-object-id fb-object-id
:fb-publishing-in-process nil
:fb-publishing-error (unless fb-action-id
(cons (list :time (get-universal-time)
:userid userid)
it))
:fb-actions (if fb-action-id
(cons (list :fb-id fb-id
:fb-action-type fb-action-type
:fb-action-id fb-action-id)
it)
it)))
(setf (return-code*) +http-no-content+)
nil)
(progn
(setf (return-code*) +http-forbidden+)
nil)))
(defun publish-facebook-action
(id
&key (item (db id))
(action-type (case (getf item :type)
(:gratitude "express")
(t "post")))
(userid *userid*)
&aux (object-type (string-downcase (symbol-name (getf item :type))))
(user (db userid))
(user-token (getf user :fb-token))
(reply
(multiple-value-list
(http-request
(strcat *fb-graph-url*
"v3.0/me"
"/kindistadotorg:"
action-type)
:parameters (list (cons "access_token" user-token)
(cons "method" "post")
(cons "appsecret_proof" (fb-app-secret-proof user-token))
(cons object-type
(s+ ""
(resource-url id item)))
(cons "debug" "all")
(cons "fb:explicitly_shared" "true"))))))
(let ((data (when (= (second reply) 200)
(alist-plist (decode-json-octets (first reply))))))
(facebook-debugging-log userid
(second reply)
(strcat* "ITEM-PUBLISHED-TO-FB:" id)
(list :fb-id (getf user :fb-id)
:fb-token user-token)
(or data
(if (stringp (first reply))
(first reply)
(decode-json-octets (first reply)))))
(awhen (getf data :id) (safe-parse-integer it))))
(defun get-facebook-object-id
(k-id
&aux (item (db k-id))
(reply
(multiple-value-list
(http-request
(strcat *fb-graph-url*)
:parameters (list (cons "access_token" *facebook-app-token*)
(cons "id" (s+ "" (resource-url k-id item)))
)))))
(let* ((data (when (= (second reply) 200)
(alist-plist (decode-json-octets (first reply)))))
(object (alist-plist (getf data :og--object))))
(facebook-debugging-log *userid*
(second reply)
(strcat* "ITEM-ID:" k-id)
data)
(when object (safe-parse-integer (getf object :id)))))
(defun get-user-facebook-objects-of-type
(typestring
&optional (userid *userid*)
&aux (user (db userid))
(reply
(multiple-value-list
(http-request
(strcat *fb-graph-url*
"me"
( or * fb - id * ( getf user : fb - id ) )
"/kindistadotorg:post/"
typestring)
:parameters (list (cons "access_token" (getf user :fb-token))
(cons "method" "get"))))))
(when (= (second reply) 200)
(decode-json-octets (first reply))))
(defun fb-object-actions-by-user
(k-item-id
&key (data (db k-item-id))
(userid *userid*)
(fb-id (if (eql *userid* userid)
(getf *user* :fb-id)
(db userid :fb-id)))
&aux (actions))
(when userid
(dolist (action (getf data :fb-actions))
(when (eql (getf action :fb-id) fb-id)
(push (getf action :fb-action-id) actions))))
actions)
(defun update-facebook-object
(k-id
&aux (item (db k-id))
(facebook-id (getf item :fb-object-id))
(typestring (string-downcase (symbol-name (getf item :type))))
(reply (multiple-value-list
(http-request
(strcat "/" facebook-id)
:parameters (list (cons "access_token"
*facebook-app-token*)
'("method" . "POST")
(cons typestring
(strcat ""
(resource-url k-id item))))))))
"Works the same as (scrape-facebook-item)"
(when (= (second reply) 200)
(decode-json-octets (first reply))))
(defun scrape-facebook-item
(url-or-fb-id
&aux (reply (multiple-value-list
(http-request
"/"
:parameters (list (cons "id"
(if (integerp url-or-fb-id)
(write-to-string url-or-fb-id)
url-or-fb-id))
(cons "access_token"
*facebook-app-token*)
'("scrape" . "true"))
:method :post)))
(data (when (= (second reply) 200)
(decode-json-octets (first reply)))))
"Works the same as (update-facebook-object)"
(facebook-debugging-log *userid*
(second reply)
url-or-fb-id
(or data (when (stringp (first reply))
(first reply))))
data)
(defun get-facebook-action
(k-id
&optional (k-userid *userid*)
(user (or *user* (db k-userid)))
&aux (k-item (db k-id))
(action-id (cdr (assoc (getf user :fb-id)
(getf k-item :fb-actions))))
(reply (multiple-value-list
(http-request
(strcat "/" action-id)
:parameters (list (cons "access_token"
*facebook-app-token*)
(cons "access_token"
(getf user :fb-token))
'("method" . "GET")))))
(data))
(unless (stringp (first reply))
(setf data (decode-json-octets (first reply))))
(facebook-debugging-log k-userid
(second reply)
(if (stringp (first reply))
(first reply)
data))
(values data (second reply)))
(defun delete-facebook-action
(facebook-action-id
&aux (reply (multiple-value-list
(http-request
(strcat "/" facebook-action-id)
:parameters (list (cons "access_token"
*facebook-app-token*)
'("method" . "DELETE"))))))
(values
(decode-json-octets (first reply))
(second reply)))
(defun get-taggable-fb-friends
(&optional (userid *userid*)
(user (if (eql userid *userid*) *user* (db userid)))
(url (strcat *fb-graph-url*
"v3.0/"
(getf user :fb-id)
"/taggable_friends"))
&aux (response)
(user-token (getf user :fb-token)))
"Performs a call to the FB graph taggable_friends endpoint to get a list of all taggable friends."
(when (active-facebook-user-p userid user)
(setf response
(multiple-value-list
(http-request
url
:parameters (list (cons "access_token" *facebook-app-token*)
(cons "access_token" user-token)
(cons "appsecret_proof" (fb-app-secret-proof user-token))
(cons "limit" "5000")
(cons "method" "get"))))))
(case (second response)
(200 (decode-json-octets (first response)))
(t (facebook-debugging-log *userid*
(second response)
(if (stringp (first response))
(first response)
(decode-json-octets (first response)))))))
(defun get-all-taggable-fb-friends
(&optional (userid *userid*)
(user (if (eql userid *userid*) *user* (db userid)))
&aux (all-results)
(current-results)
(next)
(requests 0))
"Performs multiple calls to the FB graph taggable_friends endpoint to accumulate a list of all taggable friends. Not currently needed because that endpoint allows a 'limit' get parameter to get a list of all taggable friends."
(labels ((request-loop ()
(setf current-results
(apply #'get-taggable-fb-friends (remove nil (list userid user next))))
(setf next (cdr (find :next
(cdr (find :paging current-results :key 'car))
:key 'car)))
(incf requests)
(if all-results
(asetf all-results (append it (cdr (find :data current-results :key 'car))))
(setf all-results (cdr (find :data current-results :key 'car))))
(when (and (< requests 5)
(stringp next))
(request-loop))))
(request-loop))
all-results)
(defun find-taggable-fb-friend-by-name (k-id name)
(find name
(get-all-taggable-fb-friends k-id)
:key (lambda (item)
(cdr (find :name item :key 'car)))
:test #'string=))
(defun facebook-taggable-friend-tokens
(k-user-ids-to-test
&optional (userid *userid*)
&aux (image-identifiers (mapcar (lambda (id)
(cons id (facebook-image-identifyier id)))
k-user-ids-to-test))
(logged-out-of-fb)
(taggable-fb-friends (get-all-taggable-fb-friends userid))
(taggable-k-users))
"Returns and a-list of (k-userid . fb-taggable-token)"
(flet ((get-pic-url-identifier (fb-data)
(car
(split "\\?"
(car
(last
(url-parts
(cdr (find :url
(cdr (find :data
(cdr (find :picture fb-data :key 'car))
:key 'car))
:key 'car)))))))))
(dolist (pair image-identifiers)
(if (eql (cdr pair) :authentication-error)
(push (car pair) logged-out-of-fb)
(awhen (find (cdr pair)
taggable-fb-friends
:key #'get-pic-url-identifier
:test #'string=)
(push (cons (car pair) (getf (alist-plist it) :id))
taggable-k-users)))))
(facebook-debugging-log *userid* nil "Facebook Taggable Friend Tokens" taggable-k-users logged-out-of-fb)
(values taggable-k-users logged-out-of-fb))
(defun fb-taggable-friends-auth-warning (id-list)
(when id-list
(flash (s+ (name-list-all id-list)
(if (> (length id-list) 1)
" are" " is")
" not logged into Facebook through Kindista. You can tag them in this statement of gratitude after they authorize their Facebook account through Kindista.")
:error t)))
(defun facebook-friends-permission-html
(&key redirect-uri
fb-gratitude-subjects
(cancel-link "home")
re-request
(page-title "Tag your Facebook friends"))
(standard-page
page-title
(html
(:div :id "tag-fb-friends-auth"
(:p :class "large"
"Would you like to tag "
(:strong (str (name-list-all fb-gratitude-subjects :stringp t
:conjunction :or)))
" in the gratitude you published to Facebook?")
(:p :class "small"
"To enable tagging, Facebook requires that you give Kindista access to your Facebook friends list. We respect your privacy and your relationships; we will not spam your friends.")
(str (facebook-sign-in-button :redirect-uri redirect-uri
:scope "user_friends"
:state "user_friends_scope_granted"
:re-request re-request
:button-text "Allow Kindista to see my list of Facebook friends"))
(:a :href cancel-link :class "gray-text cancel" "Not now")))
:selected "people"))
(defun tag-facebook-friends-html
(&key gratitude-id
fb-gratitude-subjects
(page-title "Tag your Facebook friends")
&aux (gratitude (when gratitude-id (db gratitude-id)))
(fb-g-subject-ids (mapcar #'cdr fb-gratitude-subjects)))
(awhen (set-difference (getf gratitude :subjects) fb-g-subject-ids)
(flash (s+ (name-list it :links nil :maximum-links 10)
" cannot be tagged. Either they have not linked their Facebook"
" accounts with Kindista or they have not given permission"
" for Kindista to see if you are friends on Facebook.")))
(standard-page
page-title
(html
(:div :id "tag-fb-friends"
(:h3 "You have published this Statement of Gratitude on your Facebook feed:")
(:blockquote
(str (gratitude-activity-item (gethash gratitude-id *db-results*)
:show-actions nil)))
(:form :method "post" :action (strcat "/gratitude/" gratitude-id)
(:fieldset
(:legend (str page-title))
(dolist (pair fb-gratitude-subjects)
(htm
(:div :class "friend-to-tag"
(:div :class "g-recipient item"
(:input :type "checkbox"
:name "tag-fb-friend"
:value (cdr pair)
:id (cdr pair)
:checked "")
(:label :for (cdr pair)
(:img :src (get-avatar-thumbnail (cdr pair) 70 70))
(str (car pair))))))))
(:p (:button :class "cancel" :type "submit" :class "cancel" :name "cancel" "Cancel")
(:button :class "yes" :type "submit" :class "submit" :name "tag-friends" "Tag Friends")))))
:selected "people"))
(defun tag-facebook-friends
(k-item-id
k-contacts-to-tag-on-fb
&optional (userid *userid*)
&aux (item (db k-item-id))
(user (if (eql userid *userid*) *user* (db userid)))
(user-token (getf user :fb-token))
(response)
(taggable-friend-tokens (facebook-taggable-friend-tokens
k-contacts-to-tag-on-fb
userid))
(friends-to-tag)
(tagged-friends)
(action-id (first (fb-object-actions-by-user k-item-id
:data item
:userid userid
:fb-id (getf user :fb-id)))))
(dolist (id k-contacts-to-tag-on-fb)
(awhen (assoc id taggable-friend-tokens)
(push (car it) tagged-friends)
(push (cdr it) friends-to-tag)))
(when (and friends-to-tag (active-facebook-user-p userid user))
(asetf friends-to-tag (separate-with-commas it :omit-spaces t))
(setf response
(multiple-value-list
(http-request
(strcat *fb-graph-url*
"v3.0/"
action-id)
:parameters (list (cons "access_token" user-token)
(cons "appsecret_proof" (fb-app-secret-proof user-token))
(cons "tags" friends-to-tag))
:method :post)))
(setf response (decode-json-octets (first response)))
(when (and (eql (caar response) :success)
(eql (cdar response) t))
(flash (s+ (name-list-all tagged-friends) " have been tagged in your statement of gratitude on Facebook."))
(amodify-db k-item-id :fb-tagged-friends (append tagged-friends it)))
(facebook-debugging-log userid
nil
action-id
(strcat* "Contacts to tag on fb: "
k-contacts-to-tag-on-fb)
taggable-friend-tokens
friends-to-tag
response)
response))
(defun fb-app-secret-proof
(&optional (access-token *facebook-app-token*)
&aux (hmac (ironclad:make-hmac (ironclad:ascii-string-to-byte-array *facebook-secret*) :sha256))
(hmac-hash (ironclad:update-hmac hmac (ironclad:ascii-string-to-byte-array access-token)))
(digest (ironclad:hmac-digest hmac-hash)))
(ironclad:byte-array-to-hex-string digest))
(defun post-uninstall-facebook
(&aux (signed-request (post-parameter "signed_request"))
(split-request (split "\\." signed-request))
(signature (substitute #\+ #\- (substitute #\/ #\_ (first split-request))))
(expected-sig)
(raw-data (second split-request))
(hmac (ironclad:make-hmac (string-to-octets *facebook-secret*) :sha256))
(json)
(fb-id)
(userid))
(ironclad:update-hmac hmac (string-to-octets raw-data))
(setf expected-sig
(remove #\= (base64:usb8-array-to-base64-string
(ironclad:hmac-digest hmac))))
(facebook-debugging-log nil
nil
"Uninstalling FB"
signed-request
expected-sig
signature)
(if (equalp expected-sig signature)
(progn
(setf json
(json:decode-json-from-string
(with-output-to-string (s)
(base64:base64-string-to-stream raw-data :uri t :stream s))))
(setf fb-id (safe-parse-integer (getf (alist-plist json) :user--id)))
(setf userid (gethash fb-id *facebook-id-index*))
(facebook-debugging-log userid nil json)
(when userid
(modify-db userid :fb-link-active nil
:fb-token nil
:fb-expires (get-universal-time)))
(setf (return-code*) +http-no-content+)
nil)
(progn (setf (return-code*) +http-forbidden+)
nil)))
|
12e90e97b06e98608b229fdaa90c4b50ef1b7d772332ea18e341a154c4d5ca2c | markus-git/hardware-edsl | Types.hs | {-# LANGUAGE TypeOperators #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE DataKinds #-}
# LANGUAGE ScopedTypeVariables #
module Types where
import Language.VHDL (Mode(..))
import Language.Embedded.Hardware
import Control.Monad.Identity
import Control.Monad.Operational.Higher
import Data.ALaCarte
import Data.Int
import Data.Word
import Text.PrettyPrint
import Prelude hiding (and, or, not, toInteger)
--------------------------------------------------------------------------------
-- * Example of a program that performs type casting.
--------------------------------------------------------------------------------
-- | Command set used for our programs.
type CMD =
SignalCMD
:+: VariableCMD
:+: ArrayCMD
:+: VArrayCMD
:+: LoopCMD
:+: ConditionalCMD
:+: ComponentCMD
:+: ProcessCMD
:+: VHDLCMD
type HProg = Program CMD (Param2 HExp HType)
type HSig = Sig CMD HExp HType Identity
--------------------------------------------------------------------------------
casting :: HProg ()
casting =
do a :: Variable Word8 <- initVariable 0
b :: Variable Int8 <- initVariable 2
c :: Variable Int16 <- initVariable 200
av :: HExp Word8 <- getVariable a
bv :: HExp Int8 <- getVariable b
cv :: HExp Int16 <- getVariable c
setVariable b (toSigned av)
setVariable c (toSigned av)
setVariable a (toUnsigned cv)
let x = 2 :: HExp Word8
setVariable a (av `sll` (toInteger x))
--------------------------------------------------------------------------------
test = icompile casting
--------------------------------------------------------------------------------
| null | https://raw.githubusercontent.com/markus-git/hardware-edsl/d0fde93ff57a8f5c2c37e273ff3a1d2a761fc5eb/examples/Types.hs | haskell | # LANGUAGE TypeOperators #
# LANGUAGE FlexibleContexts #
# LANGUAGE DataKinds #
------------------------------------------------------------------------------
* Example of a program that performs type casting.
------------------------------------------------------------------------------
| Command set used for our programs.
------------------------------------------------------------------------------
------------------------------------------------------------------------------
------------------------------------------------------------------------------ | # LANGUAGE ScopedTypeVariables #
module Types where
import Language.VHDL (Mode(..))
import Language.Embedded.Hardware
import Control.Monad.Identity
import Control.Monad.Operational.Higher
import Data.ALaCarte
import Data.Int
import Data.Word
import Text.PrettyPrint
import Prelude hiding (and, or, not, toInteger)
type CMD =
SignalCMD
:+: VariableCMD
:+: ArrayCMD
:+: VArrayCMD
:+: LoopCMD
:+: ConditionalCMD
:+: ComponentCMD
:+: ProcessCMD
:+: VHDLCMD
type HProg = Program CMD (Param2 HExp HType)
type HSig = Sig CMD HExp HType Identity
casting :: HProg ()
casting =
do a :: Variable Word8 <- initVariable 0
b :: Variable Int8 <- initVariable 2
c :: Variable Int16 <- initVariable 200
av :: HExp Word8 <- getVariable a
bv :: HExp Int8 <- getVariable b
cv :: HExp Int16 <- getVariable c
setVariable b (toSigned av)
setVariable c (toSigned av)
setVariable a (toUnsigned cv)
let x = 2 :: HExp Word8
setVariable a (av `sll` (toInteger x))
test = icompile casting
|
e94edd21314f7dbe8cfc05dfc979f8602d19206c8514ebd074bede8c04834b1f | pdarragh/parsing-with-zippers-paper-artifact | pwz_bench.ml | module Command = Core.Command
open Benchmarking
open Core_bench
open Interface
open Pwz_cli_common
open Pytokens
(* A small module for properly timing parses. This needed to be parameterized for the PI.tok, hence the module. *)
module MakeTimer (PI : ParserInterface) = struct
let time_parse (tokens : PI.tok list) () =
ignore (PI.parse tokens)
end
let strip_filename (filename : string) : string =
match String.rindex_opt filename '/' with
| Some i -> String.sub filename (i + 1) ((String.length filename) - i - 1)
| None -> filename
Create a Core_bench benchmarking test for a given file and parser .
let make_test_from_file (filename : string) (parser_name : string) ((module Parser) : (module ParserInterface)) : Bench.Test.t =
let module Timer = MakeTimer(Parser) in
let tokens = Parser.process_tokens (token_list_from_file filename) in
Bench.Test.create ~name:(Printf.sprintf "%s:%s:%d" parser_name (strip_filename filename) (List.length tokens)) (Timer.time_parse tokens)
Create Core_bench benchmarking tests for all file for the given parser .
let make_tests_for_parser (parser : parser_desc) (filenames : string list) : Bench.Test.t list =
let make_test_from_file (filename : string) = make_test_from_file filename (fst parser) (snd parser) in
List.map make_test_from_file filenames
Construct all Core_bench benchmarking tests .
let make_tests (filenames : string list) (parsers : string list) : Bench.Test.t list =
let pds = List.map (fun parser -> (parser, List.assoc parser parsers_to_interfaces)) parsers in
List.concat (List.map (fun pd -> make_tests_for_parser pd filenames) pds)
(* The base parsing command. *)
let command : Command.t =
Bench.make_command_ext ~summary:"benchmark stuff" (
let open Command.Param in
both
(flag "input" (listed string) ~doc:"FILENAME Specify a .lex file to parse and benchmark. This flag may be specified multiple times to benchmark multiple files.")
(flag "parser" (listed string) ~doc:"PARSER Specify a parser to parse with. This flag may be specified multiple times.")
|> map ~f:(fun (filenames, parsers) -> make_bench_command (make_tests filenames parsers))
)
let () = Command.run command
| null | https://raw.githubusercontent.com/pdarragh/parsing-with-zippers-paper-artifact/c5c08306cfe4eec588237c7fa45b794649ccb68a/benchmark/pwz_bench/generate/static/pwz_bench.ml | ocaml | A small module for properly timing parses. This needed to be parameterized for the PI.tok, hence the module.
The base parsing command. | module Command = Core.Command
open Benchmarking
open Core_bench
open Interface
open Pwz_cli_common
open Pytokens
module MakeTimer (PI : ParserInterface) = struct
let time_parse (tokens : PI.tok list) () =
ignore (PI.parse tokens)
end
let strip_filename (filename : string) : string =
match String.rindex_opt filename '/' with
| Some i -> String.sub filename (i + 1) ((String.length filename) - i - 1)
| None -> filename
Create a Core_bench benchmarking test for a given file and parser .
let make_test_from_file (filename : string) (parser_name : string) ((module Parser) : (module ParserInterface)) : Bench.Test.t =
let module Timer = MakeTimer(Parser) in
let tokens = Parser.process_tokens (token_list_from_file filename) in
Bench.Test.create ~name:(Printf.sprintf "%s:%s:%d" parser_name (strip_filename filename) (List.length tokens)) (Timer.time_parse tokens)
Create Core_bench benchmarking tests for all file for the given parser .
let make_tests_for_parser (parser : parser_desc) (filenames : string list) : Bench.Test.t list =
let make_test_from_file (filename : string) = make_test_from_file filename (fst parser) (snd parser) in
List.map make_test_from_file filenames
Construct all Core_bench benchmarking tests .
let make_tests (filenames : string list) (parsers : string list) : Bench.Test.t list =
let pds = List.map (fun parser -> (parser, List.assoc parser parsers_to_interfaces)) parsers in
List.concat (List.map (fun pd -> make_tests_for_parser pd filenames) pds)
let command : Command.t =
Bench.make_command_ext ~summary:"benchmark stuff" (
let open Command.Param in
both
(flag "input" (listed string) ~doc:"FILENAME Specify a .lex file to parse and benchmark. This flag may be specified multiple times to benchmark multiple files.")
(flag "parser" (listed string) ~doc:"PARSER Specify a parser to parse with. This flag may be specified multiple times.")
|> map ~f:(fun (filenames, parsers) -> make_bench_command (make_tests filenames parsers))
)
let () = Command.run command
|
25d51e277e588af83c2bf348bc93f27fbaa89f588e4e67b6b3bc82967897c1c7 | HouzuoGuo/Aurinko | db.clj | (ns Aurinko.db
(:use [clojure.java.io :only [file]])
(:require (Aurinko [fs :as fs] [col :as col])))
(defprotocol DbP
(create [this name])
(rename [this old new])
(delete [this name])
(compress [this name] "Compact space consumed by deleted documents")
(repair [this name] "Recreate the collection from its log file")
(col [this name])
(all [this])
(save [this])
(close [this]))
(deftype Db [dir ^{:unsynchronized-mutable true} cols] DbP
(create [this name]
(save this)
(when ((keyword name) cols)
(throw (Exception. (str "collection " name " already exists"))))
(if (.mkdirs (file (str dir fs/sep name)))
(set! cols (assoc cols (keyword name) (col/open (str dir fs/sep name))))
(throw (Exception. (str "failed to create directory for collection " name)))))
(rename [this old new]
(save this)
(when ((keyword new) cols)
(throw (Exception. (str "new collection name " new " is already used"))))
(when-not ((keyword old) cols)
(throw (Exception. (str "collection " old " does not exist"))))
(when-not (.renameTo (file dir old) (file dir new))
(throw (Exception. (str "failed to rename collection directory"))))
(set! cols (assoc (dissoc cols (keyword old))
(keyword new) (col/open (str dir fs/sep new)))))
(delete [this name]
(save this)
(when-not ((keyword name) cols)
(throw (Exception. (str "collection " name " does not exist"))))
(fs/rmrf (file dir name))
(set! cols (dissoc cols (keyword name))))
(compress [this name]
(save this)
(if-let [c ((keyword name) cols)]
(let [hash-indexed (col/indexed c)
tmp-name (str (System/nanoTime))
tmp (do (create this tmp-name) ((keyword tmp-name) cols))]
(col/all ((keyword name) cols) #(col/insert tmp %))
(delete this name)
(rename this tmp-name name)
(let [repaired (col this name)]
(doseq [i hash-indexed] (col/index-path repaired i))))
(throw (Exception. (str "collection " name " does not exist")))))
(repair [this name]
(save this)
(if-let [c ((keyword name) cols)]
(let [hash-indexed (col/indexed c)
tmp-name (str (System/nanoTime))
tmp (do (create this tmp-name) (col this tmp-name))]
(fs/lines (str dir fs/sep name fs/sep "log")
(fn [line]
(try
(let [entry (read-string line)
[op info _] entry]
(case op
:i (col/insert tmp info)
:u (col/update tmp info)
:d (col/delete tmp {:_pos info})))
(catch Exception e (prn "Failed to repair from log line" line)))))
(delete this name)
(rename this tmp-name name)
(let [repaired (col this name)]
(doseq [i hash-indexed] (col/index-path repaired i))))
(throw (Exception. (str "collection " name " does not exist")))))
(col [this name]
(when-not (contains? cols (keyword name))
(throw (Exception. (str "collection " name " does not exist"))))
((keyword name) cols))
(all [this] (fs/ls dir))
(save [this] (doseq [c (vals cols)] (col/save c)))
(close [this] (save this) (doseq [c (vals cols)] (col/close c))))
(defn open [path]
(when-not (.exists (file path))
(.mkdir (file path)))
(Db. (str path fs/sep)
(into {} (for [f (fs/ls path)]
[(keyword f) (col/open (str path fs/sep f))])))) | null | https://raw.githubusercontent.com/HouzuoGuo/Aurinko/f24bcab53da45b477d0b842bc4ab9ff1e08f505c/src/Aurinko/db.clj | clojure | (ns Aurinko.db
(:use [clojure.java.io :only [file]])
(:require (Aurinko [fs :as fs] [col :as col])))
(defprotocol DbP
(create [this name])
(rename [this old new])
(delete [this name])
(compress [this name] "Compact space consumed by deleted documents")
(repair [this name] "Recreate the collection from its log file")
(col [this name])
(all [this])
(save [this])
(close [this]))
(deftype Db [dir ^{:unsynchronized-mutable true} cols] DbP
(create [this name]
(save this)
(when ((keyword name) cols)
(throw (Exception. (str "collection " name " already exists"))))
(if (.mkdirs (file (str dir fs/sep name)))
(set! cols (assoc cols (keyword name) (col/open (str dir fs/sep name))))
(throw (Exception. (str "failed to create directory for collection " name)))))
(rename [this old new]
(save this)
(when ((keyword new) cols)
(throw (Exception. (str "new collection name " new " is already used"))))
(when-not ((keyword old) cols)
(throw (Exception. (str "collection " old " does not exist"))))
(when-not (.renameTo (file dir old) (file dir new))
(throw (Exception. (str "failed to rename collection directory"))))
(set! cols (assoc (dissoc cols (keyword old))
(keyword new) (col/open (str dir fs/sep new)))))
(delete [this name]
(save this)
(when-not ((keyword name) cols)
(throw (Exception. (str "collection " name " does not exist"))))
(fs/rmrf (file dir name))
(set! cols (dissoc cols (keyword name))))
(compress [this name]
(save this)
(if-let [c ((keyword name) cols)]
(let [hash-indexed (col/indexed c)
tmp-name (str (System/nanoTime))
tmp (do (create this tmp-name) ((keyword tmp-name) cols))]
(col/all ((keyword name) cols) #(col/insert tmp %))
(delete this name)
(rename this tmp-name name)
(let [repaired (col this name)]
(doseq [i hash-indexed] (col/index-path repaired i))))
(throw (Exception. (str "collection " name " does not exist")))))
(repair [this name]
(save this)
(if-let [c ((keyword name) cols)]
(let [hash-indexed (col/indexed c)
tmp-name (str (System/nanoTime))
tmp (do (create this tmp-name) (col this tmp-name))]
(fs/lines (str dir fs/sep name fs/sep "log")
(fn [line]
(try
(let [entry (read-string line)
[op info _] entry]
(case op
:i (col/insert tmp info)
:u (col/update tmp info)
:d (col/delete tmp {:_pos info})))
(catch Exception e (prn "Failed to repair from log line" line)))))
(delete this name)
(rename this tmp-name name)
(let [repaired (col this name)]
(doseq [i hash-indexed] (col/index-path repaired i))))
(throw (Exception. (str "collection " name " does not exist")))))
(col [this name]
(when-not (contains? cols (keyword name))
(throw (Exception. (str "collection " name " does not exist"))))
((keyword name) cols))
(all [this] (fs/ls dir))
(save [this] (doseq [c (vals cols)] (col/save c)))
(close [this] (save this) (doseq [c (vals cols)] (col/close c))))
(defn open [path]
(when-not (.exists (file path))
(.mkdir (file path)))
(Db. (str path fs/sep)
(into {} (for [f (fs/ls path)]
[(keyword f) (col/open (str path fs/sep f))])))) | |
ebaf135ce8e5b0ab80f0b032e0f972800728eb4adeb1a43232e780f33b4156c0 | rmculpepper/crypto | info.rkt | #lang info
;; pkg info
(define version "1.0")
(define collection "crypto")
(define deps '("base" "rackunit-lib" "asn1-lib" "crypto-lib"))
(define pkg-authors '(ryanc))
;; collection info
(define name "crypto")
| null | https://raw.githubusercontent.com/rmculpepper/crypto/fec745e8af7e3f4d5eaf83407dde2817de4c2eb0/crypto-test/info.rkt | racket | pkg info
collection info | #lang info
(define version "1.0")
(define collection "crypto")
(define deps '("base" "rackunit-lib" "asn1-lib" "crypto-lib"))
(define pkg-authors '(ryanc))
(define name "crypto")
|
271e038d9e422cefae84dc611b9c800aca922c0fae1c0289dd541be5b432a841 | Average-user/MazeGen | Spec.hs | import Data.Array
import Solver
import System.Random
import Utils
import Data.Set (fromList)
import Test.QuickCheck
import Data.Time
-- | Algorithms implemented so far
import qualified Algorithm.HuntKill
import qualified Algorithm.Sidewinder
import qualified Algorithm.Prims
import qualified Algorithm.GrowingTree
import qualified Algorithm.Backtracker
import qualified Algorithm.Kruskals
import qualified Algorithm.Ellers
implies :: Bool -> Bool -> Bool
implies a b = not a || b
perfectMaze :: StdGen -> ((Int,Int) -> StdGen -> Graph) -> (Int, Int) -> Bool
perfectMaze g algorithm (n,m) =
(m > 0 && n > 0) `implies` (length (connected graph) == 1 && acyclic graph)
where
graph = algorithm (n,m) g
nonPerfectMaze :: StdGen -> ((Int,Int) -> StdGen -> Graph) -> (Int, Int) -> Int -> Bool
nonPerfectMaze g algorithm (n,m) walls =
(m > 1 && n > 1 && walls > 0 && walls < n*m)
`implies`
(length (connected graph) == 1 && not (acyclic graph))
where
graph = nonPerfect algorithm walls (n,m) g
testAlgorithm :: String -> ((Int,Int) -> StdGen -> Graph) -> IO ()
testAlgorithm s alg = do
g <- getStdGen
timeIO s (do quickCheck (perfectMaze g alg)
quickCheck (nonPerfectMaze g alg))
main :: IO ()
main = do
testAlgorithm "\nTesting Huntkill: \n" Algorithm.HuntKill.generate
testAlgorithm "Testing Sidewinder: \n" Algorithm.HuntKill.generate
testAlgorithm "Testing Prims: \n" Algorithm.HuntKill.generate
testAlgorithm "Testing GrowingTree: \n" Algorithm.HuntKill.generate
testAlgorithm "Testing Backtracker: \n" Algorithm.HuntKill.generate
testAlgorithm "Testing Kruskals: \n" Algorithm.HuntKill.generate
testAlgorithm "Testing Ellers: \n" Algorithm.HuntKill.generate
timeIO :: String -> IO () -> IO ()
timeIO msg f = do
putStr msg
start <- getCurrentTime
f
stop <- getCurrentTime
print $ diffUTCTime stop start
putStr "\n"
| null | https://raw.githubusercontent.com/Average-user/MazeGen/e6788c05ccd1bd10e1d4b00c23404b9b1d3352a9/test/Spec.hs | haskell | | Algorithms implemented so far | import Data.Array
import Solver
import System.Random
import Utils
import Data.Set (fromList)
import Test.QuickCheck
import Data.Time
import qualified Algorithm.HuntKill
import qualified Algorithm.Sidewinder
import qualified Algorithm.Prims
import qualified Algorithm.GrowingTree
import qualified Algorithm.Backtracker
import qualified Algorithm.Kruskals
import qualified Algorithm.Ellers
implies :: Bool -> Bool -> Bool
implies a b = not a || b
perfectMaze :: StdGen -> ((Int,Int) -> StdGen -> Graph) -> (Int, Int) -> Bool
perfectMaze g algorithm (n,m) =
(m > 0 && n > 0) `implies` (length (connected graph) == 1 && acyclic graph)
where
graph = algorithm (n,m) g
nonPerfectMaze :: StdGen -> ((Int,Int) -> StdGen -> Graph) -> (Int, Int) -> Int -> Bool
nonPerfectMaze g algorithm (n,m) walls =
(m > 1 && n > 1 && walls > 0 && walls < n*m)
`implies`
(length (connected graph) == 1 && not (acyclic graph))
where
graph = nonPerfect algorithm walls (n,m) g
testAlgorithm :: String -> ((Int,Int) -> StdGen -> Graph) -> IO ()
testAlgorithm s alg = do
g <- getStdGen
timeIO s (do quickCheck (perfectMaze g alg)
quickCheck (nonPerfectMaze g alg))
main :: IO ()
main = do
testAlgorithm "\nTesting Huntkill: \n" Algorithm.HuntKill.generate
testAlgorithm "Testing Sidewinder: \n" Algorithm.HuntKill.generate
testAlgorithm "Testing Prims: \n" Algorithm.HuntKill.generate
testAlgorithm "Testing GrowingTree: \n" Algorithm.HuntKill.generate
testAlgorithm "Testing Backtracker: \n" Algorithm.HuntKill.generate
testAlgorithm "Testing Kruskals: \n" Algorithm.HuntKill.generate
testAlgorithm "Testing Ellers: \n" Algorithm.HuntKill.generate
timeIO :: String -> IO () -> IO ()
timeIO msg f = do
putStr msg
start <- getCurrentTime
f
stop <- getCurrentTime
print $ diffUTCTime stop start
putStr "\n"
|
e2075f31b879983c5821248c5dcbc6c2d1ed8de927b8d0a3fde87ec4c7db0761 | aisamanra/s-cargot | Comments.hs | {-# LANGUAGE OverloadedStrings #-}
module Data.SCargot.Comments
( -- $intro
-- * Lisp-Style Syntax
-- $lisp
withLispComments
-- * Other Existing Comment Syntaxes
-- ** Scripting Language Syntax
-- $script
, withOctothorpeComments
* * Prolog- or Matlab - Style Syntax
, withPercentComments
, withPercentBlockComments
-- ** C-Style Syntax
-- $clike
, withCLikeLineComments
, withCLikeBlockComments
, withCLikeComments
-- ** Haskell-Style Syntax
$ haskell
, withHaskellLineComments
, withHaskellBlockComments
, withHaskellComments
-- * Comment Syntax Helper Functions
, lineComment
, simpleBlockComment
) where
import Text.Parsec ( (<|>)
, anyChar
, manyTill
, noneOf
, skipMany
, string
)
import Data.SCargot.Parse ( Comment
, SExprParser
, setComment
)
-- | Given a string, produce a comment parser that matches that
-- initial string and ignores everything until the end of the
-- line.
lineComment :: String -> Comment
lineComment s = string s >> skipMany (noneOf "\n") >> return ()
| Given two strings , a begin and an end delimiter , produce a
-- parser that matches the beginning delimiter and then ignores
-- everything until it finds the end delimiter. This does not
-- consider nesting, so, for example, a comment created with
--
-- > curlyComment :: Comment
> = simpleBlockComment " { " " } "
--
-- will consider
--
-- > { this { comment }
--
-- to be a complete comment, despite the apparent improper nesting.
-- This is analogous to standard C-style comments in which
--
-- > /* this /* comment */
--
-- is a complete comment.
simpleBlockComment :: String -> String -> Comment
simpleBlockComment begin end =
string begin >>
manyTill anyChar (string end) >>
return ()
-- | Lisp-style line-oriented comments start with @;@ and last
-- until the end of the line. This is usually the comment
-- syntax you want.
withLispComments :: SExprParser t a -> SExprParser t a
withLispComments = setComment (lineComment ";")
-- | C++-like line-oriented comment start with @//@ and last
-- until the end of the line.
withCLikeLineComments :: SExprParser t a -> SExprParser t a
withCLikeLineComments = setComment (lineComment "//")
-- | C-like block comments start with @/*@ and end with @*/@.
-- They do not nest.
withCLikeBlockComments :: SExprParser t a -> SExprParser t a
withCLikeBlockComments = setComment (simpleBlockComment "/*" "*/")
-- | C-like comments include both line- and block-comments, the
-- former starting with @//@ and the latter contained within
-- @//* ... *//@.
withCLikeComments :: SExprParser t a -> SExprParser t a
withCLikeComments = setComment (lineComment "//" <|>
simpleBlockComment "/*" "*/")
-- | Haskell line-oriented comments start with @--@ and last
-- until the end of the line.
withHaskellLineComments :: SExprParser t a -> SExprParser t a
withHaskellLineComments = setComment (lineComment "--")
-- | Haskell block comments start with @{-@ and end with @-}@.
-- They do not nest.
withHaskellBlockComments :: SExprParser t a -> SExprParser t a
withHaskellBlockComments = setComment (simpleBlockComment "{-" "-}")
-- | Haskell comments include both the line-oriented @--@ comments
-- and the block-oriented @{- ... -}@ comments
withHaskellComments :: SExprParser t a -> SExprParser t a
withHaskellComments = setComment (lineComment "--" <|>
simpleBlockComment "{-" "-}")
-- | Many scripting and shell languages use these, which begin with
-- @#@ and last until the end of the line.
withOctothorpeComments :: SExprParser t a -> SExprParser t a
withOctothorpeComments = setComment (lineComment "#")
| MATLAB , , PostScript , and others use comments which begin
-- with @%@ and last until the end of the line.
withPercentComments :: SExprParser t a -> SExprParser t a
withPercentComments = setComment (lineComment "%")
| MATLAB block comments are started with @%{@ and end with
withPercentBlockComments :: SExprParser t a -> SExprParser t a
withPercentBlockComments = setComment (simpleBlockComment "%{" "%}")
$ intro
By default a ' SExprParser ' will not understand any kind of comment
syntax . Most varieties of s - expression will , however , want some kind
of commenting capability , so the below functions will produce a new
' SExprParser ' which understands various kinds of comment syntaxes .
For example :
> mySpec : : SExprParser Text ( SExpr Text )
> mySpec = asWellFormed $ mkParser ( pack < $ > many1 alphaNum )
>
> myLispySpec : : SExprParser Text ( SExpr Text )
> myLispySpec = withLispComments mySpec
>
> myCLikeSpec : : SExprParser Text ( SExpr Text )
> myCLikeSpec =
We can then use these to parse s - expressions with different kinds of
comment syntaxes :
> > > decode mySpec " ( foo ; a lisp comment\n bar)\n "
Left " ( line 1 , column 6):\nunexpected \";\"\nexpecting space or atom "
> > > decode myLispySpec " ( foo ; a lisp comment\n bar)\n "
Right [ WFSList [ " foo " , " bar " ] ]
> > > decode mySpec " ( foo / * a c - like\n comment * / bar)\n "
Left " ( line 1 , column 6):\nunexpected \"/\"\nexpecting space or atom "
> > > decode myCLikeSpec " ( foo / * a c - like\n comment * / bar)\n "
Right [ WFSList [ " foo " , " bar " ] ]
By default a 'SExprParser' will not understand any kind of comment
syntax. Most varieties of s-expression will, however, want some kind
of commenting capability, so the below functions will produce a new
'SExprParser' which understands various kinds of comment syntaxes.
For example:
> mySpec :: SExprParser Text (SExpr Text)
> mySpec = asWellFormed $ mkParser (pack <$> many1 alphaNum)
>
> myLispySpec :: SExprParser Text (SExpr Text)
> myLispySpec = withLispComments mySpec
>
> myCLikeSpec :: SExprParser Text (SExpr Text)
> myCLikeSpec = withCLikeComment mySpec
We can then use these to parse s-expressions with different kinds of
comment syntaxes:
>>> decode mySpec "(foo ; a lisp comment\n bar)\n"
Left "(line 1, column 6):\nunexpected \";\"\nexpecting space or atom"
>>> decode myLispySpec "(foo ; a lisp comment\n bar)\n"
Right [WFSList [WFSAtom "foo", WFSAtom "bar"]]
>>> decode mySpec "(foo /* a c-like\n comment */ bar)\n"
Left "(line 1, column 6):\nunexpected \"/\"\nexpecting space or atom"
>>> decode myCLikeSpec "(foo /* a c-like\n comment */ bar)\n"
Right [WFSList [WFSAtom "foo", WFSAtom "bar"]]
-}
$ lisp
> ( one ; a comment
> two ; another one
> three )
> (one ; a comment
> two ; another one
> three)
-}
$ script
> ( one # a comment
> two # another one
> three )
> (one # a comment
> two # another one
> three)
-}
$ clike
> ( one // a comment
> two / * another
> one * /
> three )
> (one // a comment
> two /* another
> one */
> three)
-}
$ haskell
-- > (one -- a comment
> two { - another
> one - }
> three )
| null | https://raw.githubusercontent.com/aisamanra/s-cargot/71d2ec896f50877110df8622de3efdccfa6b8d59/Data/SCargot/Comments.hs | haskell | # LANGUAGE OverloadedStrings #
$intro
* Lisp-Style Syntax
$lisp
* Other Existing Comment Syntaxes
** Scripting Language Syntax
$script
** C-Style Syntax
$clike
** Haskell-Style Syntax
* Comment Syntax Helper Functions
| Given a string, produce a comment parser that matches that
initial string and ignores everything until the end of the
line.
parser that matches the beginning delimiter and then ignores
everything until it finds the end delimiter. This does not
consider nesting, so, for example, a comment created with
> curlyComment :: Comment
will consider
> { this { comment }
to be a complete comment, despite the apparent improper nesting.
This is analogous to standard C-style comments in which
> /* this /* comment */
is a complete comment.
| Lisp-style line-oriented comments start with @;@ and last
until the end of the line. This is usually the comment
syntax you want.
| C++-like line-oriented comment start with @//@ and last
until the end of the line.
| C-like block comments start with @/*@ and end with @*/@.
They do not nest.
| C-like comments include both line- and block-comments, the
former starting with @//@ and the latter contained within
@//* ... *//@.
| Haskell line-oriented comments start with @--@ and last
until the end of the line.
| Haskell block comments start with @{-@ and end with @-}@.
They do not nest.
| Haskell comments include both the line-oriented @--@ comments
and the block-oriented @{- ... -}@ comments
| Many scripting and shell languages use these, which begin with
@#@ and last until the end of the line.
with @%@ and last until the end of the line.
> (one -- a comment |
module Data.SCargot.Comments
withLispComments
, withOctothorpeComments
* * Prolog- or Matlab - Style Syntax
, withPercentComments
, withPercentBlockComments
, withCLikeLineComments
, withCLikeBlockComments
, withCLikeComments
$ haskell
, withHaskellLineComments
, withHaskellBlockComments
, withHaskellComments
, lineComment
, simpleBlockComment
) where
import Text.Parsec ( (<|>)
, anyChar
, manyTill
, noneOf
, skipMany
, string
)
import Data.SCargot.Parse ( Comment
, SExprParser
, setComment
)
lineComment :: String -> Comment
lineComment s = string s >> skipMany (noneOf "\n") >> return ()
| Given two strings , a begin and an end delimiter , produce a
> = simpleBlockComment " { " " } "
simpleBlockComment :: String -> String -> Comment
simpleBlockComment begin end =
string begin >>
manyTill anyChar (string end) >>
return ()
withLispComments :: SExprParser t a -> SExprParser t a
withLispComments = setComment (lineComment ";")
withCLikeLineComments :: SExprParser t a -> SExprParser t a
withCLikeLineComments = setComment (lineComment "//")
withCLikeBlockComments :: SExprParser t a -> SExprParser t a
withCLikeBlockComments = setComment (simpleBlockComment "/*" "*/")
withCLikeComments :: SExprParser t a -> SExprParser t a
withCLikeComments = setComment (lineComment "//" <|>
simpleBlockComment "/*" "*/")
withHaskellLineComments :: SExprParser t a -> SExprParser t a
withHaskellLineComments = setComment (lineComment "--")
withHaskellBlockComments :: SExprParser t a -> SExprParser t a
withHaskellBlockComments = setComment (simpleBlockComment "{-" "-}")
withHaskellComments :: SExprParser t a -> SExprParser t a
withHaskellComments = setComment (lineComment "--" <|>
simpleBlockComment "{-" "-}")
withOctothorpeComments :: SExprParser t a -> SExprParser t a
withOctothorpeComments = setComment (lineComment "#")
| MATLAB , , PostScript , and others use comments which begin
withPercentComments :: SExprParser t a -> SExprParser t a
withPercentComments = setComment (lineComment "%")
| MATLAB block comments are started with @%{@ and end with
withPercentBlockComments :: SExprParser t a -> SExprParser t a
withPercentBlockComments = setComment (simpleBlockComment "%{" "%}")
$ intro
By default a ' SExprParser ' will not understand any kind of comment
syntax . Most varieties of s - expression will , however , want some kind
of commenting capability , so the below functions will produce a new
' SExprParser ' which understands various kinds of comment syntaxes .
For example :
> mySpec : : SExprParser Text ( SExpr Text )
> mySpec = asWellFormed $ mkParser ( pack < $ > many1 alphaNum )
>
> myLispySpec : : SExprParser Text ( SExpr Text )
> myLispySpec = withLispComments mySpec
>
> myCLikeSpec : : SExprParser Text ( SExpr Text )
> myCLikeSpec =
We can then use these to parse s - expressions with different kinds of
comment syntaxes :
> > > decode mySpec " ( foo ; a lisp comment\n bar)\n "
Left " ( line 1 , column 6):\nunexpected \";\"\nexpecting space or atom "
> > > decode myLispySpec " ( foo ; a lisp comment\n bar)\n "
Right [ WFSList [ " foo " , " bar " ] ]
> > > decode mySpec " ( foo / * a c - like\n comment * / bar)\n "
Left " ( line 1 , column 6):\nunexpected \"/\"\nexpecting space or atom "
> > > decode myCLikeSpec " ( foo / * a c - like\n comment * / bar)\n "
Right [ WFSList [ " foo " , " bar " ] ]
By default a 'SExprParser' will not understand any kind of comment
syntax. Most varieties of s-expression will, however, want some kind
of commenting capability, so the below functions will produce a new
'SExprParser' which understands various kinds of comment syntaxes.
For example:
> mySpec :: SExprParser Text (SExpr Text)
> mySpec = asWellFormed $ mkParser (pack <$> many1 alphaNum)
>
> myLispySpec :: SExprParser Text (SExpr Text)
> myLispySpec = withLispComments mySpec
>
> myCLikeSpec :: SExprParser Text (SExpr Text)
> myCLikeSpec = withCLikeComment mySpec
We can then use these to parse s-expressions with different kinds of
comment syntaxes:
>>> decode mySpec "(foo ; a lisp comment\n bar)\n"
Left "(line 1, column 6):\nunexpected \";\"\nexpecting space or atom"
>>> decode myLispySpec "(foo ; a lisp comment\n bar)\n"
Right [WFSList [WFSAtom "foo", WFSAtom "bar"]]
>>> decode mySpec "(foo /* a c-like\n comment */ bar)\n"
Left "(line 1, column 6):\nunexpected \"/\"\nexpecting space or atom"
>>> decode myCLikeSpec "(foo /* a c-like\n comment */ bar)\n"
Right [WFSList [WFSAtom "foo", WFSAtom "bar"]]
-}
$ lisp
> ( one ; a comment
> two ; another one
> three )
> (one ; a comment
> two ; another one
> three)
-}
$ script
> ( one # a comment
> two # another one
> three )
> (one # a comment
> two # another one
> three)
-}
$ clike
> ( one // a comment
> two / * another
> one * /
> three )
> (one // a comment
> two /* another
> one */
> three)
-}
$ haskell
> two { - another
> one - }
> three )
|
36a1b3358ac2cb17fad278c71e79bba7fbe591594d2ae49d82611e21d4c3e04f | dmjio/miso | Main.hs | # LANGUAGE DeriveGeneric #
{-# LANGUAGE OverloadedStrings #-}
# LANGUAGE ScopedTypeVariables #
{-# LANGUAGE TypeOperators #-}
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE RecordWildCards #-}
# LANGUAGE TypeFamilies #
module Main where
import Miso hiding (asyncCallback)
import Miso.String
import Control.Concurrent.MVar
import GHCJS.Types
import GHCJS.Foreign.Callback
-- | Model
data Model
= Model
{ info :: MisoString
} deriving (Eq, Show)
-- | Action
data Action
= ReadFile
| NoOp
| SetContent MisoString
deriving (Show, Eq)
-- | Main entry point
main :: IO ()
main = do
startApp App { model = Model ""
, initialAction = NoOp
, ..
}
where
mountPoint = Nothing
update = updateModel
events = defaultEvents
subs = []
view = viewModel
logLevel = Off
-- | Update your model
updateModel :: Action -> Model -> Effect Action Model
updateModel ReadFile m = m <# do
fileReaderInput <- getElementById "fileReader"
file <- getFile fileReaderInput
reader <- newReader
mvar <- newEmptyMVar
setOnLoad reader =<< do
asyncCallback $ do
r <- getResult reader
putMVar mvar r
readText reader file
SetContent <$> readMVar mvar
updateModel (SetContent c) m = noEff m { info = c }
updateModel NoOp m = noEff m
-- | View function, with routing
viewModel :: Model -> View Action
viewModel Model {..} = view
where
view = div_ [] [
"FileReader API example"
, input_ [ id_ "fileReader"
, type_ "file"
, onChange (const ReadFile)
]
, div_ [] [ text info ]
]
foreign import javascript unsafe "$r = new FileReader();"
newReader :: IO JSVal
foreign import javascript unsafe "$r = $1.files[0];"
getFile :: JSVal -> IO JSVal
foreign import javascript unsafe "$1.onload = $2;"
setOnLoad :: JSVal -> Callback (IO ()) -> IO ()
foreign import javascript unsafe "$r = $1.result;"
getResult :: JSVal -> IO MisoString
foreign import javascript unsafe "$1.readAsText($2);"
readText :: JSVal -> JSVal -> IO ()
| null | https://raw.githubusercontent.com/dmjio/miso/0be227bca6e0aec16a69a1c09f9a90624af070c1/examples/file-reader/Main.hs | haskell | # LANGUAGE OverloadedStrings #
# LANGUAGE TypeOperators #
# LANGUAGE DataKinds #
# LANGUAGE RecordWildCards #
| Model
| Action
| Main entry point
| Update your model
| View function, with routing | # LANGUAGE DeriveGeneric #
# LANGUAGE ScopedTypeVariables #
# LANGUAGE TypeFamilies #
module Main where
import Miso hiding (asyncCallback)
import Miso.String
import Control.Concurrent.MVar
import GHCJS.Types
import GHCJS.Foreign.Callback
data Model
= Model
{ info :: MisoString
} deriving (Eq, Show)
data Action
= ReadFile
| NoOp
| SetContent MisoString
deriving (Show, Eq)
main :: IO ()
main = do
startApp App { model = Model ""
, initialAction = NoOp
, ..
}
where
mountPoint = Nothing
update = updateModel
events = defaultEvents
subs = []
view = viewModel
logLevel = Off
updateModel :: Action -> Model -> Effect Action Model
updateModel ReadFile m = m <# do
fileReaderInput <- getElementById "fileReader"
file <- getFile fileReaderInput
reader <- newReader
mvar <- newEmptyMVar
setOnLoad reader =<< do
asyncCallback $ do
r <- getResult reader
putMVar mvar r
readText reader file
SetContent <$> readMVar mvar
updateModel (SetContent c) m = noEff m { info = c }
updateModel NoOp m = noEff m
viewModel :: Model -> View Action
viewModel Model {..} = view
where
view = div_ [] [
"FileReader API example"
, input_ [ id_ "fileReader"
, type_ "file"
, onChange (const ReadFile)
]
, div_ [] [ text info ]
]
foreign import javascript unsafe "$r = new FileReader();"
newReader :: IO JSVal
foreign import javascript unsafe "$r = $1.files[0];"
getFile :: JSVal -> IO JSVal
foreign import javascript unsafe "$1.onload = $2;"
setOnLoad :: JSVal -> Callback (IO ()) -> IO ()
foreign import javascript unsafe "$r = $1.result;"
getResult :: JSVal -> IO MisoString
foreign import javascript unsafe "$1.readAsText($2);"
readText :: JSVal -> JSVal -> IO ()
|
1c304b11d3da615c804fb4658f188da180cc1ad5938bcd290309825bfda0b3bd | cerner/clara-rules | test_rule_execution.cljc | (ns clara.performance.test-rule-execution
(:require [clara.rules.accumulators :as acc]
[clara.rules :as r]
#?(:clj
[clojure.test :refer :all]
:cljs [cljs.test :refer-macros [is deftest]])
#?(:clj
[clara.tools.testing-utils :refer [def-rules-test run-performance-test]]
:cljs [clara.tools.testing-utils :refer [run-performance-test]]))
#?(:cljs (:require-macros [clara.tools.testing-utils :refer [def-rules-test]])))
(defrecord AFact [id])
(defrecord BFact [id])
(defrecord ParentFact [a-id b-id])
(def counter (atom {:a-count 0
:b-count 0}))
(def number-of-facts #?(:clj 1500 :cljs 150))
(def-rules-test test-get-in-perf
{:rules [rule [[[?parent <- ParentFact]
[?as <- (acc/all) :from [AFact (= (:a-id ?parent) id)]]
[?bs <- (acc/all) :from [BFact (= (:b-id ?parent) id)]]]
'(do (swap! counter update :a-count inc))]]
:sessions [session [rule] {}]}
(let [parents (for [x (range number-of-facts)]
(->ParentFact x (inc x)))
a-facts (for [id (range number-of-facts)]
(->AFact id))
b-facts (for [id (range number-of-facts)]
(->BFact id))
facts (doall (concat parents
a-facts
b-facts))]
(run-performance-test {:description "Slow get-in perf"
:func #(-> session
(r/insert-all facts)
r/fire-rules)
:iterations 5
:mean-assertion (partial > 10000)}))) | null | https://raw.githubusercontent.com/cerner/clara-rules/8107a5ab7fdb475e323c0bcb39084a83454deb1c/src/test/common/clara/performance/test_rule_execution.cljc | clojure | (ns clara.performance.test-rule-execution
(:require [clara.rules.accumulators :as acc]
[clara.rules :as r]
#?(:clj
[clojure.test :refer :all]
:cljs [cljs.test :refer-macros [is deftest]])
#?(:clj
[clara.tools.testing-utils :refer [def-rules-test run-performance-test]]
:cljs [clara.tools.testing-utils :refer [run-performance-test]]))
#?(:cljs (:require-macros [clara.tools.testing-utils :refer [def-rules-test]])))
(defrecord AFact [id])
(defrecord BFact [id])
(defrecord ParentFact [a-id b-id])
(def counter (atom {:a-count 0
:b-count 0}))
(def number-of-facts #?(:clj 1500 :cljs 150))
(def-rules-test test-get-in-perf
{:rules [rule [[[?parent <- ParentFact]
[?as <- (acc/all) :from [AFact (= (:a-id ?parent) id)]]
[?bs <- (acc/all) :from [BFact (= (:b-id ?parent) id)]]]
'(do (swap! counter update :a-count inc))]]
:sessions [session [rule] {}]}
(let [parents (for [x (range number-of-facts)]
(->ParentFact x (inc x)))
a-facts (for [id (range number-of-facts)]
(->AFact id))
b-facts (for [id (range number-of-facts)]
(->BFact id))
facts (doall (concat parents
a-facts
b-facts))]
(run-performance-test {:description "Slow get-in perf"
:func #(-> session
(r/insert-all facts)
r/fire-rules)
:iterations 5
:mean-assertion (partial > 10000)}))) | |
6d844dafa7c8a6aa9f66f3196775c7fc0fab62e620d461ab650597025620c106 | danhper/evm-analyzer | testTraceParser.ml | open Evm_analyzer
let parse_regular_format () =
let traces = TraceParser.parse_string Fixtures.regular_trace_0xdd77a7d375e in
Alcotest.(check int) "has all traces" 165 (List.length traces)
let parse_stripped_format () =
let regular_traces = TraceParser.parse_string Fixtures.regular_trace_0xdd77a7d375e in
let stripped_traces = TraceParser.parse_string Fixtures.stripped_trace_0xdd77a7d375e in
Alcotest.(check (list Testable.trace)) "regular and stripped yield same result"
regular_traces stripped_traces
let trace_parser_tests = [
("parse_regular_format", `Quick, parse_regular_format);
("parse_stripped_format", `Quick, parse_stripped_format);
]
| null | https://raw.githubusercontent.com/danhper/evm-analyzer/9fb1cf6dc743c2f779973b2f0892047ebbd4e5fd/test/testTraceParser.ml | ocaml | open Evm_analyzer
let parse_regular_format () =
let traces = TraceParser.parse_string Fixtures.regular_trace_0xdd77a7d375e in
Alcotest.(check int) "has all traces" 165 (List.length traces)
let parse_stripped_format () =
let regular_traces = TraceParser.parse_string Fixtures.regular_trace_0xdd77a7d375e in
let stripped_traces = TraceParser.parse_string Fixtures.stripped_trace_0xdd77a7d375e in
Alcotest.(check (list Testable.trace)) "regular and stripped yield same result"
regular_traces stripped_traces
let trace_parser_tests = [
("parse_regular_format", `Quick, parse_regular_format);
("parse_stripped_format", `Quick, parse_stripped_format);
]
| |
3d3e0dfb601c4445f2df71ddfd3cfe5b5e432ee130140326af0d070f849b908a | intolerable/api-builder | RoutesSpec.hs | module Network.API.Builder.RoutesSpec where
import Network.API.Builder.Routes
import Test.Hspec
main :: IO ()
main = hspec spec
spec :: Spec
spec = do
describe "routeURL" $ do
it "should be able to create a basic url" $ do
routeURL "" (Route [ "api", "index" ] [ ] "GET")
`shouldBe` "/api/index"
routeURL "" (Route [ "api", "index.json" ] [ ] "GET")
`shouldBe` "/api/index.json"
routeURL "" (Route [ ] [ "test" =. False ] "GET")
`shouldBe` "?test=false"
routeURL "" (Route [ "about.json" ] [ "test" =. True ] "GET")
`shouldBe` "/about.json?test=true"
routeURL "" (Route [ "about.json" ] [ "test" =. True ] "GET")
`shouldBe` "/about.json?test=true"
| null | https://raw.githubusercontent.com/intolerable/api-builder/f7440211195da98cfa93b6a97e51892b939919e1/test/Network/API/Builder/RoutesSpec.hs | haskell | module Network.API.Builder.RoutesSpec where
import Network.API.Builder.Routes
import Test.Hspec
main :: IO ()
main = hspec spec
spec :: Spec
spec = do
describe "routeURL" $ do
it "should be able to create a basic url" $ do
routeURL "" (Route [ "api", "index" ] [ ] "GET")
`shouldBe` "/api/index"
routeURL "" (Route [ "api", "index.json" ] [ ] "GET")
`shouldBe` "/api/index.json"
routeURL "" (Route [ ] [ "test" =. False ] "GET")
`shouldBe` "?test=false"
routeURL "" (Route [ "about.json" ] [ "test" =. True ] "GET")
`shouldBe` "/about.json?test=true"
routeURL "" (Route [ "about.json" ] [ "test" =. True ] "GET")
`shouldBe` "/about.json?test=true"
| |
eb4b5a8baf634bc7d0d0f098fd45ea3155b8ea4f3d842af1f9d6d3a5d72330ca | andersfugmann/ppx_protocol_conv | xmlm.ml | (* Xml driver for ppx_protocol_conv *)
open StdLabels
open Protocol_conv.Runtime
module Helper = Protocol_conv.Runtime.Helper
type t = Ezxmlm.node
type error = string * t option
exception Protocol_error of error
module StringMap = Map.Make(String)
let make_error ?value msg = (msg, value)
let to_string_hum xml = Ezxmlm.to_string [xml]
let error_to_string_hum: error -> string = function
| (s, Some t) -> Printf.sprintf "%s. T: '%s'" s (to_string_hum t)
| (s, None) -> s
(* Register exception printer *)
let () = Printexc.register_printer (function
| Protocol_error err -> Some (error_to_string_hum err)
| _ -> None)
let try_with: (t -> 'a) -> t -> ('a, error) result = fun f t ->
match f t with
| v -> Ok v
| exception (Protocol_error e) -> Error e
let raise_errorf t fmt =
Caml.Printf.kprintf (fun s -> raise (Protocol_error (s, t))) fmt
let wrap t f x = match f x with
| v -> v
| exception Helper.Protocol_error s -> raise (Protocol_error (s, Some t))
let element name t = Ezxmlm.make_tag name ([], t)
let record_to_xml (assoc:(string * t) list) =
List.map ~f:(
function
| (field, `El (((_,"record"), attrs), xs)) -> [`El ((("",field), attrs), xs)]
| (field, `El (((_,"variant"), attrs), xs)) -> [`El ((("",field), attrs), xs)]
| (field, `El (((_,"__option"), attrs), xs)) -> [`El ((("",field), attrs), xs)]
| (field, `El (((_,_), _), xs)) ->
List.map ~f:(function
| `El (((_,_), attrs), xs) -> `El ((("",field), attrs), xs)
| `Data _ as p -> `El ((("",field), []), [p])
) xs
| (field, e) -> raise_errorf (Some e) "Must be an element: %s" field
) assoc
|> List.concat |> element "record"
let of_variant: string -> (t, 'a, t) Tuple_out.t -> 'a = fun spec ->
let to_t name args = `El ((("","variant"), []), `Data name :: args) in
Helper.of_variant to_t spec
let to_variant: (t, 'a) Variant_in.t list -> t -> 'a = fun spec ->
let f = Helper.to_variant spec in
function
| `El (((_, _), _), (`Data s) :: es) as t ->
wrap t (f s) es
| `El (((_, name), _), []) as t -> raise_errorf (Some t) "No contents for variant type: %s" name
| t -> raise_errorf (Some t) "Wrong variant data"
let of_record: type a. (t, a, t) Record_out.t -> a = fun spec ->
Helper.of_record ~omit_default:false record_to_xml spec
let to_record: (t, 'constr, 'b) Record_in.t -> 'constr -> t -> 'b = fun spec constr ->
let rec inner: type constr b. (t, constr, b) Record_in.t -> string list = function
| Record_in.Cons ((field, _, _), xs) -> field :: inner xs
| Record_in.Nil -> []
in
let fields = inner spec in
(* Join all elements, including default empty ones *)
let default_map = List.fold_left fields ~init:StringMap.empty ~f:(fun acc field -> StringMap.add field [] acc) in
let f = Helper.to_record spec constr in
function
| `El (((_,_), _), xs) as t ->
let args =
List.fold_left ~init:default_map
~f:(fun map -> function
| `El (((_,name), _), _) as x ->
let v = match StringMap.find name map with
| l -> x :: l
| exception Not_found -> [x]
in
StringMap.add name v map
| _ -> map
) xs
|> (fun map -> StringMap.fold (fun key v acc -> (key, v) :: acc) map [])
|> List.map ~f:(function
| (field, [ `El (((_, name), attrs), xs) ]) -> (field, `El ((("",name), (("","record"), "unwrapped") :: attrs), xs))
| (field, [ `Data _ as d ]) -> (field, d)
| (field, xs) -> (field, `El ((("",field), []), List.rev xs))
)
in
wrap t f args
| t -> raise_errorf (Some t) "Expected record element"
let of_tuple: (t, 'a, t) Tuple_out.t -> 'a = fun spec ->
let rec inner: type a b c. int -> (a, b, c) Tuple_out.t -> (a, b, c) Record_out.t = fun i -> function
| Tuple_out.Cons (f, xs) ->
let tail = inner (i+1) xs in
Record_out.Cons ( (Printf.sprintf "t%d" i, f, None), tail)
| Tuple_out.Nil -> Record_out.Nil
in
of_record (inner 0 spec)
let to_tuple: type constr b. (t, constr, b) Tuple_in.t -> constr -> t -> b = fun spec constr ->
let rec inner: type a b c. int -> (a, b, c) Tuple_in.t -> (a, b, c) Record_in.t = fun i -> function
| Tuple_in.Cons (f, xs) ->
let tail = inner (i+1) xs in
Record_in.Cons ( (Printf.sprintf "t%d" i, f, None), tail)
| Tuple_in.Nil -> Record_in.Nil
in
let spec = inner 0 spec in
let f = to_record spec constr in
fun t -> wrap t f t
let to_option: (t -> 'a) -> t -> 'a option = fun to_value_fun t ->
match t with
| (`El (((_,_), ((_,_), "unwrapped") :: _), []))
| (`El (((_,_), _), []))
| (`El (((_,_), _), [ `Data "" ] )) ->
None
| (`El (((_,_), ((_,_), "unwrapped") :: _), [ (`El ((((_,"__option"), _), _)) as t)]))
| (`El (((_,"__option"), _), [t]))
| t ->
Some (to_value_fun t)
let of_option: ('a -> t) -> 'a option -> t = fun of_value_fun v ->
match v with
| None ->
(`El ((("","__option"), []), []))
| Some x -> begin
match of_value_fun x with
| (`El (((_,"__option"), _), _) as t) ->
(`El ((("","__option"), []), [t]))
| t ->
t
end
let to_ref: (t -> 'a) -> t -> 'a ref = fun to_value_fun t ->
let v = to_value_fun t in
ref v
let of_ref: ('a -> t) -> 'a ref -> t = fun of_value_fun v ->
of_value_fun !v
let to_result: (t -> 'a) -> (t -> 'b) -> t -> ('a, 'b) result = fun to_ok to_err ->
let ok = Tuple_in.(Cons (to_ok, Nil)) in
let err = Tuple_in.(Cons (to_err, Nil)) in
to_variant Variant_in.[Variant ("Ok", ok, fun v -> Ok v); Variant ("Error", err, fun v -> Error v)]
let of_result: ('a -> t) -> ('b -> t) -> ('a, 'b) result -> t = fun of_ok of_err ->
let of_ok = of_variant "Ok" Tuple_out.(Cons (of_ok, Nil)) in
let of_err = of_variant "Error" Tuple_out.(Cons (of_err, Nil)) in
function
| Ok ok -> of_ok ok
| Error err -> of_err err
(** If the given list has been unwrapped since its part of a record, we "rewrap it". *)
let to_list: (t -> 'a) -> t -> 'a list = fun to_value_fun -> function
| (`El ((_, (_, "unwrapped") :: _), _)) as elm ->
(* If the given list has been unwrapped since its part of a record, we "rewrap it". *)
[ to_value_fun elm ]
| (`El ((_, _), ts)) ->
Helper.list_map ~f:(fun t -> to_value_fun t) ts
| e -> raise_errorf (Some e) "Must be an element type"
let of_list: ('a -> t) -> 'a list -> t = fun of_value_fun vs ->
(`El ((("","l"), []), Helper.list_map ~f:(fun v -> of_value_fun v) vs))
let to_array: (t -> 'a) -> t -> 'a array = fun to_value_fun t ->
to_list to_value_fun t |> Array.of_list
let of_array: ('a -> t) -> 'a array -> t = fun of_value_fun vs ->
of_list of_value_fun (Array.to_list vs)
let to_lazy_t: (t -> 'a) -> t -> 'a lazy_t = fun to_value_fun t -> Lazy.from_fun (fun () -> to_value_fun t)
let of_lazy_t: ('a -> t) -> 'a lazy_t -> t = fun of_value_fun v ->
Lazy.force v |> of_value_fun
let of_value to_string v = (`El ((("","p"), []), [ `Data (to_string v) ]))
let to_value type_name of_string t =
let s = match t with
| (`El ((_, _), [])) -> ""
| (`El ((_, _), [`Data s])) -> s
| (`El (((_,name), _), _)) as e -> raise_errorf (Some e) "Primitive value expected in node: %s for %s" name type_name
| `Data _ as e -> raise_errorf (Some e) "Primitive type not expected here when deserializing %s" type_name
in
try of_string s with
| _ -> raise_errorf (Some t) "Failed to convert element to %s." type_name
let to_bool = to_value "bool" bool_of_string
let of_bool = of_value string_of_bool
let to_int = to_value "int" int_of_string
let of_int = of_value string_of_int
let to_int32 = to_value "int32" Int32.of_string
let of_int32 = of_value Int32.to_string
let to_int64 = to_value "int64" Int64.of_string
let of_int64 = of_value Int64.to_string
let to_float = to_value "float" float_of_string
let of_float = of_value string_of_float
let to_string = to_value "string" (fun x -> x)
let of_string = of_value (fun x -> x)
let to_char = to_value "char" (function s when String.length s = 1 -> s.[0]
| s -> raise_errorf None "Expected char, got %s" s)
let of_char = of_value (fun c -> (String.make 1 c))
let to_bytes = to_value "bytes" Bytes.of_string
let of_bytes = of_value Bytes.to_string
let to_unit = to_value "unit" (function "()" -> () | _ -> raise_errorf None "Expected unit")
let of_unit = of_value (fun () -> "()")
let to_nativeint = to_value "nativeint" Nativeint.of_string
let of_nativeint = of_value Nativeint.to_string
let of_xmlm_exn: t -> t =
function
| (`El ((_v, (_, "unwrapped") :: ((_, "__name"), v') :: xs), d)) -> (`El ((("", v'), xs), d))
| (`El ((v, (_, "unwrapped") :: xs), d)) -> (`El ((v, xs), d))
| (`El ((_v, ((_, "__name"), v') :: xs), d)) -> (`El ((("", v'), xs), d))
| x -> x
let of_xmlm t = Ok (of_xmlm_exn t)
let to_xmlm: t -> t = function
| (`El ((v, attrs), d)) -> (`El ((v, (("", "__name"), snd v) :: attrs), d))
| v -> v
| null | https://raw.githubusercontent.com/andersfugmann/ppx_protocol_conv/e93eb01ca8ba8c7dd734070316cd281a199dee0d/drivers/xmlm/xmlm.ml | ocaml | Xml driver for ppx_protocol_conv
Register exception printer
Join all elements, including default empty ones
* If the given list has been unwrapped since its part of a record, we "rewrap it".
If the given list has been unwrapped since its part of a record, we "rewrap it". | open StdLabels
open Protocol_conv.Runtime
module Helper = Protocol_conv.Runtime.Helper
type t = Ezxmlm.node
type error = string * t option
exception Protocol_error of error
module StringMap = Map.Make(String)
let make_error ?value msg = (msg, value)
let to_string_hum xml = Ezxmlm.to_string [xml]
let error_to_string_hum: error -> string = function
| (s, Some t) -> Printf.sprintf "%s. T: '%s'" s (to_string_hum t)
| (s, None) -> s
let () = Printexc.register_printer (function
| Protocol_error err -> Some (error_to_string_hum err)
| _ -> None)
let try_with: (t -> 'a) -> t -> ('a, error) result = fun f t ->
match f t with
| v -> Ok v
| exception (Protocol_error e) -> Error e
let raise_errorf t fmt =
Caml.Printf.kprintf (fun s -> raise (Protocol_error (s, t))) fmt
let wrap t f x = match f x with
| v -> v
| exception Helper.Protocol_error s -> raise (Protocol_error (s, Some t))
let element name t = Ezxmlm.make_tag name ([], t)
let record_to_xml (assoc:(string * t) list) =
List.map ~f:(
function
| (field, `El (((_,"record"), attrs), xs)) -> [`El ((("",field), attrs), xs)]
| (field, `El (((_,"variant"), attrs), xs)) -> [`El ((("",field), attrs), xs)]
| (field, `El (((_,"__option"), attrs), xs)) -> [`El ((("",field), attrs), xs)]
| (field, `El (((_,_), _), xs)) ->
List.map ~f:(function
| `El (((_,_), attrs), xs) -> `El ((("",field), attrs), xs)
| `Data _ as p -> `El ((("",field), []), [p])
) xs
| (field, e) -> raise_errorf (Some e) "Must be an element: %s" field
) assoc
|> List.concat |> element "record"
let of_variant: string -> (t, 'a, t) Tuple_out.t -> 'a = fun spec ->
let to_t name args = `El ((("","variant"), []), `Data name :: args) in
Helper.of_variant to_t spec
let to_variant: (t, 'a) Variant_in.t list -> t -> 'a = fun spec ->
let f = Helper.to_variant spec in
function
| `El (((_, _), _), (`Data s) :: es) as t ->
wrap t (f s) es
| `El (((_, name), _), []) as t -> raise_errorf (Some t) "No contents for variant type: %s" name
| t -> raise_errorf (Some t) "Wrong variant data"
let of_record: type a. (t, a, t) Record_out.t -> a = fun spec ->
Helper.of_record ~omit_default:false record_to_xml spec
let to_record: (t, 'constr, 'b) Record_in.t -> 'constr -> t -> 'b = fun spec constr ->
let rec inner: type constr b. (t, constr, b) Record_in.t -> string list = function
| Record_in.Cons ((field, _, _), xs) -> field :: inner xs
| Record_in.Nil -> []
in
let fields = inner spec in
let default_map = List.fold_left fields ~init:StringMap.empty ~f:(fun acc field -> StringMap.add field [] acc) in
let f = Helper.to_record spec constr in
function
| `El (((_,_), _), xs) as t ->
let args =
List.fold_left ~init:default_map
~f:(fun map -> function
| `El (((_,name), _), _) as x ->
let v = match StringMap.find name map with
| l -> x :: l
| exception Not_found -> [x]
in
StringMap.add name v map
| _ -> map
) xs
|> (fun map -> StringMap.fold (fun key v acc -> (key, v) :: acc) map [])
|> List.map ~f:(function
| (field, [ `El (((_, name), attrs), xs) ]) -> (field, `El ((("",name), (("","record"), "unwrapped") :: attrs), xs))
| (field, [ `Data _ as d ]) -> (field, d)
| (field, xs) -> (field, `El ((("",field), []), List.rev xs))
)
in
wrap t f args
| t -> raise_errorf (Some t) "Expected record element"
let of_tuple: (t, 'a, t) Tuple_out.t -> 'a = fun spec ->
let rec inner: type a b c. int -> (a, b, c) Tuple_out.t -> (a, b, c) Record_out.t = fun i -> function
| Tuple_out.Cons (f, xs) ->
let tail = inner (i+1) xs in
Record_out.Cons ( (Printf.sprintf "t%d" i, f, None), tail)
| Tuple_out.Nil -> Record_out.Nil
in
of_record (inner 0 spec)
let to_tuple: type constr b. (t, constr, b) Tuple_in.t -> constr -> t -> b = fun spec constr ->
let rec inner: type a b c. int -> (a, b, c) Tuple_in.t -> (a, b, c) Record_in.t = fun i -> function
| Tuple_in.Cons (f, xs) ->
let tail = inner (i+1) xs in
Record_in.Cons ( (Printf.sprintf "t%d" i, f, None), tail)
| Tuple_in.Nil -> Record_in.Nil
in
let spec = inner 0 spec in
let f = to_record spec constr in
fun t -> wrap t f t
let to_option: (t -> 'a) -> t -> 'a option = fun to_value_fun t ->
match t with
| (`El (((_,_), ((_,_), "unwrapped") :: _), []))
| (`El (((_,_), _), []))
| (`El (((_,_), _), [ `Data "" ] )) ->
None
| (`El (((_,_), ((_,_), "unwrapped") :: _), [ (`El ((((_,"__option"), _), _)) as t)]))
| (`El (((_,"__option"), _), [t]))
| t ->
Some (to_value_fun t)
let of_option: ('a -> t) -> 'a option -> t = fun of_value_fun v ->
match v with
| None ->
(`El ((("","__option"), []), []))
| Some x -> begin
match of_value_fun x with
| (`El (((_,"__option"), _), _) as t) ->
(`El ((("","__option"), []), [t]))
| t ->
t
end
let to_ref: (t -> 'a) -> t -> 'a ref = fun to_value_fun t ->
let v = to_value_fun t in
ref v
let of_ref: ('a -> t) -> 'a ref -> t = fun of_value_fun v ->
of_value_fun !v
let to_result: (t -> 'a) -> (t -> 'b) -> t -> ('a, 'b) result = fun to_ok to_err ->
let ok = Tuple_in.(Cons (to_ok, Nil)) in
let err = Tuple_in.(Cons (to_err, Nil)) in
to_variant Variant_in.[Variant ("Ok", ok, fun v -> Ok v); Variant ("Error", err, fun v -> Error v)]
let of_result: ('a -> t) -> ('b -> t) -> ('a, 'b) result -> t = fun of_ok of_err ->
let of_ok = of_variant "Ok" Tuple_out.(Cons (of_ok, Nil)) in
let of_err = of_variant "Error" Tuple_out.(Cons (of_err, Nil)) in
function
| Ok ok -> of_ok ok
| Error err -> of_err err
let to_list: (t -> 'a) -> t -> 'a list = fun to_value_fun -> function
| (`El ((_, (_, "unwrapped") :: _), _)) as elm ->
[ to_value_fun elm ]
| (`El ((_, _), ts)) ->
Helper.list_map ~f:(fun t -> to_value_fun t) ts
| e -> raise_errorf (Some e) "Must be an element type"
let of_list: ('a -> t) -> 'a list -> t = fun of_value_fun vs ->
(`El ((("","l"), []), Helper.list_map ~f:(fun v -> of_value_fun v) vs))
let to_array: (t -> 'a) -> t -> 'a array = fun to_value_fun t ->
to_list to_value_fun t |> Array.of_list
let of_array: ('a -> t) -> 'a array -> t = fun of_value_fun vs ->
of_list of_value_fun (Array.to_list vs)
let to_lazy_t: (t -> 'a) -> t -> 'a lazy_t = fun to_value_fun t -> Lazy.from_fun (fun () -> to_value_fun t)
let of_lazy_t: ('a -> t) -> 'a lazy_t -> t = fun of_value_fun v ->
Lazy.force v |> of_value_fun
let of_value to_string v = (`El ((("","p"), []), [ `Data (to_string v) ]))
let to_value type_name of_string t =
let s = match t with
| (`El ((_, _), [])) -> ""
| (`El ((_, _), [`Data s])) -> s
| (`El (((_,name), _), _)) as e -> raise_errorf (Some e) "Primitive value expected in node: %s for %s" name type_name
| `Data _ as e -> raise_errorf (Some e) "Primitive type not expected here when deserializing %s" type_name
in
try of_string s with
| _ -> raise_errorf (Some t) "Failed to convert element to %s." type_name
let to_bool = to_value "bool" bool_of_string
let of_bool = of_value string_of_bool
let to_int = to_value "int" int_of_string
let of_int = of_value string_of_int
let to_int32 = to_value "int32" Int32.of_string
let of_int32 = of_value Int32.to_string
let to_int64 = to_value "int64" Int64.of_string
let of_int64 = of_value Int64.to_string
let to_float = to_value "float" float_of_string
let of_float = of_value string_of_float
let to_string = to_value "string" (fun x -> x)
let of_string = of_value (fun x -> x)
let to_char = to_value "char" (function s when String.length s = 1 -> s.[0]
| s -> raise_errorf None "Expected char, got %s" s)
let of_char = of_value (fun c -> (String.make 1 c))
let to_bytes = to_value "bytes" Bytes.of_string
let of_bytes = of_value Bytes.to_string
let to_unit = to_value "unit" (function "()" -> () | _ -> raise_errorf None "Expected unit")
let of_unit = of_value (fun () -> "()")
let to_nativeint = to_value "nativeint" Nativeint.of_string
let of_nativeint = of_value Nativeint.to_string
let of_xmlm_exn: t -> t =
function
| (`El ((_v, (_, "unwrapped") :: ((_, "__name"), v') :: xs), d)) -> (`El ((("", v'), xs), d))
| (`El ((v, (_, "unwrapped") :: xs), d)) -> (`El ((v, xs), d))
| (`El ((_v, ((_, "__name"), v') :: xs), d)) -> (`El ((("", v'), xs), d))
| x -> x
let of_xmlm t = Ok (of_xmlm_exn t)
let to_xmlm: t -> t = function
| (`El ((v, attrs), d)) -> (`El ((v, (("", "__name"), snd v) :: attrs), d))
| v -> v
|
5d2ae91355a7cd1e8ffbe445ada9389b23ef95d88056cdd46c7659730babd950 | avsm/eeww | list.ml | (**************************************************************************)
(* *)
(* OCaml *)
(* *)
, projet Cristal , INRIA Rocquencourt
(* *)
Copyright 1996 Institut National de Recherche en Informatique et
(* en Automatique. *)
(* *)
(* All rights reserved. This file is distributed under the terms of *)
the GNU Lesser General Public License version 2.1 , with the
(* special exception on linking described in the file LICENSE. *)
(* *)
(**************************************************************************)
(* An alias for the type of lists. *)
type 'a t = 'a list = [] | (::) of 'a * 'a list
(* List operations *)
let rec length_aux len = function
[] -> len
| _::l -> length_aux (len + 1) l
let length l = length_aux 0 l
let cons a l = a::l
let hd = function
[] -> failwith "hd"
| a::_ -> a
let tl = function
[] -> failwith "tl"
| _::l -> l
let nth l n =
if n < 0 then invalid_arg "List.nth" else
let rec nth_aux l n =
match l with
| [] -> failwith "nth"
| a::l -> if n = 0 then a else nth_aux l (n-1)
in nth_aux l n
let nth_opt l n =
if n < 0 then invalid_arg "List.nth" else
let rec nth_aux l n =
match l with
| [] -> None
| a::l -> if n = 0 then Some a else nth_aux l (n-1)
in nth_aux l n
let append = (@)
let rec rev_append l1 l2 =
match l1 with
[] -> l2
| a :: l -> rev_append l (a :: l2)
let rev l = rev_append l []
let[@tail_mod_cons] rec init i last f =
if i > last then []
else if i = last then [f i]
else
let r1 = f i in
let r2 = f (i+1) in
r1 :: r2 :: init (i+2) last f
let init len f =
if len < 0 then invalid_arg "List.init" else
init 0 (len - 1) f
let rec flatten = function
[] -> []
| l::r -> l @ flatten r
let concat = flatten
let[@tail_mod_cons] rec map f = function
[] -> []
| [a1] ->
let r1 = f a1 in
[r1]
| a1::a2::l ->
let r1 = f a1 in
let r2 = f a2 in
r1::r2::map f l
let[@tail_mod_cons] rec mapi i f = function
[] -> []
| [a1] ->
let r1 = f i a1 in
[r1]
| a1::a2::l ->
let r1 = f i a1 in
let r2 = f (i+1) a2 in
r1::r2::mapi (i+2) f l
let mapi f l = mapi 0 f l
let rev_map f l =
let rec rmap_f accu = function
| [] -> accu
| a::l -> rmap_f (f a :: accu) l
in
rmap_f [] l
let rec iter f = function
[] -> ()
| a::l -> f a; iter f l
let rec iteri i f = function
[] -> ()
| a::l -> f i a; iteri (i + 1) f l
let iteri f l = iteri 0 f l
let rec fold_left f accu l =
match l with
[] -> accu
| a::l -> fold_left f (f accu a) l
let rec fold_right f l accu =
match l with
[] -> accu
| a::l -> f a (fold_right f l accu)
let[@tail_mod_cons] rec map2 f l1 l2 =
match (l1, l2) with
([], []) -> []
| ([a1], [b1]) ->
let r1 = f a1 b1 in
[r1]
| (a1::a2::l1, b1::b2::l2) ->
let r1 = f a1 b1 in
let r2 = f a2 b2 in
r1::r2::map2 f l1 l2
| (_, _) -> invalid_arg "List.map2"
let rev_map2 f l1 l2 =
let rec rmap2_f accu l1 l2 =
match (l1, l2) with
| ([], []) -> accu
| (a1::l1, a2::l2) -> rmap2_f (f a1 a2 :: accu) l1 l2
| (_, _) -> invalid_arg "List.rev_map2"
in
rmap2_f [] l1 l2
let rec iter2 f l1 l2 =
match (l1, l2) with
([], []) -> ()
| (a1::l1, a2::l2) -> f a1 a2; iter2 f l1 l2
| (_, _) -> invalid_arg "List.iter2"
let rec fold_left2 f accu l1 l2 =
match (l1, l2) with
([], []) -> accu
| (a1::l1, a2::l2) -> fold_left2 f (f accu a1 a2) l1 l2
| (_, _) -> invalid_arg "List.fold_left2"
let rec fold_right2 f l1 l2 accu =
match (l1, l2) with
([], []) -> accu
| (a1::l1, a2::l2) -> f a1 a2 (fold_right2 f l1 l2 accu)
| (_, _) -> invalid_arg "List.fold_right2"
let rec for_all p = function
[] -> true
| a::l -> p a && for_all p l
let rec exists p = function
[] -> false
| a::l -> p a || exists p l
let rec for_all2 p l1 l2 =
match (l1, l2) with
([], []) -> true
| (a1::l1, a2::l2) -> p a1 a2 && for_all2 p l1 l2
| (_, _) -> invalid_arg "List.for_all2"
let rec exists2 p l1 l2 =
match (l1, l2) with
([], []) -> false
| (a1::l1, a2::l2) -> p a1 a2 || exists2 p l1 l2
| (_, _) -> invalid_arg "List.exists2"
let rec mem x = function
[] -> false
| a::l -> compare a x = 0 || mem x l
let rec memq x = function
[] -> false
| a::l -> a == x || memq x l
let rec assoc x = function
[] -> raise Not_found
| (a,b)::l -> if compare a x = 0 then b else assoc x l
let rec assoc_opt x = function
[] -> None
| (a,b)::l -> if compare a x = 0 then Some b else assoc_opt x l
let rec assq x = function
[] -> raise Not_found
| (a,b)::l -> if a == x then b else assq x l
let rec assq_opt x = function
[] -> None
| (a,b)::l -> if a == x then Some b else assq_opt x l
let rec mem_assoc x = function
| [] -> false
| (a, _) :: l -> compare a x = 0 || mem_assoc x l
let rec mem_assq x = function
| [] -> false
| (a, _) :: l -> a == x || mem_assq x l
let rec remove_assoc x = function
| [] -> []
| (a, _ as pair) :: l ->
if compare a x = 0 then l else pair :: remove_assoc x l
let rec remove_assq x = function
| [] -> []
| (a, _ as pair) :: l -> if a == x then l else pair :: remove_assq x l
let rec find p = function
| [] -> raise Not_found
| x :: l -> if p x then x else find p l
let rec find_opt p = function
| [] -> None
| x :: l -> if p x then Some x else find_opt p l
let find_index p =
let rec aux i = function
[] -> None
| a::l -> if p a then Some i else aux (i+1) l in
aux 0
let rec find_map f = function
| [] -> None
| x :: l ->
begin match f x with
| Some _ as result -> result
| None -> find_map f l
end
let find_mapi f =
let rec aux i = function
| [] -> None
| x :: l ->
begin match f i x with
| Some _ as result -> result
| None -> aux (i+1) l
end in
aux 0
let[@tail_mod_cons] rec find_all p = function
| [] -> []
| x :: l -> if p x then x :: find_all p l else find_all p l
let filter = find_all
let[@tail_mod_cons] rec filteri p i = function
| [] -> []
| x::l ->
let i' = i + 1 in
if p i x then x :: filteri p i' l else filteri p i' l
let filteri p l = filteri p 0 l
let[@tail_mod_cons] rec filter_map f = function
| [] -> []
| x :: l ->
match f x with
| None -> filter_map f l
| Some v -> v :: filter_map f l
let[@tail_mod_cons] rec concat_map f = function
| [] -> []
| x::xs -> prepend_concat_map (f x) f xs
and[@tail_mod_cons] prepend_concat_map ys f xs =
match ys with
| [] -> concat_map f xs
| y :: ys -> y :: prepend_concat_map ys f xs
let fold_left_map f accu l =
let rec aux accu l_accu = function
| [] -> accu, rev l_accu
| x :: l ->
let accu, x = f accu x in
aux accu (x :: l_accu) l in
aux accu [] l
let partition p l =
let rec part yes no = function
| [] -> (rev yes, rev no)
| x :: l -> if p x then part (x :: yes) no l else part yes (x :: no) l in
part [] [] l
let partition_map p l =
let rec part left right = function
| [] -> (rev left, rev right)
| x :: l ->
begin match p x with
| Either.Left v -> part (v :: left) right l
| Either.Right v -> part left (v :: right) l
end
in
part [] [] l
let rec split = function
[] -> ([], [])
| (x,y)::l ->
let (rx, ry) = split l in (x::rx, y::ry)
let rec combine l1 l2 =
match (l1, l2) with
([], []) -> []
| (a1::l1, a2::l2) -> (a1, a2) :: combine l1 l2
| (_, _) -> invalid_arg "List.combine"
(** sorting *)
let rec merge cmp l1 l2 =
match l1, l2 with
| [], l2 -> l2
| l1, [] -> l1
| h1 :: t1, h2 :: t2 ->
if cmp h1 h2 <= 0
then h1 :: merge cmp t1 l2
else h2 :: merge cmp l1 t2
let stable_sort cmp l =
let rec rev_merge l1 l2 accu =
match l1, l2 with
| [], l2 -> rev_append l2 accu
| l1, [] -> rev_append l1 accu
| h1::t1, h2::t2 ->
if cmp h1 h2 <= 0
then rev_merge t1 l2 (h1::accu)
else rev_merge l1 t2 (h2::accu)
in
let rec rev_merge_rev l1 l2 accu =
match l1, l2 with
| [], l2 -> rev_append l2 accu
| l1, [] -> rev_append l1 accu
| h1::t1, h2::t2 ->
if cmp h1 h2 > 0
then rev_merge_rev t1 l2 (h1::accu)
else rev_merge_rev l1 t2 (h2::accu)
in
let rec sort n l =
match n, l with
| 2, x1 :: x2 :: tl ->
let s = if cmp x1 x2 <= 0 then [x1; x2] else [x2; x1] in
(s, tl)
| 3, x1 :: x2 :: x3 :: tl ->
let s =
if cmp x1 x2 <= 0 then
if cmp x2 x3 <= 0 then [x1; x2; x3]
else if cmp x1 x3 <= 0 then [x1; x3; x2]
else [x3; x1; x2]
else if cmp x1 x3 <= 0 then [x2; x1; x3]
else if cmp x2 x3 <= 0 then [x2; x3; x1]
else [x3; x2; x1]
in
(s, tl)
| n, l ->
let n1 = n asr 1 in
let n2 = n - n1 in
let s1, l2 = rev_sort n1 l in
let s2, tl = rev_sort n2 l2 in
(rev_merge_rev s1 s2 [], tl)
and rev_sort n l =
match n, l with
| 2, x1 :: x2 :: tl ->
let s = if cmp x1 x2 > 0 then [x1; x2] else [x2; x1] in
(s, tl)
| 3, x1 :: x2 :: x3 :: tl ->
let s =
if cmp x1 x2 > 0 then
if cmp x2 x3 > 0 then [x1; x2; x3]
else if cmp x1 x3 > 0 then [x1; x3; x2]
else [x3; x1; x2]
else if cmp x1 x3 > 0 then [x2; x1; x3]
else if cmp x2 x3 > 0 then [x2; x3; x1]
else [x3; x2; x1]
in
(s, tl)
| n, l ->
let n1 = n asr 1 in
let n2 = n - n1 in
let s1, l2 = sort n1 l in
let s2, tl = sort n2 l2 in
(rev_merge s1 s2 [], tl)
in
let len = length l in
if len < 2 then l else fst (sort len l)
let sort = stable_sort
let fast_sort = stable_sort
Note : on a very long list ( length over about 100000 ) , it used to be
faster to convert the list to an array , sort the array , and convert
back , truncating the array object after prepending each thousand
entries to the resulting list . Impossible now that Obj.truncate has
been removed .
faster to convert the list to an array, sort the array, and convert
back, truncating the array object after prepending each thousand
entries to the resulting list. Impossible now that Obj.truncate has
been removed. *)
(** sorting + removing duplicates *)
let sort_uniq cmp l =
let rec rev_merge l1 l2 accu =
match l1, l2 with
| [], l2 -> rev_append l2 accu
| l1, [] -> rev_append l1 accu
| h1::t1, h2::t2 ->
let c = cmp h1 h2 in
if c = 0 then rev_merge t1 t2 (h1::accu)
else if c < 0
then rev_merge t1 l2 (h1::accu)
else rev_merge l1 t2 (h2::accu)
in
let rec rev_merge_rev l1 l2 accu =
match l1, l2 with
| [], l2 -> rev_append l2 accu
| l1, [] -> rev_append l1 accu
| h1::t1, h2::t2 ->
let c = cmp h1 h2 in
if c = 0 then rev_merge_rev t1 t2 (h1::accu)
else if c > 0
then rev_merge_rev t1 l2 (h1::accu)
else rev_merge_rev l1 t2 (h2::accu)
in
let rec sort n l =
match n, l with
| 2, x1 :: x2 :: tl ->
let s =
let c = cmp x1 x2 in
if c = 0 then [x1] else if c < 0 then [x1; x2] else [x2; x1]
in
(s, tl)
| 3, x1 :: x2 :: x3 :: tl ->
let s =
let c = cmp x1 x2 in
if c = 0 then
let c = cmp x2 x3 in
if c = 0 then [x2] else if c < 0 then [x2; x3] else [x3; x2]
else if c < 0 then
let c = cmp x2 x3 in
if c = 0 then [x1; x2]
else if c < 0 then [x1; x2; x3]
else
let c = cmp x1 x3 in
if c = 0 then [x1; x2]
else if c < 0 then [x1; x3; x2]
else [x3; x1; x2]
else
let c = cmp x1 x3 in
if c = 0 then [x2; x1]
else if c < 0 then [x2; x1; x3]
else
let c = cmp x2 x3 in
if c = 0 then [x2; x1]
else if c < 0 then [x2; x3; x1]
else [x3; x2; x1]
in
(s, tl)
| n, l ->
let n1 = n asr 1 in
let n2 = n - n1 in
let s1, l2 = rev_sort n1 l in
let s2, tl = rev_sort n2 l2 in
(rev_merge_rev s1 s2 [], tl)
and rev_sort n l =
match n, l with
| 2, x1 :: x2 :: tl ->
let s =
let c = cmp x1 x2 in
if c = 0 then [x1] else if c > 0 then [x1; x2] else [x2; x1]
in
(s, tl)
| 3, x1 :: x2 :: x3 :: tl ->
let s =
let c = cmp x1 x2 in
if c = 0 then
let c = cmp x2 x3 in
if c = 0 then [x2] else if c > 0 then [x2; x3] else [x3; x2]
else if c > 0 then
let c = cmp x2 x3 in
if c = 0 then [x1; x2]
else if c > 0 then [x1; x2; x3]
else
let c = cmp x1 x3 in
if c = 0 then [x1; x2]
else if c > 0 then [x1; x3; x2]
else [x3; x1; x2]
else
let c = cmp x1 x3 in
if c = 0 then [x2; x1]
else if c > 0 then [x2; x1; x3]
else
let c = cmp x2 x3 in
if c = 0 then [x2; x1]
else if c > 0 then [x2; x3; x1]
else [x3; x2; x1]
in
(s, tl)
| n, l ->
let n1 = n asr 1 in
let n2 = n - n1 in
let s1, l2 = sort n1 l in
let s2, tl = sort n2 l2 in
(rev_merge s1 s2 [], tl)
in
let len = length l in
if len < 2 then l else fst (sort len l)
let rec compare_lengths l1 l2 =
match l1, l2 with
| [], [] -> 0
| [], _ -> -1
| _, [] -> 1
| _ :: l1, _ :: l2 -> compare_lengths l1 l2
let rec compare_length_with l n =
match l with
| [] ->
if n = 0 then 0 else
if n > 0 then -1 else 1
| _ :: l ->
if n <= 0 then 1 else
compare_length_with l (n-1)
let is_empty = function
| [] -> true
| _ :: _ -> false
* { 1 Comparison }
Note : we are * not * shortcutting the list by using
[ List.compare_lengths ] first ; this may be slower on long lists
immediately start with distinct elements . It is also incorrect for
[ compare ] below , and it is better ( principle of least surprise ) to
use the same approach for both functions .
[List.compare_lengths] first; this may be slower on long lists
immediately start with distinct elements. It is also incorrect for
[compare] below, and it is better (principle of least surprise) to
use the same approach for both functions. *)
let rec equal eq l1 l2 =
match l1, l2 with
| [], [] -> true
| [], _::_ | _::_, [] -> false
| a1::l1, a2::l2 -> eq a1 a2 && equal eq l1 l2
let rec compare cmp l1 l2 =
match l1, l2 with
| [], [] -> 0
| [], _::_ -> -1
| _::_, [] -> 1
| a1::l1, a2::l2 ->
let c = cmp a1 a2 in
if c <> 0 then c
else compare cmp l1 l2
(** {1 Iterators} *)
let to_seq l =
let rec aux l () = match l with
| [] -> Seq.Nil
| x :: tail -> Seq.Cons (x, aux tail)
in
aux l
let[@tail_mod_cons] rec of_seq seq =
match seq () with
| Seq.Nil -> []
| Seq.Cons (x1, seq) ->
begin match seq () with
| Seq.Nil -> [x1]
| Seq.Cons (x2, seq) -> x1 :: x2 :: of_seq seq
end
| null | https://raw.githubusercontent.com/avsm/eeww/651d8da20a3cc9e88354ed0c8da270632b9c0c19/boot/ocaml/stdlib/list.ml | ocaml | ************************************************************************
OCaml
en Automatique.
All rights reserved. This file is distributed under the terms of
special exception on linking described in the file LICENSE.
************************************************************************
An alias for the type of lists.
List operations
* sorting
* sorting + removing duplicates
* {1 Iterators} | , projet Cristal , INRIA Rocquencourt
Copyright 1996 Institut National de Recherche en Informatique et
the GNU Lesser General Public License version 2.1 , with the
type 'a t = 'a list = [] | (::) of 'a * 'a list
let rec length_aux len = function
[] -> len
| _::l -> length_aux (len + 1) l
let length l = length_aux 0 l
let cons a l = a::l
let hd = function
[] -> failwith "hd"
| a::_ -> a
let tl = function
[] -> failwith "tl"
| _::l -> l
let nth l n =
if n < 0 then invalid_arg "List.nth" else
let rec nth_aux l n =
match l with
| [] -> failwith "nth"
| a::l -> if n = 0 then a else nth_aux l (n-1)
in nth_aux l n
let nth_opt l n =
if n < 0 then invalid_arg "List.nth" else
let rec nth_aux l n =
match l with
| [] -> None
| a::l -> if n = 0 then Some a else nth_aux l (n-1)
in nth_aux l n
let append = (@)
let rec rev_append l1 l2 =
match l1 with
[] -> l2
| a :: l -> rev_append l (a :: l2)
let rev l = rev_append l []
let[@tail_mod_cons] rec init i last f =
if i > last then []
else if i = last then [f i]
else
let r1 = f i in
let r2 = f (i+1) in
r1 :: r2 :: init (i+2) last f
let init len f =
if len < 0 then invalid_arg "List.init" else
init 0 (len - 1) f
let rec flatten = function
[] -> []
| l::r -> l @ flatten r
let concat = flatten
let[@tail_mod_cons] rec map f = function
[] -> []
| [a1] ->
let r1 = f a1 in
[r1]
| a1::a2::l ->
let r1 = f a1 in
let r2 = f a2 in
r1::r2::map f l
let[@tail_mod_cons] rec mapi i f = function
[] -> []
| [a1] ->
let r1 = f i a1 in
[r1]
| a1::a2::l ->
let r1 = f i a1 in
let r2 = f (i+1) a2 in
r1::r2::mapi (i+2) f l
let mapi f l = mapi 0 f l
let rev_map f l =
let rec rmap_f accu = function
| [] -> accu
| a::l -> rmap_f (f a :: accu) l
in
rmap_f [] l
let rec iter f = function
[] -> ()
| a::l -> f a; iter f l
let rec iteri i f = function
[] -> ()
| a::l -> f i a; iteri (i + 1) f l
let iteri f l = iteri 0 f l
let rec fold_left f accu l =
match l with
[] -> accu
| a::l -> fold_left f (f accu a) l
let rec fold_right f l accu =
match l with
[] -> accu
| a::l -> f a (fold_right f l accu)
let[@tail_mod_cons] rec map2 f l1 l2 =
match (l1, l2) with
([], []) -> []
| ([a1], [b1]) ->
let r1 = f a1 b1 in
[r1]
| (a1::a2::l1, b1::b2::l2) ->
let r1 = f a1 b1 in
let r2 = f a2 b2 in
r1::r2::map2 f l1 l2
| (_, _) -> invalid_arg "List.map2"
let rev_map2 f l1 l2 =
let rec rmap2_f accu l1 l2 =
match (l1, l2) with
| ([], []) -> accu
| (a1::l1, a2::l2) -> rmap2_f (f a1 a2 :: accu) l1 l2
| (_, _) -> invalid_arg "List.rev_map2"
in
rmap2_f [] l1 l2
let rec iter2 f l1 l2 =
match (l1, l2) with
([], []) -> ()
| (a1::l1, a2::l2) -> f a1 a2; iter2 f l1 l2
| (_, _) -> invalid_arg "List.iter2"
let rec fold_left2 f accu l1 l2 =
match (l1, l2) with
([], []) -> accu
| (a1::l1, a2::l2) -> fold_left2 f (f accu a1 a2) l1 l2
| (_, _) -> invalid_arg "List.fold_left2"
let rec fold_right2 f l1 l2 accu =
match (l1, l2) with
([], []) -> accu
| (a1::l1, a2::l2) -> f a1 a2 (fold_right2 f l1 l2 accu)
| (_, _) -> invalid_arg "List.fold_right2"
let rec for_all p = function
[] -> true
| a::l -> p a && for_all p l
let rec exists p = function
[] -> false
| a::l -> p a || exists p l
let rec for_all2 p l1 l2 =
match (l1, l2) with
([], []) -> true
| (a1::l1, a2::l2) -> p a1 a2 && for_all2 p l1 l2
| (_, _) -> invalid_arg "List.for_all2"
let rec exists2 p l1 l2 =
match (l1, l2) with
([], []) -> false
| (a1::l1, a2::l2) -> p a1 a2 || exists2 p l1 l2
| (_, _) -> invalid_arg "List.exists2"
let rec mem x = function
[] -> false
| a::l -> compare a x = 0 || mem x l
let rec memq x = function
[] -> false
| a::l -> a == x || memq x l
let rec assoc x = function
[] -> raise Not_found
| (a,b)::l -> if compare a x = 0 then b else assoc x l
let rec assoc_opt x = function
[] -> None
| (a,b)::l -> if compare a x = 0 then Some b else assoc_opt x l
let rec assq x = function
[] -> raise Not_found
| (a,b)::l -> if a == x then b else assq x l
let rec assq_opt x = function
[] -> None
| (a,b)::l -> if a == x then Some b else assq_opt x l
let rec mem_assoc x = function
| [] -> false
| (a, _) :: l -> compare a x = 0 || mem_assoc x l
let rec mem_assq x = function
| [] -> false
| (a, _) :: l -> a == x || mem_assq x l
let rec remove_assoc x = function
| [] -> []
| (a, _ as pair) :: l ->
if compare a x = 0 then l else pair :: remove_assoc x l
let rec remove_assq x = function
| [] -> []
| (a, _ as pair) :: l -> if a == x then l else pair :: remove_assq x l
let rec find p = function
| [] -> raise Not_found
| x :: l -> if p x then x else find p l
let rec find_opt p = function
| [] -> None
| x :: l -> if p x then Some x else find_opt p l
let find_index p =
let rec aux i = function
[] -> None
| a::l -> if p a then Some i else aux (i+1) l in
aux 0
let rec find_map f = function
| [] -> None
| x :: l ->
begin match f x with
| Some _ as result -> result
| None -> find_map f l
end
let find_mapi f =
let rec aux i = function
| [] -> None
| x :: l ->
begin match f i x with
| Some _ as result -> result
| None -> aux (i+1) l
end in
aux 0
let[@tail_mod_cons] rec find_all p = function
| [] -> []
| x :: l -> if p x then x :: find_all p l else find_all p l
let filter = find_all
let[@tail_mod_cons] rec filteri p i = function
| [] -> []
| x::l ->
let i' = i + 1 in
if p i x then x :: filteri p i' l else filteri p i' l
let filteri p l = filteri p 0 l
let[@tail_mod_cons] rec filter_map f = function
| [] -> []
| x :: l ->
match f x with
| None -> filter_map f l
| Some v -> v :: filter_map f l
let[@tail_mod_cons] rec concat_map f = function
| [] -> []
| x::xs -> prepend_concat_map (f x) f xs
and[@tail_mod_cons] prepend_concat_map ys f xs =
match ys with
| [] -> concat_map f xs
| y :: ys -> y :: prepend_concat_map ys f xs
let fold_left_map f accu l =
let rec aux accu l_accu = function
| [] -> accu, rev l_accu
| x :: l ->
let accu, x = f accu x in
aux accu (x :: l_accu) l in
aux accu [] l
let partition p l =
let rec part yes no = function
| [] -> (rev yes, rev no)
| x :: l -> if p x then part (x :: yes) no l else part yes (x :: no) l in
part [] [] l
let partition_map p l =
let rec part left right = function
| [] -> (rev left, rev right)
| x :: l ->
begin match p x with
| Either.Left v -> part (v :: left) right l
| Either.Right v -> part left (v :: right) l
end
in
part [] [] l
let rec split = function
[] -> ([], [])
| (x,y)::l ->
let (rx, ry) = split l in (x::rx, y::ry)
let rec combine l1 l2 =
match (l1, l2) with
([], []) -> []
| (a1::l1, a2::l2) -> (a1, a2) :: combine l1 l2
| (_, _) -> invalid_arg "List.combine"
let rec merge cmp l1 l2 =
match l1, l2 with
| [], l2 -> l2
| l1, [] -> l1
| h1 :: t1, h2 :: t2 ->
if cmp h1 h2 <= 0
then h1 :: merge cmp t1 l2
else h2 :: merge cmp l1 t2
let stable_sort cmp l =
let rec rev_merge l1 l2 accu =
match l1, l2 with
| [], l2 -> rev_append l2 accu
| l1, [] -> rev_append l1 accu
| h1::t1, h2::t2 ->
if cmp h1 h2 <= 0
then rev_merge t1 l2 (h1::accu)
else rev_merge l1 t2 (h2::accu)
in
let rec rev_merge_rev l1 l2 accu =
match l1, l2 with
| [], l2 -> rev_append l2 accu
| l1, [] -> rev_append l1 accu
| h1::t1, h2::t2 ->
if cmp h1 h2 > 0
then rev_merge_rev t1 l2 (h1::accu)
else rev_merge_rev l1 t2 (h2::accu)
in
let rec sort n l =
match n, l with
| 2, x1 :: x2 :: tl ->
let s = if cmp x1 x2 <= 0 then [x1; x2] else [x2; x1] in
(s, tl)
| 3, x1 :: x2 :: x3 :: tl ->
let s =
if cmp x1 x2 <= 0 then
if cmp x2 x3 <= 0 then [x1; x2; x3]
else if cmp x1 x3 <= 0 then [x1; x3; x2]
else [x3; x1; x2]
else if cmp x1 x3 <= 0 then [x2; x1; x3]
else if cmp x2 x3 <= 0 then [x2; x3; x1]
else [x3; x2; x1]
in
(s, tl)
| n, l ->
let n1 = n asr 1 in
let n2 = n - n1 in
let s1, l2 = rev_sort n1 l in
let s2, tl = rev_sort n2 l2 in
(rev_merge_rev s1 s2 [], tl)
and rev_sort n l =
match n, l with
| 2, x1 :: x2 :: tl ->
let s = if cmp x1 x2 > 0 then [x1; x2] else [x2; x1] in
(s, tl)
| 3, x1 :: x2 :: x3 :: tl ->
let s =
if cmp x1 x2 > 0 then
if cmp x2 x3 > 0 then [x1; x2; x3]
else if cmp x1 x3 > 0 then [x1; x3; x2]
else [x3; x1; x2]
else if cmp x1 x3 > 0 then [x2; x1; x3]
else if cmp x2 x3 > 0 then [x2; x3; x1]
else [x3; x2; x1]
in
(s, tl)
| n, l ->
let n1 = n asr 1 in
let n2 = n - n1 in
let s1, l2 = sort n1 l in
let s2, tl = sort n2 l2 in
(rev_merge s1 s2 [], tl)
in
let len = length l in
if len < 2 then l else fst (sort len l)
let sort = stable_sort
let fast_sort = stable_sort
Note : on a very long list ( length over about 100000 ) , it used to be
faster to convert the list to an array , sort the array , and convert
back , truncating the array object after prepending each thousand
entries to the resulting list . Impossible now that Obj.truncate has
been removed .
faster to convert the list to an array, sort the array, and convert
back, truncating the array object after prepending each thousand
entries to the resulting list. Impossible now that Obj.truncate has
been removed. *)
let sort_uniq cmp l =
let rec rev_merge l1 l2 accu =
match l1, l2 with
| [], l2 -> rev_append l2 accu
| l1, [] -> rev_append l1 accu
| h1::t1, h2::t2 ->
let c = cmp h1 h2 in
if c = 0 then rev_merge t1 t2 (h1::accu)
else if c < 0
then rev_merge t1 l2 (h1::accu)
else rev_merge l1 t2 (h2::accu)
in
let rec rev_merge_rev l1 l2 accu =
match l1, l2 with
| [], l2 -> rev_append l2 accu
| l1, [] -> rev_append l1 accu
| h1::t1, h2::t2 ->
let c = cmp h1 h2 in
if c = 0 then rev_merge_rev t1 t2 (h1::accu)
else if c > 0
then rev_merge_rev t1 l2 (h1::accu)
else rev_merge_rev l1 t2 (h2::accu)
in
let rec sort n l =
match n, l with
| 2, x1 :: x2 :: tl ->
let s =
let c = cmp x1 x2 in
if c = 0 then [x1] else if c < 0 then [x1; x2] else [x2; x1]
in
(s, tl)
| 3, x1 :: x2 :: x3 :: tl ->
let s =
let c = cmp x1 x2 in
if c = 0 then
let c = cmp x2 x3 in
if c = 0 then [x2] else if c < 0 then [x2; x3] else [x3; x2]
else if c < 0 then
let c = cmp x2 x3 in
if c = 0 then [x1; x2]
else if c < 0 then [x1; x2; x3]
else
let c = cmp x1 x3 in
if c = 0 then [x1; x2]
else if c < 0 then [x1; x3; x2]
else [x3; x1; x2]
else
let c = cmp x1 x3 in
if c = 0 then [x2; x1]
else if c < 0 then [x2; x1; x3]
else
let c = cmp x2 x3 in
if c = 0 then [x2; x1]
else if c < 0 then [x2; x3; x1]
else [x3; x2; x1]
in
(s, tl)
| n, l ->
let n1 = n asr 1 in
let n2 = n - n1 in
let s1, l2 = rev_sort n1 l in
let s2, tl = rev_sort n2 l2 in
(rev_merge_rev s1 s2 [], tl)
and rev_sort n l =
match n, l with
| 2, x1 :: x2 :: tl ->
let s =
let c = cmp x1 x2 in
if c = 0 then [x1] else if c > 0 then [x1; x2] else [x2; x1]
in
(s, tl)
| 3, x1 :: x2 :: x3 :: tl ->
let s =
let c = cmp x1 x2 in
if c = 0 then
let c = cmp x2 x3 in
if c = 0 then [x2] else if c > 0 then [x2; x3] else [x3; x2]
else if c > 0 then
let c = cmp x2 x3 in
if c = 0 then [x1; x2]
else if c > 0 then [x1; x2; x3]
else
let c = cmp x1 x3 in
if c = 0 then [x1; x2]
else if c > 0 then [x1; x3; x2]
else [x3; x1; x2]
else
let c = cmp x1 x3 in
if c = 0 then [x2; x1]
else if c > 0 then [x2; x1; x3]
else
let c = cmp x2 x3 in
if c = 0 then [x2; x1]
else if c > 0 then [x2; x3; x1]
else [x3; x2; x1]
in
(s, tl)
| n, l ->
let n1 = n asr 1 in
let n2 = n - n1 in
let s1, l2 = sort n1 l in
let s2, tl = sort n2 l2 in
(rev_merge s1 s2 [], tl)
in
let len = length l in
if len < 2 then l else fst (sort len l)
let rec compare_lengths l1 l2 =
match l1, l2 with
| [], [] -> 0
| [], _ -> -1
| _, [] -> 1
| _ :: l1, _ :: l2 -> compare_lengths l1 l2
let rec compare_length_with l n =
match l with
| [] ->
if n = 0 then 0 else
if n > 0 then -1 else 1
| _ :: l ->
if n <= 0 then 1 else
compare_length_with l (n-1)
let is_empty = function
| [] -> true
| _ :: _ -> false
* { 1 Comparison }
Note : we are * not * shortcutting the list by using
[ List.compare_lengths ] first ; this may be slower on long lists
immediately start with distinct elements . It is also incorrect for
[ compare ] below , and it is better ( principle of least surprise ) to
use the same approach for both functions .
[List.compare_lengths] first; this may be slower on long lists
immediately start with distinct elements. It is also incorrect for
[compare] below, and it is better (principle of least surprise) to
use the same approach for both functions. *)
let rec equal eq l1 l2 =
match l1, l2 with
| [], [] -> true
| [], _::_ | _::_, [] -> false
| a1::l1, a2::l2 -> eq a1 a2 && equal eq l1 l2
let rec compare cmp l1 l2 =
match l1, l2 with
| [], [] -> 0
| [], _::_ -> -1
| _::_, [] -> 1
| a1::l1, a2::l2 ->
let c = cmp a1 a2 in
if c <> 0 then c
else compare cmp l1 l2
let to_seq l =
let rec aux l () = match l with
| [] -> Seq.Nil
| x :: tail -> Seq.Cons (x, aux tail)
in
aux l
let[@tail_mod_cons] rec of_seq seq =
match seq () with
| Seq.Nil -> []
| Seq.Cons (x1, seq) ->
begin match seq () with
| Seq.Nil -> [x1]
| Seq.Cons (x2, seq) -> x1 :: x2 :: of_seq seq
end
|
d46369199f24d50c696ec308c2b986b8f6e9411e587b71032747a794d4431611 | melange-re/melange-compiler-libs | translmod.mli | (**************************************************************************)
(* *)
(* OCaml *)
(* *)
, projet Cristal , INRIA Rocquencourt
(* *)
Copyright 1996 Institut National de Recherche en Informatique et
(* en Automatique. *)
(* *)
(* All rights reserved. This file is distributed under the terms of *)
the GNU Lesser General Public License version 2.1 , with the
(* special exception on linking described in the file LICENSE. *)
(* *)
(**************************************************************************)
(* Translation from typed abstract syntax to lambda terms,
for the module language *)
open Typedtree
open Lambda
type id_or_ignore_loc =
| Id of Ident.t
| Ignore_loc of Lambda.scoped_location
val eval_rec_bindings:
((id_or_ignore_loc * (Lambda.lambda * Lambda.lambda) option *
Lambda.lambda)
list -> Lambda.lambda -> Lambda.lambda)
ref
val transl_implementation:
string -> structure * module_coercion -> Lambda.program
val transl_store_phrases: string -> structure -> int * lambda
val transl_store_implementation:
string -> structure * module_coercion -> Lambda.program
val transl_implementation_flambda:
string -> structure * module_coercion -> Lambda.program
val transl_toplevel_definition: structure -> lambda
val transl_package:
Ident.t option list -> Ident.t -> module_coercion -> lambda
val transl_store_package:
Ident.t option list -> Ident.t -> module_coercion -> int * lambda
val transl_package_flambda:
Ident.t option list -> module_coercion -> int * lambda
val toplevel_name: Ident.t -> string
val nat_toplevel_name: Ident.t -> Ident.t * int
val primitive_declarations: Primitive.description list ref
type unsafe_component =
| Unsafe_module_binding
| Unsafe_functor
| Unsafe_non_function
| Unsafe_typext
type unsafe_info =
| Unsafe of { reason:unsafe_component; loc:Location.t; subid:Ident.t }
| Unnamed
type error =
Circular_dependency of (Ident.t * unsafe_info) list
| Conflicting_inline_attributes
exception Error of Location.t * error
val report_error: Location.t -> error -> Location.error
val reset: unit -> unit
(** make it an array for better performance*)
val get_export_identifiers : unit -> Ident.t list
| null | https://raw.githubusercontent.com/melange-re/melange-compiler-libs/83e3017d2e7a058385f71d1d9a4c4ab52dc1c008/lambda/translmod.mli | ocaml | ************************************************************************
OCaml
en Automatique.
All rights reserved. This file is distributed under the terms of
special exception on linking described in the file LICENSE.
************************************************************************
Translation from typed abstract syntax to lambda terms,
for the module language
* make it an array for better performance | , projet Cristal , INRIA Rocquencourt
Copyright 1996 Institut National de Recherche en Informatique et
the GNU Lesser General Public License version 2.1 , with the
open Typedtree
open Lambda
type id_or_ignore_loc =
| Id of Ident.t
| Ignore_loc of Lambda.scoped_location
val eval_rec_bindings:
((id_or_ignore_loc * (Lambda.lambda * Lambda.lambda) option *
Lambda.lambda)
list -> Lambda.lambda -> Lambda.lambda)
ref
val transl_implementation:
string -> structure * module_coercion -> Lambda.program
val transl_store_phrases: string -> structure -> int * lambda
val transl_store_implementation:
string -> structure * module_coercion -> Lambda.program
val transl_implementation_flambda:
string -> structure * module_coercion -> Lambda.program
val transl_toplevel_definition: structure -> lambda
val transl_package:
Ident.t option list -> Ident.t -> module_coercion -> lambda
val transl_store_package:
Ident.t option list -> Ident.t -> module_coercion -> int * lambda
val transl_package_flambda:
Ident.t option list -> module_coercion -> int * lambda
val toplevel_name: Ident.t -> string
val nat_toplevel_name: Ident.t -> Ident.t * int
val primitive_declarations: Primitive.description list ref
type unsafe_component =
| Unsafe_module_binding
| Unsafe_functor
| Unsafe_non_function
| Unsafe_typext
type unsafe_info =
| Unsafe of { reason:unsafe_component; loc:Location.t; subid:Ident.t }
| Unnamed
type error =
Circular_dependency of (Ident.t * unsafe_info) list
| Conflicting_inline_attributes
exception Error of Location.t * error
val report_error: Location.t -> error -> Location.error
val reset: unit -> unit
val get_export_identifiers : unit -> Ident.t list
|
6987360a3746ddd20f231a6e15e3bd1ae479b41d160a9c98750825d7e6b27016 | azimut/shiny | misc-gpu.lisp | (in-package :shiny)
(defvar *light-color* (v! 1 1 1))
(defvar *exposure* 1f0)
;; Range Constant Linear Quadratic
3250 , 1.0 , 0.0014 , 0.000007
600 , 1.0 , 0.007 , 0.0002
325 , 1.0 , 0.014 , 0.0007
200 , 1.0 , 0.022 , 0.0019
160 , 1.0 , 0.027 , 0.0028
100 , 1.0 , 0.045 , 0.0075
65 , 1.0 , 0.07 , 0.017
50 , 1.0 , 0.09 , 0.032
32 , 1.0 , 0.14 , 0.07
20 , 1.0 , 0.22 , 0.20
13 , 1.0 , 0.35 , 0.44
7 , 1.0 , 0.7 , 1.8
(defun-g point-light-apply ((color :vec3)
(light-color :vec3)
(light-pos :vec3)
(frag-pos :vec3)
(normal :vec3)
(constant :float)
(linear :float)
(quadratic :float))
(let* ((light-dir (normalize (- light-pos frag-pos)))
(diff (saturate (dot normal light-dir)))
(distance (length (- light-pos frag-pos)))
(attenuation (/ 1 (+ constant
(* linear distance)
(* quadratic distance distance))))
(ambient (* .1 color))
(diffuse (* diff color)))
(+ ambient diffuse)))
(defun-g dir-light-apply ((color :vec3)
(light-color :vec3)
(light-pos :vec3)
(frag-pos :vec3)
(normal :vec3))
(let* ((light-dir (normalize (- light-pos frag-pos)))
;; Diffuse shading
(diff (saturate (dot normal light-dir)))
;; combine
(ambient (* light-color .1 color))
(diffuse (* light-color diff color)))
(+ ambient diffuse)))
;;--------------------------------------------------
;; -Lighting/Normal-Mapping
;; "Pushing pixels" code
(defun-g norm-from-map ((normal-map :sampler-2d)
(uv :vec2))
(let* ((normal (s~ (texture normal-map uv) :xyz))
(normal (normalize (1- (* 2 normal)))))
(v! (x normal)
(y normal)
(z normal))))
;; Sometimes "y" component is wrong on the normal map.
(defun-g norm-from-map-flipped ((normal-map :sampler-2d)
(uv :vec2))
(let* ((normal (s~ (texture normal-map uv) :xyz))
(normal (normalize (1- (* 2 normal)))))
(v! (x normal)
(- (y normal))
(z normal))))
;; ?
;; From "pushing pixels" don't remember why it's needed
(defun-g treat-uvs ((uv :vec2))
(v! (x uv) (- 1.0 (y uv))))
;;--------------------------------------------------
;; -Lighting/Parallax-Mapping
vec3 viewDir = normalize(fs_in . TangentViewPos - fs_in . TangentFragPos ) ;
(defun-g parallax-mapping ((uv :vec2)
(view-dir :vec3)
(depth-map :sampler-2d)
(height-scale :float))
(let* ((height (x (texture depth-map uv)))
(p (* (* height height-scale)
(/ (s~ view-dir :xy)
(z view-dir)))))
(- uv p)))
;; -20/
Limit lenght of 1
(defun-g parallax-mapping-offset ((uv :vec2)
(view-dir :vec3)
(depth-map :sampler-2d)
(height-scale :float))
(let* ((height (x (texture depth-map uv)))
(height (- height .5))
(p (* height height-scale)))
(+ uv (* (s~ view-dir :xy) p))))
(defun-g parallax-mapping-offset-flipped ((uv :vec2)
(view-dir :vec3)
(depth-map :sampler-2d)
(height-scale :float))
(let* ((height (- 1 (x (texture depth-map uv))))
(height (- height .5))
(p (* height height-scale)))
(+ uv (* (s~ view-dir :xy) p))))
;;--------------------------------------------------
;; -14/
;; (Euclidean) Distance (aka radial/range) based fog:
;; more realistic and expensive than using depth
;; TODO: add depth and defered fog versions
(defun-g fog-linear ((frag-pos :vec3)
(cam-pos :vec3)
(start :float)
(end :float))
(let* ((view-distance (length (- frag-pos cam-pos)))
(fog-factor
(+ (* view-distance (/ -1 (- end start)))
(/ end (- end start)))))
fog-factor))
(defun-g fog-exp ((frag-pos :vec3)
(cam-pos :vec3)
(density :float))
(let ((view-distance (length (- frag-pos cam-pos))))
(exp2 (- (* view-distance (/ density (log 2)))))))
(defun-g fog-exp2 ((frag-pos :vec3)
(cam-pos :vec3)
(density :float))
(let* ((view-distance (length (- frag-pos cam-pos)))
(fog-density
(* (/ density (sqrt (log 2))) view-distance))
(fog-factor
(exp2 (- (* fog-density fog-density)))))
fog-factor))
;;--------------------------------------------------
;; Versions that apply the fog and returns the final color
(defun-g fog-linear-apply ((color :vec3)
(fog-color :vec3)
(frag-pos :vec3)
(cam-pos :vec3)
(start :float)
(end :float))
(let ((fog-factor (fog-linear frag-pos cam-pos start end)))
(mix fog-color color (saturate fog-factor))))
(defun-g fog-exp-apply ((color :vec3)
(fog-color :vec3)
(frag-pos :vec3)
(cam-pos :vec3)
(density :float))
(let ((fog-factor (fog-exp frag-pos cam-pos density)))
(mix fog-color color (saturate fog-factor))))
(defun-g fog-exp2-apply ((color :vec3)
(fog-color :vec3)
(frag-pos :vec3)
(cam-pos :vec3)
(density :float))
(let ((fog-factor (fog-exp2 frag-pos cam-pos density)))
(mix fog-color color (saturate fog-factor))))
;;--------------------------------------------------
;;
;; "For example, the color of the fog can tell us about the strengh of the
;; sun. Even more, if we make the color of the fog not constant but
;; orientation dependant we can introduce an extra level of realism to
;; the image. For example, we can change the typical bluish fog color to
;; something yellowish when the view vector aligns with the sun
direction . This gives a very natural light dispersion effect . One
;; would argue that sucha an effect shouldn't be called fog but
scattering , and I agree , but in the end of the day one simply has to
;; modify a bit the fog equation to get the effect done."
(defun-g apply-fog ((color :vec3)
(density :float)
(distance :float) ;; camera to point distance
(ray-dir :vec3) ;; camera to point vector
(sun-dir :vec3)) ;; sun light direction
(let* ((fog-amount (- 1 (exp (* (- distance) density))))
(sun-amount (max (dot ray-dir sun-dir) 0))
(fog-color (mix (v! .5 .6 .7) ;; blueish
(v! 1 .9 .7) ;; yellowish
(pow sun-amount 8))))
(mix color fog-color fog-amount)))
;; Modified version, with more generic args (works?)
(defun-g apply-fog ((color :vec3)
(density :float)
(frag-pos :vec3)
(cam-pos :vec3)
(sun-pos :vec3))
(let* ((distance (length (- cam-pos frag-pos)))
(ray-dir (normalize (- cam-pos frag-pos)))
(sun-dir (normalize (- sun-pos frag-pos)))
(fog-amount (- 1 (exp (* (- distance) density))))
(sun-amount (max (dot ray-dir sun-dir) 0))
(fog-color (mix (v! .5 .6 .7) ;; blueish
(v! 1 .9 .7) ;; yellowish
(pow sun-amount 8))))
(mix color fog-color fog-amount)))
;; Height fog - IQ
(defun-g apply-fog ((color :vec3)
(fog-color :vec3)
(distance :float)
(cam-pos :vec3)
(frag-pos :vec3))
(let* ((a .03) ;; .06 - .002
(b .3) ;; .3 - .02
(cam-dir (normalize (- frag-pos cam-pos)))
(fog-amount (/ (* (/ a b)
(exp (* (- (y cam-pos)) b))
(- 1 (exp (* (- distance)
(y cam-dir)
b))))
(y cam-dir))))
(mix color fog-color (saturate fog-amount))))
;;--------------------------------------------------
;; -david-palmer.com/fisa/UDK-2010-07/Engine/Shaders/HeightFogCommon.usf
;; -us/Engine/Actors/FogEffects/HeightFog
;; Calculates fogging from exponential height fog,
returns fog color in rgb , fog factor in a.
Fog Height Falloff : Height density factor , controls how the density
;; increases as height decreases. Smaller values make the
;; transition larger.
;; x - FogDensity *
;; exp2(-FogHeightFalloff *
( CameraWorldPosition.z - FogHeight ) )
;; y - FogHeightFalloff
;; z - CosTerminatorAngle
(defun-g get-exponential-height-fog ((frag-pos :vec3)
(cam-pos :vec3)
(fog-params :vec3)
(light-pos :vec3))
(let* ((cam-to-receiver (- frag-pos cam-pos))
(line-integral (* (x fog-params) (length cam-to-receiver)))
(line-integral
(if (> (abs (z cam-to-receiver)) .0001)
(* line-integral (/ (- 1 (exp2 (* (- (y fog-params)) (z cam-to-receiver))))
(* (y fog-params) (z cam-to-receiver))))
line-integral))
1 in the direction of the light vector , -1 in the opposite direction
(cos-light-angle (dot (normalize (- light-pos frag-pos))
(normalize cam-to-receiver)))
(fog-color
(if (< cos-light-angle (z fog-params))
(mix (v! .5 .6 .7)
(* .5 (+ (v! .5 .6 .7) (v! .1 .1 .1)))
(vec3 (saturate (/ (1+ cos-light-angle)
(1+ (z fog-params))))))
(let ((alpha (saturate (/ (- cos-light-angle (z fog-params))
(- 1 (z fog-params))))))
(mix (* .5 (+ (v! .5 .6 .7) (v! .1 .1 .1)))
(v! .1 .1 .1)
(vec3 (* alpha alpha))))))
(fog-factor (saturate (exp2 (- line-integral)))))
(v! (* fog-color (- 1 fog-factor)) fog-factor)))
;;--------------------------------------------------
PBR - BRDF
;;
(defun-g fresnel-schlick ((cos-theta :float)
(f0 :vec3))
(+ f0
(* (- 1 f0)
(pow (- 1 cos-theta) 5))))
(defun-g distribution-ggx ((n :vec3)
(h :vec3)
(roughness :float))
(let* ((a (* roughness roughness))
(a2 (* a a))
(n-dot-h (max (dot n h) 0))
(n-dot-h2 (* n-dot-h n-dot-h))
(num a2)
(denom (1+ (* n-dot-h2 (1- a2))))
(denom (* +PI+ denom denom)))
(/ num denom)))
(defun-g geometry-schlick-ggx ((n-dot-v :float)
(roughness :float))
(let* ((r (1+ roughness))
(k (/ (* r r) 8))
(num n-dot-v)
(denom (+ (* n-dot-v (- 1 k))
k)))
(/ num denom)))
(defun-g geometry-smith ((n :vec3)
(v :vec3)
(l :vec3)
(roughness :float))
(let* ((n-dot-v (max (dot n v) 0))
(n-dot-l (max (dot n l) 0))
(ggx2 (geometry-schlick-ggx n-dot-v roughness))
(ggx1 (geometry-schlick-ggx n-dot-l roughness)))
(* ggx1 ggx2)))
(defun-g pbr-direct-lum ((light-pos :vec3)
(frag-pos :vec3)
(v :vec3)
(n :vec3)
(roughness :float)
(f0 :vec3)
(metallic :float)
(color :vec3))
(let* ((l (normalize (- light-pos frag-pos)))
(h (normalize (+ v l)))
(distance (length (- light-pos frag-pos)))
(radiance (v! 5 5 5))
pbr - cook - torrance brdf
(ndf (distribution-ggx n h roughness))
(g (geometry-smith n v l roughness))
(f (fresnel-schlick (max (dot h v) 0) f0))
;;
(ks f)
(kd (- 1 ks))
(kd (* kd (- 1 metallic)))
;;
(numerator (* ndf g f))
(denominator (+ .001
(* (max (dot n v) 0)
(max (dot n l) 0)
4)))
(specular (/ numerator denominator))
;; add to outgoing radiance lo
(n-dot-l (max (dot n l) 0))
(lo (* (+ specular (/ (* kd color) +PI+))
radiance
n-dot-l)))
lo))
(defun-g pbr-point-lum ((light-pos :vec3)
(frag-pos :vec3)
(v :vec3)
(n :vec3)
(roughness :float)
(f0 :vec3)
(metallic :float)
(color :vec3))
(let* ((l (normalize (- light-pos frag-pos)))
(h (normalize (+ v l)))
(distance (length (- light-pos frag-pos)))
(constant 1f0)
(linear .7)
(quadratic 1.8)
(attenuation (/ 1f0 (+ constant
(* linear distance)
(* quadratic distance distance))))
(light-color (v! .9 .9 .9))
(radiance light-color attenuation)
pbr - cook - torrance brdf
(ndf (distribution-ggx n h roughness))
(g (geometry-smith n v l roughness))
(f (fresnel-schlick (max (dot h v) 0) f0))
;;
(ks f)
(kd (* (- (vec3 1) ks)
(- 1 metallic)))
;;
(numerator (* ndf g f))
(denominator (* (max (dot n v) 0)
(max (dot n l) 0)
4))
(specular (/ numerator (max denominator .001)))
;; add to outgoing radiance lo
(n-dot-l (max (dot n l) 0)))
(* (+ specular (/ (* kd color) +PI+))
radiance
n-dot-l)))
;;--------------------------------------------------
;; Billboarding
(defun-g billboard-vert ((pos :vec3)
&uniform
(time :float)
(world-view :mat4))
(* world-view (v! 0 -6 -50 1)))
(defun-g billboard-frag ((uv :vec2)
&uniform
(tex :sampler-2d)
(time :float))
(let* ((color (texture tex uv)))
(values color
(v! (x color) 0 0 (w color)))))
(defun-g billboard-geom (&uniform (camera-pos :vec3)
(view-clip :mat4))
(declare (output-primitive :kind :triangle-strip
:max-vertices 4))
(let* ((p (s~ (gl-position (aref gl-in 0)) :xyz))
(to-camera (normalize (- camera-pos p)))
(up (v! 0 1 0))
(right (cross to-camera up)))
;;
(decf p (* 9 .5 right))
(emit ()
(* view-clip (v! p 1))
(v! 0 0))
;;
(incf (y p) 9f0)
(emit ()
(* view-clip (v! p 1))
(v! 0 1))
;;
(decf (y p) 9f0)
(incf p (* right 9))
(emit ()
(* view-clip (v! p 1))
(v! 1 0))
;;
(incf (y p) 9f0)
(emit ()
(* view-clip (v! p 1))
(v! 1 1))
(end-primitive)
(values)))
(defpipeline-g billboard-pipe (:points)
:vertex (billboard-vert :vec3)
:geometry (billboard-geom)
:fragment (billboard-frag :vec2))
;;--------------------------------------------------
;; glsl-atmosphere
-atmosphere/
;; RSI
;; ray-sphere intersection that assumes
;; the sphere is centered at the origin.
;; No intersection when result.x > result.y
(defun-g rsi ((r0 :vec3)
(rd :vec3)
(sr :float))
(let* ((a (dot rd rd))
(b (* 2 (dot rd r0)))
(c (- (dot r0 r0) (* sr sr)))
(d (- (* b b) (* 4 a c))))
(if (< d 0)
(v! 100000 -100000)
(v! (/ (- (- b) (sqrt d))
(* 2 a))
(/ (+ (- b) (sqrt d))
(* 2 a))))))
;; vec3 r normalized ray direction, typically a ray cast from the observers eye through a pixel
;; vec3 r0 ray origin in meters, typically the position of the viewer's eye
vec3 pSun the position of the sun
float iSun intensity of the sun
;; float rPlanet radius of the planet in meters
;; float rAtoms radius of the atmosphere in meters
vec3 scattering coefficient
vec3 scattering coefficient
float shRlh Rayleigh scale height in meters
;; float shMie Mie scale height in meters
float preferred scattering direction
(defun-g atmosphere ((r :vec3)
(r0 :vec3)
(p-sun :vec3)
(i-sun :float)
(r-planet :float)
(r-atmos :float)
(k-rlh :vec3)
(k-mie :float)
(sh-rlh :float)
(sh-mie :float)
(g :float)
(i-steps :uint)
(j-steps :uint))
( i - steps 3 ) ; ; 16
( j - steps 2 ) ; ; 8
(pi +PI+)
;; Normalize the sun and view directions
(p-sun (normalize p-sun))
(r (normalize r))
;; Calculate the step size of the
;; primary ray.
(p (rsi r0 r r-atmos)))
(if (> (x p) (y p))
(vec3 0f0)
(let* ((p (v! (x p)
(min (y p) (x (rsi r0 r r-planet)))))
(i-step-size (/ (- (y p) (x p))
i-steps))
Initialize the primary ray time .
(i-time 0f0)
Initialize accumulators for
Rayleigh and Mie scattering
(total-rlh (vec3 0f0))
(total-mie (vec3 0f0))
Initialize optical depth
;; for the primary ray.
(i-od-rlh 0f0)
(i-od-mie 0f0)
Calculate the Rayleigh
;; and Mie phases
(mu (dot r p-sun))
(mumu (* mu mu))
(gg (* g g))
(p-rlh (* (/ 3 (* 16 pi))
(+ 1 mumu)))
(p-mie (/ (* (/ 3 (* 8 pi))
(* (- 1 gg) (+ 1 mumu)))
(* (pow (- (+ 1 gg) (* 2 mu g))
1.5)
(* 2 gg))))
(i 0))
;; sample the primary key
(dotimes (i i-steps)
(let* (;; Calculate the primary ray sample position
(i-pos (+ r0 (* r (+ i-time (* i-step-size .5)))))
;; Calculate the height of the sample
(i-height (- (length i-pos) r-planet))
;; Calculate the optical depth of the Rayleigh
;; and Mie scattering for this step.
(od-step-rlh (* i-step-size (exp (/ (- i-height) sh-rlh))))
(od-step-mie (* i-step-size (exp (/ (- i-height) sh-mie)))))
;; Accumulate optical depth.
(incf i-od-rlh od-step-rlh)
(incf i-od-mie od-step-mie)
(let (;; Calculate the step size of the secondary ray
(j-step-size (/ (y (rsi i-pos p-sun r-atmos)) j-steps))
Initialize the secondary ray time
(j-time 0f0)
Initialize optical depth accumulators for the sec ray
(j-od-rlh 0f0)
(j-od-mie 0f0))
;; Sample the seconday ray
(dotimes (j j-steps)
(let* (;; Calculate the secondary ray sample position
(j-pos (+ i-pos (* p-sun (+ j-time (* j-step-size .5)))))
;; Calculate the height of the sample
(j-height (- (length j-pos) r-planet)))
;; Accumulate the optical depth
(incf j-od-rlh (* j-step-size (exp (/ (- j-height) sh-rlh))))
(incf j-od-mie (* j-step-size (exp (/ (- j-height) sh-mie))))
;; Increment the secondary ray time
(incf j-time j-step-size)))
;; Calculate attenuation
(let ((attn (exp (- (+ (* k-mie (+ i-od-mie j-od-mie))
(* k-rlh (+ i-od-rlh j-od-rlh)))))))
;; Accumulate scattering
(incf total-rlh (* od-step-rlh attn))
(incf total-mie (* od-step-mie attn))
;; Increment the primary ray time
(incf i-time i-step-size)))))
;; Calculate and return the final color
(* i-sun (+ (* p-rlh k-rlh total-rlh)
(* p-mie k-mie total-mie)))))))
;;--------------------------------------------------
;; WORKS???
;; -nvhpdsyj-yy.html
(defun-g linear-eye-depth ((d :float))
(let* ((n .1)
(f 400f0)
(zz (/ (/ (- 1 (/ f n)) 2) f))
(zw (/ (/ (+ 1 (/ f n)) 2) f)))
(/ 1 (+ (* zz d) zw))))
(defun-g read-depth ((z :float))
(let* ((pfn (+ 400 .1))
(mfn (- 400 .1))
(coef (* 2f0 .1)))
(/ coef (- pfn (* z mfn)))))
;; -OpenGL/Depth-testing
;; Because the linearized depth values range from near to far most of
its values will be above 1.0 and displayed as completely white . By
;; dividing the linear depth value by far in the main function we
convert the linear depth value to roughly the range [ 0 , 1 ] . This
;; way we can gradually see the scene become brighter the closer the
;; fragments are to the projection frustum's far plane, which is
;; better suited for demonstration purposes.
(defun-g linearize-depth ((depth :float))
(let* ((near 0.1)
(far 400f0)
(z (- (* depth 2.0) 1.0)))
(/ (* 2.0 (* near far))
(- (+ far near) (* z (- far near))))))
;; Three.js - packaging.glsl.js
(defun-g view-zto-orthographic-depth ((view-z :float)
(near :float)
(far :float))
(/ (+ view-z near)
(- near far)))
(defun-g perspective-depth-to-view-z ((inv-clip-z :float)
(near :float)
(far :float))
(/ (* near far)
(- (* (- far near) inv-clip-z) far)))
(defun-g read-depth ((depth-sampler :sampler-2d)
(coord :vec2)
(camera-near :float)
(camera-far :float))
(let* ((frag-coord-z (x (texture depth-sampler coord)))
(view-z (perspective-depth-to-view-z frag-coord-z
camera-near
camera-far)))
(view-zto-orthographic-depth view-z camera-near camera-far)))
;;--------------------------------------------------
(defun-g fbm-hash ((p :vec2))
(fract
(* (sin (dot p (v! 41 289)))
45758.5453)))
(defun-g combine-god-frag ((uv :vec2)
&uniform
(sam-god :sampler-2d)
(sam :sampler-2d))
(let* ((color (mix (s~ (texture sam uv) :xyz)
(* *light-color* (s~ (texture sam-god uv) :xyz))
.1))
( color ( + ( s~ ( texture ) : xyz )
( * * light - color * ( s~ ( texture uv ) : xyz ) ) ) )
(ldr (nineveh.tonemapping:tone-map-reinhard color *exposure*))
(luma (rgb->luma-bt601 ldr)))
(v! ldr luma)))
(defpipeline-g combine-god-pipe (:points)
:fragment (combine-god-frag :vec2))
(defun-g god-rays-frag ((uv :vec2)
&uniform
(res :vec2)
(time :float)
(sun-pos :vec2)
(sam :sampler-2d))
( uv ( / ( s~ gl - frag - coord : xy ) res ) )
;; (v2:+s (v2:*s (v2:/ (screen-coord (resolution (current-viewport)) (v! 0 0 -30))
;; (resolution (current-viewport)))
2f0 )
)
(uv uv)
(samples 10f0)
(decay .974)
(exposure .24)
(density .93)
(weight .36)
(color (s~ (texture sam uv) :xyz))
(occ (x color))
(obj (y color))
(dtc (* (- uv sun-pos)
(/ 1f0 samples)))
(illumdecay .4f0)
(dither (fbm-hash (+ uv (fract time)))))
(dotimes (i samples)
(decf uv dtc)
(let ((s (x (texture sam (+ (* dither dtc)
uv)))))
(multf s (* illumdecay weight))
(incf occ s)
(multf illumdecay decay)
))
(v! (+ (v! 0 0 0)
(* occ exposure))
1)
( vec4 occ )
))
;; -to-get-screen-coordinates-from-a-3d-point-opengl
;; You then need to transform the [-1:1]^3 cube to window coordinates
by applying the Viewport transformation to it . window.x =
viewport.x + viewport.width * (
(defun screen-coord (res &optional (pos (v! 0 0 -10)))
(let* ((pos4 (v! pos 1))
(cpos4 (m4:*v (world->view *currentcamera*)
pos4))
(cpos4 (m4:*v (projection *currentcamera*)
cpos4))
(w (w cpos4))
(ndc (v4:/s cpos4 w)))
;; -from-pixels-to-ndc
(v2:abs (v2:/ (v! (+ (* (x res) .5 (x ndc))
(+ (* (x res) .5 ) 0))
(+ (* (y res) .5 (y ndc))
(+ (* (y res) .5))))
res))
;; -Refpages/gl2.1/xhtml/glViewport.xml
( v ! ( + ( * ( + 1 ( x ndc ) ) ( / ( x res ) 2 ) ) )
( + ( * ( + 1 ( ) ) ( / ( y res ) 2 ) ) ) )
screen.x = ( ( view.w * 0.5 ) * ndc.x ) +
( ( w * 0.5 ) + view.x )
screen.y = ( ( view.h * 0.5 ) * ndc.y ) +
( ( h * 0.5 ) + view.y )
;;
;; (v2:abs (v2:/ (v! (+ .5 (* (x res)
( / ( + 1 ( x ndc ) ) 2 ) ) )
;; (+ .5 (* (y res)
( / ( - 1 ( y ndc ) ) 2 ) ) ) )
;; res))
;; (v2:* (v2:+ (v2:/s (s~ cpos4 :xy) w)
( v ! 1 1 ) )
;; (v2:*s res .5))
))
;;--------------------------------------------------
Pipeline to create a BRDF 2d lut
;;--------------------------------------------------
ON INIT :
;;
;; (unless *f-brdf*
( setf * f - brdf *
( make - fbo ( list 0 : element - type : rg16f : dimensions ' ( 512 512 ) ) ) )
( setf * t - brdf * ( attachment - tex * f - brdf * 0 ) )
( setf * s - brdf *
( cepl : sample * t - brdf * : wrap : clamp - to - edge
;; :minify-filter :linear)))
;; ON DRAW LOOP:
;;
( unless * *
( setf * * T )
( setf ( resolution ( current - viewport ) ) ( v ! 512 512 ) )
;; (map-g-into *f-brdf* #'brdf-pipe *bs*))
(defun-g integrate-brdf ((n-dot-v :float)
(roughness :float))
;; You might've recalled from the theory tutorial that the geometry
term of the BRDF is slightly different when used alongside IBL as
;; its k variable has a slightly different interpretation:
(labels ((geometry-schlick-ggx ((n-dot-v :float)
(roughness :float))
(let* ((a roughness)
(k (/ (* a a) 2))
(nom n-dot-v)
(denom (+ k (* n-dot-v (- 1 k)))))
(/ nom denom)))
(geometry-smith ((n :vec3)
(v :vec3)
(l :vec3)
(roughness :float))
(let* ((n-dot-v (max (dot n v) 0))
(n-dot-l (max (dot n l) 0))
(ggx2 (geometry-schlick-ggx n-dot-v roughness))
(ggx1 (geometry-schlick-ggx n-dot-l roughness)))
(* ggx1 ggx2))))
(let* ((v (v! (sqrt (- 1 (* n-dot-v n-dot-v)))
0
n-dot-v))
(a 0f0)
(b 0f0)
(n (v! 0 0 1)))
(dotimes (i 1024)
(let* (;; generates a sample vector that's biased towards the
;; preferred alignment direction (importance sampling).
(xi (hammersley-nth-2d 1024 i))
(h (importance-sample-ggx xi n roughness))
(l (normalize (+ (- v) (* 2 (dot v h) h))))
(n-dot-l (max (z l) 0))
(n-dot-h (max (z h) 0))
(v-dot-h (max (dot v h) 0)))
(when (> n-dot-l 0)
(let* ((g (geometry-smith n v l roughness))
(g-vis (/ (* g v-dot-h) (* n-dot-h n-dot-v)))
(fc (pow (- 1 v-dot-h) 5)))
(incf a (* (- 1 fc) g-vis))
(incf b (* fc g-vis))))))
(divf a 1024f0)
(divf b 1024f0)
(v! a b))))
(defun-g brdf-frag ((uv :vec2))
(integrate-brdf (x uv) (y uv)))
(defpipeline-g brdf-pipe (:points)
:fragment (brdf-frag :vec2))
;;--------------------------------------------------
;; Defered fog
;; -Technologies/PostProcessing/
;; Hardcoded to work ONLY with perspective projection
(defun-g linear-01-depth ((z :float))
(let* ((far 400f0)
(near .1)
(z (* z (- 1 (/ far near)))))
(/ (+ z (/ far near)))))
PostProcessing / Shaders / StdLib.hlsl
PostProcessing / Shaders / Builtins / DeferredFog.shader
PostProcessing / Shaders / API / OpenGL.hlsl
PostProcessing / Shaders / Builtins / Fog.hlsl
(defun-g compute-fog-distance ((depth :float))
(let* ((far 400f0)
(near .1)
(dist (- (* depth far) near)))
dist))
;;
(defun-g compute-fog-exp2 ((z :float)
(density :float))
(let* ((fog 0f0)
(fog (* density z))
(fog (exp2 (* (- fog) fog))))
(saturate fog)))
(defun-g defered-fog ((fog-color :vec3)
(uv :vec2)
(tex :sampler-2d)
(depth-tex :sampler-2d))
(let* ((color (s~ (texture tex uv) :xyz))
(depth (x (texture depth-tex uv)))
(depth (linear-01-depth depth))
(dist (compute-fog-distance depth))
(fog (- 1f0 (compute-fog-exp2 dist .1))))
(mix color fog-color fog)))
| null | https://raw.githubusercontent.com/azimut/shiny/774381a9bde21c4ec7e7092c7516dd13a5a50780/lib/misc-gpu.lisp | lisp | Range Constant Linear Quadratic
Diffuse shading
combine
--------------------------------------------------
-Lighting/Normal-Mapping
"Pushing pixels" code
Sometimes "y" component is wrong on the normal map.
?
From "pushing pixels" don't remember why it's needed
--------------------------------------------------
-Lighting/Parallax-Mapping
-20/
--------------------------------------------------
-14/
(Euclidean) Distance (aka radial/range) based fog:
more realistic and expensive than using depth
TODO: add depth and defered fog versions
--------------------------------------------------
Versions that apply the fog and returns the final color
--------------------------------------------------
"For example, the color of the fog can tell us about the strengh of the
sun. Even more, if we make the color of the fog not constant but
orientation dependant we can introduce an extra level of realism to
the image. For example, we can change the typical bluish fog color to
something yellowish when the view vector aligns with the sun
would argue that sucha an effect shouldn't be called fog but
modify a bit the fog equation to get the effect done."
camera to point distance
camera to point vector
sun light direction
blueish
yellowish
Modified version, with more generic args (works?)
blueish
yellowish
Height fog - IQ
.06 - .002
.3 - .02
--------------------------------------------------
-david-palmer.com/fisa/UDK-2010-07/Engine/Shaders/HeightFogCommon.usf
-us/Engine/Actors/FogEffects/HeightFog
Calculates fogging from exponential height fog,
increases as height decreases. Smaller values make the
transition larger.
x - FogDensity *
exp2(-FogHeightFalloff *
y - FogHeightFalloff
z - CosTerminatorAngle
--------------------------------------------------
add to outgoing radiance lo
add to outgoing radiance lo
--------------------------------------------------
Billboarding
--------------------------------------------------
glsl-atmosphere
RSI
ray-sphere intersection that assumes
the sphere is centered at the origin.
No intersection when result.x > result.y
vec3 r normalized ray direction, typically a ray cast from the observers eye through a pixel
vec3 r0 ray origin in meters, typically the position of the viewer's eye
float rPlanet radius of the planet in meters
float rAtoms radius of the atmosphere in meters
float shMie Mie scale height in meters
; 16
; 8
Normalize the sun and view directions
Calculate the step size of the
primary ray.
for the primary ray.
and Mie phases
sample the primary key
Calculate the primary ray sample position
Calculate the height of the sample
Calculate the optical depth of the Rayleigh
and Mie scattering for this step.
Accumulate optical depth.
Calculate the step size of the secondary ray
Sample the seconday ray
Calculate the secondary ray sample position
Calculate the height of the sample
Accumulate the optical depth
Increment the secondary ray time
Calculate attenuation
Accumulate scattering
Increment the primary ray time
Calculate and return the final color
--------------------------------------------------
WORKS???
-nvhpdsyj-yy.html
-OpenGL/Depth-testing
Because the linearized depth values range from near to far most of
dividing the linear depth value by far in the main function we
way we can gradually see the scene become brighter the closer the
fragments are to the projection frustum's far plane, which is
better suited for demonstration purposes.
Three.js - packaging.glsl.js
--------------------------------------------------
(v2:+s (v2:*s (v2:/ (screen-coord (resolution (current-viewport)) (v! 0 0 -30))
(resolution (current-viewport)))
-to-get-screen-coordinates-from-a-3d-point-opengl
You then need to transform the [-1:1]^3 cube to window coordinates
-from-pixels-to-ndc
-Refpages/gl2.1/xhtml/glViewport.xml
(v2:abs (v2:/ (v! (+ .5 (* (x res)
(+ .5 (* (y res)
res))
(v2:* (v2:+ (v2:/s (s~ cpos4 :xy) w)
(v2:*s res .5))
--------------------------------------------------
--------------------------------------------------
(unless *f-brdf*
:minify-filter :linear)))
ON DRAW LOOP:
(map-g-into *f-brdf* #'brdf-pipe *bs*))
You might've recalled from the theory tutorial that the geometry
its k variable has a slightly different interpretation:
generates a sample vector that's biased towards the
preferred alignment direction (importance sampling).
--------------------------------------------------
Defered fog
-Technologies/PostProcessing/
Hardcoded to work ONLY with perspective projection
| (in-package :shiny)
(defvar *light-color* (v! 1 1 1))
(defvar *exposure* 1f0)
3250 , 1.0 , 0.0014 , 0.000007
600 , 1.0 , 0.007 , 0.0002
325 , 1.0 , 0.014 , 0.0007
200 , 1.0 , 0.022 , 0.0019
160 , 1.0 , 0.027 , 0.0028
100 , 1.0 , 0.045 , 0.0075
65 , 1.0 , 0.07 , 0.017
50 , 1.0 , 0.09 , 0.032
32 , 1.0 , 0.14 , 0.07
20 , 1.0 , 0.22 , 0.20
13 , 1.0 , 0.35 , 0.44
7 , 1.0 , 0.7 , 1.8
(defun-g point-light-apply ((color :vec3)
(light-color :vec3)
(light-pos :vec3)
(frag-pos :vec3)
(normal :vec3)
(constant :float)
(linear :float)
(quadratic :float))
(let* ((light-dir (normalize (- light-pos frag-pos)))
(diff (saturate (dot normal light-dir)))
(distance (length (- light-pos frag-pos)))
(attenuation (/ 1 (+ constant
(* linear distance)
(* quadratic distance distance))))
(ambient (* .1 color))
(diffuse (* diff color)))
(+ ambient diffuse)))
(defun-g dir-light-apply ((color :vec3)
(light-color :vec3)
(light-pos :vec3)
(frag-pos :vec3)
(normal :vec3))
(let* ((light-dir (normalize (- light-pos frag-pos)))
(diff (saturate (dot normal light-dir)))
(ambient (* light-color .1 color))
(diffuse (* light-color diff color)))
(+ ambient diffuse)))
(defun-g norm-from-map ((normal-map :sampler-2d)
(uv :vec2))
(let* ((normal (s~ (texture normal-map uv) :xyz))
(normal (normalize (1- (* 2 normal)))))
(v! (x normal)
(y normal)
(z normal))))
(defun-g norm-from-map-flipped ((normal-map :sampler-2d)
(uv :vec2))
(let* ((normal (s~ (texture normal-map uv) :xyz))
(normal (normalize (1- (* 2 normal)))))
(v! (x normal)
(- (y normal))
(z normal))))
(defun-g treat-uvs ((uv :vec2))
(v! (x uv) (- 1.0 (y uv))))
(defun-g parallax-mapping ((uv :vec2)
(view-dir :vec3)
(depth-map :sampler-2d)
(height-scale :float))
(let* ((height (x (texture depth-map uv)))
(p (* (* height height-scale)
(/ (s~ view-dir :xy)
(z view-dir)))))
(- uv p)))
Limit lenght of 1
(defun-g parallax-mapping-offset ((uv :vec2)
(view-dir :vec3)
(depth-map :sampler-2d)
(height-scale :float))
(let* ((height (x (texture depth-map uv)))
(height (- height .5))
(p (* height height-scale)))
(+ uv (* (s~ view-dir :xy) p))))
(defun-g parallax-mapping-offset-flipped ((uv :vec2)
(view-dir :vec3)
(depth-map :sampler-2d)
(height-scale :float))
(let* ((height (- 1 (x (texture depth-map uv))))
(height (- height .5))
(p (* height height-scale)))
(+ uv (* (s~ view-dir :xy) p))))
(defun-g fog-linear ((frag-pos :vec3)
(cam-pos :vec3)
(start :float)
(end :float))
(let* ((view-distance (length (- frag-pos cam-pos)))
(fog-factor
(+ (* view-distance (/ -1 (- end start)))
(/ end (- end start)))))
fog-factor))
(defun-g fog-exp ((frag-pos :vec3)
(cam-pos :vec3)
(density :float))
(let ((view-distance (length (- frag-pos cam-pos))))
(exp2 (- (* view-distance (/ density (log 2)))))))
(defun-g fog-exp2 ((frag-pos :vec3)
(cam-pos :vec3)
(density :float))
(let* ((view-distance (length (- frag-pos cam-pos)))
(fog-density
(* (/ density (sqrt (log 2))) view-distance))
(fog-factor
(exp2 (- (* fog-density fog-density)))))
fog-factor))
(defun-g fog-linear-apply ((color :vec3)
(fog-color :vec3)
(frag-pos :vec3)
(cam-pos :vec3)
(start :float)
(end :float))
(let ((fog-factor (fog-linear frag-pos cam-pos start end)))
(mix fog-color color (saturate fog-factor))))
(defun-g fog-exp-apply ((color :vec3)
(fog-color :vec3)
(frag-pos :vec3)
(cam-pos :vec3)
(density :float))
(let ((fog-factor (fog-exp frag-pos cam-pos density)))
(mix fog-color color (saturate fog-factor))))
(defun-g fog-exp2-apply ((color :vec3)
(fog-color :vec3)
(frag-pos :vec3)
(cam-pos :vec3)
(density :float))
(let ((fog-factor (fog-exp2 frag-pos cam-pos density)))
(mix fog-color color (saturate fog-factor))))
direction . This gives a very natural light dispersion effect . One
scattering , and I agree , but in the end of the day one simply has to
(defun-g apply-fog ((color :vec3)
(density :float)
(let* ((fog-amount (- 1 (exp (* (- distance) density))))
(sun-amount (max (dot ray-dir sun-dir) 0))
(pow sun-amount 8))))
(mix color fog-color fog-amount)))
(defun-g apply-fog ((color :vec3)
(density :float)
(frag-pos :vec3)
(cam-pos :vec3)
(sun-pos :vec3))
(let* ((distance (length (- cam-pos frag-pos)))
(ray-dir (normalize (- cam-pos frag-pos)))
(sun-dir (normalize (- sun-pos frag-pos)))
(fog-amount (- 1 (exp (* (- distance) density))))
(sun-amount (max (dot ray-dir sun-dir) 0))
(pow sun-amount 8))))
(mix color fog-color fog-amount)))
(defun-g apply-fog ((color :vec3)
(fog-color :vec3)
(distance :float)
(cam-pos :vec3)
(frag-pos :vec3))
(cam-dir (normalize (- frag-pos cam-pos)))
(fog-amount (/ (* (/ a b)
(exp (* (- (y cam-pos)) b))
(- 1 (exp (* (- distance)
(y cam-dir)
b))))
(y cam-dir))))
(mix color fog-color (saturate fog-amount))))
returns fog color in rgb , fog factor in a.
Fog Height Falloff : Height density factor , controls how the density
( CameraWorldPosition.z - FogHeight ) )
(defun-g get-exponential-height-fog ((frag-pos :vec3)
(cam-pos :vec3)
(fog-params :vec3)
(light-pos :vec3))
(let* ((cam-to-receiver (- frag-pos cam-pos))
(line-integral (* (x fog-params) (length cam-to-receiver)))
(line-integral
(if (> (abs (z cam-to-receiver)) .0001)
(* line-integral (/ (- 1 (exp2 (* (- (y fog-params)) (z cam-to-receiver))))
(* (y fog-params) (z cam-to-receiver))))
line-integral))
1 in the direction of the light vector , -1 in the opposite direction
(cos-light-angle (dot (normalize (- light-pos frag-pos))
(normalize cam-to-receiver)))
(fog-color
(if (< cos-light-angle (z fog-params))
(mix (v! .5 .6 .7)
(* .5 (+ (v! .5 .6 .7) (v! .1 .1 .1)))
(vec3 (saturate (/ (1+ cos-light-angle)
(1+ (z fog-params))))))
(let ((alpha (saturate (/ (- cos-light-angle (z fog-params))
(- 1 (z fog-params))))))
(mix (* .5 (+ (v! .5 .6 .7) (v! .1 .1 .1)))
(v! .1 .1 .1)
(vec3 (* alpha alpha))))))
(fog-factor (saturate (exp2 (- line-integral)))))
(v! (* fog-color (- 1 fog-factor)) fog-factor)))
PBR - BRDF
(defun-g fresnel-schlick ((cos-theta :float)
(f0 :vec3))
(+ f0
(* (- 1 f0)
(pow (- 1 cos-theta) 5))))
(defun-g distribution-ggx ((n :vec3)
(h :vec3)
(roughness :float))
(let* ((a (* roughness roughness))
(a2 (* a a))
(n-dot-h (max (dot n h) 0))
(n-dot-h2 (* n-dot-h n-dot-h))
(num a2)
(denom (1+ (* n-dot-h2 (1- a2))))
(denom (* +PI+ denom denom)))
(/ num denom)))
(defun-g geometry-schlick-ggx ((n-dot-v :float)
(roughness :float))
(let* ((r (1+ roughness))
(k (/ (* r r) 8))
(num n-dot-v)
(denom (+ (* n-dot-v (- 1 k))
k)))
(/ num denom)))
(defun-g geometry-smith ((n :vec3)
(v :vec3)
(l :vec3)
(roughness :float))
(let* ((n-dot-v (max (dot n v) 0))
(n-dot-l (max (dot n l) 0))
(ggx2 (geometry-schlick-ggx n-dot-v roughness))
(ggx1 (geometry-schlick-ggx n-dot-l roughness)))
(* ggx1 ggx2)))
(defun-g pbr-direct-lum ((light-pos :vec3)
(frag-pos :vec3)
(v :vec3)
(n :vec3)
(roughness :float)
(f0 :vec3)
(metallic :float)
(color :vec3))
(let* ((l (normalize (- light-pos frag-pos)))
(h (normalize (+ v l)))
(distance (length (- light-pos frag-pos)))
(radiance (v! 5 5 5))
pbr - cook - torrance brdf
(ndf (distribution-ggx n h roughness))
(g (geometry-smith n v l roughness))
(f (fresnel-schlick (max (dot h v) 0) f0))
(ks f)
(kd (- 1 ks))
(kd (* kd (- 1 metallic)))
(numerator (* ndf g f))
(denominator (+ .001
(* (max (dot n v) 0)
(max (dot n l) 0)
4)))
(specular (/ numerator denominator))
(n-dot-l (max (dot n l) 0))
(lo (* (+ specular (/ (* kd color) +PI+))
radiance
n-dot-l)))
lo))
(defun-g pbr-point-lum ((light-pos :vec3)
(frag-pos :vec3)
(v :vec3)
(n :vec3)
(roughness :float)
(f0 :vec3)
(metallic :float)
(color :vec3))
(let* ((l (normalize (- light-pos frag-pos)))
(h (normalize (+ v l)))
(distance (length (- light-pos frag-pos)))
(constant 1f0)
(linear .7)
(quadratic 1.8)
(attenuation (/ 1f0 (+ constant
(* linear distance)
(* quadratic distance distance))))
(light-color (v! .9 .9 .9))
(radiance light-color attenuation)
pbr - cook - torrance brdf
(ndf (distribution-ggx n h roughness))
(g (geometry-smith n v l roughness))
(f (fresnel-schlick (max (dot h v) 0) f0))
(ks f)
(kd (* (- (vec3 1) ks)
(- 1 metallic)))
(numerator (* ndf g f))
(denominator (* (max (dot n v) 0)
(max (dot n l) 0)
4))
(specular (/ numerator (max denominator .001)))
(n-dot-l (max (dot n l) 0)))
(* (+ specular (/ (* kd color) +PI+))
radiance
n-dot-l)))
(defun-g billboard-vert ((pos :vec3)
&uniform
(time :float)
(world-view :mat4))
(* world-view (v! 0 -6 -50 1)))
(defun-g billboard-frag ((uv :vec2)
&uniform
(tex :sampler-2d)
(time :float))
(let* ((color (texture tex uv)))
(values color
(v! (x color) 0 0 (w color)))))
(defun-g billboard-geom (&uniform (camera-pos :vec3)
(view-clip :mat4))
(declare (output-primitive :kind :triangle-strip
:max-vertices 4))
(let* ((p (s~ (gl-position (aref gl-in 0)) :xyz))
(to-camera (normalize (- camera-pos p)))
(up (v! 0 1 0))
(right (cross to-camera up)))
(decf p (* 9 .5 right))
(emit ()
(* view-clip (v! p 1))
(v! 0 0))
(incf (y p) 9f0)
(emit ()
(* view-clip (v! p 1))
(v! 0 1))
(decf (y p) 9f0)
(incf p (* right 9))
(emit ()
(* view-clip (v! p 1))
(v! 1 0))
(incf (y p) 9f0)
(emit ()
(* view-clip (v! p 1))
(v! 1 1))
(end-primitive)
(values)))
(defpipeline-g billboard-pipe (:points)
:vertex (billboard-vert :vec3)
:geometry (billboard-geom)
:fragment (billboard-frag :vec2))
-atmosphere/
(defun-g rsi ((r0 :vec3)
(rd :vec3)
(sr :float))
(let* ((a (dot rd rd))
(b (* 2 (dot rd r0)))
(c (- (dot r0 r0) (* sr sr)))
(d (- (* b b) (* 4 a c))))
(if (< d 0)
(v! 100000 -100000)
(v! (/ (- (- b) (sqrt d))
(* 2 a))
(/ (+ (- b) (sqrt d))
(* 2 a))))))
vec3 pSun the position of the sun
float iSun intensity of the sun
vec3 scattering coefficient
vec3 scattering coefficient
float shRlh Rayleigh scale height in meters
float preferred scattering direction
(defun-g atmosphere ((r :vec3)
(r0 :vec3)
(p-sun :vec3)
(i-sun :float)
(r-planet :float)
(r-atmos :float)
(k-rlh :vec3)
(k-mie :float)
(sh-rlh :float)
(sh-mie :float)
(g :float)
(i-steps :uint)
(j-steps :uint))
(pi +PI+)
(p-sun (normalize p-sun))
(r (normalize r))
(p (rsi r0 r r-atmos)))
(if (> (x p) (y p))
(vec3 0f0)
(let* ((p (v! (x p)
(min (y p) (x (rsi r0 r r-planet)))))
(i-step-size (/ (- (y p) (x p))
i-steps))
Initialize the primary ray time .
(i-time 0f0)
Initialize accumulators for
Rayleigh and Mie scattering
(total-rlh (vec3 0f0))
(total-mie (vec3 0f0))
Initialize optical depth
(i-od-rlh 0f0)
(i-od-mie 0f0)
Calculate the Rayleigh
(mu (dot r p-sun))
(mumu (* mu mu))
(gg (* g g))
(p-rlh (* (/ 3 (* 16 pi))
(+ 1 mumu)))
(p-mie (/ (* (/ 3 (* 8 pi))
(* (- 1 gg) (+ 1 mumu)))
(* (pow (- (+ 1 gg) (* 2 mu g))
1.5)
(* 2 gg))))
(i 0))
(dotimes (i i-steps)
(i-pos (+ r0 (* r (+ i-time (* i-step-size .5)))))
(i-height (- (length i-pos) r-planet))
(od-step-rlh (* i-step-size (exp (/ (- i-height) sh-rlh))))
(od-step-mie (* i-step-size (exp (/ (- i-height) sh-mie)))))
(incf i-od-rlh od-step-rlh)
(incf i-od-mie od-step-mie)
(j-step-size (/ (y (rsi i-pos p-sun r-atmos)) j-steps))
Initialize the secondary ray time
(j-time 0f0)
Initialize optical depth accumulators for the sec ray
(j-od-rlh 0f0)
(j-od-mie 0f0))
(dotimes (j j-steps)
(j-pos (+ i-pos (* p-sun (+ j-time (* j-step-size .5)))))
(j-height (- (length j-pos) r-planet)))
(incf j-od-rlh (* j-step-size (exp (/ (- j-height) sh-rlh))))
(incf j-od-mie (* j-step-size (exp (/ (- j-height) sh-mie))))
(incf j-time j-step-size)))
(let ((attn (exp (- (+ (* k-mie (+ i-od-mie j-od-mie))
(* k-rlh (+ i-od-rlh j-od-rlh)))))))
(incf total-rlh (* od-step-rlh attn))
(incf total-mie (* od-step-mie attn))
(incf i-time i-step-size)))))
(* i-sun (+ (* p-rlh k-rlh total-rlh)
(* p-mie k-mie total-mie)))))))
(defun-g linear-eye-depth ((d :float))
(let* ((n .1)
(f 400f0)
(zz (/ (/ (- 1 (/ f n)) 2) f))
(zw (/ (/ (+ 1 (/ f n)) 2) f)))
(/ 1 (+ (* zz d) zw))))
(defun-g read-depth ((z :float))
(let* ((pfn (+ 400 .1))
(mfn (- 400 .1))
(coef (* 2f0 .1)))
(/ coef (- pfn (* z mfn)))))
its values will be above 1.0 and displayed as completely white . By
convert the linear depth value to roughly the range [ 0 , 1 ] . This
(defun-g linearize-depth ((depth :float))
(let* ((near 0.1)
(far 400f0)
(z (- (* depth 2.0) 1.0)))
(/ (* 2.0 (* near far))
(- (+ far near) (* z (- far near))))))
(defun-g view-zto-orthographic-depth ((view-z :float)
(near :float)
(far :float))
(/ (+ view-z near)
(- near far)))
(defun-g perspective-depth-to-view-z ((inv-clip-z :float)
(near :float)
(far :float))
(/ (* near far)
(- (* (- far near) inv-clip-z) far)))
(defun-g read-depth ((depth-sampler :sampler-2d)
(coord :vec2)
(camera-near :float)
(camera-far :float))
(let* ((frag-coord-z (x (texture depth-sampler coord)))
(view-z (perspective-depth-to-view-z frag-coord-z
camera-near
camera-far)))
(view-zto-orthographic-depth view-z camera-near camera-far)))
(defun-g fbm-hash ((p :vec2))
(fract
(* (sin (dot p (v! 41 289)))
45758.5453)))
(defun-g combine-god-frag ((uv :vec2)
&uniform
(sam-god :sampler-2d)
(sam :sampler-2d))
(let* ((color (mix (s~ (texture sam uv) :xyz)
(* *light-color* (s~ (texture sam-god uv) :xyz))
.1))
( color ( + ( s~ ( texture ) : xyz )
( * * light - color * ( s~ ( texture uv ) : xyz ) ) ) )
(ldr (nineveh.tonemapping:tone-map-reinhard color *exposure*))
(luma (rgb->luma-bt601 ldr)))
(v! ldr luma)))
(defpipeline-g combine-god-pipe (:points)
:fragment (combine-god-frag :vec2))
(defun-g god-rays-frag ((uv :vec2)
&uniform
(res :vec2)
(time :float)
(sun-pos :vec2)
(sam :sampler-2d))
( uv ( / ( s~ gl - frag - coord : xy ) res ) )
2f0 )
)
(uv uv)
(samples 10f0)
(decay .974)
(exposure .24)
(density .93)
(weight .36)
(color (s~ (texture sam uv) :xyz))
(occ (x color))
(obj (y color))
(dtc (* (- uv sun-pos)
(/ 1f0 samples)))
(illumdecay .4f0)
(dither (fbm-hash (+ uv (fract time)))))
(dotimes (i samples)
(decf uv dtc)
(let ((s (x (texture sam (+ (* dither dtc)
uv)))))
(multf s (* illumdecay weight))
(incf occ s)
(multf illumdecay decay)
))
(v! (+ (v! 0 0 0)
(* occ exposure))
1)
( vec4 occ )
))
by applying the Viewport transformation to it . window.x =
viewport.x + viewport.width * (
(defun screen-coord (res &optional (pos (v! 0 0 -10)))
(let* ((pos4 (v! pos 1))
(cpos4 (m4:*v (world->view *currentcamera*)
pos4))
(cpos4 (m4:*v (projection *currentcamera*)
cpos4))
(w (w cpos4))
(ndc (v4:/s cpos4 w)))
(v2:abs (v2:/ (v! (+ (* (x res) .5 (x ndc))
(+ (* (x res) .5 ) 0))
(+ (* (y res) .5 (y ndc))
(+ (* (y res) .5))))
res))
( v ! ( + ( * ( + 1 ( x ndc ) ) ( / ( x res ) 2 ) ) )
( + ( * ( + 1 ( ) ) ( / ( y res ) 2 ) ) ) )
screen.x = ( ( view.w * 0.5 ) * ndc.x ) +
( ( w * 0.5 ) + view.x )
screen.y = ( ( view.h * 0.5 ) * ndc.y ) +
( ( h * 0.5 ) + view.y )
( / ( + 1 ( x ndc ) ) 2 ) ) )
( / ( - 1 ( y ndc ) ) 2 ) ) ) )
( v ! 1 1 ) )
))
Pipeline to create a BRDF 2d lut
ON INIT :
( setf * f - brdf *
( make - fbo ( list 0 : element - type : rg16f : dimensions ' ( 512 512 ) ) ) )
( setf * t - brdf * ( attachment - tex * f - brdf * 0 ) )
( setf * s - brdf *
( cepl : sample * t - brdf * : wrap : clamp - to - edge
( unless * *
( setf * * T )
( setf ( resolution ( current - viewport ) ) ( v ! 512 512 ) )
(defun-g integrate-brdf ((n-dot-v :float)
(roughness :float))
term of the BRDF is slightly different when used alongside IBL as
(labels ((geometry-schlick-ggx ((n-dot-v :float)
(roughness :float))
(let* ((a roughness)
(k (/ (* a a) 2))
(nom n-dot-v)
(denom (+ k (* n-dot-v (- 1 k)))))
(/ nom denom)))
(geometry-smith ((n :vec3)
(v :vec3)
(l :vec3)
(roughness :float))
(let* ((n-dot-v (max (dot n v) 0))
(n-dot-l (max (dot n l) 0))
(ggx2 (geometry-schlick-ggx n-dot-v roughness))
(ggx1 (geometry-schlick-ggx n-dot-l roughness)))
(* ggx1 ggx2))))
(let* ((v (v! (sqrt (- 1 (* n-dot-v n-dot-v)))
0
n-dot-v))
(a 0f0)
(b 0f0)
(n (v! 0 0 1)))
(dotimes (i 1024)
(xi (hammersley-nth-2d 1024 i))
(h (importance-sample-ggx xi n roughness))
(l (normalize (+ (- v) (* 2 (dot v h) h))))
(n-dot-l (max (z l) 0))
(n-dot-h (max (z h) 0))
(v-dot-h (max (dot v h) 0)))
(when (> n-dot-l 0)
(let* ((g (geometry-smith n v l roughness))
(g-vis (/ (* g v-dot-h) (* n-dot-h n-dot-v)))
(fc (pow (- 1 v-dot-h) 5)))
(incf a (* (- 1 fc) g-vis))
(incf b (* fc g-vis))))))
(divf a 1024f0)
(divf b 1024f0)
(v! a b))))
(defun-g brdf-frag ((uv :vec2))
(integrate-brdf (x uv) (y uv)))
(defpipeline-g brdf-pipe (:points)
:fragment (brdf-frag :vec2))
(defun-g linear-01-depth ((z :float))
(let* ((far 400f0)
(near .1)
(z (* z (- 1 (/ far near)))))
(/ (+ z (/ far near)))))
PostProcessing / Shaders / StdLib.hlsl
PostProcessing / Shaders / Builtins / DeferredFog.shader
PostProcessing / Shaders / API / OpenGL.hlsl
PostProcessing / Shaders / Builtins / Fog.hlsl
(defun-g compute-fog-distance ((depth :float))
(let* ((far 400f0)
(near .1)
(dist (- (* depth far) near)))
dist))
(defun-g compute-fog-exp2 ((z :float)
(density :float))
(let* ((fog 0f0)
(fog (* density z))
(fog (exp2 (* (- fog) fog))))
(saturate fog)))
(defun-g defered-fog ((fog-color :vec3)
(uv :vec2)
(tex :sampler-2d)
(depth-tex :sampler-2d))
(let* ((color (s~ (texture tex uv) :xyz))
(depth (x (texture depth-tex uv)))
(depth (linear-01-depth depth))
(dist (compute-fog-distance depth))
(fog (- 1f0 (compute-fog-exp2 dist .1))))
(mix color fog-color fog)))
|
3652e624a435d8a43a65fab940f6b4ffb766803d8f2186f2a2c69cbba43ba320 | wdebeaum/step | yourselves.lisp | ;;;;
;;;; W::YOURSELVES
;;;;
(define-words :pos W::pro :boost-word t :templ PRONOUN-TEMPL
:tags (:base500)
:words (
(W::YOURSELVES
(wordfeats (W::agr W::2p) (W::stem W::you) (W::REFL +) (W::CASE W::OBJ))
(SENSES
((LF-PARENT ONT::PERSON)
(templ pronoun-plural-templ)
)
)
)
))
| null | https://raw.githubusercontent.com/wdebeaum/step/f38c07d9cd3a58d0e0183159d4445de9a0eafe26/src/LexiconManager/Data/new/yourselves.lisp | lisp |
W::YOURSELVES
|
(define-words :pos W::pro :boost-word t :templ PRONOUN-TEMPL
:tags (:base500)
:words (
(W::YOURSELVES
(wordfeats (W::agr W::2p) (W::stem W::you) (W::REFL +) (W::CASE W::OBJ))
(SENSES
((LF-PARENT ONT::PERSON)
(templ pronoun-plural-templ)
)
)
)
))
|
4ac5a5bf8fd2e72868ccf6c9460432e0298eb7b6dab3c47d8b81361ec05994ab | wireapp/wire-server | Cargohold.hs | -- This file is part of the Wire Server implementation.
--
Copyright ( C ) 2022 Wire Swiss GmbH < >
--
-- This program is free software: you can redistribute it and/or modify it under
the terms of the GNU Affero General Public License as published by the Free
Software Foundation , either version 3 of the License , or ( at your option ) any
-- later version.
--
-- This program is distributed in the hope that it will be useful, but WITHOUT
-- ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
-- details.
--
You should have received a copy of the GNU Affero General Public License along
-- with this program. If not, see </>.
module Wire.API.Routes.Internal.Cargohold where
import Control.Lens
import Data.Swagger
import Imports
import Servant
import Servant.Swagger
import Wire.API.Routes.MultiVerb
type InternalAPI =
"i"
:> "status"
:> MultiVerb 'GET '() '[RespondEmpty 200 "OK"] ()
swaggerDoc :: Swagger
swaggerDoc =
toSwagger (Proxy @InternalAPI)
& info . title .~ "Wire-Server internal cargohold API"
| null | https://raw.githubusercontent.com/wireapp/wire-server/1fcda9671f2b4cb8cb5574d9c9d9de5cf915b043/libs/wire-api/src/Wire/API/Routes/Internal/Cargohold.hs | haskell | This file is part of the Wire Server implementation.
This program is free software: you can redistribute it and/or modify it under
later version.
This program is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
details.
with this program. If not, see </>. | Copyright ( C ) 2022 Wire Swiss GmbH < >
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
You should have received a copy of the GNU Affero General Public License along
module Wire.API.Routes.Internal.Cargohold where
import Control.Lens
import Data.Swagger
import Imports
import Servant
import Servant.Swagger
import Wire.API.Routes.MultiVerb
type InternalAPI =
"i"
:> "status"
:> MultiVerb 'GET '() '[RespondEmpty 200 "OK"] ()
swaggerDoc :: Swagger
swaggerDoc =
toSwagger (Proxy @InternalAPI)
& info . title .~ "Wire-Server internal cargohold API"
|
f9158b4e3eb4ad6bbe0c788632ad7588b26dc51d9e032444b92d859c9c9c1ec7 | arrdem/stacks | pygmentize.clj | (ns stacks.tools.articles.middleware.pygmentize
"Article middleware for pygmentizing code blocks."
(:require [stacks.tools.articles :refer [handle-render-block]]
[stacks.tools.pygments :refer [lexers pygmentize]]))
(defonce +known-lexers+
(delay (set (lexers))))
(defn handle-render-pygmentize
"Article middleware.
Handle most code blocks by pygmentizing the content."
[middleware]
(fn [{:keys [tag attrs raw] :as node}]
(if (and (Boolean/parseBoolean (get attrs :highlight "true"))
(contains? @+known-lexers+ tag))
(pygmentize tag raw)
(middleware node))))
(comment
;; clj is known to pygments
((render-with-pygmentize handle-render-block)
{:type :shelving.tools.articles/code
:tag "clj"
:attrs {}
:raw "(def foo 1)\n"})
;; foo is not
((render-with-pygmentize handle-render-block)
{:type :shelving.tools.articles/code
:tag "foo"
:attrs {}
:raw "foo bar baz qux\n"}))
| null | https://raw.githubusercontent.com/arrdem/stacks/a16a7a6301e400c0c40c8774d07df0a86f9806f5/src/main/clj/stacks/tools/articles/middleware/pygmentize.clj | clojure | clj is known to pygments
foo is not | (ns stacks.tools.articles.middleware.pygmentize
"Article middleware for pygmentizing code blocks."
(:require [stacks.tools.articles :refer [handle-render-block]]
[stacks.tools.pygments :refer [lexers pygmentize]]))
(defonce +known-lexers+
(delay (set (lexers))))
(defn handle-render-pygmentize
"Article middleware.
Handle most code blocks by pygmentizing the content."
[middleware]
(fn [{:keys [tag attrs raw] :as node}]
(if (and (Boolean/parseBoolean (get attrs :highlight "true"))
(contains? @+known-lexers+ tag))
(pygmentize tag raw)
(middleware node))))
(comment
((render-with-pygmentize handle-render-block)
{:type :shelving.tools.articles/code
:tag "clj"
:attrs {}
:raw "(def foo 1)\n"})
((render-with-pygmentize handle-render-block)
{:type :shelving.tools.articles/code
:tag "foo"
:attrs {}
:raw "foo bar baz qux\n"}))
|
344fe51cf1789fb6501eddc17a35af7e4543bcdf8954a799f21c26cfad4471b0 | bhaskara/programmable-reinforcement-learning | maxq0-q-fn.lisp | (defpackage maxq0-q-function
(:documentation
"Package for defining MAXQ0 Q-functions and associated feature templates for concurrent ALisp programs.
Types
-----
<maxq0-q-function>
")
(:use
utils
calisp)
(:export
<maxq0-q-function>))
(in-package maxq0-q-function)
(defclass <maxq0-q-function> (<calisp-approx-q-function>)
((linear-fn-approx :initform (make-instance 'fn-approx:<linear-fn-approx>))
(tabular-fn-approx :initform (make-instance 'fn-approx:<tabular-fn-approx>))))
(defmethod update ((q-fn <maxq0-q-function>) omega u target eta)
(dolist (tid (get-thread-ids omega))
(update-linear-or-tabular (fn-approx q-fn) (featurize q-fn omega u tid) target eta)))
(defmethod update-tid ((q-fn <maxq0-q-function>) omega u target eta tid)
(update-linear-or-tabular (fn-approx q-fn) (featurize q-fn omega u tid) target eta))
(defmethod clone ((q-fn <maxq0-q-function>))
(make-instance '<maxq0-q-function> :fn-approx (clone (fn-approx q-fn))))
(defmethod evaluate ((q-fn <maxq0-q-function>) omega u)
(let ((sum 0))
(dolist (tid (get-thread-ids omega))
(let ((subtask (get-subtask tid omega)))
(setf sum (+ sum (car (evaluate-max-node omega tid subtask))))))))
(evaluate-linear-or-tabular (fn-approx q-fn) (featurize q-fn omega u tid)))
(defmethod evaluate-tid ((q-fn <maxq0-q-function>) omega u tid)
(evaluate-linear-or-tabular (fn-approx q-fn) (featurize q-fn omega u tid)))
(defmethod featurize ((q-fn <maxq0-q-function>) omega u thread-id)
(funcall (featurizer q-fn) omega (get-choice u thread-id) thread-id))
(defun get-thread-ids (omega)
(let ((list-of-ids nil))
(maphash (lambda(k v) (setf list-of-ids (append list-of-ids (list k)))) (js-thread-states omega)))
list-of-ids)
(defun get-choice (u tid)
(second (assoc-if #'(lambda(x) (= tid x)) u)))
(defun evaluate-max-node (omega tid subtask)
(if (primitive-subtask? subtask)
(cons (evaluate-linear-or-tabular (fn-approx q-fn) (featurize q-fn omega nil tid)) subtask)
(let ((children-subtasks (get-children-subtasks subtask)))
(let ((max-so-far (cons 0 nil)))
(dolist (j children-subtasks)
(let* ((recursive-evaluate (evaluate-max-node omega tid j))
(j-value (+ (car (recursive-evaluate)) (evaluate-linear-or-tabular (fn-approx q-fn) (featurize q-fn omega
(acons tid j '()) tid)))))
(if (> j-value (car max-so-far))
(setf max-so-far (cons j-value j))))))
max-so-far)))
(defun get-subtask (tid omega)
)
;; these are references into the hash table
(defun get-children-subtasks (subtask)
)
(defun primitive-subtask? (subtask)
)
;; TODO: Implement Featurizer, inform-env-step, and inform-end-choice-block
(defmethod update-linear-or-tabular ((q-fn <maxq0-q-function>) features target eta)
(if (equalp (car features) 'linear)
(fn-approx:update (linear-fn-approx q-fn) (cdr features) target eta)
(fn-approx:update (tabular-fn-approx q-fn) (cdr features) target eta)))
(defmethod evaluate-linear-or-tabular ((q-fn <maxq0-q-function) features)
(if (equalp (car features) 'linear)
(fn-approx:evaluate (linear-fn-approx q-fn) (cdr features))
(fn-approx:evaluate (tabular-fn-approx q-fn) (cdr features)))) | null | https://raw.githubusercontent.com/bhaskara/programmable-reinforcement-learning/8afc98116a8f78163b3f86076498d84b3f596217/lisp/envs/stratagus/resource/maxq0-q-fn.lisp | lisp | these are references into the hash table
TODO: Implement Featurizer, inform-env-step, and inform-end-choice-block | (defpackage maxq0-q-function
(:documentation
"Package for defining MAXQ0 Q-functions and associated feature templates for concurrent ALisp programs.
Types
-----
<maxq0-q-function>
")
(:use
utils
calisp)
(:export
<maxq0-q-function>))
(in-package maxq0-q-function)
(defclass <maxq0-q-function> (<calisp-approx-q-function>)
((linear-fn-approx :initform (make-instance 'fn-approx:<linear-fn-approx>))
(tabular-fn-approx :initform (make-instance 'fn-approx:<tabular-fn-approx>))))
(defmethod update ((q-fn <maxq0-q-function>) omega u target eta)
(dolist (tid (get-thread-ids omega))
(update-linear-or-tabular (fn-approx q-fn) (featurize q-fn omega u tid) target eta)))
(defmethod update-tid ((q-fn <maxq0-q-function>) omega u target eta tid)
(update-linear-or-tabular (fn-approx q-fn) (featurize q-fn omega u tid) target eta))
(defmethod clone ((q-fn <maxq0-q-function>))
(make-instance '<maxq0-q-function> :fn-approx (clone (fn-approx q-fn))))
(defmethod evaluate ((q-fn <maxq0-q-function>) omega u)
(let ((sum 0))
(dolist (tid (get-thread-ids omega))
(let ((subtask (get-subtask tid omega)))
(setf sum (+ sum (car (evaluate-max-node omega tid subtask))))))))
(evaluate-linear-or-tabular (fn-approx q-fn) (featurize q-fn omega u tid)))
(defmethod evaluate-tid ((q-fn <maxq0-q-function>) omega u tid)
(evaluate-linear-or-tabular (fn-approx q-fn) (featurize q-fn omega u tid)))
(defmethod featurize ((q-fn <maxq0-q-function>) omega u thread-id)
(funcall (featurizer q-fn) omega (get-choice u thread-id) thread-id))
(defun get-thread-ids (omega)
(let ((list-of-ids nil))
(maphash (lambda(k v) (setf list-of-ids (append list-of-ids (list k)))) (js-thread-states omega)))
list-of-ids)
(defun get-choice (u tid)
(second (assoc-if #'(lambda(x) (= tid x)) u)))
(defun evaluate-max-node (omega tid subtask)
(if (primitive-subtask? subtask)
(cons (evaluate-linear-or-tabular (fn-approx q-fn) (featurize q-fn omega nil tid)) subtask)
(let ((children-subtasks (get-children-subtasks subtask)))
(let ((max-so-far (cons 0 nil)))
(dolist (j children-subtasks)
(let* ((recursive-evaluate (evaluate-max-node omega tid j))
(j-value (+ (car (recursive-evaluate)) (evaluate-linear-or-tabular (fn-approx q-fn) (featurize q-fn omega
(acons tid j '()) tid)))))
(if (> j-value (car max-so-far))
(setf max-so-far (cons j-value j))))))
max-so-far)))
(defun get-subtask (tid omega)
)
(defun get-children-subtasks (subtask)
)
(defun primitive-subtask? (subtask)
)
(defmethod update-linear-or-tabular ((q-fn <maxq0-q-function>) features target eta)
(if (equalp (car features) 'linear)
(fn-approx:update (linear-fn-approx q-fn) (cdr features) target eta)
(fn-approx:update (tabular-fn-approx q-fn) (cdr features) target eta)))
(defmethod evaluate-linear-or-tabular ((q-fn <maxq0-q-function) features)
(if (equalp (car features) 'linear)
(fn-approx:evaluate (linear-fn-approx q-fn) (cdr features))
(fn-approx:evaluate (tabular-fn-approx q-fn) (cdr features)))) |
e01ce379d23e9f86f276620aeb3978a24e9cece0bbf1bfacf3d653d35ce2e505 | brownplt/TeJaS | typeScript_types.ml | open Prelude
open Sig
open TypeScript_sigs
open Strobe_sigs
module Make : TYPESCRIPT_TYP = functor (STROBE : TYPS) ->
struct
type baseKind = STROBE.kind
type kind =
(* and anything new... *)
| KStrobe of baseKind
type baseTyp = STROBE.typ
type typ =
| TStrobe of baseTyp
| TArrow of typ list * typ option * typ
type baseBinding = STROBE.binding
type binding =
(* and anything new... *)
| BStrobe of baseBinding
type env = binding list IdMap.t
end
module MakeActions
(Strobe : STROBE_ACTIONS)
(TypeScript : TYPESCRIPT_TYPS
with type baseTyp = Strobe.typ
with type baseKind = Strobe.kind
with type baseBinding = Strobe.binding
with type typ = Strobe.extTyp
with type kind = Strobe.extKind
with type binding = Strobe.extBinding
with type env = Strobe.env)
: (TYPESCRIPT_ACTIONS
with type typ = TypeScript.typ
with type kind = TypeScript.kind
with type binding = TypeScript.binding
with type baseTyp = TypeScript.baseTyp
with type baseKind = TypeScript.baseKind
with type baseBinding = TypeScript.baseBinding
with type env = TypeScript.env) =
struct
include TypeScript
open TypeScript
let rec embed_t t =
match t with
| Strobe.TEmbed (TStrobe t) -> embed_t t
| Strobe.TEmbed t -> t
| t -> TStrobe t
let rec embed_k k =
match k with Strobe.KEmbed (KStrobe k) -> embed_k k | k -> KStrobe k
let rec embed_b b =
match b with Strobe.BEmbed (BStrobe b) -> embed_b b | b -> BStrobe b
let rec extract_t t =
match t with
| TStrobe (Strobe.TEmbed t) -> extract_t t
| TStrobe t -> t
| t -> Strobe.TEmbed t
let rec extract_k k =
match k with KStrobe (Strobe.KEmbed k) -> extract_k k | KStrobe k -> k
let rec extract_b b =
match b with BStrobe (Strobe.BEmbed b) -> extract_b b | BStrobe b -> b
let rec unwrap_bt t =
match t with Strobe.TEmbed (TStrobe t) -> unwrap_bt t | _ -> t
let rec unwrap_bk k =
match k with Strobe.KEmbed (KStrobe k) -> unwrap_bk k | _ -> k
let rec unwrap_bb b =
match b with Strobe.BEmbed (BStrobe b) -> unwrap_bb b | _ -> b
let rec unwrap_t t =
match t with
| TStrobe (Strobe.TEmbed t) -> unwrap_t t
| TStrobe (Strobe.TUninit inner) -> begin
match !inner with
| None -> t
| Some t' -> embed_t t'
end
| _ -> t
let rec unwrap_k k =
match k with KStrobe (Strobe.KEmbed k) -> unwrap_k k | _ -> k
let rec unwrap_b b =
match b with BStrobe (Strobe.BEmbed b) -> unwrap_b b | _ -> b
let rec simpl_typ env typ =
match typ with
| TStrobe t -> embed_t (Strobe.simpl_typ env (extract_t typ))
| _ -> typ
let mapopt f t = match t with None -> None | Some t -> Some (f t)
let expose_twith env t =
let rec squash_s t =
let open Strobe in
match t with
| TWith _ -> Strobe.simpl_typ env t
| TRef (n, t) -> TRef (n, squash_s t)
| TSource (n, t) -> TSource (n, squash_s t)
| TSink (n, t) -> TSink (n, squash_s t)
| TUnion (n, t1, t2) -> TUnion(n, squash_s t1, squash_s t2)
| TInter(n, t1, t2) -> TInter(n, squash_s t1, squash_s t2)
| TArrow(args, vararg, ret) -> TArrow(map squash_s args, mapopt squash_s vararg, squash_s ret)
| TObject ot -> TObject (mk_obj_typ (map (third3 squash_s) (fields ot)) (absent_pat ot))
| TTop
| TBot -> t
| TForall(n, id, t, b) -> TForall(n, id, squash_s t, squash_s b)
| TId _
| TRegex _
| TPrim _ -> t
| TThis t -> TThis (squash_s t)
| TRec(n, id, t) -> TRec(n, id, squash_s t)
| TLambda (n, args, t) -> TLambda(n, args, squash_s t)
| TApp(t, ts) -> TApp(squash_s t, map squash_s ts)
| TFix(n, id, k, t) -> TFix(n, id, k, squash_s t)
| TUninit ty -> ty := mapopt squash_s !ty; t
| TEmbed t -> extract_t (squash_t t)
and squash_t t = match t with
| TStrobe t -> embed_t (squash_s t)
| TArrow(args, vararg, ret) -> TArrow(map squash_t args, mapopt squash_t vararg, squash_t ret)
in squash_t t
let assoc_merge = IdMap.merge (fun x opt_s opt_t -> match opt_s, opt_t with
| Some (BStrobe (Strobe.BTermTyp (Strobe.TId y))),
Some (BStrobe (Strobe.BTermTyp (Strobe.TId z))) ->
if x = y then opt_t else opt_s
| Some t, _
| _, Some t ->
Some t
| None, None -> None)
let rec typ_assoc env t1 t2 = typ_assoc' env t1 t2
(* trace "TypeScript:typ_assoc" *)
(* (Pretty.simpl_typ t1 ^ " with " ^ Pretty.simpl_typ t2) *)
(* (fun _ -> true) (fun () -> (typ_assoc' add merge env t1 t2)) *)
and typ_assoc' (env : env) (t1 : typ) (t2 : typ) =
let add_strobe x t m =
IdMap.add x (embed_b (Strobe.BTermTyp t)) m in
match t1, t2 with
| TStrobe s, TStrobe t ->
Strobe.typ_assoc add_strobe assoc_merge env s t
| TArrow (args1, v1, r1), TArrow (args2, v2, r2) ->
List.fold_left assoc_merge
((fun base -> match v1, v2 with
| Some v1, Some v2 -> assoc_merge (typ_assoc env v1 v2) base
| _ -> base)
(typ_assoc env r1 r2))
(ListExt.map2_noerr (typ_assoc env) args1 args2)
| _ -> IdMap.empty
module Pretty = struct
open Format
open FormatExt
let useNames, shouldUseNames =
let _useNames = ref true in
let useNames b = _useNames := b; Strobe.Pretty.useNames b in
let shouldUseNames () = !_useNames in
useNames, shouldUseNames
let kind k = match k with
| KStrobe k ->
(if shouldUseNames ()
then squish
else label_angles "KSTROBE" cut) [Strobe.Pretty.kind k]
let rec typ t = typ' false t
and typ' horzOnly t =
let typ = typ' horzOnly in
let hnestOrHorz n = if horzOnly then horz else (fun ps -> hnest n (squish ps)) in
match t with
| TStrobe t ->
(if shouldUseNames ()
then squish
else label_angles "STROBE" cut) [Strobe.Pretty.typ t]
| TArrow (tt::arg_typs, varargs, r_typ) ->
let multiLine = horzOnly ||
List.exists (fun at -> match extract_t at with
Strobe.TEmbed (TArrow _) | Strobe.TObject _ -> true | _ -> false) arg_typs in
let rec pairOff ls = match ls with
| [] -> []
| [_] -> ls
| a::b::ls -> horz [a;b] :: pairOff ls in
let vararg = match varargs with
| None -> []
| Some t -> [horz[squish [parens[horz[typ' true t]]; text "..."]]] in
let argTexts =
(intersperse (text "*")
((map (fun at -> begin match at with
| TArrow _ -> parens [horz [typ' true at]]
| _ -> typ' true at
end) arg_typs) @ vararg)) in
hnestOrHorz 0
[ squish [brackets [typ tt];
(if multiLine
then vert (pairOff (text " " :: argTexts))
else horz (empty::argTexts))] ;
horz [text "->"; typ r_typ ]]
| TArrow (arg_typs, varargs, r_typ) ->
let vararg = match varargs with
| None -> []
| Some t -> [horz[squish [parens[horz[typ' true t]]; text "..."]]] in
let argText = horz (intersperse (text "*")
((map (fun at -> begin match at with
| TArrow _ -> parens [horz [typ' true at]]
| _ -> typ' true at
end) arg_typs) @ vararg)) in
hnestOrHorz 0 [ argText; horz [text "->"; typ r_typ ]]
let env e = [empty]
let rec simpl_typ typ = match typ with
| TStrobe t -> "TSTROBE(" ^ (Strobe.Pretty.simpl_typ t) ^ ")"
| TArrow _ -> "_ -> _"
and simpl_kind k = FormatExt.to_string kind k
end
let string_of_typ = FormatExt.to_string Pretty.typ
let string_of_kind = FormatExt.to_string Pretty.kind
let apply_name n typ = match typ with
| TStrobe t -> embed_t (Strobe.apply_name n t)
| TArrow _ -> typ
let name_of typ = match typ with
| TStrobe t -> Strobe.name_of t
| TArrow _ -> None
let replace_name n typ = match typ with
| TStrobe t -> embed_t (Strobe.replace_name n t)
| TArrow _ -> typ
(* substitute x FOR s IN t *)
let rec typ_subst x s t =
let typ_help = typ_subst x s in
match t with
| TStrobe tstrobe -> begin
let subst_t =
embed_t (Strobe.subst (Some x) (extract_t s) typ_help tstrobe)
in unwrap_t subst_t
end
| TArrow(args, varargs, ret) -> TArrow(map typ_help args, mapopt typ_help varargs, typ_help ret)
let rec free_ids typ =
let open IdSet in
let open IdSetExt in
match typ with
| TStrobe t -> Strobe.free_ids t
| TArrow (ss, v, t) ->
unions (free_ids t :: (match v with None -> empty | Some v -> free_ids v) :: (map free_ids ss))
let rec equivalent_typ env t1 t2 = match t1, t2 with
| TStrobe (Strobe.TEmbed t1), _ -> equivalent_typ env t1 t2
| _, TStrobe (Strobe.TEmbed t2) -> equivalent_typ env t1 t2
| TStrobe t1, TStrobe t2 -> Strobe.equivalent_typ env t1 t2
| TArrow (args1, v1, r1), TArrow (args2, v2, r2) ->
List.length args1 = List.length args2
&& List.for_all2 (equivalent_typ env) args1 args2
&& equivalent_typ env r1 r2
&& (match v1, v2 with
| None, None -> true
| Some v1, Some v2 -> equivalent_typ env v1 v2
| _ -> false)
| _ -> false
let rec rename_avoid_capture (free : IdSet.t) (ys : id list) (t : typ) =
let fresh_var old = (* a, b, ... z, aa, bb, ..., zz, ... *)
let rec try_ascii m n =
let attempt = String.make m (Char.chr n) in
if not (List.mem attempt old) then attempt
else if (n < int_of_char 'z') then try_ascii m (n+1)
else try_ascii (m+1) (Char.code 'a') in
try_ascii 1 (Char.code 'a') in
let (rev_new_ys, substs) =
List.fold_left (fun (new_ys, substs) y ->
if not (IdSet.mem y free) then (y::new_ys, substs)
else
let x = fresh_var ((IdMapExt.keys substs) @ IdSetExt.to_list free) in
(x::new_ys, IdMap.add y (embed_t (Strobe.TId x)) substs))
([], IdMap.empty) ys in
let new_ys = List.rev rev_new_ys in
let t' = IdMap.fold typ_subst substs t in
(new_ys, t')
let rec canonical_type typ =
let c = canonical_type in
let c'' t = c (embed_t t) in
let c' t = extract_t (c'' t) in
match unwrap_t typ with
| TStrobe(Strobe.TUnion (n, _, _)) -> begin
let rec collect t = match unwrap_t t with
| TStrobe(Strobe.TUnion (_, t1, t2)) -> collect (c (embed_t t1)) @ collect (c (embed_t t2))
| TStrobe(Strobe.TEmbed t) -> failwith "impossible: embed_t should've removed this case"
| TStrobe t -> [unwrap_bt t]
| _ -> [extract_t t] in
let pieces = collect typ in
let nodups = ListExt.remove_dups pieces in
match List.rev nodups with
| [] -> failwith "impossible, 008"
| hd::tl ->
embed_t (Strobe.apply_name n (List.fold_left (fun acc t ->
if t = Strobe.TBot
then acc
else Strobe.TUnion(None, t, acc)) hd tl))
end
| TStrobe(Strobe.TInter (n, t1, t2)) -> begin
match unwrap_bt t1, unwrap_bt t2 with
| Strobe.TUnion (_, u1, u2), t -> c'' (Strobe.TUnion (n, c' (Strobe.TInter (None, u1, t)), c' (Strobe.TInter (None, u2, t))))
| t, Strobe.TUnion (_, u1, u2) -> c'' (Strobe.TUnion (n, c' (Strobe.TInter (None, t, u1)), c' (Strobe.TInter (None, t, u2))))
| t1, t2 -> match Strobe.canonical_type t1, Strobe.canonical_type t2 with
| Strobe.TTop, t
| t, Strobe.TTop -> begin match t with
| Strobe.TEmbed t -> unwrap_t t
| t -> embed_t t
end
| Strobe.TBot, _
| _, Strobe.TBot -> embed_t Strobe.TBot
Prims are unique
| t1, t2 -> if t1 = t2 then embed_t t1 else embed_t (Strobe.TInter(n, t1, t2))
end
| TStrobe t -> begin
match Strobe.canonical_type t with
| Strobe.TEmbed t -> t
| t -> embed_t t
end
| TArrow (args, var, ret) -> TArrow (map c args, mapopt c var, c ret)
if you have special - purpose type constructors that would
be nice to un - expand , try to politely do so here , otherwise
do n't bother , and just be the identity function
be nice to un-expand, try to politely do so here, otherwise
don't bother, and just be the identity function *)
let collapse_if_possible env typ = typ
end
module MakeModule
(Strobe : STROBE_MODULE)
(TypeScript : TYPESCRIPT_ACTIONS
with type baseTyp = Strobe.typ
with type baseKind = Strobe.kind
with type baseBinding = Strobe.binding
with type typ = Strobe.extTyp
with type kind = Strobe.extKind
with type binding = Strobe.extBinding
with type env = Strobe.env)
: (TYPESCRIPT_MODULE
with type baseTyp = Strobe.typ
with type baseKind = Strobe.kind
with type baseBinding = Strobe.binding
with type typ = Strobe.extTyp
with type kind = Strobe.extKind
with type binding = Strobe.extBinding
with type env = Strobe.env
with module Strobe = Strobe) =
struct
include TypeScript
module Strobe = Strobe
end
| null | https://raw.githubusercontent.com/brownplt/TeJaS/a8ad7e5e9ad938db205074469bbde6a688ec913e/src/typescript/typeScript_types.ml | ocaml | and anything new...
and anything new...
trace "TypeScript:typ_assoc"
(Pretty.simpl_typ t1 ^ " with " ^ Pretty.simpl_typ t2)
(fun _ -> true) (fun () -> (typ_assoc' add merge env t1 t2))
substitute x FOR s IN t
a, b, ... z, aa, bb, ..., zz, ... | open Prelude
open Sig
open TypeScript_sigs
open Strobe_sigs
module Make : TYPESCRIPT_TYP = functor (STROBE : TYPS) ->
struct
type baseKind = STROBE.kind
type kind =
| KStrobe of baseKind
type baseTyp = STROBE.typ
type typ =
| TStrobe of baseTyp
| TArrow of typ list * typ option * typ
type baseBinding = STROBE.binding
type binding =
| BStrobe of baseBinding
type env = binding list IdMap.t
end
module MakeActions
(Strobe : STROBE_ACTIONS)
(TypeScript : TYPESCRIPT_TYPS
with type baseTyp = Strobe.typ
with type baseKind = Strobe.kind
with type baseBinding = Strobe.binding
with type typ = Strobe.extTyp
with type kind = Strobe.extKind
with type binding = Strobe.extBinding
with type env = Strobe.env)
: (TYPESCRIPT_ACTIONS
with type typ = TypeScript.typ
with type kind = TypeScript.kind
with type binding = TypeScript.binding
with type baseTyp = TypeScript.baseTyp
with type baseKind = TypeScript.baseKind
with type baseBinding = TypeScript.baseBinding
with type env = TypeScript.env) =
struct
include TypeScript
open TypeScript
let rec embed_t t =
match t with
| Strobe.TEmbed (TStrobe t) -> embed_t t
| Strobe.TEmbed t -> t
| t -> TStrobe t
let rec embed_k k =
match k with Strobe.KEmbed (KStrobe k) -> embed_k k | k -> KStrobe k
let rec embed_b b =
match b with Strobe.BEmbed (BStrobe b) -> embed_b b | b -> BStrobe b
let rec extract_t t =
match t with
| TStrobe (Strobe.TEmbed t) -> extract_t t
| TStrobe t -> t
| t -> Strobe.TEmbed t
let rec extract_k k =
match k with KStrobe (Strobe.KEmbed k) -> extract_k k | KStrobe k -> k
let rec extract_b b =
match b with BStrobe (Strobe.BEmbed b) -> extract_b b | BStrobe b -> b
let rec unwrap_bt t =
match t with Strobe.TEmbed (TStrobe t) -> unwrap_bt t | _ -> t
let rec unwrap_bk k =
match k with Strobe.KEmbed (KStrobe k) -> unwrap_bk k | _ -> k
let rec unwrap_bb b =
match b with Strobe.BEmbed (BStrobe b) -> unwrap_bb b | _ -> b
let rec unwrap_t t =
match t with
| TStrobe (Strobe.TEmbed t) -> unwrap_t t
| TStrobe (Strobe.TUninit inner) -> begin
match !inner with
| None -> t
| Some t' -> embed_t t'
end
| _ -> t
let rec unwrap_k k =
match k with KStrobe (Strobe.KEmbed k) -> unwrap_k k | _ -> k
let rec unwrap_b b =
match b with BStrobe (Strobe.BEmbed b) -> unwrap_b b | _ -> b
let rec simpl_typ env typ =
match typ with
| TStrobe t -> embed_t (Strobe.simpl_typ env (extract_t typ))
| _ -> typ
let mapopt f t = match t with None -> None | Some t -> Some (f t)
let expose_twith env t =
let rec squash_s t =
let open Strobe in
match t with
| TWith _ -> Strobe.simpl_typ env t
| TRef (n, t) -> TRef (n, squash_s t)
| TSource (n, t) -> TSource (n, squash_s t)
| TSink (n, t) -> TSink (n, squash_s t)
| TUnion (n, t1, t2) -> TUnion(n, squash_s t1, squash_s t2)
| TInter(n, t1, t2) -> TInter(n, squash_s t1, squash_s t2)
| TArrow(args, vararg, ret) -> TArrow(map squash_s args, mapopt squash_s vararg, squash_s ret)
| TObject ot -> TObject (mk_obj_typ (map (third3 squash_s) (fields ot)) (absent_pat ot))
| TTop
| TBot -> t
| TForall(n, id, t, b) -> TForall(n, id, squash_s t, squash_s b)
| TId _
| TRegex _
| TPrim _ -> t
| TThis t -> TThis (squash_s t)
| TRec(n, id, t) -> TRec(n, id, squash_s t)
| TLambda (n, args, t) -> TLambda(n, args, squash_s t)
| TApp(t, ts) -> TApp(squash_s t, map squash_s ts)
| TFix(n, id, k, t) -> TFix(n, id, k, squash_s t)
| TUninit ty -> ty := mapopt squash_s !ty; t
| TEmbed t -> extract_t (squash_t t)
and squash_t t = match t with
| TStrobe t -> embed_t (squash_s t)
| TArrow(args, vararg, ret) -> TArrow(map squash_t args, mapopt squash_t vararg, squash_t ret)
in squash_t t
let assoc_merge = IdMap.merge (fun x opt_s opt_t -> match opt_s, opt_t with
| Some (BStrobe (Strobe.BTermTyp (Strobe.TId y))),
Some (BStrobe (Strobe.BTermTyp (Strobe.TId z))) ->
if x = y then opt_t else opt_s
| Some t, _
| _, Some t ->
Some t
| None, None -> None)
let rec typ_assoc env t1 t2 = typ_assoc' env t1 t2
and typ_assoc' (env : env) (t1 : typ) (t2 : typ) =
let add_strobe x t m =
IdMap.add x (embed_b (Strobe.BTermTyp t)) m in
match t1, t2 with
| TStrobe s, TStrobe t ->
Strobe.typ_assoc add_strobe assoc_merge env s t
| TArrow (args1, v1, r1), TArrow (args2, v2, r2) ->
List.fold_left assoc_merge
((fun base -> match v1, v2 with
| Some v1, Some v2 -> assoc_merge (typ_assoc env v1 v2) base
| _ -> base)
(typ_assoc env r1 r2))
(ListExt.map2_noerr (typ_assoc env) args1 args2)
| _ -> IdMap.empty
module Pretty = struct
open Format
open FormatExt
let useNames, shouldUseNames =
let _useNames = ref true in
let useNames b = _useNames := b; Strobe.Pretty.useNames b in
let shouldUseNames () = !_useNames in
useNames, shouldUseNames
let kind k = match k with
| KStrobe k ->
(if shouldUseNames ()
then squish
else label_angles "KSTROBE" cut) [Strobe.Pretty.kind k]
let rec typ t = typ' false t
and typ' horzOnly t =
let typ = typ' horzOnly in
let hnestOrHorz n = if horzOnly then horz else (fun ps -> hnest n (squish ps)) in
match t with
| TStrobe t ->
(if shouldUseNames ()
then squish
else label_angles "STROBE" cut) [Strobe.Pretty.typ t]
| TArrow (tt::arg_typs, varargs, r_typ) ->
let multiLine = horzOnly ||
List.exists (fun at -> match extract_t at with
Strobe.TEmbed (TArrow _) | Strobe.TObject _ -> true | _ -> false) arg_typs in
let rec pairOff ls = match ls with
| [] -> []
| [_] -> ls
| a::b::ls -> horz [a;b] :: pairOff ls in
let vararg = match varargs with
| None -> []
| Some t -> [horz[squish [parens[horz[typ' true t]]; text "..."]]] in
let argTexts =
(intersperse (text "*")
((map (fun at -> begin match at with
| TArrow _ -> parens [horz [typ' true at]]
| _ -> typ' true at
end) arg_typs) @ vararg)) in
hnestOrHorz 0
[ squish [brackets [typ tt];
(if multiLine
then vert (pairOff (text " " :: argTexts))
else horz (empty::argTexts))] ;
horz [text "->"; typ r_typ ]]
| TArrow (arg_typs, varargs, r_typ) ->
let vararg = match varargs with
| None -> []
| Some t -> [horz[squish [parens[horz[typ' true t]]; text "..."]]] in
let argText = horz (intersperse (text "*")
((map (fun at -> begin match at with
| TArrow _ -> parens [horz [typ' true at]]
| _ -> typ' true at
end) arg_typs) @ vararg)) in
hnestOrHorz 0 [ argText; horz [text "->"; typ r_typ ]]
let env e = [empty]
let rec simpl_typ typ = match typ with
| TStrobe t -> "TSTROBE(" ^ (Strobe.Pretty.simpl_typ t) ^ ")"
| TArrow _ -> "_ -> _"
and simpl_kind k = FormatExt.to_string kind k
end
let string_of_typ = FormatExt.to_string Pretty.typ
let string_of_kind = FormatExt.to_string Pretty.kind
let apply_name n typ = match typ with
| TStrobe t -> embed_t (Strobe.apply_name n t)
| TArrow _ -> typ
let name_of typ = match typ with
| TStrobe t -> Strobe.name_of t
| TArrow _ -> None
let replace_name n typ = match typ with
| TStrobe t -> embed_t (Strobe.replace_name n t)
| TArrow _ -> typ
let rec typ_subst x s t =
let typ_help = typ_subst x s in
match t with
| TStrobe tstrobe -> begin
let subst_t =
embed_t (Strobe.subst (Some x) (extract_t s) typ_help tstrobe)
in unwrap_t subst_t
end
| TArrow(args, varargs, ret) -> TArrow(map typ_help args, mapopt typ_help varargs, typ_help ret)
let rec free_ids typ =
let open IdSet in
let open IdSetExt in
match typ with
| TStrobe t -> Strobe.free_ids t
| TArrow (ss, v, t) ->
unions (free_ids t :: (match v with None -> empty | Some v -> free_ids v) :: (map free_ids ss))
let rec equivalent_typ env t1 t2 = match t1, t2 with
| TStrobe (Strobe.TEmbed t1), _ -> equivalent_typ env t1 t2
| _, TStrobe (Strobe.TEmbed t2) -> equivalent_typ env t1 t2
| TStrobe t1, TStrobe t2 -> Strobe.equivalent_typ env t1 t2
| TArrow (args1, v1, r1), TArrow (args2, v2, r2) ->
List.length args1 = List.length args2
&& List.for_all2 (equivalent_typ env) args1 args2
&& equivalent_typ env r1 r2
&& (match v1, v2 with
| None, None -> true
| Some v1, Some v2 -> equivalent_typ env v1 v2
| _ -> false)
| _ -> false
let rec rename_avoid_capture (free : IdSet.t) (ys : id list) (t : typ) =
let rec try_ascii m n =
let attempt = String.make m (Char.chr n) in
if not (List.mem attempt old) then attempt
else if (n < int_of_char 'z') then try_ascii m (n+1)
else try_ascii (m+1) (Char.code 'a') in
try_ascii 1 (Char.code 'a') in
let (rev_new_ys, substs) =
List.fold_left (fun (new_ys, substs) y ->
if not (IdSet.mem y free) then (y::new_ys, substs)
else
let x = fresh_var ((IdMapExt.keys substs) @ IdSetExt.to_list free) in
(x::new_ys, IdMap.add y (embed_t (Strobe.TId x)) substs))
([], IdMap.empty) ys in
let new_ys = List.rev rev_new_ys in
let t' = IdMap.fold typ_subst substs t in
(new_ys, t')
let rec canonical_type typ =
let c = canonical_type in
let c'' t = c (embed_t t) in
let c' t = extract_t (c'' t) in
match unwrap_t typ with
| TStrobe(Strobe.TUnion (n, _, _)) -> begin
let rec collect t = match unwrap_t t with
| TStrobe(Strobe.TUnion (_, t1, t2)) -> collect (c (embed_t t1)) @ collect (c (embed_t t2))
| TStrobe(Strobe.TEmbed t) -> failwith "impossible: embed_t should've removed this case"
| TStrobe t -> [unwrap_bt t]
| _ -> [extract_t t] in
let pieces = collect typ in
let nodups = ListExt.remove_dups pieces in
match List.rev nodups with
| [] -> failwith "impossible, 008"
| hd::tl ->
embed_t (Strobe.apply_name n (List.fold_left (fun acc t ->
if t = Strobe.TBot
then acc
else Strobe.TUnion(None, t, acc)) hd tl))
end
| TStrobe(Strobe.TInter (n, t1, t2)) -> begin
match unwrap_bt t1, unwrap_bt t2 with
| Strobe.TUnion (_, u1, u2), t -> c'' (Strobe.TUnion (n, c' (Strobe.TInter (None, u1, t)), c' (Strobe.TInter (None, u2, t))))
| t, Strobe.TUnion (_, u1, u2) -> c'' (Strobe.TUnion (n, c' (Strobe.TInter (None, t, u1)), c' (Strobe.TInter (None, t, u2))))
| t1, t2 -> match Strobe.canonical_type t1, Strobe.canonical_type t2 with
| Strobe.TTop, t
| t, Strobe.TTop -> begin match t with
| Strobe.TEmbed t -> unwrap_t t
| t -> embed_t t
end
| Strobe.TBot, _
| _, Strobe.TBot -> embed_t Strobe.TBot
Prims are unique
| t1, t2 -> if t1 = t2 then embed_t t1 else embed_t (Strobe.TInter(n, t1, t2))
end
| TStrobe t -> begin
match Strobe.canonical_type t with
| Strobe.TEmbed t -> t
| t -> embed_t t
end
| TArrow (args, var, ret) -> TArrow (map c args, mapopt c var, c ret)
if you have special - purpose type constructors that would
be nice to un - expand , try to politely do so here , otherwise
do n't bother , and just be the identity function
be nice to un-expand, try to politely do so here, otherwise
don't bother, and just be the identity function *)
let collapse_if_possible env typ = typ
end
module MakeModule
(Strobe : STROBE_MODULE)
(TypeScript : TYPESCRIPT_ACTIONS
with type baseTyp = Strobe.typ
with type baseKind = Strobe.kind
with type baseBinding = Strobe.binding
with type typ = Strobe.extTyp
with type kind = Strobe.extKind
with type binding = Strobe.extBinding
with type env = Strobe.env)
: (TYPESCRIPT_MODULE
with type baseTyp = Strobe.typ
with type baseKind = Strobe.kind
with type baseBinding = Strobe.binding
with type typ = Strobe.extTyp
with type kind = Strobe.extKind
with type binding = Strobe.extBinding
with type env = Strobe.env
with module Strobe = Strobe) =
struct
include TypeScript
module Strobe = Strobe
end
|
d14c82128facbff27cca2a5962e4291f9baece3cf788468605b015714458d493 | hemmi/coq2scala | coqc.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 *)
(************************************************************************)
Afin de rendre Coq plus portable , ce programme remplace le script
coqc .
Ici , on trie la ligne de commande pour en extraire les fichiers à compiler ,
puis on les compile un par un en passant le reste de la ligne de commande
à un process " coqtop -batch -load - vernac - source < fichier > " .
On essaye au maximum d'utiliser les modules et Filename pour que la
portabilité soit maximale , des appels à des fonctions
du module Unix . Ceux - ci sont préfixés par " Unix . "
coqc.
Ici, on trie la ligne de commande pour en extraire les fichiers à compiler,
puis on les compile un par un en passant le reste de la ligne de commande
à un process "coqtop -batch -load-vernac-source <fichier>".
On essaye au maximum d'utiliser les modules Sys et Filename pour que la
portabilité soit maximale, mais il reste encore des appels à des fonctions
du module Unix. Ceux-ci sont préfixés par "Unix."
*)
(* environment *)
let environment = Unix.environment ()
let best = if Coq_config.arch = "win32" then "" else ("."^Coq_config.best)
let binary = ref ("coqtop" ^ best)
let image = ref ""
(* coqc options *)
let verbose = ref false
Verifies that a string starts by a letter and do not contain
others caracters than letters , digits , or ` _ `
others caracters than letters, digits, or `_` *)
let check_module_name s =
let err c =
output_string stderr "Invalid module name: ";
output_string stderr s;
output_string stderr " character ";
if c = '\'' then
output_string stderr "\"'\""
else
(output_string stderr"'"; output_char stderr c; output_string stderr"'");
output_string stderr " is not allowed in module names\n";
exit 1
in
match String.get s 0 with
| 'a' .. 'z' | 'A' .. 'Z' ->
for i = 1 to (String.length s)-1 do
match String.get s i with
| 'a' .. 'z' | 'A' .. 'Z' | '0' .. '9' | '_' -> ()
| c -> err c
done
| c -> err c
let rec make_compilation_args = function
| [] -> []
| file :: fl ->
let dirname = Filename.dirname file in
let basename = Filename.basename file in
let modulename =
if Filename.check_suffix basename ".v" then
Filename.chop_suffix basename ".v"
else
basename
in
check_module_name modulename;
let file = Filename.concat dirname modulename in
(if !verbose then "-compile-verbose" else "-compile")
:: file :: (make_compilation_args fl)
(* compilation of files [files] with command [command] and args [args] *)
let compile command args files =
let args' = command :: args @ (make_compilation_args files) in
match Sys.os_type with
| "Win32" ->
let pid =
Unix.create_process_env command (Array.of_list args') environment
Unix.stdin Unix.stdout Unix.stderr
in
let status = snd (Unix.waitpid [] pid) in
let errcode =
match status with Unix.WEXITED c|Unix.WSTOPPED c|Unix.WSIGNALED c -> c
in
exit errcode
| _ ->
Unix.execvpe command (Array.of_list args') environment
(* parsing of the command line
*
* special treatment for -bindir and -i.
* other options are passed to coqtop *)
let usage () =
Usage.print_usage_coqc () ;
flush stderr ;
exit 1
let parse_args () =
let rec parse (cfiles,args) = function
| [] ->
List.rev cfiles, List.rev args
| ("-verbose" | "--verbose") :: rem ->
verbose := true ; parse (cfiles,args) rem
| "-image" :: f :: rem ->
image := f; parse (cfiles,args) rem
| "-image" :: [] ->
usage ()
| "-byte" :: rem ->
binary := "coqtop.byte"; parse (cfiles,args) rem
| "-opt" :: rem ->
binary := "coqtop.opt"; parse (cfiles,args) rem
| "-libdir" :: _ :: rem ->
print_string "Warning: option -libdir deprecated and ignored\n"; flush stdout;
parse (cfiles,args) rem
| ("-db"|"-debugger") :: rem ->
print_string "Warning: option -db/-debugger deprecated and ignored\n";flush stdout;
parse (cfiles,args) rem
| ("-?"|"-h"|"-H"|"-help"|"--help") :: _ -> usage ()
| ("-outputstate"|"-inputstate"|"-is"
|"-load-vernac-source"|"-l"|"-load-vernac-object"
|"-load-ml-source"|"-require"|"-load-ml-object"
|"-init-file"|"-dump-glob"|"-compat"|"-coqlib" as o) :: rem ->
begin
match rem with
| s :: rem' -> parse (cfiles,s::o::args) rem'
| [] -> usage ()
end
| ("-I"|"-include" as o) :: rem ->
begin
match rem with
| s :: "-as" :: t :: rem' -> parse (cfiles,t::"-as"::s::o::args) rem'
| s :: "-as" :: [] -> usage ()
| s :: rem' -> parse (cfiles,s::o::args) rem'
| [] -> usage ()
end
| "-R" :: s :: "-as" :: t :: rem -> parse (cfiles,t::"-as"::s::"-R"::args) rem
| "-R" :: s :: "-as" :: [] -> usage ()
| "-R" :: s :: t :: rem -> parse (cfiles,t::s::"-R"::args) rem
| ("-notactics"|"-debug"|"-nolib"|"-boot"
|"-batch"|"-nois"|"-noglob"|"-no-glob"
|"-q"|"-full"|"-profile"|"-just-parsing"|"-echo" |"-unsafe"|"-quiet"
|"-silent"|"-m"|"-xml"|"-v7"|"-v8"|"-beautify"|"-strict-implicit"
|"-dont-load-proofs"|"-load-proofs"|"-force-load-proofs"
|"-impredicative-set"|"-vm" as o) :: rem ->
parse (cfiles,o::args) rem
| ("-where") :: _ ->
(try print_endline (Envars.coqlib ())
with Util.UserError(_,pps) -> Pp.msgerrnl (Pp.hov 0 pps));
exit 0
| ("-config" | "--config") :: _ -> Usage.print_config (); exit 0
| ("-v"|"--version") :: _ ->
Usage.version 0
| f :: rem ->
if Sys.file_exists f then
parse (f::cfiles,args) rem
else
let fv = f ^ ".v" in
if Sys.file_exists fv then
parse (fv::cfiles,args) rem
else begin
prerr_endline ("coqc: "^f^": no such file or directory") ;
exit 1
end
in
parse ([],[]) (List.tl (Array.to_list Sys.argv))
(* main: we parse the command line, define the command to compile files
* and then call the compilation on each file *)
let main () =
let cfiles, args = parse_args () in
if cfiles = [] then begin
prerr_endline "coqc: too few arguments" ;
usage ()
end;
let coqtopname =
if !image <> "" then !image
else Filename.concat Envars.coqbin (!binary ^ Coq_config.exec_extension)
in
(* List.iter (compile coqtopname args) cfiles*)
Unix.handle_unix_error (compile coqtopname args) cfiles
let _ = Printexc.print main ()
| null | https://raw.githubusercontent.com/hemmi/coq2scala/d10f441c18146933a99bf2088116bd213ac3648d/coq-8.4pl2-old/scripts/coqc.ml | ocaml | **********************************************************************
// * This file is distributed under the terms of the
* GNU Lesser General Public License Version 2.1
**********************************************************************
environment
coqc options
compilation of files [files] with command [command] and args [args]
parsing of the command line
*
* special treatment for -bindir and -i.
* other options are passed to coqtop
main: we parse the command line, define the command to compile files
* and then call the compilation on each file
List.iter (compile coqtopname args) cfiles | v * The Coq Proof Assistant / The Coq Development Team
< O _ _ _ , , * INRIA - CNRS - LIX - LRI - PPS - Copyright 1999 - 2012
\VV/ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
Afin de rendre Coq plus portable , ce programme remplace le script
coqc .
Ici , on trie la ligne de commande pour en extraire les fichiers à compiler ,
puis on les compile un par un en passant le reste de la ligne de commande
à un process " coqtop -batch -load - vernac - source < fichier > " .
On essaye au maximum d'utiliser les modules et Filename pour que la
portabilité soit maximale , des appels à des fonctions
du module Unix . Ceux - ci sont préfixés par " Unix . "
coqc.
Ici, on trie la ligne de commande pour en extraire les fichiers à compiler,
puis on les compile un par un en passant le reste de la ligne de commande
à un process "coqtop -batch -load-vernac-source <fichier>".
On essaye au maximum d'utiliser les modules Sys et Filename pour que la
portabilité soit maximale, mais il reste encore des appels à des fonctions
du module Unix. Ceux-ci sont préfixés par "Unix."
*)
let environment = Unix.environment ()
let best = if Coq_config.arch = "win32" then "" else ("."^Coq_config.best)
let binary = ref ("coqtop" ^ best)
let image = ref ""
let verbose = ref false
Verifies that a string starts by a letter and do not contain
others caracters than letters , digits , or ` _ `
others caracters than letters, digits, or `_` *)
let check_module_name s =
let err c =
output_string stderr "Invalid module name: ";
output_string stderr s;
output_string stderr " character ";
if c = '\'' then
output_string stderr "\"'\""
else
(output_string stderr"'"; output_char stderr c; output_string stderr"'");
output_string stderr " is not allowed in module names\n";
exit 1
in
match String.get s 0 with
| 'a' .. 'z' | 'A' .. 'Z' ->
for i = 1 to (String.length s)-1 do
match String.get s i with
| 'a' .. 'z' | 'A' .. 'Z' | '0' .. '9' | '_' -> ()
| c -> err c
done
| c -> err c
let rec make_compilation_args = function
| [] -> []
| file :: fl ->
let dirname = Filename.dirname file in
let basename = Filename.basename file in
let modulename =
if Filename.check_suffix basename ".v" then
Filename.chop_suffix basename ".v"
else
basename
in
check_module_name modulename;
let file = Filename.concat dirname modulename in
(if !verbose then "-compile-verbose" else "-compile")
:: file :: (make_compilation_args fl)
let compile command args files =
let args' = command :: args @ (make_compilation_args files) in
match Sys.os_type with
| "Win32" ->
let pid =
Unix.create_process_env command (Array.of_list args') environment
Unix.stdin Unix.stdout Unix.stderr
in
let status = snd (Unix.waitpid [] pid) in
let errcode =
match status with Unix.WEXITED c|Unix.WSTOPPED c|Unix.WSIGNALED c -> c
in
exit errcode
| _ ->
Unix.execvpe command (Array.of_list args') environment
let usage () =
Usage.print_usage_coqc () ;
flush stderr ;
exit 1
let parse_args () =
let rec parse (cfiles,args) = function
| [] ->
List.rev cfiles, List.rev args
| ("-verbose" | "--verbose") :: rem ->
verbose := true ; parse (cfiles,args) rem
| "-image" :: f :: rem ->
image := f; parse (cfiles,args) rem
| "-image" :: [] ->
usage ()
| "-byte" :: rem ->
binary := "coqtop.byte"; parse (cfiles,args) rem
| "-opt" :: rem ->
binary := "coqtop.opt"; parse (cfiles,args) rem
| "-libdir" :: _ :: rem ->
print_string "Warning: option -libdir deprecated and ignored\n"; flush stdout;
parse (cfiles,args) rem
| ("-db"|"-debugger") :: rem ->
print_string "Warning: option -db/-debugger deprecated and ignored\n";flush stdout;
parse (cfiles,args) rem
| ("-?"|"-h"|"-H"|"-help"|"--help") :: _ -> usage ()
| ("-outputstate"|"-inputstate"|"-is"
|"-load-vernac-source"|"-l"|"-load-vernac-object"
|"-load-ml-source"|"-require"|"-load-ml-object"
|"-init-file"|"-dump-glob"|"-compat"|"-coqlib" as o) :: rem ->
begin
match rem with
| s :: rem' -> parse (cfiles,s::o::args) rem'
| [] -> usage ()
end
| ("-I"|"-include" as o) :: rem ->
begin
match rem with
| s :: "-as" :: t :: rem' -> parse (cfiles,t::"-as"::s::o::args) rem'
| s :: "-as" :: [] -> usage ()
| s :: rem' -> parse (cfiles,s::o::args) rem'
| [] -> usage ()
end
| "-R" :: s :: "-as" :: t :: rem -> parse (cfiles,t::"-as"::s::"-R"::args) rem
| "-R" :: s :: "-as" :: [] -> usage ()
| "-R" :: s :: t :: rem -> parse (cfiles,t::s::"-R"::args) rem
| ("-notactics"|"-debug"|"-nolib"|"-boot"
|"-batch"|"-nois"|"-noglob"|"-no-glob"
|"-q"|"-full"|"-profile"|"-just-parsing"|"-echo" |"-unsafe"|"-quiet"
|"-silent"|"-m"|"-xml"|"-v7"|"-v8"|"-beautify"|"-strict-implicit"
|"-dont-load-proofs"|"-load-proofs"|"-force-load-proofs"
|"-impredicative-set"|"-vm" as o) :: rem ->
parse (cfiles,o::args) rem
| ("-where") :: _ ->
(try print_endline (Envars.coqlib ())
with Util.UserError(_,pps) -> Pp.msgerrnl (Pp.hov 0 pps));
exit 0
| ("-config" | "--config") :: _ -> Usage.print_config (); exit 0
| ("-v"|"--version") :: _ ->
Usage.version 0
| f :: rem ->
if Sys.file_exists f then
parse (f::cfiles,args) rem
else
let fv = f ^ ".v" in
if Sys.file_exists fv then
parse (fv::cfiles,args) rem
else begin
prerr_endline ("coqc: "^f^": no such file or directory") ;
exit 1
end
in
parse ([],[]) (List.tl (Array.to_list Sys.argv))
let main () =
let cfiles, args = parse_args () in
if cfiles = [] then begin
prerr_endline "coqc: too few arguments" ;
usage ()
end;
let coqtopname =
if !image <> "" then !image
else Filename.concat Envars.coqbin (!binary ^ Coq_config.exec_extension)
in
Unix.handle_unix_error (compile coqtopname args) cfiles
let _ = Printexc.print main ()
|
ec35329e7f1b34d777c4b3c5ce5c5e790a3595ac42adae8a24631cf5bd89eb3a | janestreet/ppx_typed_fields | nested.mli | open! Core
module Make (Leaf_data : T1) : sig
module rec Tree : sig
type 'a t = private
| Leaf : 'a Leaf_data.t -> 'a t
| Branch : (module Branch.S with type Typed_field.derived_on = 'a) -> 'a t
end
and Branch : sig
module type S = sig
module Typed_field : Typed_fields_lib.S
module Map :
The_map.S with module Key := Typed_field and type 'a Data.t := 'a Tree.t
val map : Map.t
end
end
module type S = sig
module Typed_field : Typed_fields_lib.S
val children : 'a Typed_field.t -> 'a Tree.t
end
type 'a t = 'a Tree.t
val leaf : 'a Leaf_data.t -> 'a t
val branch : (module S with type Typed_field.derived_on = 'a) -> 'a t
end
| null | https://raw.githubusercontent.com/janestreet/ppx_typed_fields/bc4f91fd95cae8e1d790250cbd8fcc1a8d7d8aea/typed_field_map/nested.mli | ocaml | open! Core
module Make (Leaf_data : T1) : sig
module rec Tree : sig
type 'a t = private
| Leaf : 'a Leaf_data.t -> 'a t
| Branch : (module Branch.S with type Typed_field.derived_on = 'a) -> 'a t
end
and Branch : sig
module type S = sig
module Typed_field : Typed_fields_lib.S
module Map :
The_map.S with module Key := Typed_field and type 'a Data.t := 'a Tree.t
val map : Map.t
end
end
module type S = sig
module Typed_field : Typed_fields_lib.S
val children : 'a Typed_field.t -> 'a Tree.t
end
type 'a t = 'a Tree.t
val leaf : 'a Leaf_data.t -> 'a t
val branch : (module S with type Typed_field.derived_on = 'a) -> 'a t
end
| |
167381e26d0292ac6b0c1d6d696ab5568e73d553a6d873f1cd4510964c9236b8 | byorgey/AoC | 07.hs | import Data.Bits
import Data.Map ((!))
import qualified Data.Map as M
import Data.Word
import Text.Parsec
import Text.Parsec.String
type Wire = String
data Input
= Pass Wire
| Val Word16
| NOT Wire
| AND Wire Wire
special case for 1 AND xx
| OR Wire Wire
| LSHIFT Wire Int
| RSHIFT Wire Int
deriving Show
data Component = Component Input Wire
deriving Show
outputWire :: Component -> Wire
outputWire (Component _ w) = w
parseComponent :: Parser Component
parseComponent =
Component
<$> parseInput
<* string " -> "
<*> parseWire
parseWire :: Parser Wire
parseWire = many1 (oneOf ['a'..'z'])
parseInput :: Parser Input
parseInput
= NOT <$ string "NOT " <*> parseWire
<|> try (AND <$> parseWire <* string " AND " <*> parseWire)
<|> try (MASK <$ string "1 AND " <*> parseWire)
<|> try (OR <$> parseWire <* string " OR " <*> parseWire)
<|> try (LSHIFT <$> parseWire <* string " LSHIFT " <*> val)
<|> try (RSHIFT <$> parseWire <* string " RSHIFT " <*> val)
<|> Val <$> val
<|> Pass <$> parseWire
val :: Read a => Parser a
val = read <$> many1 digit
readCircuit :: String -> [Component]
readCircuit = map readComponent . lines
where
readComponent l = case runParser parseComponent () "" l of
Left err -> error (show err)
Right c -> c
runCircuit :: [Component] -> M.Map Wire Word16
runCircuit comps = outputs
where
outputs = M.fromList $ map setResult comps
setResult (Component inp out) = (out, eval inp)
eval (Pass w) = outputs ! w
eval (Val v) = v
eval (NOT w) = complement (outputs ! w)
eval (AND w1 w2) = (outputs ! w1) .&. (outputs ! w2)
eval (MASK w) = 1 .&. (outputs ! w)
eval (OR w1 w2) = (outputs ! w1) .|. (outputs ! w2)
eval (LSHIFT w v) = (outputs ! w) `shiftL` v
eval (RSHIFT w v) = (outputs ! w) `shiftR` v
main = do
f <- getContents
print $ runCircuit (readCircuit f)
| null | https://raw.githubusercontent.com/byorgey/AoC/30eb51eb41af9ca86b05de598a3a96d25bd428e3/2015/07/07.hs | haskell | import Data.Bits
import Data.Map ((!))
import qualified Data.Map as M
import Data.Word
import Text.Parsec
import Text.Parsec.String
type Wire = String
data Input
= Pass Wire
| Val Word16
| NOT Wire
| AND Wire Wire
special case for 1 AND xx
| OR Wire Wire
| LSHIFT Wire Int
| RSHIFT Wire Int
deriving Show
data Component = Component Input Wire
deriving Show
outputWire :: Component -> Wire
outputWire (Component _ w) = w
parseComponent :: Parser Component
parseComponent =
Component
<$> parseInput
<* string " -> "
<*> parseWire
parseWire :: Parser Wire
parseWire = many1 (oneOf ['a'..'z'])
parseInput :: Parser Input
parseInput
= NOT <$ string "NOT " <*> parseWire
<|> try (AND <$> parseWire <* string " AND " <*> parseWire)
<|> try (MASK <$ string "1 AND " <*> parseWire)
<|> try (OR <$> parseWire <* string " OR " <*> parseWire)
<|> try (LSHIFT <$> parseWire <* string " LSHIFT " <*> val)
<|> try (RSHIFT <$> parseWire <* string " RSHIFT " <*> val)
<|> Val <$> val
<|> Pass <$> parseWire
val :: Read a => Parser a
val = read <$> many1 digit
readCircuit :: String -> [Component]
readCircuit = map readComponent . lines
where
readComponent l = case runParser parseComponent () "" l of
Left err -> error (show err)
Right c -> c
runCircuit :: [Component] -> M.Map Wire Word16
runCircuit comps = outputs
where
outputs = M.fromList $ map setResult comps
setResult (Component inp out) = (out, eval inp)
eval (Pass w) = outputs ! w
eval (Val v) = v
eval (NOT w) = complement (outputs ! w)
eval (AND w1 w2) = (outputs ! w1) .&. (outputs ! w2)
eval (MASK w) = 1 .&. (outputs ! w)
eval (OR w1 w2) = (outputs ! w1) .|. (outputs ! w2)
eval (LSHIFT w v) = (outputs ! w) `shiftL` v
eval (RSHIFT w v) = (outputs ! w) `shiftR` v
main = do
f <- getContents
print $ runCircuit (readCircuit f)
| |
664816d5cd775cfa5c106cf981d50d8f15644d62f1b81caaf760b6b07c9cb3b2 | uxbox/uxbox-old | material_design_file.cljs | (ns uxbox.ui.icon-sets.material-design-file
(:require [uxbox.ui.tools :as t]))
(def material-design-file (sorted-map
:attachment {
:name "Attachment"
:svg [:path
{:d
"M15 36c-6.08 0-11-4.93-11-11s4.92-11 11-11h21c4.42 0 8 3.58 8 8s-3.58 8-8 8h-17c-2.76 0-5-2.24-5-5s2.24-5 5-5h15v3h-15c-1.1 0-2 .89-2 2s.9 2 2 2h17c2.76 0 5-2.24 5-5s-2.24-5-5-5h-21c-4.42 0-8 3.58-8 8s3.58 8 8 8h19v3h-19z"}]}
:cloud {
:name "Cloud"
:svg [:path
{:d
"M38.71 20.07c-1.36-6.88-7.43-12.07-14.71-12.07-5.78 0-10.79 3.28-13.3 8.07-6.01.65-10.7 5.74-10.7 11.93 0 6.63 5.37 12 12 12h26c5.52 0 10-4.48 10-10 0-5.28-4.11-9.56-9.29-9.93z"}]}
:cloud-circle {
:name "Cloud Circle"
:svg [:path
{:d
"M24 4c-11.05 0-20 8.95-20 20s8.95 20 20 20 20-8.95 20-20-8.95-20-20-20zm9 28h-17c-3.31 0-6-2.69-6-6s2.69-6 6-6l.27.03c.89-3.46 4-6.03 7.73-6.03 4.42 0 8 3.58 8 8h1c2.76 0 5 2.24 5 5s-2.24 5-5 5z"}]}
:cloud-done {
:name "Cloud Done"
:svg [:path
{:d
"M38.71 20.07c-1.36-6.88-7.43-12.07-14.71-12.07-5.78 0-10.79 3.28-13.3 8.07-6.01.65-10.7 5.74-10.7 11.93 0 6.63 5.37 12 12 12h26c5.52 0 10-4.48 10-10 0-5.28-4.11-9.56-9.29-9.93zm-18.71 13.93l-7-7 2.83-2.83 4.17 4.17 10.35-10.35 2.83 2.83-13.18 13.18z"}]}
:cloud-download {
:name "Cloud Download"
:svg [:path
{:d
"M38.71 20.07c-1.36-6.88-7.43-12.07-14.71-12.07-5.78 0-10.79 3.28-13.3 8.07-6.01.65-10.7 5.74-10.7 11.93 0 6.63 5.37 12 12 12h26c5.52 0 10-4.48 10-10 0-5.28-4.11-9.56-9.29-9.93zm-4.71 5.93l-10 10-10-10h6v-8h8v8h6z"}]}
:cloud-off {
:name "Cloud Off"
:svg [:path
{:style {:stroke nil}
:d
"M38.71 20.07c-1.36-6.88-7.43-12.07-14.71-12.07-2.95 0-5.7.87-8.02 2.34l2.92 2.92c1.53-.79 3.26-1.26 5.1-1.26 6.08 0 11 4.92 11 11v1h3c3.31 0 6 2.69 6 6 0 2.27-1.27 4.22-3.13 5.24l2.9 2.9c2.55-1.81 4.23-4.77 4.23-8.14 0-5.28-4.11-9.56-9.29-9.93zm-32.71-9.52l5.5 5.48c-6.38.27-11.5 5.52-11.5 11.97 0 6.63 5.37 12 12 12h23.45l4 4 2.55-2.54-33.45-33.46-2.55 2.55zm9.45 9.45l16 16h-19.45c-4.42 0-8-3.58-8-8s3.58-8 8-8h3.45z"}]}
:cloud-queue {
:name "Cloud Queue"
:svg [:path
{:style {:stroke nil}
:d
"M38.71 20.07c-1.36-6.88-7.43-12.07-14.71-12.07-5.78 0-10.79 3.28-13.3 8.07-6.01.65-10.7 5.74-10.7 11.93 0 6.63 5.37 12 12 12h26c5.52 0 10-4.48 10-10 0-5.28-4.11-9.56-9.29-9.93zm-.71 15.93h-26c-4.42 0-8-3.58-8-8s3.58-8 8-8h1.42c1.31-4.61 5.54-8 10.58-8 6.08 0 11 4.92 11 11v1h3c3.31 0 6 2.69 6 6s-2.69 6-6 6z"}]}
:cloud-upload {
:name "Cloud Upload"
:svg [:path
{:style {:stroke nil}
:d
"M38.71 20.07c-1.36-6.88-7.43-12.07-14.71-12.07-5.78 0-10.79 3.28-13.3 8.07-6.01.65-10.7 5.74-10.7 11.93 0 6.63 5.37 12 12 12h26c5.52 0 10-4.48 10-10 0-5.28-4.11-9.56-9.29-9.93zm-10.71 5.93v8h-8v-8h-6l10-10 10 10h-6z"}]}
:file-download {
:name "File Download"
:svg [:path
{:style {:stroke nil}
:d "M38 18h-8v-12h-12v12h-8l14 14 14-14zm-28 18v4h28v-4h-28z"}]}
:file-upload {
:name "File Upload"
:svg [:path
{:style {:stroke nil}
:d "M18 32h12v-12h8l-14-14-14 14h8zm-8 4h28v4h-28z"}]}
:folder {
:name "Folder"
:svg [:path
{:style {:stroke nil}
:d
"M20 8h-12c-2.21 0-3.98 1.79-3.98 4l-.02 24c0 2.21 1.79 4 4 4h32c2.21 0 4-1.79 4-4v-20c0-2.21-1.79-4-4-4h-16l-4-4z"}]}
:folder-open {
:name "Folder Open"
:svg [:path
{:style {:stroke nil}
:d
"M40 12h-16l-4-4h-12c-2.21 0-3.98 1.79-3.98 4l-.02 24c0 2.21 1.79 4 4 4h32c2.21 0 4-1.79 4-4v-20c0-2.21-1.79-4-4-4zm0 24h-32v-20h32v20z"}]}
:folder-shared {
:name "Folder Shared"
:svg [:path
{:style {:stroke nil}
:d
"M40 12h-16l-4-4h-12c-2.21 0-3.98 1.79-3.98 4l-.02 24c0 2.21 1.79 4 4 4h32c2.21 0 4-1.79 4-4v-20c0-2.21-1.79-4-4-4zm-10 6c2.21 0 4 1.79 4 4s-1.79 4-4 4-4-1.79-4-4 1.79-4 4-4zm8 16h-16v-2c0-2.67 5.33-4 8-4s8 1.33 8 4v2z"}]}))
(t/register-icon-set! {:key :material-design-file
:name "Material Design (File)"
:icons material-design-file})
| null | https://raw.githubusercontent.com/uxbox/uxbox-old/9c3c3c406a6c629717cfc40e3da2f96df3bdebf7/src/frontend/uxbox/ui/icon_sets/material_design_file.cljs | clojure | (ns uxbox.ui.icon-sets.material-design-file
(:require [uxbox.ui.tools :as t]))
(def material-design-file (sorted-map
:attachment {
:name "Attachment"
:svg [:path
{:d
"M15 36c-6.08 0-11-4.93-11-11s4.92-11 11-11h21c4.42 0 8 3.58 8 8s-3.58 8-8 8h-17c-2.76 0-5-2.24-5-5s2.24-5 5-5h15v3h-15c-1.1 0-2 .89-2 2s.9 2 2 2h17c2.76 0 5-2.24 5-5s-2.24-5-5-5h-21c-4.42 0-8 3.58-8 8s3.58 8 8 8h19v3h-19z"}]}
:cloud {
:name "Cloud"
:svg [:path
{:d
"M38.71 20.07c-1.36-6.88-7.43-12.07-14.71-12.07-5.78 0-10.79 3.28-13.3 8.07-6.01.65-10.7 5.74-10.7 11.93 0 6.63 5.37 12 12 12h26c5.52 0 10-4.48 10-10 0-5.28-4.11-9.56-9.29-9.93z"}]}
:cloud-circle {
:name "Cloud Circle"
:svg [:path
{:d
"M24 4c-11.05 0-20 8.95-20 20s8.95 20 20 20 20-8.95 20-20-8.95-20-20-20zm9 28h-17c-3.31 0-6-2.69-6-6s2.69-6 6-6l.27.03c.89-3.46 4-6.03 7.73-6.03 4.42 0 8 3.58 8 8h1c2.76 0 5 2.24 5 5s-2.24 5-5 5z"}]}
:cloud-done {
:name "Cloud Done"
:svg [:path
{:d
"M38.71 20.07c-1.36-6.88-7.43-12.07-14.71-12.07-5.78 0-10.79 3.28-13.3 8.07-6.01.65-10.7 5.74-10.7 11.93 0 6.63 5.37 12 12 12h26c5.52 0 10-4.48 10-10 0-5.28-4.11-9.56-9.29-9.93zm-18.71 13.93l-7-7 2.83-2.83 4.17 4.17 10.35-10.35 2.83 2.83-13.18 13.18z"}]}
:cloud-download {
:name "Cloud Download"
:svg [:path
{:d
"M38.71 20.07c-1.36-6.88-7.43-12.07-14.71-12.07-5.78 0-10.79 3.28-13.3 8.07-6.01.65-10.7 5.74-10.7 11.93 0 6.63 5.37 12 12 12h26c5.52 0 10-4.48 10-10 0-5.28-4.11-9.56-9.29-9.93zm-4.71 5.93l-10 10-10-10h6v-8h8v8h6z"}]}
:cloud-off {
:name "Cloud Off"
:svg [:path
{:style {:stroke nil}
:d
"M38.71 20.07c-1.36-6.88-7.43-12.07-14.71-12.07-2.95 0-5.7.87-8.02 2.34l2.92 2.92c1.53-.79 3.26-1.26 5.1-1.26 6.08 0 11 4.92 11 11v1h3c3.31 0 6 2.69 6 6 0 2.27-1.27 4.22-3.13 5.24l2.9 2.9c2.55-1.81 4.23-4.77 4.23-8.14 0-5.28-4.11-9.56-9.29-9.93zm-32.71-9.52l5.5 5.48c-6.38.27-11.5 5.52-11.5 11.97 0 6.63 5.37 12 12 12h23.45l4 4 2.55-2.54-33.45-33.46-2.55 2.55zm9.45 9.45l16 16h-19.45c-4.42 0-8-3.58-8-8s3.58-8 8-8h3.45z"}]}
:cloud-queue {
:name "Cloud Queue"
:svg [:path
{:style {:stroke nil}
:d
"M38.71 20.07c-1.36-6.88-7.43-12.07-14.71-12.07-5.78 0-10.79 3.28-13.3 8.07-6.01.65-10.7 5.74-10.7 11.93 0 6.63 5.37 12 12 12h26c5.52 0 10-4.48 10-10 0-5.28-4.11-9.56-9.29-9.93zm-.71 15.93h-26c-4.42 0-8-3.58-8-8s3.58-8 8-8h1.42c1.31-4.61 5.54-8 10.58-8 6.08 0 11 4.92 11 11v1h3c3.31 0 6 2.69 6 6s-2.69 6-6 6z"}]}
:cloud-upload {
:name "Cloud Upload"
:svg [:path
{:style {:stroke nil}
:d
"M38.71 20.07c-1.36-6.88-7.43-12.07-14.71-12.07-5.78 0-10.79 3.28-13.3 8.07-6.01.65-10.7 5.74-10.7 11.93 0 6.63 5.37 12 12 12h26c5.52 0 10-4.48 10-10 0-5.28-4.11-9.56-9.29-9.93zm-10.71 5.93v8h-8v-8h-6l10-10 10 10h-6z"}]}
:file-download {
:name "File Download"
:svg [:path
{:style {:stroke nil}
:d "M38 18h-8v-12h-12v12h-8l14 14 14-14zm-28 18v4h28v-4h-28z"}]}
:file-upload {
:name "File Upload"
:svg [:path
{:style {:stroke nil}
:d "M18 32h12v-12h8l-14-14-14 14h8zm-8 4h28v4h-28z"}]}
:folder {
:name "Folder"
:svg [:path
{:style {:stroke nil}
:d
"M20 8h-12c-2.21 0-3.98 1.79-3.98 4l-.02 24c0 2.21 1.79 4 4 4h32c2.21 0 4-1.79 4-4v-20c0-2.21-1.79-4-4-4h-16l-4-4z"}]}
:folder-open {
:name "Folder Open"
:svg [:path
{:style {:stroke nil}
:d
"M40 12h-16l-4-4h-12c-2.21 0-3.98 1.79-3.98 4l-.02 24c0 2.21 1.79 4 4 4h32c2.21 0 4-1.79 4-4v-20c0-2.21-1.79-4-4-4zm0 24h-32v-20h32v20z"}]}
:folder-shared {
:name "Folder Shared"
:svg [:path
{:style {:stroke nil}
:d
"M40 12h-16l-4-4h-12c-2.21 0-3.98 1.79-3.98 4l-.02 24c0 2.21 1.79 4 4 4h32c2.21 0 4-1.79 4-4v-20c0-2.21-1.79-4-4-4zm-10 6c2.21 0 4 1.79 4 4s-1.79 4-4 4-4-1.79-4-4 1.79-4 4-4zm8 16h-16v-2c0-2.67 5.33-4 8-4s8 1.33 8 4v2z"}]}))
(t/register-icon-set! {:key :material-design-file
:name "Material Design (File)"
:icons material-design-file})
| |
709a62962cb1496b85d9b7d5fc7a94e2efe96667f97c62f7878469094f084c67 | ocaml-flambda/ocaml-jst | maindriver.ml | (**************************************************************************)
(* *)
(* OCaml *)
(* *)
, projet Cristal , INRIA Rocquencourt
(* *)
Copyright 1996 Institut National de Recherche en Informatique et
(* en Automatique. *)
(* *)
(* All rights reserved. This file is distributed under the terms of *)
the GNU Lesser General Public License version 2.1 , with the
(* special exception on linking described in the file LICENSE. *)
(* *)
(**************************************************************************)
open Clflags
module Options = Main_args.Make_bytecomp_options (Main_args.Default.Main)
let main argv ppf =
let program = "ocamlc" in
Clflags.add_arguments __LOC__ Options.list;
Clflags.add_arguments __LOC__
["-depend", Arg.Unit Makedepend.main_from_option,
"<options> Compute dependencies (use 'ocamlc -depend -help' for details)"];
match
Compenv.readenv ppf Before_args;
Compenv.parse_arguments (ref argv) Compenv.anonymous program;
Compmisc.read_clflags_from_env ();
if !Clflags.plugin then
Compenv.fatal "-plugin is only supported up to OCaml 4.08.0";
begin try
Compenv.process_deferred_actions
(ppf,
Compile.implementation,
Compile.interface,
".cmo",
".cma");
with Arg.Bad msg ->
begin
prerr_endline msg;
Clflags.print_arguments program;
exit 2
end
end;
Compenv.readenv ppf Before_link;
if
List.length
(List.filter (fun x -> !x)
[make_archive;make_package;Compenv.stop_early;output_c_object])
> 1
then begin
let module P = Clflags.Compiler_pass in
match !stop_after with
| None ->
Compenv.fatal
"Please specify at most one of -pack, -a, -c, -output-obj";
| Some ((P.Parsing | P.Typing) as p) ->
assert (P.is_compilation_pass p);
Printf.ksprintf Compenv.fatal
"Options -i and -stop-after (%s) \
are incompatible with -pack, -a, -output-obj"
(String.concat "|"
(P.available_pass_names ~filter:(fun _ -> true) ~native:false))
| Some (P.Scheduling | P.Simplify_cfg | P.Emit | P.Selection) ->
assert false (* native only *)
end;
if !make_archive then begin
Compmisc.init_path ();
Bytelibrarian.create_archive
(Compenv.get_objfiles ~with_ocamlparam:false)
(Compenv.extract_output !output_name);
Warnings.check_fatal ();
end
else if !make_package then begin
Compmisc.init_path ();
let extracted_output = Compenv.extract_output !output_name in
let revd = Compenv.get_objfiles ~with_ocamlparam:false in
Compmisc.with_ppf_dump ~file_prefix:extracted_output (fun ppf_dump ->
Bytepackager.package_files ~ppf_dump (Compmisc.initial_env ())
revd (extracted_output));
Warnings.check_fatal ();
end
else if not !Compenv.stop_early && !objfiles <> [] then begin
let target =
if !output_c_object && not !output_complete_executable then
let s = Compenv.extract_output !output_name in
if (Filename.check_suffix s Config.ext_obj
|| Filename.check_suffix s Config.ext_dll
|| Filename.check_suffix s ".c")
then s
else
Compenv.fatal
(Printf.sprintf
"The extension of the output file must be .c, %s or %s"
Config.ext_obj Config.ext_dll
)
else
Compenv.default_output !output_name
in
Compmisc.init_path ();
Bytelink.link (Compenv.get_objfiles ~with_ocamlparam:true) target;
Warnings.check_fatal ();
end;
with
| exception (Compenv.Exit_with_status n) ->
n
| exception x ->
Location.report_exception ppf x;
2
| () ->
Compmisc.with_ppf_dump ~stdout:() ~file_prefix:"profile"
(fun ppf -> Profile.print ppf !Clflags.profile_columns ~timings_precision:!Clflags.timings_precision);
0
| null | https://raw.githubusercontent.com/ocaml-flambda/ocaml-jst/1bb6c797df7c63ddae1fc2e6f403a0ee9896cc8e/driver/maindriver.ml | ocaml | ************************************************************************
OCaml
en Automatique.
All rights reserved. This file is distributed under the terms of
special exception on linking described in the file LICENSE.
************************************************************************
native only | , projet Cristal , INRIA Rocquencourt
Copyright 1996 Institut National de Recherche en Informatique et
the GNU Lesser General Public License version 2.1 , with the
open Clflags
module Options = Main_args.Make_bytecomp_options (Main_args.Default.Main)
let main argv ppf =
let program = "ocamlc" in
Clflags.add_arguments __LOC__ Options.list;
Clflags.add_arguments __LOC__
["-depend", Arg.Unit Makedepend.main_from_option,
"<options> Compute dependencies (use 'ocamlc -depend -help' for details)"];
match
Compenv.readenv ppf Before_args;
Compenv.parse_arguments (ref argv) Compenv.anonymous program;
Compmisc.read_clflags_from_env ();
if !Clflags.plugin then
Compenv.fatal "-plugin is only supported up to OCaml 4.08.0";
begin try
Compenv.process_deferred_actions
(ppf,
Compile.implementation,
Compile.interface,
".cmo",
".cma");
with Arg.Bad msg ->
begin
prerr_endline msg;
Clflags.print_arguments program;
exit 2
end
end;
Compenv.readenv ppf Before_link;
if
List.length
(List.filter (fun x -> !x)
[make_archive;make_package;Compenv.stop_early;output_c_object])
> 1
then begin
let module P = Clflags.Compiler_pass in
match !stop_after with
| None ->
Compenv.fatal
"Please specify at most one of -pack, -a, -c, -output-obj";
| Some ((P.Parsing | P.Typing) as p) ->
assert (P.is_compilation_pass p);
Printf.ksprintf Compenv.fatal
"Options -i and -stop-after (%s) \
are incompatible with -pack, -a, -output-obj"
(String.concat "|"
(P.available_pass_names ~filter:(fun _ -> true) ~native:false))
| Some (P.Scheduling | P.Simplify_cfg | P.Emit | P.Selection) ->
end;
if !make_archive then begin
Compmisc.init_path ();
Bytelibrarian.create_archive
(Compenv.get_objfiles ~with_ocamlparam:false)
(Compenv.extract_output !output_name);
Warnings.check_fatal ();
end
else if !make_package then begin
Compmisc.init_path ();
let extracted_output = Compenv.extract_output !output_name in
let revd = Compenv.get_objfiles ~with_ocamlparam:false in
Compmisc.with_ppf_dump ~file_prefix:extracted_output (fun ppf_dump ->
Bytepackager.package_files ~ppf_dump (Compmisc.initial_env ())
revd (extracted_output));
Warnings.check_fatal ();
end
else if not !Compenv.stop_early && !objfiles <> [] then begin
let target =
if !output_c_object && not !output_complete_executable then
let s = Compenv.extract_output !output_name in
if (Filename.check_suffix s Config.ext_obj
|| Filename.check_suffix s Config.ext_dll
|| Filename.check_suffix s ".c")
then s
else
Compenv.fatal
(Printf.sprintf
"The extension of the output file must be .c, %s or %s"
Config.ext_obj Config.ext_dll
)
else
Compenv.default_output !output_name
in
Compmisc.init_path ();
Bytelink.link (Compenv.get_objfiles ~with_ocamlparam:true) target;
Warnings.check_fatal ();
end;
with
| exception (Compenv.Exit_with_status n) ->
n
| exception x ->
Location.report_exception ppf x;
2
| () ->
Compmisc.with_ppf_dump ~stdout:() ~file_prefix:"profile"
(fun ppf -> Profile.print ppf !Clflags.profile_columns ~timings_precision:!Clflags.timings_precision);
0
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.