_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
|
---|---|---|---|---|---|---|---|---|
bf7a48e991794cd0b30e1ca753535844417725a09cbfdaf1627d0668bb1ba83c | zotonic/zotonic | z_fileuploader_recorddefs.erl | @author < >
2021
@doc All record definitions for the file uploader . Used by .
Copyright 2018
%%
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(z_fileuploader_recorddefs).
%% ONLY include header files whose record definitions are allowed
to be defined in jsxrecord .
-include("../../include/fileuploader.hrl").
| null | https://raw.githubusercontent.com/zotonic/zotonic/852f627c28adf6e5212e8ad5383d4af3a2f25e3f/apps/zotonic_mod_fileuploader/src/support/z_fileuploader_recorddefs.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.
ONLY include header files whose record definitions are allowed | @author < >
2021
@doc All record definitions for the file uploader . Used by .
Copyright 2018
Licensed under the Apache License , Version 2.0 ( the " License " ) ;
distributed under the License is distributed on an " AS IS " BASIS ,
-module(z_fileuploader_recorddefs).
to be defined in jsxrecord .
-include("../../include/fileuploader.hrl").
|
c2910dba3a6405f796ee11937160287a68bee766ba31e724d50e81e7eee82bf3 | archaelus/tsung | ts_os_mon_snmp.erl | %%%
Copyright 2008 ©
%%%
Author : < >
Created : 21 oct 2008 by < >
%%%
%%% This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation ; either version 2 of the License , or
%%% (at your option) any later version.
%%%
%%% This program is distributed in the hope that it will be useful,
%%% but WITHOUT ANY WARRANTY; without even the implied warranty of
%%% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
%%% GNU General Public License for more details.
%%%
You should have received a copy of the GNU General Public License
%%% along with this program; if not, write to the Free Software
Foundation , Inc. , 59 Temple Place , Suite 330 , Boston , MA 02111 - 1307 , USA .
%%%
%%% In addition, as a special exception, you have the permission to
%%% link the code of this program with any library released under
the EPL license and distribute linked combinations including
the two .
-module(ts_os_mon_snmp).
-vc('$Id: ts_os_mon_snmp.erl,v 0.0 2008/10/21 12:57:49 nniclaus Exp $ ').
-author('').
-behaviour(gen_server).
-include("ts_profile.hrl").
-include("ts_os_mon.hrl").
-include_lib("snmp/include/snmp_types.hrl").
-export([start/1]).
%% gen_server callbacks
-export([init/1, handle_call/3, handle_cast/2, handle_info/2,
terminate/2, code_change/3]).
-record(state,{
pid of mon server
dnscache=[],
interval,
pid, % pid of snmp_mgr
host,
version,
port,
community,
addr
}).
%% SNMP definitions
FIXME : make this customizable in the XML config file ?
-define(SNMP_CPU_RAW_USER, [1,3,6,1,4,1,2021,11,50,0]).
-define(SNMP_CPU_RAW_SYSTEM, [1,3,6,1,4,1,2021,11,52,0]).
-define(SNMP_CPU_RAW_IDLE, [1,3,6,1,4,1,2021,11,53,0]).
-define(SNMP_CPU_LOAD1, [1,3,6,1,4,1,2021,10,1,5,1]).
-define(SNMP_MEM_BUFFER, [1,3,6,1,4,1,2021,4,14,0]).
-define(SNMP_MEM_CACHED, [1,3,6,1,4,1,2021,4,15,0]).
-define(SNMP_MEM_AVAIL, [1,3,6,1,4,1,2021,4,6,0]).
-define(SNMP_MEM_TOTAL, [1,3,6,1,4,1,2021,4,5,0]).
start(Args) ->
?LOGF("starting os_mon_snmp with args ~p",[Args],?NOTICE),
gen_server:start_link(?MODULE, Args, []).
%%--------------------------------------------------------------------
%% Function: init/1
%% Description: Initiates the server
%% Returns: {ok, State} |
{ ok , State , Timeout } |
%% ignore |
%% {stop, Reason}
%%--------------------------------------------------------------------
init({HostStr, {Port, Community, Version}, Interval, MonServer}) ->
{ok, IP} = inet:getaddr(HostStr, inet),
ts_utils:init_seed(),
%% wait randomly a few miliseconds to avoid concurrents starts of
%% the snmp_mgr (see the unregister call later)
Wait = random:uniform(?INIT_WAIT),
erlang:start_timer(Wait, self(), connect ),
?LOGF("Starting SNMP mgr on ~p (~p)~n", [IP,Wait], ?DEB),
{ok, #state{ mon_server = MonServer,
host = HostStr,
port = Port,
addr = IP,
community = Community,
version = Version,
interval = Interval}}.
%%--------------------------------------------------------------------
Function : handle_call/3
%% Description: Handling call messages
%% Returns: {reply, Reply, State} |
{ reply , Reply , State , Timeout } |
{ noreply , State } |
{ noreply , State , Timeout } |
%% {stop, Reason, Reply, State} | (terminate/2 is called)
%% {stop, Reason, State} (terminate/2 is called)
%%--------------------------------------------------------------------
handle_call(_Request, _From, State) ->
Reply = ok,
{reply, Reply, State}.
%%--------------------------------------------------------------------
%% Function: handle_cast/2
%% Description: Handling cast messages
Returns : { noreply , State } |
{ noreply , State , Timeout } |
%% {stop, Reason, State} (terminate/2 is called)
%%--------------------------------------------------------------------
handle_cast(Msg, State) ->
{stop, {unknown_message, Msg}, State}.
%%--------------------------------------------------------------------
%% Function: handle_info/2
%% Description: Handling all non call/cast messages
Returns : { noreply , State } |
{ noreply , State , Timeout } |
%% {stop, Reason, State} (terminate/2 is called)
%%--------------------------------------------------------------------
handle_info({timeout,_Ref,connect},State=#state{addr=IP,port=Port,community=Community,version=Version}) ->
{ok, Pid} = snmp_mgr:start_link([{agent, IP},
{agent_udp, Port},
{community, Community},
{receive_type, msg},
Version,
quiet
]),
%% since snmp_mgr can handle only a single snmp server, change the
%% registered name to start several smp_mgr at once !
unregister(snmp_mgr),
?LOGF("SNMP mgr started; remote node is ~p~n", [IP],?INFO),
erlang:start_timer(State#state.interval, self(), send_request ),
{noreply, State#state{pid=Pid}};
handle_info({timeout,_Ref,send_request},State=#state{pid=Pid, host=Host}) ->
?LOGF("SNMP mgr; get data from host ~p~n", [Host],?DEB),
snmp_get(Pid,
[?SNMP_CPU_RAW_SYSTEM,
?SNMP_CPU_RAW_USER,
?SNMP_MEM_AVAIL,
?SNMP_CPU_LOAD1]),
erlang:start_timer(State#state.interval, self(), send_request ),
{noreply,State};
handle_info({snmp_msg, Msg, Ip, _Udp}, State) ->
PDU = snmp_mgr_misc:get_pdu(Msg),
case PDU#pdu.type of
'get-response' ->
?LOGF("Got SNMP PDU ~p from ~p~n",[PDU, Ip],?DEB),
{Hostname, NewCache} = ts_utils:resolve(Ip, State#state.dnscache),
analyse_snmp_data(PDU#pdu.varbinds, Hostname, State),
{noreply, State#state{dnscache=NewCache}};
_ ->
?LOGF("Got unknown SNMP data ~p from ~p~n",[PDU, Ip],?WARN),
{noreply, State}
end;
handle_info(Message, State) ->
{stop, {unknown_message, Message} , State}.
%%--------------------------------------------------------------------
%% Function: terminate/2
%% Description: Shutdown the server
%% Returns: any (ignored by gen_server)
%%--------------------------------------------------------------------
terminate(_Reason, _State) ->
ok.
%%--------------------------------------------------------------------
%% Func: code_change/3
%% Purpose: Convert process state when code is changed
%% Returns: {ok, NewState}
%%--------------------------------------------------------------------
code_change(_OldVsn, State, _Extra) ->
{ok, State}.
%%%----------------------------------------------------------------------
Internal functions
%%%----------------------------------------------------------------------
%%--------------------------------------------------------------------
%% Function: analyse_snmp_data/3
%% Returns: any (send msg to ts_mon)
%%--------------------------------------------------------------------
analyse_snmp_data(Args, Host, State) ->
analyse_snmp_data(Args, Host, [], State).
%% Function: analyse_snmp_data/4
analyse_snmp_data([], _Host, Resp, State) ->
ts_os_mon:send(State#state.mon_server,Resp);
analyse_snmp_data([Val=#varbind{value='NULL'}| Tail], Host, Stats, State) ->
?LOGF("SNMP: Skip void result (~p) ~n", [Val],?DEB),
analyse_snmp_data(Tail, Host, Stats, State);
%% FIXME: this may not be accurate: if we lost packets (the server is
%% overloaded), the value will be inconsistent, since we assume a
%% constant time across samples ($INTERVAL)
analyse_snmp_data([#varbind{oid=?SNMP_CPU_RAW_SYSTEM, value=Val}| Tail], Host, Stats, State) ->
{value, User} = lists:keysearch(?SNMP_CPU_RAW_USER, #varbind.oid, Tail),
Value = Val + User#varbind.value,
CountName = {cpu , Host},
NewValue = Value/(State#state.interval/1000),
NewTail = lists:keydelete(?SNMP_CPU_RAW_USER, #varbind.oid, Tail),
analyse_snmp_data(NewTail, Host, [{sample_counter, CountName, NewValue}| Stats], State);
analyse_snmp_data([User=#varbind{oid=?SNMP_CPU_RAW_USER}| Tail], Host, Stats, State) ->
%%put this entry at the end, this will be used when SYSTEM match
analyse_snmp_data(Tail ++ [User], Host, Stats, State);
analyse_snmp_data([#varbind{oid=OID, value=Val}| Tail], Host, Stats, State) ->
{Type, Name, Value}= oid_to_statname(OID, Host, Val),
?LOGF("Analyse SNMP: ~p:~p:~p ~n", [Type, Name, Value],?DEB),
analyse_snmp_data(Tail, Host, [{Type, Name, Value}| Stats], State).
%%--------------------------------------------------------------------
Function : oid_to_statname/3
%%--------------------------------------------------------------------
oid_to_statname(?SNMP_CPU_RAW_IDLE, Name, Value) ->
CountName = {cpu_idle, Name},
?DebugF("Adding counter value for ~p~n",[CountName]),
{sample_counter, CountName, Value/(?INTERVAL/1000)}; % FIXME ? Interval ??
oid_to_statname(?SNMP_MEM_AVAIL, Name, Value)->
CountName = {freemem, Name},
?DebugF("Adding counter value for ~p~n",[CountName]),
{sample,CountName, Value/1000};
oid_to_statname(?SNMP_CPU_LOAD1, Name, Value)->
CountName = {load, Name},
?DebugF("Adding counter value for ~p~n",[CountName]),
{sample,CountName, Value/100}.
%%--------------------------------------------------------------------
Function : snmp_get/2
%% Description: ask a list of OIDs to the given snmp_mgr
%%--------------------------------------------------------------------
snmp_get(Pid, Oids) ->
?DebugF("send snmp get for oid ~p to pid ~p ",[Oids,Pid]),
Pid ! {get, Oids}.
| null | https://raw.githubusercontent.com/archaelus/tsung/b4ea0419c6902d8bb63795200964d25b19e46532/src/tsung_controller/ts_os_mon_snmp.erl | erlang |
This program is free software; you can redistribute it and/or modify
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
along with this program; if not, write to the Free Software
In addition, as a special exception, you have the permission to
link the code of this program with any library released under
gen_server callbacks
pid of snmp_mgr
SNMP definitions
--------------------------------------------------------------------
Function: init/1
Description: Initiates the server
Returns: {ok, State} |
ignore |
{stop, Reason}
--------------------------------------------------------------------
wait randomly a few miliseconds to avoid concurrents starts of
the snmp_mgr (see the unregister call later)
--------------------------------------------------------------------
Description: Handling call messages
Returns: {reply, Reply, State} |
{stop, Reason, Reply, State} | (terminate/2 is called)
{stop, Reason, State} (terminate/2 is called)
--------------------------------------------------------------------
--------------------------------------------------------------------
Function: handle_cast/2
Description: Handling cast messages
{stop, Reason, State} (terminate/2 is called)
--------------------------------------------------------------------
--------------------------------------------------------------------
Function: handle_info/2
Description: Handling all non call/cast messages
{stop, Reason, State} (terminate/2 is called)
--------------------------------------------------------------------
since snmp_mgr can handle only a single snmp server, change the
registered name to start several smp_mgr at once !
--------------------------------------------------------------------
Function: terminate/2
Description: Shutdown the server
Returns: any (ignored by gen_server)
--------------------------------------------------------------------
--------------------------------------------------------------------
Func: code_change/3
Purpose: Convert process state when code is changed
Returns: {ok, NewState}
--------------------------------------------------------------------
----------------------------------------------------------------------
----------------------------------------------------------------------
--------------------------------------------------------------------
Function: analyse_snmp_data/3
Returns: any (send msg to ts_mon)
--------------------------------------------------------------------
Function: analyse_snmp_data/4
FIXME: this may not be accurate: if we lost packets (the server is
overloaded), the value will be inconsistent, since we assume a
constant time across samples ($INTERVAL)
put this entry at the end, this will be used when SYSTEM match
--------------------------------------------------------------------
--------------------------------------------------------------------
FIXME ? Interval ??
--------------------------------------------------------------------
Description: ask a list of OIDs to the given snmp_mgr
-------------------------------------------------------------------- | Copyright 2008 ©
Author : < >
Created : 21 oct 2008 by < >
it under the terms of the GNU General Public License as published by
the Free Software Foundation ; either version 2 of the License , or
You should have received a copy of the GNU General Public License
Foundation , Inc. , 59 Temple Place , Suite 330 , Boston , MA 02111 - 1307 , USA .
the EPL license and distribute linked combinations including
the two .
-module(ts_os_mon_snmp).
-vc('$Id: ts_os_mon_snmp.erl,v 0.0 2008/10/21 12:57:49 nniclaus Exp $ ').
-author('').
-behaviour(gen_server).
-include("ts_profile.hrl").
-include("ts_os_mon.hrl").
-include_lib("snmp/include/snmp_types.hrl").
-export([start/1]).
-export([init/1, handle_call/3, handle_cast/2, handle_info/2,
terminate/2, code_change/3]).
-record(state,{
pid of mon server
dnscache=[],
interval,
host,
version,
port,
community,
addr
}).
FIXME : make this customizable in the XML config file ?
-define(SNMP_CPU_RAW_USER, [1,3,6,1,4,1,2021,11,50,0]).
-define(SNMP_CPU_RAW_SYSTEM, [1,3,6,1,4,1,2021,11,52,0]).
-define(SNMP_CPU_RAW_IDLE, [1,3,6,1,4,1,2021,11,53,0]).
-define(SNMP_CPU_LOAD1, [1,3,6,1,4,1,2021,10,1,5,1]).
-define(SNMP_MEM_BUFFER, [1,3,6,1,4,1,2021,4,14,0]).
-define(SNMP_MEM_CACHED, [1,3,6,1,4,1,2021,4,15,0]).
-define(SNMP_MEM_AVAIL, [1,3,6,1,4,1,2021,4,6,0]).
-define(SNMP_MEM_TOTAL, [1,3,6,1,4,1,2021,4,5,0]).
start(Args) ->
?LOGF("starting os_mon_snmp with args ~p",[Args],?NOTICE),
gen_server:start_link(?MODULE, Args, []).
{ ok , State , Timeout } |
init({HostStr, {Port, Community, Version}, Interval, MonServer}) ->
{ok, IP} = inet:getaddr(HostStr, inet),
ts_utils:init_seed(),
Wait = random:uniform(?INIT_WAIT),
erlang:start_timer(Wait, self(), connect ),
?LOGF("Starting SNMP mgr on ~p (~p)~n", [IP,Wait], ?DEB),
{ok, #state{ mon_server = MonServer,
host = HostStr,
port = Port,
addr = IP,
community = Community,
version = Version,
interval = Interval}}.
Function : handle_call/3
{ reply , Reply , State , Timeout } |
{ noreply , State } |
{ noreply , State , Timeout } |
handle_call(_Request, _From, State) ->
Reply = ok,
{reply, Reply, State}.
Returns : { noreply , State } |
{ noreply , State , Timeout } |
handle_cast(Msg, State) ->
{stop, {unknown_message, Msg}, State}.
Returns : { noreply , State } |
{ noreply , State , Timeout } |
handle_info({timeout,_Ref,connect},State=#state{addr=IP,port=Port,community=Community,version=Version}) ->
{ok, Pid} = snmp_mgr:start_link([{agent, IP},
{agent_udp, Port},
{community, Community},
{receive_type, msg},
Version,
quiet
]),
unregister(snmp_mgr),
?LOGF("SNMP mgr started; remote node is ~p~n", [IP],?INFO),
erlang:start_timer(State#state.interval, self(), send_request ),
{noreply, State#state{pid=Pid}};
handle_info({timeout,_Ref,send_request},State=#state{pid=Pid, host=Host}) ->
?LOGF("SNMP mgr; get data from host ~p~n", [Host],?DEB),
snmp_get(Pid,
[?SNMP_CPU_RAW_SYSTEM,
?SNMP_CPU_RAW_USER,
?SNMP_MEM_AVAIL,
?SNMP_CPU_LOAD1]),
erlang:start_timer(State#state.interval, self(), send_request ),
{noreply,State};
handle_info({snmp_msg, Msg, Ip, _Udp}, State) ->
PDU = snmp_mgr_misc:get_pdu(Msg),
case PDU#pdu.type of
'get-response' ->
?LOGF("Got SNMP PDU ~p from ~p~n",[PDU, Ip],?DEB),
{Hostname, NewCache} = ts_utils:resolve(Ip, State#state.dnscache),
analyse_snmp_data(PDU#pdu.varbinds, Hostname, State),
{noreply, State#state{dnscache=NewCache}};
_ ->
?LOGF("Got unknown SNMP data ~p from ~p~n",[PDU, Ip],?WARN),
{noreply, State}
end;
handle_info(Message, State) ->
{stop, {unknown_message, Message} , State}.
terminate(_Reason, _State) ->
ok.
code_change(_OldVsn, State, _Extra) ->
{ok, State}.
Internal functions
analyse_snmp_data(Args, Host, State) ->
analyse_snmp_data(Args, Host, [], State).
analyse_snmp_data([], _Host, Resp, State) ->
ts_os_mon:send(State#state.mon_server,Resp);
analyse_snmp_data([Val=#varbind{value='NULL'}| Tail], Host, Stats, State) ->
?LOGF("SNMP: Skip void result (~p) ~n", [Val],?DEB),
analyse_snmp_data(Tail, Host, Stats, State);
analyse_snmp_data([#varbind{oid=?SNMP_CPU_RAW_SYSTEM, value=Val}| Tail], Host, Stats, State) ->
{value, User} = lists:keysearch(?SNMP_CPU_RAW_USER, #varbind.oid, Tail),
Value = Val + User#varbind.value,
CountName = {cpu , Host},
NewValue = Value/(State#state.interval/1000),
NewTail = lists:keydelete(?SNMP_CPU_RAW_USER, #varbind.oid, Tail),
analyse_snmp_data(NewTail, Host, [{sample_counter, CountName, NewValue}| Stats], State);
analyse_snmp_data([User=#varbind{oid=?SNMP_CPU_RAW_USER}| Tail], Host, Stats, State) ->
analyse_snmp_data(Tail ++ [User], Host, Stats, State);
analyse_snmp_data([#varbind{oid=OID, value=Val}| Tail], Host, Stats, State) ->
{Type, Name, Value}= oid_to_statname(OID, Host, Val),
?LOGF("Analyse SNMP: ~p:~p:~p ~n", [Type, Name, Value],?DEB),
analyse_snmp_data(Tail, Host, [{Type, Name, Value}| Stats], State).
Function : oid_to_statname/3
oid_to_statname(?SNMP_CPU_RAW_IDLE, Name, Value) ->
CountName = {cpu_idle, Name},
?DebugF("Adding counter value for ~p~n",[CountName]),
oid_to_statname(?SNMP_MEM_AVAIL, Name, Value)->
CountName = {freemem, Name},
?DebugF("Adding counter value for ~p~n",[CountName]),
{sample,CountName, Value/1000};
oid_to_statname(?SNMP_CPU_LOAD1, Name, Value)->
CountName = {load, Name},
?DebugF("Adding counter value for ~p~n",[CountName]),
{sample,CountName, Value/100}.
Function : snmp_get/2
snmp_get(Pid, Oids) ->
?DebugF("send snmp get for oid ~p to pid ~p ",[Oids,Pid]),
Pid ! {get, Oids}.
|
d8e307ed367f3d327a32f8383a9840bfd67202e30096b7db05c731629e737c19 | haskellfoundation/error-message-index | DerivingInt.hs | module DerivingInt where
data Example = Example
deriving Eq
| null | https://raw.githubusercontent.com/haskellfoundation/error-message-index/6b80c2fe6d8d2941190bda587bcea6f775ded0a4/message-index/messages/GHC-11913/deriving-int/after/DerivingInt.hs | haskell | module DerivingInt where
data Example = Example
deriving Eq
|
|
9cb85be5cab31728fdd43db5db7d05afd8fe240ce80851a7562c03d521a78a54 | Clozure/ccl-tests | subst-if-not.lsp | ;-*- Mode: Lisp -*-
Author :
Created : Sat Apr 19 21:48:22 2003
Contains : Tests of SUBST - IF - NOT
(in-package :cl-test)
(compile-and-load "cons-aux.lsp")
(deftest subst-if-not.1
(check-subst-if-not '(x) 'consp '(1 (1 2) (1 2 3) (1 2 3 4)))
((x)
((x) (x) x)
((x) (x) (x) x)
((x) (x) (x) (x) x)
x))
(deftest subst-if-not.2
(check-subst-if-not 'a (complement #'listp)
'((100 1) (2 3) (4 3 2 1) (a b c)))
a)
(deftest subst-if-not.3
(check-subst-if-not 'c #'identity
'((100 1) (2 3) (4 3 2 1) (a b c))
:key (complement #'listp))
c)
(deftest subst-if-not.4
(check-subst-if-not
40
#'(lambda (x) (not (eql x 17)))
'((17) (17 22) (17 22 31) (17 21 34 54))
:key #'(lambda (x)
(and (consp x)
(car x))))
(40 40 40 40))
(deftest subst-if-not.5
(check-subst-if-not 'a #'(lambda (x) (not (eql x 'b)))
'((a) (b) (c) (d))
:key nil)
((a) (a) (c) (d)))
(deftest subst-if-not.7
(let ((i 0) w x y z)
(values
(subst-if-not
(progn (setf w (incf i)) 'a)
(progn (setf x (incf i)) #'(lambda (x) (not (eql x 'b))))
(progn (setf y (incf i)) (copy-list '(1 2 a b c)))
:key (progn (setf z (incf i)) #'identity))
i w x y z))
(1 2 a a c)
4 1 2 3 4)
(def-fold-test subst-if-not.fold.1 (subst-if-not 'a #'consp '((1 . 2) 3 . 4)))
;;; Keywords tests for subst-if-not
(deftest subst-if-not.allow-other-keys.1
(subst-if-not 'a #'identity nil :bad t :allow-other-keys t)
a)
(deftest subst-if-not.allow-other-keys.2
(subst-if-not 'a #'identity nil :allow-other-keys t)
a)
(deftest subst-if-not.allow-other-keys.3
(subst-if-not 'a #'identity nil :allow-other-keys nil)
a)
(deftest subst-if-not.allow-other-keys.4
(subst-if-not 'a #'identity nil :allow-other-keys t :bad t)
a)
(deftest subst-if-not.allow-other-keys.5
(subst-if-not 'a #'identity nil :allow-other-keys t
:allow-other-keys nil :bad t)
a)
(deftest subst-if-not.keywords.6
(subst-if-not 'a #'identity nil :key nil :key (constantly 'b))
a)
;;; error cases
(deftest subst-if-not.error.1
(signals-error (subst-if-not) program-error)
t)
(deftest subst-if-not.error.2
(signals-error (subst-if-not 'a) program-error)
t)
(deftest subst-if-not.error.3
(signals-error (subst-if-not 'a #'null) program-error)
t)
(deftest subst-if-not.error.4
(signals-error (subst-if-not 'a #'null nil :foo nil) program-error)
t)
(deftest subst-if-not.error.5
(signals-error (subst-if-not 'a #'null nil :test) program-error)
t)
(deftest subst-if-not.error.6
(signals-error (subst-if-not 'a #'null nil 1) program-error)
t)
(deftest subst-if-not.error.7
(signals-error (subst-if-not 'a #'null nil
:bad t :allow-other-keys nil) program-error)
t)
(deftest subst-if-not.error.8
(signals-error (subst-if-not 'a #'null (list 'a nil 'c) :key #'cons) program-error)
t)
| null | https://raw.githubusercontent.com/Clozure/ccl-tests/0478abddb34dbc16487a1975560d8d073a988060/ansi-tests/subst-if-not.lsp | lisp | -*- Mode: Lisp -*-
Keywords tests for subst-if-not
error cases | Author :
Created : Sat Apr 19 21:48:22 2003
Contains : Tests of SUBST - IF - NOT
(in-package :cl-test)
(compile-and-load "cons-aux.lsp")
(deftest subst-if-not.1
(check-subst-if-not '(x) 'consp '(1 (1 2) (1 2 3) (1 2 3 4)))
((x)
((x) (x) x)
((x) (x) (x) x)
((x) (x) (x) (x) x)
x))
(deftest subst-if-not.2
(check-subst-if-not 'a (complement #'listp)
'((100 1) (2 3) (4 3 2 1) (a b c)))
a)
(deftest subst-if-not.3
(check-subst-if-not 'c #'identity
'((100 1) (2 3) (4 3 2 1) (a b c))
:key (complement #'listp))
c)
(deftest subst-if-not.4
(check-subst-if-not
40
#'(lambda (x) (not (eql x 17)))
'((17) (17 22) (17 22 31) (17 21 34 54))
:key #'(lambda (x)
(and (consp x)
(car x))))
(40 40 40 40))
(deftest subst-if-not.5
(check-subst-if-not 'a #'(lambda (x) (not (eql x 'b)))
'((a) (b) (c) (d))
:key nil)
((a) (a) (c) (d)))
(deftest subst-if-not.7
(let ((i 0) w x y z)
(values
(subst-if-not
(progn (setf w (incf i)) 'a)
(progn (setf x (incf i)) #'(lambda (x) (not (eql x 'b))))
(progn (setf y (incf i)) (copy-list '(1 2 a b c)))
:key (progn (setf z (incf i)) #'identity))
i w x y z))
(1 2 a a c)
4 1 2 3 4)
(def-fold-test subst-if-not.fold.1 (subst-if-not 'a #'consp '((1 . 2) 3 . 4)))
(deftest subst-if-not.allow-other-keys.1
(subst-if-not 'a #'identity nil :bad t :allow-other-keys t)
a)
(deftest subst-if-not.allow-other-keys.2
(subst-if-not 'a #'identity nil :allow-other-keys t)
a)
(deftest subst-if-not.allow-other-keys.3
(subst-if-not 'a #'identity nil :allow-other-keys nil)
a)
(deftest subst-if-not.allow-other-keys.4
(subst-if-not 'a #'identity nil :allow-other-keys t :bad t)
a)
(deftest subst-if-not.allow-other-keys.5
(subst-if-not 'a #'identity nil :allow-other-keys t
:allow-other-keys nil :bad t)
a)
(deftest subst-if-not.keywords.6
(subst-if-not 'a #'identity nil :key nil :key (constantly 'b))
a)
(deftest subst-if-not.error.1
(signals-error (subst-if-not) program-error)
t)
(deftest subst-if-not.error.2
(signals-error (subst-if-not 'a) program-error)
t)
(deftest subst-if-not.error.3
(signals-error (subst-if-not 'a #'null) program-error)
t)
(deftest subst-if-not.error.4
(signals-error (subst-if-not 'a #'null nil :foo nil) program-error)
t)
(deftest subst-if-not.error.5
(signals-error (subst-if-not 'a #'null nil :test) program-error)
t)
(deftest subst-if-not.error.6
(signals-error (subst-if-not 'a #'null nil 1) program-error)
t)
(deftest subst-if-not.error.7
(signals-error (subst-if-not 'a #'null nil
:bad t :allow-other-keys nil) program-error)
t)
(deftest subst-if-not.error.8
(signals-error (subst-if-not 'a #'null (list 'a nil 'c) :key #'cons) program-error)
t)
|
2199768357267c280678b34bba28c992ead8340faf188a246d658a3e20d57a0f | macourtney/drift | dynamic_config.clj | (ns config.dynamic-config
(use clojure.test))
(defn config []
{:init (fn [args]
(is (= args ["bloop" "blargh"]))
{:more-config 42})})
| null | https://raw.githubusercontent.com/macourtney/drift/b5cf735ab41ff2c95b0b1d9cf990faa342353171/test/config/dynamic_config.clj | clojure | (ns config.dynamic-config
(use clojure.test))
(defn config []
{:init (fn [args]
(is (= args ["bloop" "blargh"]))
{:more-config 42})})
|
|
5380b9ba7ea02fef545bc1c1153bf7791b2be62842014284fc7aac9c13266dd2 | lem-project/lem | swank-arglists.lisp | ;;; swank-arglists.lisp --- arglist related code ??
;;
Authors : < >
< >
;; and others
;;
;; License: Public Domain
;;
(in-package :micros)
Utilities
(defun compose (&rest functions)
"Compose FUNCTIONS right-associatively, returning a function"
#'(lambda (x)
(reduce #'funcall functions :initial-value x :from-end t)))
(defun length= (seq n)
"Test for whether SEQ contains N number of elements. I.e. it's equivalent
to (= (LENGTH SEQ) N), but besides being more concise, it may also be more
efficiently implemented."
(etypecase seq
(list (do ((i n (1- i))
(list seq (cdr list)))
((or (<= i 0) (null list))
(and (zerop i) (null list)))))
(sequence (= (length seq) n))))
(declaim (inline memq))
(defun memq (item list)
(member item list :test #'eq))
(defun exactly-one-p (&rest values)
"If exactly one value in VALUES is non-NIL, this value is returned.
Otherwise NIL is returned."
(let ((found nil))
(dolist (v values)
(when v (if found
(return-from exactly-one-p nil)
(setq found v))))
found))
(defun valid-operator-symbol-p (symbol)
"Is SYMBOL the name of a function, a macro, or a special-operator?"
(or (fboundp symbol)
(macro-function symbol)
(special-operator-p symbol)
(member symbol '(declare declaim))))
(defun function-exists-p (form)
(and (valid-function-name-p form)
(fboundp form)
t))
(defmacro multiple-value-or (&rest forms)
(if (null forms)
nil
(let ((first (first forms))
(rest (rest forms)))
`(let* ((values (multiple-value-list ,first))
(primary-value (first values)))
(if primary-value
(values-list values)
(multiple-value-or ,@rest))))))
(defun arglist-available-p (arglist)
(not (eql arglist :not-available)))
(defmacro with-available-arglist ((var &rest more-vars) form &body body)
`(multiple-value-bind (,var ,@more-vars) ,form
(if (eql ,var :not-available)
:not-available
(progn ,@body))))
;;;; Arglist Definition
(defstruct (arglist (:conc-name arglist.) (:predicate arglist-p))
provided-args ; list of the provided actual arguments
required-args ; list of the required arguments
optional-args ; list of the optional arguments
key-p ; whether &key appeared
keyword-args ; list of the keywords
name of the & rest or & body argument ( if any )
body-p ; whether the rest argument is a &body
allow-other-keys-p ; whether &allow-other-keys appeared
list of & aux variables
any-p ; whether &any appeared
any-args ; list of &any arguments [*]
known-junk ; &whole, &environment
unknown-junk) ; unparsed stuff
;;;
;;; [*] The &ANY lambda keyword is an extension to ANSI Common Lisp,
;;; and is only used to describe certain arglists that cannot be
;;; described in another way.
;;;
;;; &ANY is very similiar to &KEY but while &KEY is based upon
;;; the idea of a plist (key1 value1 key2 value2), &ANY is a
cross between & OPTIONAL , & KEY and * FEATURES * lists :
;;;
;;; a) (&ANY :A :B :C) means that you can provide any (non-null)
;;; set consisting of the keywords `:A', `:B', or `:C' in
;;; the arglist. E.g. (:A) or (:C :B :A).
;;;
;;; (This is not restricted to keywords only, but any self-evaluating
;;; expression is allowed.)
;;;
b ) ( & ANY ( key1 v1 ) ( key2 v2 ) ( key3 v3 ) ) means that you can
;;; provide any (non-null) set consisting of lists where
the CAR of the list is one of ` key1 ' , ` key2 ' , or ` key3 ' .
E.g. ( ( key1 100 ) ( key3 42 ) ) , or ( ( key3 66 ) ( key2 23 ) )
;;;
;;;
For example , a ) let us describe the situations of EVAL - WHEN as
;;;
;;; (EVAL-WHEN (&ANY :compile-toplevel :load-toplevel :execute) &BODY body)
;;;
;;; and b) let us describe the optimization qualifiers that are valid
;;; in the declaration specifier `OPTIMIZE':
;;;
( DECLARE ( OPTIMIZE & ANY ( compilation - speed 1 ) ( safety 1 ) ... ) )
;;;
;; This is a wrapper object around anything that came from Slime and
;; could not reliably be read.
(defstruct (arglist-dummy
(:conc-name #:arglist-dummy.)
(:constructor make-arglist-dummy (string-representation)))
string-representation)
(defun empty-arg-p (dummy)
(and (arglist-dummy-p dummy)
(zerop (length (arglist-dummy.string-representation dummy)))))
(eval-when (:compile-toplevel :load-toplevel :execute)
(defparameter +lambda-list-keywords+
'(&provided &required &optional &rest &key &any)))
;; muffle warnings about using accessors prior to the definition of struct
(declaim (notinline keyword-arg.keyword
keyword-arg.arg-name
keyword-arg.default-arg
optional-arg.arg-name
optional-arg.default-arg))
(defmacro do-decoded-arglist (decoded-arglist &body clauses)
(assert (loop for clause in clauses
thereis (member (car clause) +lambda-list-keywords+)))
(flet ((parse-clauses (clauses)
(let* ((size (length +lambda-list-keywords+))
(initial (make-hash-table :test #'eq :size size))
(main (make-hash-table :test #'eq :size size))
(final (make-hash-table :test #'eq :size size)))
(loop for clause in clauses
for lambda-list-keyword = (first clause)
for clause-parameter = (second clause)
do
(case clause-parameter
(:initially
(setf (gethash lambda-list-keyword initial) clause))
(:finally
(setf (gethash lambda-list-keyword final) clause))
(t
(setf (gethash lambda-list-keyword main) clause)))
finally
(return (values initial main final)))))
(generate-main-clause (clause arglist)
(dcase clause
((&provided (&optional arg) . body)
(let ((gensym (gensym "PROVIDED-ARG+")))
`(dolist (,gensym (arglist.provided-args ,arglist))
(declare (ignorable ,gensym))
(let (,@(when arg `((,arg ,gensym))))
,@body))))
((&required (&optional arg) . body)
(let ((gensym (gensym "REQUIRED-ARG+")))
`(dolist (,gensym (arglist.required-args ,arglist))
(declare (ignorable ,gensym))
(let (,@(when arg `((,arg ,gensym))))
,@body))))
((&optional (&optional arg init) . body)
(let ((optarg (gensym "OPTIONAL-ARG+")))
`(dolist (,optarg (arglist.optional-args ,arglist))
(declare (ignorable ,optarg))
(let (,@(when arg
`((,arg (optional-arg.arg-name ,optarg))))
,@(when init
`((,init (optional-arg.default-arg ,optarg)))))
,@body))))
((&key (&optional keyword arg init) . body)
(let ((keyarg (gensym "KEY-ARG+")))
`(dolist (,keyarg (arglist.keyword-args ,arglist))
(declare (ignorable ,keyarg))
(let (,@(when keyword
`((,keyword (keyword-arg.keyword ,keyarg))))
,@(when arg
`((,arg (keyword-arg.arg-name ,keyarg))))
,@(when init
`((,init (keyword-arg.default-arg ,keyarg)))))
,@body))))
((&rest (&optional arg body-p) . body)
`(when (arglist.rest ,arglist)
(let (,@(when arg `((,arg (arglist.rest ,arglist))))
,@(when body-p `((,body-p (arglist.body-p ,arglist)))))
,@body)))
((&any (&optional arg) . body)
(let ((gensym (gensym "REQUIRED-ARG+")))
`(dolist (,gensym (arglist.any-args ,arglist))
(declare (ignorable ,gensym))
(let (,@(when arg `((,arg ,gensym))))
,@body)))))))
(let ((arglist (gensym "DECODED-ARGLIST+")))
(multiple-value-bind (initially-clauses main-clauses finally-clauses)
(parse-clauses clauses)
`(let ((,arglist ,decoded-arglist))
(block do-decoded-arglist
,@(loop for keyword in '(&provided &required
&optional &rest &key &any)
append (cddr (gethash keyword initially-clauses))
collect (let ((clause (gethash keyword main-clauses)))
(when clause
(generate-main-clause clause arglist)))
append (cddr (gethash keyword finally-clauses)))))))))
;;;; Arglist Printing
(defun undummy (x)
(if (typep x 'arglist-dummy)
(arglist-dummy.string-representation x)
(prin1-to-string x)))
(defun print-decoded-arglist (arglist &key operator provided-args highlight)
(let ((first-space-after-operator (and operator t)))
(macrolet ((space ()
: When OPERATOR is not given , we do n't want to
print a space for the first argument .
`(if (not operator)
(setq operator t)
(progn (write-char #\space)
(if first-space-after-operator
(setq first-space-after-operator nil)
(pprint-newline :fill)))))
(with-highlighting ((&key index) &body body)
`(if (eql ,index (car highlight))
(progn (princ "===> ") ,@body (princ " <==="))
(progn ,@body)))
(print-arglist-recursively (argl &key index)
`(if (eql ,index (car highlight))
(print-decoded-arglist ,argl :highlight (cdr highlight))
(print-decoded-arglist ,argl))))
(let ((index 0))
(pprint-logical-block (nil nil :prefix "(" :suffix ")")
(when operator
(print-arg operator)
1 due to possibly added space
(do-decoded-arglist (remove-given-args arglist provided-args)
(&provided (arg)
(space)
(print-arg arg :literal-strings t)
(incf index))
(&required (arg)
(space)
(if (arglist-p arg)
(print-arglist-recursively arg :index index)
(with-highlighting (:index index)
(print-arg arg)))
(incf index))
(&optional :initially
(when (arglist.optional-args arglist)
(space)
(princ '&optional)))
(&optional (arg init-value)
(space)
(if (arglist-p arg)
(print-arglist-recursively arg :index index)
(with-highlighting (:index index)
(if (null init-value)
(print-arg arg)
(format t "~:@<~A ~A~@:>"
(undummy arg) (undummy init-value)))))
(incf index))
(&key :initially
(when (arglist.key-p arglist)
(space)
(princ '&key)))
(&key (keyword arg init)
(space)
(if (arglist-p arg)
(pprint-logical-block (nil nil :prefix "(" :suffix ")")
(prin1 keyword) (space)
(print-arglist-recursively arg :index keyword))
(with-highlighting (:index keyword)
(cond ((and init (keywordp keyword))
(format t "~:@<~A ~A~@:>" keyword (undummy init)))
(init
(format t "~:@<(~A ..) ~A~@:>"
(undummy keyword) (undummy init)))
((not (keywordp keyword))
(format t "~:@<(~S ..)~@:>" keyword))
(t
(princ keyword))))))
(&key :finally
(when (arglist.allow-other-keys-p arglist)
(space)
(princ '&allow-other-keys)))
(&any :initially
(when (arglist.any-p arglist)
(space)
(princ '&any)))
(&any (arg)
(space)
(print-arg arg))
(&rest (args bodyp)
(space)
(princ (if bodyp '&body '&rest))
(space)
(if (arglist-p args)
(print-arglist-recursively args :index index)
(with-highlighting (:index index)
(print-arg args))))
;; FIXME: add &UNKNOWN-JUNK?
))))))
(defun print-arg (arg &key literal-strings)
(let ((arg (if (arglist-dummy-p arg)
(arglist-dummy.string-representation arg)
arg)))
(if (or
(and literal-strings
(stringp arg))
(keywordp arg))
(prin1 arg)
(princ arg))))
(defun print-decoded-arglist-as-template (decoded-arglist &key
(prefix "(") (suffix ")"))
(let ((first-p t))
(flet ((space ()
(unless first-p
(write-char #\space))
(setq first-p nil))
(print-arg-or-pattern (arg)
(etypecase arg
(symbol (if (keywordp arg) (prin1 arg) (princ arg)))
(string (princ arg))
(list (princ arg))
(arglist-dummy (princ
(arglist-dummy.string-representation arg)))
(arglist (print-decoded-arglist-as-template arg)))
(pprint-newline :fill)))
(pprint-logical-block (nil nil :prefix prefix :suffix suffix)
(do-decoded-arglist decoded-arglist
(&provided ()) ; do nothing; provided args are in the buffer already.
(&required (arg)
(space) (print-arg-or-pattern arg))
(&optional (arg)
(space) (princ "[") (print-arg-or-pattern arg) (princ "]"))
(&key (keyword arg)
(space)
(prin1 (if (keywordp keyword) keyword `',keyword))
(space)
(print-arg-or-pattern arg)
(pprint-newline :linear))
(&any (arg)
(space) (print-arg-or-pattern arg))
(&rest (args)
(when (or (not (arglist.keyword-args decoded-arglist))
(arglist.allow-other-keys-p decoded-arglist))
(space)
(format t "~A..." args))))))))
(defvar *arglist-pprint-bindings*
'((*print-case* . :downcase)
(*print-pretty* . t)
(*print-circle* . nil)
(*print-readably* . nil)
(*print-level* . 10)
(*print-length* . 20)
(*print-escape* . nil)))
(defvar *arglist-show-packages* t)
(defmacro with-arglist-io-syntax (&body body)
(let ((package (gensym)))
`(let ((,package *package*))
(with-standard-io-syntax
(let ((*package* (if *arglist-show-packages*
*package*
,package)))
(with-bindings *arglist-pprint-bindings*
,@body))))))
(defun decoded-arglist-to-string (decoded-arglist
&key operator highlight
print-right-margin)
(with-output-to-string (*standard-output*)
(with-arglist-io-syntax
(let ((*print-right-margin* print-right-margin))
(print-decoded-arglist decoded-arglist
:operator operator
:highlight highlight)))))
(defun decoded-arglist-to-template-string (decoded-arglist
&key (prefix "(") (suffix ")"))
(with-output-to-string (*standard-output*)
(with-arglist-io-syntax
(print-decoded-arglist-as-template decoded-arglist
:prefix prefix
:suffix suffix))))
Arglist Decoding / Encoding
(defun decode-required-arg (arg)
"ARG can be a symbol or a destructuring pattern."
(etypecase arg
(symbol arg)
(arglist-dummy arg)
(list (decode-arglist arg))))
(defun encode-required-arg (arg)
(etypecase arg
(symbol arg)
(arglist (encode-arglist arg))))
(defstruct (keyword-arg
(:conc-name keyword-arg.)
(:constructor %make-keyword-arg))
keyword
arg-name
default-arg)
(defun canonicalize-default-arg (form)
(if (equalp ''nil form)
nil
form))
(defun make-keyword-arg (keyword arg-name default-arg)
(%make-keyword-arg :keyword keyword
:arg-name arg-name
:default-arg (canonicalize-default-arg default-arg)))
(defun decode-keyword-arg (arg)
"Decode a keyword item of formal argument list.
Return three values: keyword, argument name, default arg."
(flet ((intern-as-keyword (arg)
(intern (etypecase arg
(symbol (symbol-name arg))
(arglist-dummy (arglist-dummy.string-representation arg)))
keyword-package)))
(cond ((or (symbolp arg) (arglist-dummy-p arg))
(make-keyword-arg (intern-as-keyword arg) arg nil))
((and (consp arg)
(consp (car arg)))
(make-keyword-arg (caar arg)
(decode-required-arg (cadar arg))
(cadr arg)))
((consp arg)
(make-keyword-arg (intern-as-keyword (car arg))
(car arg) (cadr arg)))
(t
(error "Bad keyword item of formal argument list")))))
(defun encode-keyword-arg (arg)
(cond
((arglist-p (keyword-arg.arg-name arg))
;; Destructuring pattern
(let ((keyword/name (list (keyword-arg.keyword arg)
(encode-required-arg
(keyword-arg.arg-name arg)))))
(if (keyword-arg.default-arg arg)
(list keyword/name
(keyword-arg.default-arg arg))
(list keyword/name))))
((eql (intern (symbol-name (keyword-arg.arg-name arg))
keyword-package)
(keyword-arg.keyword arg))
(if (keyword-arg.default-arg arg)
(list (keyword-arg.arg-name arg)
(keyword-arg.default-arg arg))
(keyword-arg.arg-name arg)))
(t
(let ((keyword/name (list (keyword-arg.keyword arg)
(keyword-arg.arg-name arg))))
(if (keyword-arg.default-arg arg)
(list keyword/name
(keyword-arg.default-arg arg))
(list keyword/name))))))
(progn
(assert (equalp (decode-keyword-arg 'x)
(make-keyword-arg :x 'x nil)))
(assert (equalp (decode-keyword-arg '(x t))
(make-keyword-arg :x 'x t)))
(assert (equalp (decode-keyword-arg '((:x y)))
(make-keyword-arg :x 'y nil)))
(assert (equalp (decode-keyword-arg '((:x y) t))
(make-keyword-arg :x 'y t))))
;;; FIXME suppliedp?
(defstruct (optional-arg
(:conc-name optional-arg.)
(:constructor %make-optional-arg))
arg-name
default-arg)
(defun make-optional-arg (arg-name default-arg)
(%make-optional-arg :arg-name arg-name
:default-arg (canonicalize-default-arg default-arg)))
(defun decode-optional-arg (arg)
"Decode an optional item of a formal argument list.
Return an OPTIONAL-ARG structure."
(etypecase arg
(symbol (make-optional-arg arg nil))
(arglist-dummy (make-optional-arg arg nil))
(list (make-optional-arg (decode-required-arg (car arg))
(cadr arg)))))
(defun encode-optional-arg (optional-arg)
(if (or (optional-arg.default-arg optional-arg)
(arglist-p (optional-arg.arg-name optional-arg)))
(list (encode-required-arg
(optional-arg.arg-name optional-arg))
(optional-arg.default-arg optional-arg))
(optional-arg.arg-name optional-arg)))
(progn
(assert (equalp (decode-optional-arg 'x)
(make-optional-arg 'x nil)))
(assert (equalp (decode-optional-arg '(x t))
(make-optional-arg 'x t))))
(define-modify-macro nreversef () nreverse "Reverse the list in PLACE.")
(defun decode-arglist (arglist)
"Parse the list ARGLIST and return an ARGLIST structure."
(if (eq arglist :not-available)
:not-available
(loop
with mode = nil
with result = (make-arglist)
for arg = (if (consp arglist)
(pop arglist)
(progn
(prog1 arglist
(setf mode '&rest
arglist nil))))
do (cond
((eql mode '&unknown-junk)
;; don't leave this mode -- we don't know how the arglist
;; after unknown lambda-list keywords is interpreted
(push arg (arglist.unknown-junk result)))
((eql arg '&allow-other-keys)
(setf (arglist.allow-other-keys-p result) t))
((eql arg '&key)
(setf (arglist.key-p result) t
mode arg))
((memq arg '(&optional &rest &body &aux))
(setq mode arg))
((memq arg '(&whole &environment))
(setq mode arg)
(push arg (arglist.known-junk result)))
((and (symbolp arg)
(string= (symbol-name arg) (string '#:&any))) ; may be interned
(setf (arglist.any-p result) t) ; in any *package*.
(setq mode '&any))
((memq arg lambda-list-keywords)
(setq mode '&unknown-junk)
(push arg (arglist.unknown-junk result)))
(t
(ecase mode
(&key
(push (decode-keyword-arg arg)
(arglist.keyword-args result)))
(&optional
(push (decode-optional-arg arg)
(arglist.optional-args result)))
(&body
(setf (arglist.body-p result) t
(arglist.rest result) arg))
(&rest
(setf (arglist.rest result) arg))
(&aux
(push (decode-optional-arg arg)
(arglist.aux-args result)))
((nil)
(push (decode-required-arg arg)
(arglist.required-args result)))
((&whole &environment)
(setf mode nil)
(push arg (arglist.known-junk result)))
(&any
(push arg (arglist.any-args result))))))
until (null arglist)
finally (nreversef (arglist.required-args result))
finally (nreversef (arglist.optional-args result))
finally (nreversef (arglist.keyword-args result))
finally (nreversef (arglist.aux-args result))
finally (nreversef (arglist.any-args result))
finally (nreversef (arglist.known-junk result))
finally (nreversef (arglist.unknown-junk result))
finally (assert (or (and (not (arglist.key-p result))
(not (arglist.any-p result)))
(exactly-one-p (arglist.key-p result)
(arglist.any-p result))))
finally (return result))))
(defun encode-arglist (decoded-arglist)
(append (mapcar #'encode-required-arg
(arglist.required-args decoded-arglist))
(when (arglist.optional-args decoded-arglist)
'(&optional))
(mapcar #'encode-optional-arg
(arglist.optional-args decoded-arglist))
(when (arglist.key-p decoded-arglist)
'(&key))
(mapcar #'encode-keyword-arg
(arglist.keyword-args decoded-arglist))
(when (arglist.allow-other-keys-p decoded-arglist)
'(&allow-other-keys))
(when (arglist.any-args decoded-arglist)
`(&any ,@(arglist.any-args decoded-arglist)))
(cond ((not (arglist.rest decoded-arglist))
'())
((arglist.body-p decoded-arglist)
`(&body ,(arglist.rest decoded-arglist)))
(t
`(&rest ,(arglist.rest decoded-arglist))))
(when (arglist.aux-args decoded-arglist)
`(&aux ,(arglist.aux-args decoded-arglist)))
(arglist.known-junk decoded-arglist)
(arglist.unknown-junk decoded-arglist)))
Arglist Enrichment
(defun arglist-keywords (lambda-list)
"Return the list of keywords in ARGLIST.
As a secondary value, return whether &allow-other-keys appears."
(let ((decoded-arglist (decode-arglist lambda-list)))
(values (arglist.keyword-args decoded-arglist)
(arglist.allow-other-keys-p decoded-arglist))))
(defun methods-keywords (methods)
"Collect all keywords in the arglists of METHODS.
As a secondary value, return whether &allow-other-keys appears somewhere."
(let ((keywords '())
(allow-other-keys nil))
(dolist (method methods)
(multiple-value-bind (kw aok)
(arglist-keywords
(micros/mop:method-lambda-list method))
(setq keywords (remove-duplicates (append keywords kw)
:key #'keyword-arg.keyword)
allow-other-keys (or allow-other-keys aok))))
(values keywords allow-other-keys)))
(defun generic-function-keywords (generic-function)
"Collect all keywords in the methods of GENERIC-FUNCTION.
As a secondary value, return whether &allow-other-keys appears somewhere."
(methods-keywords
(micros/mop:generic-function-methods generic-function)))
(defun applicable-methods-keywords (generic-function arguments)
"Collect all keywords in the methods of GENERIC-FUNCTION that are
applicable for argument of CLASSES. As a secondary value, return
whether &allow-other-keys appears somewhere."
(methods-keywords
(multiple-value-bind (amuc okp)
(micros/mop:compute-applicable-methods-using-classes
generic-function (mapcar #'class-of arguments))
(if okp
amuc
(compute-applicable-methods generic-function arguments)))))
(defgeneric extra-keywords (operator args)
(:documentation "Return a list of extra keywords of OPERATOR (a
symbol) when applied to the (unevaluated) ARGS.
As a secondary value, return whether other keys are allowed.
As a tertiary value, return the initial sublist of ARGS that was needed
to determine the extra keywords."))
We make sure that symbol - from - KEYWORD - using keywords come before
;;; symbol-from-arbitrary-package-using keywords. And we sort the
;;; latter according to how their home-packages relate to *PACKAGE*.
;;;
Rationale is to show those key parameters first which make most
;;; sense in the current context. And in particular: to put
;;; implementation-internal stuff last.
;;;
This matters tremendeously on Allegro in combination with
AllegroCache as that does some evil tinkering with initargs ,
;;; obfuscating the arglist of MAKE-INSTANCE.
;;;
(defmethod extra-keywords :around (op args)
(declare (ignorable op args))
(multiple-value-bind (keywords aok enrichments) (call-next-method)
(values (sort-extra-keywords keywords) aok enrichments)))
(defun make-package-comparator (reference-packages)
"Returns a two-argument test function which compares packages
according to their used-by relation with REFERENCE-PACKAGES. Packages
will be sorted first which appear first in the PACKAGE-USE-LIST of the
reference packages."
(let ((package-use-table (make-hash-table :test 'eq)))
;; Walk the package dependency graph breadth-fist, and fill
;; PACKAGE-USE-TABLE accordingly.
(loop with queue = (copy-list reference-packages)
with bfn = 0 ; Breadth-First Number
for p = (pop queue)
unless (gethash p package-use-table)
do (setf (gethash p package-use-table) (shiftf bfn (1+ bfn)))
and do (setf queue (nconc queue (copy-list (package-use-list p))))
while queue)
#'(lambda (p1 p2)
(let ((bfn1 (gethash p1 package-use-table))
(bfn2 (gethash p2 package-use-table)))
(cond ((and bfn1 bfn2) (<= bfn1 bfn2))
(bfn1 bfn1)
(bfn2 nil) ; p2 is used, p1 not
(t (string<= (package-name p1) (package-name p2))))))))
(defun sort-extra-keywords (kwds)
(stable-sort kwds (make-package-comparator (list keyword-package *package*))
:key (compose #'symbol-package #'keyword-arg.keyword)))
(defun keywords-of-operator (operator)
"Return a list of KEYWORD-ARGs that OPERATOR accepts.
This function is useful for writing EXTRA-KEYWORDS methods for
user-defined functions which are declared &ALLOW-OTHER-KEYS and which
forward keywords to OPERATOR."
(with-available-arglist (arglist) (arglist-from-form (ensure-list operator))
(values (arglist.keyword-args arglist)
(arglist.allow-other-keys-p arglist))))
(defmethod extra-keywords (operator args)
;; default method
(declare (ignore args))
(let ((symbol-function (symbol-function operator)))
(if (typep symbol-function 'generic-function)
(generic-function-keywords symbol-function)
nil)))
(defun class-from-class-name-form (class-name-form)
(when (and (listp class-name-form)
(= (length class-name-form) 2)
(eq (car class-name-form) 'quote))
(let* ((class-name (cadr class-name-form))
(class (find-class class-name nil)))
(when (and class
(not (micros/mop:class-finalized-p class)))
;; Try to finalize the class, which can fail if
;; superclasses are not defined yet
(ignore-errors (micros/mop:finalize-inheritance class)))
class)))
(defun extra-keywords/slots (class)
(multiple-value-bind (slots allow-other-keys-p)
(if (micros/mop:class-finalized-p class)
(values (micros/mop:class-slots class) nil)
(values (micros/mop:class-direct-slots class) t))
(let ((slot-init-keywords
(loop for slot in slots append
(mapcar (lambda (initarg)
(make-keyword-arg
initarg
(micros/mop:slot-definition-name slot)
(and (micros/mop:slot-definition-initfunction slot)
(micros/mop:slot-definition-initform slot))))
(micros/mop:slot-definition-initargs slot)))))
(values slot-init-keywords allow-other-keys-p))))
(defun extra-keywords/make-instance (operator args)
(declare (ignore operator))
(unless (null args)
(let* ((class-name-form (car args))
(class (class-from-class-name-form class-name-form)))
(when class
(multiple-value-bind (slot-init-keywords class-aokp)
(extra-keywords/slots class)
(multiple-value-bind (allocate-instance-keywords ai-aokp)
(applicable-methods-keywords
#'allocate-instance (list class))
(multiple-value-bind (initialize-instance-keywords ii-aokp)
(ignore-errors
(applicable-methods-keywords
#'initialize-instance
(list (micros/mop:class-prototype class))))
(multiple-value-bind (shared-initialize-keywords si-aokp)
(ignore-errors
(applicable-methods-keywords
#'shared-initialize
(list (micros/mop:class-prototype class) t)))
(values (append slot-init-keywords
allocate-instance-keywords
initialize-instance-keywords
shared-initialize-keywords)
(or class-aokp ai-aokp ii-aokp si-aokp)
(list class-name-form))))))))))
(defun extra-keywords/change-class (operator args)
(declare (ignore operator))
(unless (null args)
(let* ((class-name-form (car args))
(class (class-from-class-name-form class-name-form)))
(when class
(multiple-value-bind (slot-init-keywords class-aokp)
(extra-keywords/slots class)
(declare (ignore class-aokp))
(multiple-value-bind (shared-initialize-keywords si-aokp)
(ignore-errors
(applicable-methods-keywords
#'shared-initialize
(list (micros/mop:class-prototype class) t)))
;; FIXME: much as it would be nice to include the
;; applicable keywords from
;; UPDATE-INSTANCE-FOR-DIFFERENT-CLASS, I don't really see
;; how to do it: so we punt, always declaring
;; &ALLOW-OTHER-KEYS.
(declare (ignore si-aokp))
(values (append slot-init-keywords shared-initialize-keywords)
t
(list class-name-form))))))))
(defmethod extra-keywords ((operator (eql 'make-instance))
args)
(multiple-value-or (extra-keywords/make-instance operator args)
(call-next-method)))
(defmethod extra-keywords ((operator (eql 'make-condition))
args)
(multiple-value-or (extra-keywords/make-instance operator args)
(call-next-method)))
(defmethod extra-keywords ((operator (eql 'error))
args)
(multiple-value-or (extra-keywords/make-instance operator args)
(call-next-method)))
(defmethod extra-keywords ((operator (eql 'signal))
args)
(multiple-value-or (extra-keywords/make-instance operator args)
(call-next-method)))
(defmethod extra-keywords ((operator (eql 'warn))
args)
(multiple-value-or (extra-keywords/make-instance operator args)
(call-next-method)))
(defmethod extra-keywords ((operator (eql 'cerror))
args)
(multiple-value-bind (keywords aok determiners)
(extra-keywords/make-instance operator (cdr args))
(if keywords
(values keywords aok
(cons (car args) determiners))
(call-next-method))))
(defmethod extra-keywords ((operator (eql 'change-class))
args)
(multiple-value-bind (keywords aok determiners)
(extra-keywords/change-class operator (cdr args))
(if keywords
(values keywords aok
(cons (car args) determiners))
(call-next-method))))
(defun enrich-decoded-arglist-with-keywords (decoded-arglist keywords
allow-other-keys-p)
"Modify DECODED-ARGLIST using KEYWORDS and ALLOW-OTHER-KEYS-P."
(when keywords
(setf (arglist.key-p decoded-arglist) t)
(setf (arglist.keyword-args decoded-arglist)
(remove-duplicates
(append (arglist.keyword-args decoded-arglist)
keywords)
:key #'keyword-arg.keyword)))
(setf (arglist.allow-other-keys-p decoded-arglist)
(or (arglist.allow-other-keys-p decoded-arglist)
allow-other-keys-p)))
(defun enrich-decoded-arglist-with-extra-keywords (decoded-arglist form)
"Determine extra keywords from the function call FORM, and modify
DECODED-ARGLIST to include them. As a secondary return value, return
the initial sublist of ARGS that was needed to determine the extra
keywords. As a tertiary return value, return whether any enrichment
was done."
(multiple-value-bind (extra-keywords extra-aok determining-args)
(extra-keywords (car form) (cdr form))
;; enrich the list of keywords with the extra keywords
(enrich-decoded-arglist-with-keywords decoded-arglist
extra-keywords extra-aok)
(values decoded-arglist
determining-args
(or extra-keywords extra-aok))))
(defgeneric compute-enriched-decoded-arglist (operator-form argument-forms)
(:documentation
"Return three values: DECODED-ARGLIST, DETERMINING-ARGS, and
ANY-ENRICHMENT, just like enrich-decoded-arglist-with-extra-keywords.
If the arglist is not available, return :NOT-AVAILABLE."))
(defmethod compute-enriched-decoded-arglist (operator-form argument-forms)
(with-available-arglist (decoded-arglist)
(decode-arglist (arglist operator-form))
(enrich-decoded-arglist-with-extra-keywords decoded-arglist
(cons operator-form
argument-forms))))
(defmethod compute-enriched-decoded-arglist
((operator-form (eql 'with-open-file)) argument-forms)
(declare (ignore argument-forms))
(multiple-value-bind (decoded-arglist determining-args)
(call-next-method)
(let ((first-arg (first (arglist.required-args decoded-arglist)))
(open-arglist (compute-enriched-decoded-arglist 'open nil)))
(when (and (arglist-p first-arg) (arglist-p open-arglist))
(enrich-decoded-arglist-with-keywords
first-arg
(arglist.keyword-args open-arglist)
nil)))
(values decoded-arglist determining-args t)))
(defmethod compute-enriched-decoded-arglist ((operator-form (eql 'apply))
argument-forms)
(let ((function-name-form (car argument-forms)))
(when (and (listp function-name-form)
(length= function-name-form 2)
(memq (car function-name-form) '(quote function)))
(let ((function-name (cadr function-name-form)))
(when (valid-operator-symbol-p function-name)
(let ((function-arglist
(compute-enriched-decoded-arglist function-name
(cdr argument-forms))))
(return-from compute-enriched-decoded-arglist
(values
(make-arglist :required-args
(list 'function)
:optional-args
(append
(mapcar #'(lambda (arg)
(make-optional-arg arg nil))
(arglist.required-args function-arglist))
(arglist.optional-args function-arglist))
:key-p
(arglist.key-p function-arglist)
:keyword-args
(arglist.keyword-args function-arglist)
:rest
'args
:allow-other-keys-p
(arglist.allow-other-keys-p function-arglist))
(list function-name-form)
t)))))))
(call-next-method))
(defmethod compute-enriched-decoded-arglist
((operator-form (eql 'multiple-value-call)) argument-forms)
(compute-enriched-decoded-arglist 'apply argument-forms))
(defun delete-given-args (decoded-arglist args)
"Delete given ARGS from DECODED-ARGLIST."
(macrolet ((pop-or-return (list)
`(if (null ,list)
(return-from do-decoded-arglist)
(pop ,list))))
(do-decoded-arglist decoded-arglist
(&provided ()
(assert (eq (pop-or-return args)
(pop (arglist.provided-args decoded-arglist)))))
(&required ()
(pop-or-return args)
(pop (arglist.required-args decoded-arglist)))
(&optional ()
(pop-or-return args)
(pop (arglist.optional-args decoded-arglist)))
(&key (keyword)
;; N.b. we consider a keyword to be given only when the keyword
;; _and_ a value has been given for it.
(loop for (key value) on args by #'cddr
when (and (eq keyword key) value)
do (setf (arglist.keyword-args decoded-arglist)
(remove keyword (arglist.keyword-args decoded-arglist)
:key #'keyword-arg.keyword))))))
decoded-arglist)
(defun remove-given-args (decoded-arglist args)
;; FIXME: We actually needa deep copy here.
(delete-given-args (copy-arglist decoded-arglist) args))
;;;; Arglist Retrieval
(defun arglist-from-form (form)
(if (null form)
:not-available
(arglist-dispatch (car form) (cdr form))))
(export 'arglist-dispatch)
(defgeneric arglist-dispatch (operator arguments)
;; Default method
(:method (operator arguments)
(unless (and (symbolp operator) (valid-operator-symbol-p operator))
(return-from arglist-dispatch :not-available))
(when (equalp (package-name (symbol-package operator)) "closer-mop")
(let ((standard-symbol (or (find-symbol (symbol-name operator) :cl)
(find-symbol (symbol-name operator) :micros/mop))))
(when standard-symbol
(return-from arglist-dispatch
(arglist-dispatch standard-symbol arguments)))))
(multiple-value-bind (decoded-arglist determining-args)
(compute-enriched-decoded-arglist operator arguments)
(with-available-arglist (arglist) decoded-arglist
;; replace some formal args by determining actual args
(setf arglist (delete-given-args arglist determining-args))
(setf (arglist.provided-args arglist) determining-args)
arglist))))
(defmethod arglist-dispatch ((operator (eql 'defmethod)) arguments)
(match (cons operator arguments)
(('defmethod (#'function-exists-p gf-name) . rest)
(let ((gf (fdefinition gf-name)))
(when (typep gf 'generic-function)
(let ((lambda-list (micros/mop:generic-function-lambda-list gf)))
(with-available-arglist (arglist) (decode-arglist lambda-list)
(let ((qualifiers (loop for x in rest
until (or (listp x) (empty-arg-p x))
collect x)))
(return-from arglist-dispatch
(make-arglist :provided-args (cons gf-name qualifiers)
:required-args (list arglist)
:rest "body" :body-p t))))))))
Fall through
(call-next-method))
(defmethod arglist-dispatch ((operator (eql 'define-compiler-macro)) arguments)
(match (cons operator arguments)
(('define-compiler-macro (#'function-exists-p gf-name) . _)
(let ((gf (fdefinition gf-name)))
(with-available-arglist (arglist) (decode-arglist (arglist gf))
(return-from arglist-dispatch
(make-arglist :provided-args (list gf-name)
:required-args (list arglist)
:rest "body" :body-p t)))))
Fall through
(call-next-method))
(defmethod arglist-dispatch ((operator (eql 'eval-when)) arguments)
(declare (ignore arguments))
(let ((eval-when-args '(:compile-toplevel :load-toplevel :execute)))
(make-arglist
:required-args (list (make-arglist :any-p t :any-args eval-when-args))
:rest '#:body :body-p t)))
(defmethod arglist-dispatch ((operator (eql 'declare)) arguments)
(let* ((declaration (cons operator (last arguments)))
(typedecl-arglist (arglist-for-type-declaration declaration)))
(if (arglist-available-p typedecl-arglist)
typedecl-arglist
(match declaration
(('declare ((#'consp typespec) . decl-args))
(with-available-arglist (typespec-arglist)
(decoded-arglist-for-type-specifier typespec)
(make-arglist
:required-args (list (make-arglist
:required-args (list typespec-arglist)
:rest '#:variables)))))
(('declare (decl-identifier . decl-args))
(decoded-arglist-for-declaration decl-identifier decl-args))
(_ (make-arglist :rest '#:declaration-specifiers))))))
(defmethod arglist-dispatch ((operator (eql 'declaim)) arguments)
(arglist-dispatch 'declare arguments))
(defun arglist-for-type-declaration (declaration)
(flet ((%arglist-for-type-declaration (identifier typespec rest-var-name)
(with-available-arglist (typespec-arglist)
(decoded-arglist-for-type-specifier typespec)
(make-arglist
:required-args (list (make-arglist
:provided-args (list identifier)
:required-args (list typespec-arglist)
:rest rest-var-name))))))
(match declaration
(('declare ('type (#'consp typespec) . decl-args))
(%arglist-for-type-declaration 'type typespec '#:variables))
(('declare ('ftype (#'consp typespec) . decl-args))
(%arglist-for-type-declaration 'ftype typespec '#:function-names))
(('declare ((#'consp typespec) . decl-args))
(with-available-arglist (typespec-arglist)
(decoded-arglist-for-type-specifier typespec)
(make-arglist
:required-args (list (make-arglist
:required-args (list typespec-arglist)
:rest '#:variables)))))
(_ :not-available))))
(defun decoded-arglist-for-declaration (decl-identifier decl-args)
(declare (ignore decl-args))
(with-available-arglist (arglist)
(decode-arglist (declaration-arglist decl-identifier))
(setf (arglist.provided-args arglist) (list decl-identifier))
(make-arglist :required-args (list arglist))))
(defun decoded-arglist-for-type-specifier (type-specifier)
(etypecase type-specifier
(arglist-dummy :not-available)
(cons (decoded-arglist-for-type-specifier (car type-specifier)))
(symbol
(with-available-arglist (arglist)
(decode-arglist (type-specifier-arglist type-specifier))
(setf (arglist.provided-args arglist) (list type-specifier))
arglist))))
Slimefuns
;;; We work on a RAW-FORM, or BUFFER-FORM, which represent the form at
user 's point in Emacs . A RAW - FORM looks like
;;;
( " FOO " ( " BAR " ... ) " QUUX " ( " ZURP " LSP - BACKEND::%CURSOR - MARKER% ) )
;;;
;;; The expression before the cursor marker is the expression where
;;; user's cursor points at. An explicit marker is necessary to
;;; disambiguate between
;;;
;;; ("IF" ("PRED")
( " F " " X " " Y " % CURSOR - MARKER% ) )
;;;
;;; and
;;; ("IF" ("PRED")
( " F " " X " " Y " ) % CURSOR - MARKER% )
Notice that for a form like ( FOO ( BAR | ) QUUX ) , where | denotes
user 's point , the following should be sent ( " FOO " ( " BAR " " "
% CURSOR - MARKER% ) ) . Only the forms up to point should be
;;; considered.
(defun call-with-autodoc-error-handler (function print-right-margin)
(handler-bind ((serious-condition
#'(lambda (c)
(unless (debug-on-swank-error)
(let ((*print-right-margin* print-right-margin))
(return-from call-with-autodoc-error-handler
(format nil "Arglist Error: \"~A\"" c)))))))
(funcall function)))
(defmacro with-autodoc-error-handler ((&key print-right-margin) &body body)
`(call-with-autodoc-error-handler (lambda () ,@body)
,print-right-margin))
(defun autodoc-function (raw-form &key print-right-margin)
(with-autodoc-error-handler (:print-right-margin print-right-margin)
(with-buffer-syntax ()
(multiple-value-bind (form arglist obj-at-cursor form-path)
(find-subform-with-arglist (parse-raw-form raw-form))
(declare (ignore obj-at-cursor))
(list
(with-available-arglist (arglist) arglist
(decoded-arglist-to-string
arglist
:print-right-margin print-right-margin
:operator (car form)
:highlight (form-path-to-arglist-path form-path
form
arglist)))
(let ((*package* (find-package :cl-user)))
(prin1-to-string
(first form))))))))
(defslimefun autodoc (raw-form &key print-right-margin)
"Return a list of two elements.
First, a string representing the arglist for the deepest subform in
RAW-FORM that does have an arglist. The highlighted parameter is
wrapped in ===> X <===.
Second, a boolean value telling whether the returned string can be cached."
(with-autodoc-error-handler (:print-right-margin print-right-margin)
(with-buffer-syntax ()
(multiple-value-bind (form arglist obj-at-cursor form-path)
(find-subform-with-arglist (parse-raw-form raw-form))
(cond ((boundp-and-interesting obj-at-cursor)
(list (print-variable-to-string obj-at-cursor) nil))
(t
(list
(with-available-arglist (arglist) arglist
(decoded-arglist-to-string
arglist
:print-right-margin print-right-margin
:operator (car form)
:highlight (form-path-to-arglist-path form-path
form
arglist)))
t)))))))
(defun boundp-and-interesting (symbol)
(and symbol
(symbolp symbol)
(boundp symbol)
(not (memq symbol '(cl:t cl:nil)))
(not (keywordp symbol))))
(defun print-variable-to-string (symbol)
"Return a short description of VARIABLE-NAME, or NIL."
(let ((*print-pretty* t) (*print-level* 4)
(*print-length* 10) (*print-lines* 1)
(*print-readably* nil)
(value (symbol-value symbol)))
(call/truncated-output-to-string
75 (lambda (s)
(without-printing-errors (:object value :stream s)
(format s "~A ~A~S" symbol *echo-area-prefix* value))))))
(defslimefun complete-form (raw-form)
"Read FORM-STRING in the current buffer package, then complete it
by adding a template for the missing arguments."
;; We do not catch errors here because COMPLETE-FORM is an
;; interactive command, not automatically run in the background like
ARGLIST - FOR - ECHO - AREA .
(with-buffer-syntax ()
(multiple-value-bind (arglist provided-args)
(find-immediately-containing-arglist (parse-raw-form raw-form))
(with-available-arglist (arglist) arglist
(decoded-arglist-to-template-string
(delete-given-args arglist
(remove-if #'empty-arg-p provided-args
:from-end t :count 1))
:prefix "" :suffix "")))))
(defslimefun completions-for-keyword (keyword-string raw-form)
"Return a list of possible completions for KEYWORD-STRING relative
to the context provided by RAW-FORM."
(with-buffer-syntax ()
(let ((arglist (find-immediately-containing-arglist
(parse-raw-form raw-form))))
(when (arglist-available-p arglist)
;; It would be possible to complete keywords only if we are in
;; a keyword position, but it is not clear if we want that.
(let* ((keywords
(append (mapcar #'keyword-arg.keyword
(arglist.keyword-args arglist))
(remove-if-not #'keywordp (arglist.any-args arglist))))
(keyword-name
(tokenize-symbol keyword-string))
(matching-keywords
(find-matching-symbols-in-list
keyword-name keywords (make-compound-prefix-matcher #\-)))
(converter (completion-output-symbol-converter keyword-string))
(strings
(mapcar converter
(mapcar #'symbol-name matching-keywords)))
(completion-set
(format-completion-set strings nil "")))
(list completion-set
(longest-compound-prefix completion-set)))))))
(defparameter +cursor-marker+ '%cursor-marker%)
(defun find-subform-with-arglist (form)
"Returns four values:
The appropriate subform of `form' which is closest to the
+CURSOR-MARKER+ and whose operator is valid and has an
arglist. The +CURSOR-MARKER+ is removed from that subform.
Second value is the arglist. Local function and macro definitions
appearing in `form' into account.
Third value is the object in front of +CURSOR-MARKER+.
Fourth value is a form path to that object."
(labels
((yield-success (form local-ops)
(multiple-value-bind (form obj-at-cursor form-path)
(extract-cursor-marker form)
(values form
(let ((entry (assoc (car form) local-ops :test #'op=)))
(if entry
(decode-arglist (cdr entry))
(arglist-from-form form)))
obj-at-cursor
form-path)))
(yield-failure ()
(values nil :not-available))
(operator-p (operator local-ops)
(or (and (symbolp operator) (valid-operator-symbol-p operator))
(assoc operator local-ops :test #'op=)))
(op= (op1 op2)
(cond ((and (symbolp op1) (symbolp op2))
(eq op1 op2))
((and (arglist-dummy-p op1) (arglist-dummy-p op2))
(string= (arglist-dummy.string-representation op1)
(arglist-dummy.string-representation op2)))))
(grovel-form (form local-ops)
"Descend FORM top-down, always taking the rightest branch,
until +CURSOR-MARKER+."
(assert (listp form))
(destructuring-bind (operator . args) form
;; N.b. the user's cursor is at the rightmost, deepest
subform right before + CURSOR - MARKER+ .
(let ((last-subform (car (last form)))
(new-ops))
(cond
((eq last-subform +cursor-marker+)
(if (operator-p operator local-ops)
(yield-success form local-ops)
(yield-failure)))
((not (operator-p operator local-ops))
(grovel-form last-subform local-ops))
;; Make sure to pick up the arglists of local
;; function/macro definitions.
((setq new-ops (extract-local-op-arglists operator args))
(multiple-value-or (grovel-form last-subform
(nconc new-ops local-ops))
(yield-success form local-ops)))
;; Some typespecs clash with function names, so we make
;; sure to bail out early.
((member operator '(cl:declare cl:declaim))
(yield-success form local-ops))
;; Mostly uninteresting, hence skip.
((memq operator '(cl:quote cl:function))
(yield-failure))
(t
(multiple-value-or (grovel-form last-subform local-ops)
(yield-success form local-ops))))))))
(if (null form)
(yield-failure)
(grovel-form form '()))))
(defun extract-cursor-marker (form)
"Returns three values: normalized `form' without +CURSOR-MARKER+,
the object in front of +CURSOR-MARKER+, and a form path to that
object."
(labels ((grovel (form last path)
(let ((result-form))
(loop for (car . cdr) on form do
(cond ((eql car +cursor-marker+)
(decf (first path))
(return-from grovel
(values (nreconc result-form cdr)
last
(nreverse path))))
((consp car)
(multiple-value-bind (new-car new-last new-path)
(grovel car last (cons 0 path))
(when new-path ; CAR contained cursor-marker?
(return-from grovel
(values (nreconc
(cons new-car result-form) cdr)
new-last
new-path))))))
(push car result-form)
(setq last car)
(incf (first path))
finally
(return-from grovel
(values (nreverse result-form) nil nil))))))
(grovel form nil (list 0))))
(defgeneric extract-local-op-arglists (operator args)
(:documentation
"If the form `(OPERATOR ,@ARGS) is a local operator binding form,
return a list of pairs (OP . ARGLIST) for each locally bound op.")
(:method (operator args)
(declare (ignore operator args))
nil)
;; FLET
(:method ((operator (eql 'cl:flet)) args)
(let ((defs (first args))
(body (rest args)))
(cond ((null body) nil) ; `(flet ((foo (x) |'
((atom defs) nil) ; `(flet ,foo (|'
(t (%collect-op/argl-alist defs)))))
;; LABELS
(:method ((operator (eql 'cl:labels)) args)
;; Notice that we only have information to "look backward" and
;; show arglists of previously occuring local functions.
(destructuring-bind (defs . body) args
(unless (or (atom defs) (null body)) ; `(labels ,foo (|'
(let ((current-def (car (last defs))))
(cond ((atom current-def) nil) ; `(labels ((foo (x) ...)|'
((not (null body))
(extract-local-op-arglists 'cl:flet args))
(t
(let ((def.body (cddr current-def)))
(when def.body
(%collect-op/argl-alist defs)))))))))
MACROLET
(:method ((operator (eql 'cl:macrolet)) args)
(extract-local-op-arglists 'cl:labels args)))
(defun %collect-op/argl-alist (defs)
(setq defs (remove-if-not #'(lambda (x)
;; Well-formed FLET/LABELS def?
(and (consp x) (second x)))
defs))
(loop for (name arglist . nil) in defs
collect (cons name arglist)))
(defun find-immediately-containing-arglist (form)
"Returns the arglist of the subform _immediately_ containing
+CURSOR-MARKER+ in `form'. Notice, however, that +CURSOR-MARKER+ may
be in a nested arglist \(e.g. `(WITH-OPEN-FILE (<here>'\), and the
arglist of the appropriate parent form \(WITH-OPEN-FILE\) will be
returned in that case."
(flet ((try (form-path form arglist)
(let* ((arglist-path (form-path-to-arglist-path form-path
form
arglist))
(argl (apply #'arglist-ref
arglist
arglist-path))
(args (apply #'provided-arguments-ref
(cdr form)
arglist
arglist-path)))
(when (and (arglist-p argl) (listp args))
(values argl args)))))
(multiple-value-bind (form arglist obj form-path)
(find-subform-with-arglist form)
(declare (ignore obj))
(with-available-arglist (arglist) arglist
First try the form the cursor is in ( in case of a normal
;; form), then try the surrounding form (in case of a nested
;; macro form).
(multiple-value-or (try form-path form arglist)
(try (butlast form-path) form arglist)
:not-available)))))
(defun form-path-to-arglist-path (form-path form arglist)
"Convert a form path to an arglist path consisting of arglist
indices."
(labels ((convert (path args arglist)
(if (null path)
nil
(let* ((idx (car path))
(idx* (arglist-index idx args arglist))
(arglist* (and idx* (arglist-ref arglist idx*)))
(args* (and idx* (provided-arguments-ref args
arglist
idx*))))
The FORM - PATH may be more detailed than ARGLIST ;
;; consider (defun foo (x y) ...), a form path may
;; point into the function's lambda-list, but the
arglist of DEFUN wo n't contain as much information .
;; So we only recurse if possible.
(cond ((null idx*)
nil)
((arglist-p arglist*)
(cons idx* (convert (cdr path) args* arglist*)))
(t
(list idx*)))))))
(convert
;; FORM contains irrelevant operator. Adjust FORM-PATH.
(cond ((null form-path) nil)
((equal form-path '(0)) nil)
(t
(destructuring-bind (car . cdr) form-path
(cons (1- car) cdr))))
(cdr form)
arglist)))
(defun arglist-index (provided-argument-index provided-arguments arglist)
"Return the arglist index into `arglist' for the parameter belonging
to the argument (NTH `provided-argument-index' `provided-arguments')."
(let ((positional-args# (positional-args-number arglist))
(arg-index provided-argument-index))
(with-struct (arglist. key-p rest) arglist
(cond
((< arg-index positional-args#) ; required + optional
arg-index)
((and (not key-p) (not rest)) ; more provided than allowed
nil)
((not key-p) ; rest + body
(assert (arglist.rest arglist))
positional-args#)
(t ; key
;; Find last provided &key parameter
(let* ((argument (nth arg-index provided-arguments))
(provided-keys (subseq provided-arguments positional-args#)))
(loop for (key value) on provided-keys by #'cddr
when (eq value argument)
return (match key
(('quote symbol) symbol)
(_ key)))))))))
(defun arglist-ref (arglist &rest indices)
"Returns the parameter in ARGLIST along the INDICIES path. Numbers
represent positional parameters (required, optional), keywords
represent key parameters."
(flet ((ref-positional-arg (arglist index)
(check-type index (integer 0 *))
(with-struct (arglist. provided-args required-args
optional-args rest)
arglist
(loop for args in (list provided-args required-args
(mapcar #'optional-arg.arg-name
optional-args))
for args# = (length args)
if (< index args#)
return (nth index args)
else
do (decf index args#)
finally (return (or rest nil)))))
(ref-keyword-arg (arglist keyword)
;; keyword argument may be any symbol,
not only from the KEYWORD package .
(let ((keyword (match keyword
(('quote symbol) symbol)
(_ keyword))))
(do-decoded-arglist arglist
(&key (kw arg) (when (eq kw keyword)
(return-from ref-keyword-arg arg)))))
nil))
(dolist (index indices)
(assert (arglist-p arglist))
(setq arglist (if (numberp index)
(ref-positional-arg arglist index)
(ref-keyword-arg arglist index))))
arglist))
(defun provided-arguments-ref (provided-args arglist &rest indices)
"Returns the argument in PROVIDED-ARGUMENT along the INDICES path
relative to ARGLIST."
(check-type arglist arglist)
(flet ((ref (provided-args arglist index)
(if (numberp index)
(nth index provided-args)
(let ((provided-keys (subseq provided-args
(positional-args-number arglist))))
(loop for (key value) on provided-keys
when (eq key index)
return value)))))
(dolist (idx indices)
(setq provided-args (ref provided-args arglist idx))
(setq arglist (arglist-ref arglist idx)))
provided-args))
(defun positional-args-number (arglist)
(+ (length (arglist.provided-args arglist))
(length (arglist.required-args arglist))
(length (arglist.optional-args arglist))))
(defun parse-raw-form (raw-form)
"Parse a RAW-FORM into a Lisp form. I.e. substitute strings by
symbols if already interned. For strings not already interned, use
ARGLIST-DUMMY."
(unless (null raw-form)
(loop for element in raw-form
collect (etypecase element
(string (read-conversatively element))
(list (parse-raw-form element))
(symbol (prog1 element
;; Comes after list, so ELEMENT can't be NIL.
(assert (eq element +cursor-marker+))))))))
(defun read-conversatively (string)
"Tries to find the symbol that's represented by STRING.
If it can't, this either means that STRING does not represent a
symbol, or that the symbol behind STRING would have to be freshly
interned. Because this function is supposed to be called from the
automatic arglist display stuff from Slime, interning freshly
symbols is a big no-no.
In such a case (that no symbol could be found), an object of type
ARGLIST-DUMMY is returned instead, which works as a placeholder
datum for subsequent logics to rely on."
(let* ((string (string-left-trim '(#\Space #\Tab #\Newline) string))
(length (length string))
(type (cond ((zerop length) nil)
((eql (aref string 0) #\')
:quoted-symbol)
((search "#'" string :end2 (min length 2))
:sharpquoted-symbol)
((char= (char string 0) (char string (1- length))
#\")
:string)
(t
:symbol))))
(multiple-value-bind (symbol found?)
(case type
(:symbol (parse-symbol string))
(:quoted-symbol (parse-symbol (subseq string 1)))
(:sharpquoted-symbol (parse-symbol (subseq string 2)))
(:string (values string t))
(t (values string nil)))
(if found?
(ecase type
(:symbol symbol)
(:quoted-symbol `(quote ,symbol))
(:sharpquoted-symbol `(function ,symbol))
(:string (if (> length 1)
(subseq string 1 (1- length))
string)))
(make-arglist-dummy string)))))
(defun test-print-arglist ()
(flet ((test (arglist &rest strings)
(let* ((*package* (find-package :micros))
(actual (decoded-arglist-to-string
(decode-arglist arglist)
:print-right-margin 1000)))
(unless (loop for string in strings
thereis (string= actual string))
(warn "Test failed: ~S => ~S~% Expected: ~A"
arglist actual
(if (cdr strings)
(format nil "One of: ~{~S~^, ~}" strings)
(format nil "~S" (first strings))))))))
(test '(function cons) "(function cons)")
(test '(quote cons) "(quote cons)")
(test '(&key (function #'+))
"(&key (function #'+))" "(&key (function (function +)))")
(test '(&whole x y z) "(y z)")
(test '(x &aux y z) "(x)")
(test '(x &environment env y) "(x y)")
(test '(&key ((function f))) "(&key ((function ..)))")
(test
'(eval-when (&any :compile-toplevel :load-toplevel :execute) &body body)
"(eval-when (&any :compile-toplevel :load-toplevel :execute) &body body)")
(test '(declare (optimize &any (speed 1) (safety 1)))
"(declare (optimize &any (speed 1) (safety 1)))")))
(defun test-arglist-ref ()
(macrolet ((soft-assert (form)
`(unless ,form
(warn "Assertion failed: ~S~%" ',form))))
(let ((sample (decode-arglist '(x &key ((:k (y z)))))))
(soft-assert (eq (arglist-ref sample 0) 'x))
(soft-assert (eq (arglist-ref sample :k 0) 'y))
(soft-assert (eq (arglist-ref sample :k 1) 'z))
(soft-assert (eq (provided-arguments-ref '(a :k (b c)) sample 0)
'a))
(soft-assert (eq (provided-arguments-ref '(a :k (b c)) sample :k 0)
'b))
(soft-assert (eq (provided-arguments-ref '(a :k (b c)) sample :k 1)
'c)))))
(test-print-arglist)
(test-arglist-ref)
| null | https://raw.githubusercontent.com/lem-project/lem/bace7e3307cc5f419f493c3a309d771b472d3155/lib/micros/contrib/swank-arglists.lisp | lisp | swank-arglists.lisp --- arglist related code ??
and others
License: Public Domain
Arglist Definition
list of the provided actual arguments
list of the required arguments
list of the optional arguments
whether &key appeared
list of the keywords
whether the rest argument is a &body
whether &allow-other-keys appeared
whether &any appeared
list of &any arguments [*]
&whole, &environment
unparsed stuff
[*] The &ANY lambda keyword is an extension to ANSI Common Lisp,
and is only used to describe certain arglists that cannot be
described in another way.
&ANY is very similiar to &KEY but while &KEY is based upon
the idea of a plist (key1 value1 key2 value2), &ANY is a
a) (&ANY :A :B :C) means that you can provide any (non-null)
set consisting of the keywords `:A', `:B', or `:C' in
the arglist. E.g. (:A) or (:C :B :A).
(This is not restricted to keywords only, but any self-evaluating
expression is allowed.)
provide any (non-null) set consisting of lists where
(EVAL-WHEN (&ANY :compile-toplevel :load-toplevel :execute) &BODY body)
and b) let us describe the optimization qualifiers that are valid
in the declaration specifier `OPTIMIZE':
This is a wrapper object around anything that came from Slime and
could not reliably be read.
muffle warnings about using accessors prior to the definition of struct
Arglist Printing
FIXME: add &UNKNOWN-JUNK?
do nothing; provided args are in the buffer already.
Destructuring pattern
FIXME suppliedp?
don't leave this mode -- we don't know how the arglist
after unknown lambda-list keywords is interpreted
may be interned
in any *package*.
symbol-from-arbitrary-package-using keywords. And we sort the
latter according to how their home-packages relate to *PACKAGE*.
sense in the current context. And in particular: to put
implementation-internal stuff last.
obfuscating the arglist of MAKE-INSTANCE.
Walk the package dependency graph breadth-fist, and fill
PACKAGE-USE-TABLE accordingly.
Breadth-First Number
p2 is used, p1 not
default method
Try to finalize the class, which can fail if
superclasses are not defined yet
FIXME: much as it would be nice to include the
applicable keywords from
UPDATE-INSTANCE-FOR-DIFFERENT-CLASS, I don't really see
how to do it: so we punt, always declaring
&ALLOW-OTHER-KEYS.
enrich the list of keywords with the extra keywords
N.b. we consider a keyword to be given only when the keyword
_and_ a value has been given for it.
FIXME: We actually needa deep copy here.
Arglist Retrieval
Default method
replace some formal args by determining actual args
We work on a RAW-FORM, or BUFFER-FORM, which represent the form at
The expression before the cursor marker is the expression where
user's cursor points at. An explicit marker is necessary to
disambiguate between
("IF" ("PRED")
and
("IF" ("PRED")
considered.
We do not catch errors here because COMPLETE-FORM is an
interactive command, not automatically run in the background like
It would be possible to complete keywords only if we are in
a keyword position, but it is not clear if we want that.
N.b. the user's cursor is at the rightmost, deepest
Make sure to pick up the arglists of local
function/macro definitions.
Some typespecs clash with function names, so we make
sure to bail out early.
Mostly uninteresting, hence skip.
CAR contained cursor-marker?
FLET
`(flet ((foo (x) |'
`(flet ,foo (|'
LABELS
Notice that we only have information to "look backward" and
show arglists of previously occuring local functions.
`(labels ,foo (|'
`(labels ((foo (x) ...)|'
Well-formed FLET/LABELS def?
form), then try the surrounding form (in case of a nested
macro form).
consider (defun foo (x y) ...), a form path may
point into the function's lambda-list, but the
So we only recurse if possible.
FORM contains irrelevant operator. Adjust FORM-PATH.
required + optional
more provided than allowed
rest + body
key
Find last provided &key parameter
keyword argument may be any symbol,
Comes after list, so ELEMENT can't be NIL. | Authors : < >
< >
(in-package :micros)
Utilities
(defun compose (&rest functions)
"Compose FUNCTIONS right-associatively, returning a function"
#'(lambda (x)
(reduce #'funcall functions :initial-value x :from-end t)))
(defun length= (seq n)
"Test for whether SEQ contains N number of elements. I.e. it's equivalent
to (= (LENGTH SEQ) N), but besides being more concise, it may also be more
efficiently implemented."
(etypecase seq
(list (do ((i n (1- i))
(list seq (cdr list)))
((or (<= i 0) (null list))
(and (zerop i) (null list)))))
(sequence (= (length seq) n))))
(declaim (inline memq))
(defun memq (item list)
(member item list :test #'eq))
(defun exactly-one-p (&rest values)
"If exactly one value in VALUES is non-NIL, this value is returned.
Otherwise NIL is returned."
(let ((found nil))
(dolist (v values)
(when v (if found
(return-from exactly-one-p nil)
(setq found v))))
found))
(defun valid-operator-symbol-p (symbol)
"Is SYMBOL the name of a function, a macro, or a special-operator?"
(or (fboundp symbol)
(macro-function symbol)
(special-operator-p symbol)
(member symbol '(declare declaim))))
(defun function-exists-p (form)
(and (valid-function-name-p form)
(fboundp form)
t))
(defmacro multiple-value-or (&rest forms)
(if (null forms)
nil
(let ((first (first forms))
(rest (rest forms)))
`(let* ((values (multiple-value-list ,first))
(primary-value (first values)))
(if primary-value
(values-list values)
(multiple-value-or ,@rest))))))
(defun arglist-available-p (arglist)
(not (eql arglist :not-available)))
(defmacro with-available-arglist ((var &rest more-vars) form &body body)
`(multiple-value-bind (,var ,@more-vars) ,form
(if (eql ,var :not-available)
:not-available
(progn ,@body))))
(defstruct (arglist (:conc-name arglist.) (:predicate arglist-p))
name of the & rest or & body argument ( if any )
list of & aux variables
cross between & OPTIONAL , & KEY and * FEATURES * lists :
b ) ( & ANY ( key1 v1 ) ( key2 v2 ) ( key3 v3 ) ) means that you can
the CAR of the list is one of ` key1 ' , ` key2 ' , or ` key3 ' .
E.g. ( ( key1 100 ) ( key3 42 ) ) , or ( ( key3 66 ) ( key2 23 ) )
For example , a ) let us describe the situations of EVAL - WHEN as
( DECLARE ( OPTIMIZE & ANY ( compilation - speed 1 ) ( safety 1 ) ... ) )
(defstruct (arglist-dummy
(:conc-name #:arglist-dummy.)
(:constructor make-arglist-dummy (string-representation)))
string-representation)
(defun empty-arg-p (dummy)
(and (arglist-dummy-p dummy)
(zerop (length (arglist-dummy.string-representation dummy)))))
(eval-when (:compile-toplevel :load-toplevel :execute)
(defparameter +lambda-list-keywords+
'(&provided &required &optional &rest &key &any)))
(declaim (notinline keyword-arg.keyword
keyword-arg.arg-name
keyword-arg.default-arg
optional-arg.arg-name
optional-arg.default-arg))
(defmacro do-decoded-arglist (decoded-arglist &body clauses)
(assert (loop for clause in clauses
thereis (member (car clause) +lambda-list-keywords+)))
(flet ((parse-clauses (clauses)
(let* ((size (length +lambda-list-keywords+))
(initial (make-hash-table :test #'eq :size size))
(main (make-hash-table :test #'eq :size size))
(final (make-hash-table :test #'eq :size size)))
(loop for clause in clauses
for lambda-list-keyword = (first clause)
for clause-parameter = (second clause)
do
(case clause-parameter
(:initially
(setf (gethash lambda-list-keyword initial) clause))
(:finally
(setf (gethash lambda-list-keyword final) clause))
(t
(setf (gethash lambda-list-keyword main) clause)))
finally
(return (values initial main final)))))
(generate-main-clause (clause arglist)
(dcase clause
((&provided (&optional arg) . body)
(let ((gensym (gensym "PROVIDED-ARG+")))
`(dolist (,gensym (arglist.provided-args ,arglist))
(declare (ignorable ,gensym))
(let (,@(when arg `((,arg ,gensym))))
,@body))))
((&required (&optional arg) . body)
(let ((gensym (gensym "REQUIRED-ARG+")))
`(dolist (,gensym (arglist.required-args ,arglist))
(declare (ignorable ,gensym))
(let (,@(when arg `((,arg ,gensym))))
,@body))))
((&optional (&optional arg init) . body)
(let ((optarg (gensym "OPTIONAL-ARG+")))
`(dolist (,optarg (arglist.optional-args ,arglist))
(declare (ignorable ,optarg))
(let (,@(when arg
`((,arg (optional-arg.arg-name ,optarg))))
,@(when init
`((,init (optional-arg.default-arg ,optarg)))))
,@body))))
((&key (&optional keyword arg init) . body)
(let ((keyarg (gensym "KEY-ARG+")))
`(dolist (,keyarg (arglist.keyword-args ,arglist))
(declare (ignorable ,keyarg))
(let (,@(when keyword
`((,keyword (keyword-arg.keyword ,keyarg))))
,@(when arg
`((,arg (keyword-arg.arg-name ,keyarg))))
,@(when init
`((,init (keyword-arg.default-arg ,keyarg)))))
,@body))))
((&rest (&optional arg body-p) . body)
`(when (arglist.rest ,arglist)
(let (,@(when arg `((,arg (arglist.rest ,arglist))))
,@(when body-p `((,body-p (arglist.body-p ,arglist)))))
,@body)))
((&any (&optional arg) . body)
(let ((gensym (gensym "REQUIRED-ARG+")))
`(dolist (,gensym (arglist.any-args ,arglist))
(declare (ignorable ,gensym))
(let (,@(when arg `((,arg ,gensym))))
,@body)))))))
(let ((arglist (gensym "DECODED-ARGLIST+")))
(multiple-value-bind (initially-clauses main-clauses finally-clauses)
(parse-clauses clauses)
`(let ((,arglist ,decoded-arglist))
(block do-decoded-arglist
,@(loop for keyword in '(&provided &required
&optional &rest &key &any)
append (cddr (gethash keyword initially-clauses))
collect (let ((clause (gethash keyword main-clauses)))
(when clause
(generate-main-clause clause arglist)))
append (cddr (gethash keyword finally-clauses)))))))))
(defun undummy (x)
(if (typep x 'arglist-dummy)
(arglist-dummy.string-representation x)
(prin1-to-string x)))
(defun print-decoded-arglist (arglist &key operator provided-args highlight)
(let ((first-space-after-operator (and operator t)))
(macrolet ((space ()
: When OPERATOR is not given , we do n't want to
print a space for the first argument .
`(if (not operator)
(setq operator t)
(progn (write-char #\space)
(if first-space-after-operator
(setq first-space-after-operator nil)
(pprint-newline :fill)))))
(with-highlighting ((&key index) &body body)
`(if (eql ,index (car highlight))
(progn (princ "===> ") ,@body (princ " <==="))
(progn ,@body)))
(print-arglist-recursively (argl &key index)
`(if (eql ,index (car highlight))
(print-decoded-arglist ,argl :highlight (cdr highlight))
(print-decoded-arglist ,argl))))
(let ((index 0))
(pprint-logical-block (nil nil :prefix "(" :suffix ")")
(when operator
(print-arg operator)
1 due to possibly added space
(do-decoded-arglist (remove-given-args arglist provided-args)
(&provided (arg)
(space)
(print-arg arg :literal-strings t)
(incf index))
(&required (arg)
(space)
(if (arglist-p arg)
(print-arglist-recursively arg :index index)
(with-highlighting (:index index)
(print-arg arg)))
(incf index))
(&optional :initially
(when (arglist.optional-args arglist)
(space)
(princ '&optional)))
(&optional (arg init-value)
(space)
(if (arglist-p arg)
(print-arglist-recursively arg :index index)
(with-highlighting (:index index)
(if (null init-value)
(print-arg arg)
(format t "~:@<~A ~A~@:>"
(undummy arg) (undummy init-value)))))
(incf index))
(&key :initially
(when (arglist.key-p arglist)
(space)
(princ '&key)))
(&key (keyword arg init)
(space)
(if (arglist-p arg)
(pprint-logical-block (nil nil :prefix "(" :suffix ")")
(prin1 keyword) (space)
(print-arglist-recursively arg :index keyword))
(with-highlighting (:index keyword)
(cond ((and init (keywordp keyword))
(format t "~:@<~A ~A~@:>" keyword (undummy init)))
(init
(format t "~:@<(~A ..) ~A~@:>"
(undummy keyword) (undummy init)))
((not (keywordp keyword))
(format t "~:@<(~S ..)~@:>" keyword))
(t
(princ keyword))))))
(&key :finally
(when (arglist.allow-other-keys-p arglist)
(space)
(princ '&allow-other-keys)))
(&any :initially
(when (arglist.any-p arglist)
(space)
(princ '&any)))
(&any (arg)
(space)
(print-arg arg))
(&rest (args bodyp)
(space)
(princ (if bodyp '&body '&rest))
(space)
(if (arglist-p args)
(print-arglist-recursively args :index index)
(with-highlighting (:index index)
(print-arg args))))
))))))
(defun print-arg (arg &key literal-strings)
(let ((arg (if (arglist-dummy-p arg)
(arglist-dummy.string-representation arg)
arg)))
(if (or
(and literal-strings
(stringp arg))
(keywordp arg))
(prin1 arg)
(princ arg))))
(defun print-decoded-arglist-as-template (decoded-arglist &key
(prefix "(") (suffix ")"))
(let ((first-p t))
(flet ((space ()
(unless first-p
(write-char #\space))
(setq first-p nil))
(print-arg-or-pattern (arg)
(etypecase arg
(symbol (if (keywordp arg) (prin1 arg) (princ arg)))
(string (princ arg))
(list (princ arg))
(arglist-dummy (princ
(arglist-dummy.string-representation arg)))
(arglist (print-decoded-arglist-as-template arg)))
(pprint-newline :fill)))
(pprint-logical-block (nil nil :prefix prefix :suffix suffix)
(do-decoded-arglist decoded-arglist
(&required (arg)
(space) (print-arg-or-pattern arg))
(&optional (arg)
(space) (princ "[") (print-arg-or-pattern arg) (princ "]"))
(&key (keyword arg)
(space)
(prin1 (if (keywordp keyword) keyword `',keyword))
(space)
(print-arg-or-pattern arg)
(pprint-newline :linear))
(&any (arg)
(space) (print-arg-or-pattern arg))
(&rest (args)
(when (or (not (arglist.keyword-args decoded-arglist))
(arglist.allow-other-keys-p decoded-arglist))
(space)
(format t "~A..." args))))))))
(defvar *arglist-pprint-bindings*
'((*print-case* . :downcase)
(*print-pretty* . t)
(*print-circle* . nil)
(*print-readably* . nil)
(*print-level* . 10)
(*print-length* . 20)
(*print-escape* . nil)))
(defvar *arglist-show-packages* t)
(defmacro with-arglist-io-syntax (&body body)
(let ((package (gensym)))
`(let ((,package *package*))
(with-standard-io-syntax
(let ((*package* (if *arglist-show-packages*
*package*
,package)))
(with-bindings *arglist-pprint-bindings*
,@body))))))
(defun decoded-arglist-to-string (decoded-arglist
&key operator highlight
print-right-margin)
(with-output-to-string (*standard-output*)
(with-arglist-io-syntax
(let ((*print-right-margin* print-right-margin))
(print-decoded-arglist decoded-arglist
:operator operator
:highlight highlight)))))
(defun decoded-arglist-to-template-string (decoded-arglist
&key (prefix "(") (suffix ")"))
(with-output-to-string (*standard-output*)
(with-arglist-io-syntax
(print-decoded-arglist-as-template decoded-arglist
:prefix prefix
:suffix suffix))))
Arglist Decoding / Encoding
(defun decode-required-arg (arg)
"ARG can be a symbol or a destructuring pattern."
(etypecase arg
(symbol arg)
(arglist-dummy arg)
(list (decode-arglist arg))))
(defun encode-required-arg (arg)
(etypecase arg
(symbol arg)
(arglist (encode-arglist arg))))
(defstruct (keyword-arg
(:conc-name keyword-arg.)
(:constructor %make-keyword-arg))
keyword
arg-name
default-arg)
(defun canonicalize-default-arg (form)
(if (equalp ''nil form)
nil
form))
(defun make-keyword-arg (keyword arg-name default-arg)
(%make-keyword-arg :keyword keyword
:arg-name arg-name
:default-arg (canonicalize-default-arg default-arg)))
(defun decode-keyword-arg (arg)
"Decode a keyword item of formal argument list.
Return three values: keyword, argument name, default arg."
(flet ((intern-as-keyword (arg)
(intern (etypecase arg
(symbol (symbol-name arg))
(arglist-dummy (arglist-dummy.string-representation arg)))
keyword-package)))
(cond ((or (symbolp arg) (arglist-dummy-p arg))
(make-keyword-arg (intern-as-keyword arg) arg nil))
((and (consp arg)
(consp (car arg)))
(make-keyword-arg (caar arg)
(decode-required-arg (cadar arg))
(cadr arg)))
((consp arg)
(make-keyword-arg (intern-as-keyword (car arg))
(car arg) (cadr arg)))
(t
(error "Bad keyword item of formal argument list")))))
(defun encode-keyword-arg (arg)
(cond
((arglist-p (keyword-arg.arg-name arg))
(let ((keyword/name (list (keyword-arg.keyword arg)
(encode-required-arg
(keyword-arg.arg-name arg)))))
(if (keyword-arg.default-arg arg)
(list keyword/name
(keyword-arg.default-arg arg))
(list keyword/name))))
((eql (intern (symbol-name (keyword-arg.arg-name arg))
keyword-package)
(keyword-arg.keyword arg))
(if (keyword-arg.default-arg arg)
(list (keyword-arg.arg-name arg)
(keyword-arg.default-arg arg))
(keyword-arg.arg-name arg)))
(t
(let ((keyword/name (list (keyword-arg.keyword arg)
(keyword-arg.arg-name arg))))
(if (keyword-arg.default-arg arg)
(list keyword/name
(keyword-arg.default-arg arg))
(list keyword/name))))))
(progn
(assert (equalp (decode-keyword-arg 'x)
(make-keyword-arg :x 'x nil)))
(assert (equalp (decode-keyword-arg '(x t))
(make-keyword-arg :x 'x t)))
(assert (equalp (decode-keyword-arg '((:x y)))
(make-keyword-arg :x 'y nil)))
(assert (equalp (decode-keyword-arg '((:x y) t))
(make-keyword-arg :x 'y t))))
(defstruct (optional-arg
(:conc-name optional-arg.)
(:constructor %make-optional-arg))
arg-name
default-arg)
(defun make-optional-arg (arg-name default-arg)
(%make-optional-arg :arg-name arg-name
:default-arg (canonicalize-default-arg default-arg)))
(defun decode-optional-arg (arg)
"Decode an optional item of a formal argument list.
Return an OPTIONAL-ARG structure."
(etypecase arg
(symbol (make-optional-arg arg nil))
(arglist-dummy (make-optional-arg arg nil))
(list (make-optional-arg (decode-required-arg (car arg))
(cadr arg)))))
(defun encode-optional-arg (optional-arg)
(if (or (optional-arg.default-arg optional-arg)
(arglist-p (optional-arg.arg-name optional-arg)))
(list (encode-required-arg
(optional-arg.arg-name optional-arg))
(optional-arg.default-arg optional-arg))
(optional-arg.arg-name optional-arg)))
(progn
(assert (equalp (decode-optional-arg 'x)
(make-optional-arg 'x nil)))
(assert (equalp (decode-optional-arg '(x t))
(make-optional-arg 'x t))))
(define-modify-macro nreversef () nreverse "Reverse the list in PLACE.")
(defun decode-arglist (arglist)
"Parse the list ARGLIST and return an ARGLIST structure."
(if (eq arglist :not-available)
:not-available
(loop
with mode = nil
with result = (make-arglist)
for arg = (if (consp arglist)
(pop arglist)
(progn
(prog1 arglist
(setf mode '&rest
arglist nil))))
do (cond
((eql mode '&unknown-junk)
(push arg (arglist.unknown-junk result)))
((eql arg '&allow-other-keys)
(setf (arglist.allow-other-keys-p result) t))
((eql arg '&key)
(setf (arglist.key-p result) t
mode arg))
((memq arg '(&optional &rest &body &aux))
(setq mode arg))
((memq arg '(&whole &environment))
(setq mode arg)
(push arg (arglist.known-junk result)))
((and (symbolp arg)
(setq mode '&any))
((memq arg lambda-list-keywords)
(setq mode '&unknown-junk)
(push arg (arglist.unknown-junk result)))
(t
(ecase mode
(&key
(push (decode-keyword-arg arg)
(arglist.keyword-args result)))
(&optional
(push (decode-optional-arg arg)
(arglist.optional-args result)))
(&body
(setf (arglist.body-p result) t
(arglist.rest result) arg))
(&rest
(setf (arglist.rest result) arg))
(&aux
(push (decode-optional-arg arg)
(arglist.aux-args result)))
((nil)
(push (decode-required-arg arg)
(arglist.required-args result)))
((&whole &environment)
(setf mode nil)
(push arg (arglist.known-junk result)))
(&any
(push arg (arglist.any-args result))))))
until (null arglist)
finally (nreversef (arglist.required-args result))
finally (nreversef (arglist.optional-args result))
finally (nreversef (arglist.keyword-args result))
finally (nreversef (arglist.aux-args result))
finally (nreversef (arglist.any-args result))
finally (nreversef (arglist.known-junk result))
finally (nreversef (arglist.unknown-junk result))
finally (assert (or (and (not (arglist.key-p result))
(not (arglist.any-p result)))
(exactly-one-p (arglist.key-p result)
(arglist.any-p result))))
finally (return result))))
(defun encode-arglist (decoded-arglist)
(append (mapcar #'encode-required-arg
(arglist.required-args decoded-arglist))
(when (arglist.optional-args decoded-arglist)
'(&optional))
(mapcar #'encode-optional-arg
(arglist.optional-args decoded-arglist))
(when (arglist.key-p decoded-arglist)
'(&key))
(mapcar #'encode-keyword-arg
(arglist.keyword-args decoded-arglist))
(when (arglist.allow-other-keys-p decoded-arglist)
'(&allow-other-keys))
(when (arglist.any-args decoded-arglist)
`(&any ,@(arglist.any-args decoded-arglist)))
(cond ((not (arglist.rest decoded-arglist))
'())
((arglist.body-p decoded-arglist)
`(&body ,(arglist.rest decoded-arglist)))
(t
`(&rest ,(arglist.rest decoded-arglist))))
(when (arglist.aux-args decoded-arglist)
`(&aux ,(arglist.aux-args decoded-arglist)))
(arglist.known-junk decoded-arglist)
(arglist.unknown-junk decoded-arglist)))
Arglist Enrichment
(defun arglist-keywords (lambda-list)
"Return the list of keywords in ARGLIST.
As a secondary value, return whether &allow-other-keys appears."
(let ((decoded-arglist (decode-arglist lambda-list)))
(values (arglist.keyword-args decoded-arglist)
(arglist.allow-other-keys-p decoded-arglist))))
(defun methods-keywords (methods)
"Collect all keywords in the arglists of METHODS.
As a secondary value, return whether &allow-other-keys appears somewhere."
(let ((keywords '())
(allow-other-keys nil))
(dolist (method methods)
(multiple-value-bind (kw aok)
(arglist-keywords
(micros/mop:method-lambda-list method))
(setq keywords (remove-duplicates (append keywords kw)
:key #'keyword-arg.keyword)
allow-other-keys (or allow-other-keys aok))))
(values keywords allow-other-keys)))
(defun generic-function-keywords (generic-function)
"Collect all keywords in the methods of GENERIC-FUNCTION.
As a secondary value, return whether &allow-other-keys appears somewhere."
(methods-keywords
(micros/mop:generic-function-methods generic-function)))
(defun applicable-methods-keywords (generic-function arguments)
"Collect all keywords in the methods of GENERIC-FUNCTION that are
applicable for argument of CLASSES. As a secondary value, return
whether &allow-other-keys appears somewhere."
(methods-keywords
(multiple-value-bind (amuc okp)
(micros/mop:compute-applicable-methods-using-classes
generic-function (mapcar #'class-of arguments))
(if okp
amuc
(compute-applicable-methods generic-function arguments)))))
(defgeneric extra-keywords (operator args)
(:documentation "Return a list of extra keywords of OPERATOR (a
symbol) when applied to the (unevaluated) ARGS.
As a secondary value, return whether other keys are allowed.
As a tertiary value, return the initial sublist of ARGS that was needed
to determine the extra keywords."))
We make sure that symbol - from - KEYWORD - using keywords come before
Rationale is to show those key parameters first which make most
This matters tremendeously on Allegro in combination with
AllegroCache as that does some evil tinkering with initargs ,
(defmethod extra-keywords :around (op args)
(declare (ignorable op args))
(multiple-value-bind (keywords aok enrichments) (call-next-method)
(values (sort-extra-keywords keywords) aok enrichments)))
(defun make-package-comparator (reference-packages)
"Returns a two-argument test function which compares packages
according to their used-by relation with REFERENCE-PACKAGES. Packages
will be sorted first which appear first in the PACKAGE-USE-LIST of the
reference packages."
(let ((package-use-table (make-hash-table :test 'eq)))
(loop with queue = (copy-list reference-packages)
for p = (pop queue)
unless (gethash p package-use-table)
do (setf (gethash p package-use-table) (shiftf bfn (1+ bfn)))
and do (setf queue (nconc queue (copy-list (package-use-list p))))
while queue)
#'(lambda (p1 p2)
(let ((bfn1 (gethash p1 package-use-table))
(bfn2 (gethash p2 package-use-table)))
(cond ((and bfn1 bfn2) (<= bfn1 bfn2))
(bfn1 bfn1)
(t (string<= (package-name p1) (package-name p2))))))))
(defun sort-extra-keywords (kwds)
(stable-sort kwds (make-package-comparator (list keyword-package *package*))
:key (compose #'symbol-package #'keyword-arg.keyword)))
(defun keywords-of-operator (operator)
"Return a list of KEYWORD-ARGs that OPERATOR accepts.
This function is useful for writing EXTRA-KEYWORDS methods for
user-defined functions which are declared &ALLOW-OTHER-KEYS and which
forward keywords to OPERATOR."
(with-available-arglist (arglist) (arglist-from-form (ensure-list operator))
(values (arglist.keyword-args arglist)
(arglist.allow-other-keys-p arglist))))
(defmethod extra-keywords (operator args)
(declare (ignore args))
(let ((symbol-function (symbol-function operator)))
(if (typep symbol-function 'generic-function)
(generic-function-keywords symbol-function)
nil)))
(defun class-from-class-name-form (class-name-form)
(when (and (listp class-name-form)
(= (length class-name-form) 2)
(eq (car class-name-form) 'quote))
(let* ((class-name (cadr class-name-form))
(class (find-class class-name nil)))
(when (and class
(not (micros/mop:class-finalized-p class)))
(ignore-errors (micros/mop:finalize-inheritance class)))
class)))
(defun extra-keywords/slots (class)
(multiple-value-bind (slots allow-other-keys-p)
(if (micros/mop:class-finalized-p class)
(values (micros/mop:class-slots class) nil)
(values (micros/mop:class-direct-slots class) t))
(let ((slot-init-keywords
(loop for slot in slots append
(mapcar (lambda (initarg)
(make-keyword-arg
initarg
(micros/mop:slot-definition-name slot)
(and (micros/mop:slot-definition-initfunction slot)
(micros/mop:slot-definition-initform slot))))
(micros/mop:slot-definition-initargs slot)))))
(values slot-init-keywords allow-other-keys-p))))
(defun extra-keywords/make-instance (operator args)
(declare (ignore operator))
(unless (null args)
(let* ((class-name-form (car args))
(class (class-from-class-name-form class-name-form)))
(when class
(multiple-value-bind (slot-init-keywords class-aokp)
(extra-keywords/slots class)
(multiple-value-bind (allocate-instance-keywords ai-aokp)
(applicable-methods-keywords
#'allocate-instance (list class))
(multiple-value-bind (initialize-instance-keywords ii-aokp)
(ignore-errors
(applicable-methods-keywords
#'initialize-instance
(list (micros/mop:class-prototype class))))
(multiple-value-bind (shared-initialize-keywords si-aokp)
(ignore-errors
(applicable-methods-keywords
#'shared-initialize
(list (micros/mop:class-prototype class) t)))
(values (append slot-init-keywords
allocate-instance-keywords
initialize-instance-keywords
shared-initialize-keywords)
(or class-aokp ai-aokp ii-aokp si-aokp)
(list class-name-form))))))))))
(defun extra-keywords/change-class (operator args)
(declare (ignore operator))
(unless (null args)
(let* ((class-name-form (car args))
(class (class-from-class-name-form class-name-form)))
(when class
(multiple-value-bind (slot-init-keywords class-aokp)
(extra-keywords/slots class)
(declare (ignore class-aokp))
(multiple-value-bind (shared-initialize-keywords si-aokp)
(ignore-errors
(applicable-methods-keywords
#'shared-initialize
(list (micros/mop:class-prototype class) t)))
(declare (ignore si-aokp))
(values (append slot-init-keywords shared-initialize-keywords)
t
(list class-name-form))))))))
(defmethod extra-keywords ((operator (eql 'make-instance))
args)
(multiple-value-or (extra-keywords/make-instance operator args)
(call-next-method)))
(defmethod extra-keywords ((operator (eql 'make-condition))
args)
(multiple-value-or (extra-keywords/make-instance operator args)
(call-next-method)))
(defmethod extra-keywords ((operator (eql 'error))
args)
(multiple-value-or (extra-keywords/make-instance operator args)
(call-next-method)))
(defmethod extra-keywords ((operator (eql 'signal))
args)
(multiple-value-or (extra-keywords/make-instance operator args)
(call-next-method)))
(defmethod extra-keywords ((operator (eql 'warn))
args)
(multiple-value-or (extra-keywords/make-instance operator args)
(call-next-method)))
(defmethod extra-keywords ((operator (eql 'cerror))
args)
(multiple-value-bind (keywords aok determiners)
(extra-keywords/make-instance operator (cdr args))
(if keywords
(values keywords aok
(cons (car args) determiners))
(call-next-method))))
(defmethod extra-keywords ((operator (eql 'change-class))
args)
(multiple-value-bind (keywords aok determiners)
(extra-keywords/change-class operator (cdr args))
(if keywords
(values keywords aok
(cons (car args) determiners))
(call-next-method))))
(defun enrich-decoded-arglist-with-keywords (decoded-arglist keywords
allow-other-keys-p)
"Modify DECODED-ARGLIST using KEYWORDS and ALLOW-OTHER-KEYS-P."
(when keywords
(setf (arglist.key-p decoded-arglist) t)
(setf (arglist.keyword-args decoded-arglist)
(remove-duplicates
(append (arglist.keyword-args decoded-arglist)
keywords)
:key #'keyword-arg.keyword)))
(setf (arglist.allow-other-keys-p decoded-arglist)
(or (arglist.allow-other-keys-p decoded-arglist)
allow-other-keys-p)))
(defun enrich-decoded-arglist-with-extra-keywords (decoded-arglist form)
"Determine extra keywords from the function call FORM, and modify
DECODED-ARGLIST to include them. As a secondary return value, return
the initial sublist of ARGS that was needed to determine the extra
keywords. As a tertiary return value, return whether any enrichment
was done."
(multiple-value-bind (extra-keywords extra-aok determining-args)
(extra-keywords (car form) (cdr form))
(enrich-decoded-arglist-with-keywords decoded-arglist
extra-keywords extra-aok)
(values decoded-arglist
determining-args
(or extra-keywords extra-aok))))
(defgeneric compute-enriched-decoded-arglist (operator-form argument-forms)
(:documentation
"Return three values: DECODED-ARGLIST, DETERMINING-ARGS, and
ANY-ENRICHMENT, just like enrich-decoded-arglist-with-extra-keywords.
If the arglist is not available, return :NOT-AVAILABLE."))
(defmethod compute-enriched-decoded-arglist (operator-form argument-forms)
(with-available-arglist (decoded-arglist)
(decode-arglist (arglist operator-form))
(enrich-decoded-arglist-with-extra-keywords decoded-arglist
(cons operator-form
argument-forms))))
(defmethod compute-enriched-decoded-arglist
((operator-form (eql 'with-open-file)) argument-forms)
(declare (ignore argument-forms))
(multiple-value-bind (decoded-arglist determining-args)
(call-next-method)
(let ((first-arg (first (arglist.required-args decoded-arglist)))
(open-arglist (compute-enriched-decoded-arglist 'open nil)))
(when (and (arglist-p first-arg) (arglist-p open-arglist))
(enrich-decoded-arglist-with-keywords
first-arg
(arglist.keyword-args open-arglist)
nil)))
(values decoded-arglist determining-args t)))
(defmethod compute-enriched-decoded-arglist ((operator-form (eql 'apply))
argument-forms)
(let ((function-name-form (car argument-forms)))
(when (and (listp function-name-form)
(length= function-name-form 2)
(memq (car function-name-form) '(quote function)))
(let ((function-name (cadr function-name-form)))
(when (valid-operator-symbol-p function-name)
(let ((function-arglist
(compute-enriched-decoded-arglist function-name
(cdr argument-forms))))
(return-from compute-enriched-decoded-arglist
(values
(make-arglist :required-args
(list 'function)
:optional-args
(append
(mapcar #'(lambda (arg)
(make-optional-arg arg nil))
(arglist.required-args function-arglist))
(arglist.optional-args function-arglist))
:key-p
(arglist.key-p function-arglist)
:keyword-args
(arglist.keyword-args function-arglist)
:rest
'args
:allow-other-keys-p
(arglist.allow-other-keys-p function-arglist))
(list function-name-form)
t)))))))
(call-next-method))
(defmethod compute-enriched-decoded-arglist
((operator-form (eql 'multiple-value-call)) argument-forms)
(compute-enriched-decoded-arglist 'apply argument-forms))
(defun delete-given-args (decoded-arglist args)
"Delete given ARGS from DECODED-ARGLIST."
(macrolet ((pop-or-return (list)
`(if (null ,list)
(return-from do-decoded-arglist)
(pop ,list))))
(do-decoded-arglist decoded-arglist
(&provided ()
(assert (eq (pop-or-return args)
(pop (arglist.provided-args decoded-arglist)))))
(&required ()
(pop-or-return args)
(pop (arglist.required-args decoded-arglist)))
(&optional ()
(pop-or-return args)
(pop (arglist.optional-args decoded-arglist)))
(&key (keyword)
(loop for (key value) on args by #'cddr
when (and (eq keyword key) value)
do (setf (arglist.keyword-args decoded-arglist)
(remove keyword (arglist.keyword-args decoded-arglist)
:key #'keyword-arg.keyword))))))
decoded-arglist)
(defun remove-given-args (decoded-arglist args)
(delete-given-args (copy-arglist decoded-arglist) args))
(defun arglist-from-form (form)
(if (null form)
:not-available
(arglist-dispatch (car form) (cdr form))))
(export 'arglist-dispatch)
(defgeneric arglist-dispatch (operator arguments)
(:method (operator arguments)
(unless (and (symbolp operator) (valid-operator-symbol-p operator))
(return-from arglist-dispatch :not-available))
(when (equalp (package-name (symbol-package operator)) "closer-mop")
(let ((standard-symbol (or (find-symbol (symbol-name operator) :cl)
(find-symbol (symbol-name operator) :micros/mop))))
(when standard-symbol
(return-from arglist-dispatch
(arglist-dispatch standard-symbol arguments)))))
(multiple-value-bind (decoded-arglist determining-args)
(compute-enriched-decoded-arglist operator arguments)
(with-available-arglist (arglist) decoded-arglist
(setf arglist (delete-given-args arglist determining-args))
(setf (arglist.provided-args arglist) determining-args)
arglist))))
(defmethod arglist-dispatch ((operator (eql 'defmethod)) arguments)
(match (cons operator arguments)
(('defmethod (#'function-exists-p gf-name) . rest)
(let ((gf (fdefinition gf-name)))
(when (typep gf 'generic-function)
(let ((lambda-list (micros/mop:generic-function-lambda-list gf)))
(with-available-arglist (arglist) (decode-arglist lambda-list)
(let ((qualifiers (loop for x in rest
until (or (listp x) (empty-arg-p x))
collect x)))
(return-from arglist-dispatch
(make-arglist :provided-args (cons gf-name qualifiers)
:required-args (list arglist)
:rest "body" :body-p t))))))))
Fall through
(call-next-method))
(defmethod arglist-dispatch ((operator (eql 'define-compiler-macro)) arguments)
(match (cons operator arguments)
(('define-compiler-macro (#'function-exists-p gf-name) . _)
(let ((gf (fdefinition gf-name)))
(with-available-arglist (arglist) (decode-arglist (arglist gf))
(return-from arglist-dispatch
(make-arglist :provided-args (list gf-name)
:required-args (list arglist)
:rest "body" :body-p t)))))
Fall through
(call-next-method))
(defmethod arglist-dispatch ((operator (eql 'eval-when)) arguments)
(declare (ignore arguments))
(let ((eval-when-args '(:compile-toplevel :load-toplevel :execute)))
(make-arglist
:required-args (list (make-arglist :any-p t :any-args eval-when-args))
:rest '#:body :body-p t)))
(defmethod arglist-dispatch ((operator (eql 'declare)) arguments)
(let* ((declaration (cons operator (last arguments)))
(typedecl-arglist (arglist-for-type-declaration declaration)))
(if (arglist-available-p typedecl-arglist)
typedecl-arglist
(match declaration
(('declare ((#'consp typespec) . decl-args))
(with-available-arglist (typespec-arglist)
(decoded-arglist-for-type-specifier typespec)
(make-arglist
:required-args (list (make-arglist
:required-args (list typespec-arglist)
:rest '#:variables)))))
(('declare (decl-identifier . decl-args))
(decoded-arglist-for-declaration decl-identifier decl-args))
(_ (make-arglist :rest '#:declaration-specifiers))))))
(defmethod arglist-dispatch ((operator (eql 'declaim)) arguments)
(arglist-dispatch 'declare arguments))
(defun arglist-for-type-declaration (declaration)
(flet ((%arglist-for-type-declaration (identifier typespec rest-var-name)
(with-available-arglist (typespec-arglist)
(decoded-arglist-for-type-specifier typespec)
(make-arglist
:required-args (list (make-arglist
:provided-args (list identifier)
:required-args (list typespec-arglist)
:rest rest-var-name))))))
(match declaration
(('declare ('type (#'consp typespec) . decl-args))
(%arglist-for-type-declaration 'type typespec '#:variables))
(('declare ('ftype (#'consp typespec) . decl-args))
(%arglist-for-type-declaration 'ftype typespec '#:function-names))
(('declare ((#'consp typespec) . decl-args))
(with-available-arglist (typespec-arglist)
(decoded-arglist-for-type-specifier typespec)
(make-arglist
:required-args (list (make-arglist
:required-args (list typespec-arglist)
:rest '#:variables)))))
(_ :not-available))))
(defun decoded-arglist-for-declaration (decl-identifier decl-args)
(declare (ignore decl-args))
(with-available-arglist (arglist)
(decode-arglist (declaration-arglist decl-identifier))
(setf (arglist.provided-args arglist) (list decl-identifier))
(make-arglist :required-args (list arglist))))
(defun decoded-arglist-for-type-specifier (type-specifier)
(etypecase type-specifier
(arglist-dummy :not-available)
(cons (decoded-arglist-for-type-specifier (car type-specifier)))
(symbol
(with-available-arglist (arglist)
(decode-arglist (type-specifier-arglist type-specifier))
(setf (arglist.provided-args arglist) (list type-specifier))
arglist))))
Slimefuns
user 's point in Emacs . A RAW - FORM looks like
( " FOO " ( " BAR " ... ) " QUUX " ( " ZURP " LSP - BACKEND::%CURSOR - MARKER% ) )
( " F " " X " " Y " % CURSOR - MARKER% ) )
( " F " " X " " Y " ) % CURSOR - MARKER% )
Notice that for a form like ( FOO ( BAR | ) QUUX ) , where | denotes
user 's point , the following should be sent ( " FOO " ( " BAR " " "
% CURSOR - MARKER% ) ) . Only the forms up to point should be
(defun call-with-autodoc-error-handler (function print-right-margin)
(handler-bind ((serious-condition
#'(lambda (c)
(unless (debug-on-swank-error)
(let ((*print-right-margin* print-right-margin))
(return-from call-with-autodoc-error-handler
(format nil "Arglist Error: \"~A\"" c)))))))
(funcall function)))
(defmacro with-autodoc-error-handler ((&key print-right-margin) &body body)
`(call-with-autodoc-error-handler (lambda () ,@body)
,print-right-margin))
(defun autodoc-function (raw-form &key print-right-margin)
(with-autodoc-error-handler (:print-right-margin print-right-margin)
(with-buffer-syntax ()
(multiple-value-bind (form arglist obj-at-cursor form-path)
(find-subform-with-arglist (parse-raw-form raw-form))
(declare (ignore obj-at-cursor))
(list
(with-available-arglist (arglist) arglist
(decoded-arglist-to-string
arglist
:print-right-margin print-right-margin
:operator (car form)
:highlight (form-path-to-arglist-path form-path
form
arglist)))
(let ((*package* (find-package :cl-user)))
(prin1-to-string
(first form))))))))
(defslimefun autodoc (raw-form &key print-right-margin)
"Return a list of two elements.
First, a string representing the arglist for the deepest subform in
RAW-FORM that does have an arglist. The highlighted parameter is
wrapped in ===> X <===.
Second, a boolean value telling whether the returned string can be cached."
(with-autodoc-error-handler (:print-right-margin print-right-margin)
(with-buffer-syntax ()
(multiple-value-bind (form arglist obj-at-cursor form-path)
(find-subform-with-arglist (parse-raw-form raw-form))
(cond ((boundp-and-interesting obj-at-cursor)
(list (print-variable-to-string obj-at-cursor) nil))
(t
(list
(with-available-arglist (arglist) arglist
(decoded-arglist-to-string
arglist
:print-right-margin print-right-margin
:operator (car form)
:highlight (form-path-to-arglist-path form-path
form
arglist)))
t)))))))
(defun boundp-and-interesting (symbol)
(and symbol
(symbolp symbol)
(boundp symbol)
(not (memq symbol '(cl:t cl:nil)))
(not (keywordp symbol))))
(defun print-variable-to-string (symbol)
"Return a short description of VARIABLE-NAME, or NIL."
(let ((*print-pretty* t) (*print-level* 4)
(*print-length* 10) (*print-lines* 1)
(*print-readably* nil)
(value (symbol-value symbol)))
(call/truncated-output-to-string
75 (lambda (s)
(without-printing-errors (:object value :stream s)
(format s "~A ~A~S" symbol *echo-area-prefix* value))))))
(defslimefun complete-form (raw-form)
"Read FORM-STRING in the current buffer package, then complete it
by adding a template for the missing arguments."
ARGLIST - FOR - ECHO - AREA .
(with-buffer-syntax ()
(multiple-value-bind (arglist provided-args)
(find-immediately-containing-arglist (parse-raw-form raw-form))
(with-available-arglist (arglist) arglist
(decoded-arglist-to-template-string
(delete-given-args arglist
(remove-if #'empty-arg-p provided-args
:from-end t :count 1))
:prefix "" :suffix "")))))
(defslimefun completions-for-keyword (keyword-string raw-form)
"Return a list of possible completions for KEYWORD-STRING relative
to the context provided by RAW-FORM."
(with-buffer-syntax ()
(let ((arglist (find-immediately-containing-arglist
(parse-raw-form raw-form))))
(when (arglist-available-p arglist)
(let* ((keywords
(append (mapcar #'keyword-arg.keyword
(arglist.keyword-args arglist))
(remove-if-not #'keywordp (arglist.any-args arglist))))
(keyword-name
(tokenize-symbol keyword-string))
(matching-keywords
(find-matching-symbols-in-list
keyword-name keywords (make-compound-prefix-matcher #\-)))
(converter (completion-output-symbol-converter keyword-string))
(strings
(mapcar converter
(mapcar #'symbol-name matching-keywords)))
(completion-set
(format-completion-set strings nil "")))
(list completion-set
(longest-compound-prefix completion-set)))))))
(defparameter +cursor-marker+ '%cursor-marker%)
(defun find-subform-with-arglist (form)
"Returns four values:
The appropriate subform of `form' which is closest to the
+CURSOR-MARKER+ and whose operator is valid and has an
arglist. The +CURSOR-MARKER+ is removed from that subform.
Second value is the arglist. Local function and macro definitions
appearing in `form' into account.
Third value is the object in front of +CURSOR-MARKER+.
Fourth value is a form path to that object."
(labels
((yield-success (form local-ops)
(multiple-value-bind (form obj-at-cursor form-path)
(extract-cursor-marker form)
(values form
(let ((entry (assoc (car form) local-ops :test #'op=)))
(if entry
(decode-arglist (cdr entry))
(arglist-from-form form)))
obj-at-cursor
form-path)))
(yield-failure ()
(values nil :not-available))
(operator-p (operator local-ops)
(or (and (symbolp operator) (valid-operator-symbol-p operator))
(assoc operator local-ops :test #'op=)))
(op= (op1 op2)
(cond ((and (symbolp op1) (symbolp op2))
(eq op1 op2))
((and (arglist-dummy-p op1) (arglist-dummy-p op2))
(string= (arglist-dummy.string-representation op1)
(arglist-dummy.string-representation op2)))))
(grovel-form (form local-ops)
"Descend FORM top-down, always taking the rightest branch,
until +CURSOR-MARKER+."
(assert (listp form))
(destructuring-bind (operator . args) form
subform right before + CURSOR - MARKER+ .
(let ((last-subform (car (last form)))
(new-ops))
(cond
((eq last-subform +cursor-marker+)
(if (operator-p operator local-ops)
(yield-success form local-ops)
(yield-failure)))
((not (operator-p operator local-ops))
(grovel-form last-subform local-ops))
((setq new-ops (extract-local-op-arglists operator args))
(multiple-value-or (grovel-form last-subform
(nconc new-ops local-ops))
(yield-success form local-ops)))
((member operator '(cl:declare cl:declaim))
(yield-success form local-ops))
((memq operator '(cl:quote cl:function))
(yield-failure))
(t
(multiple-value-or (grovel-form last-subform local-ops)
(yield-success form local-ops))))))))
(if (null form)
(yield-failure)
(grovel-form form '()))))
(defun extract-cursor-marker (form)
"Returns three values: normalized `form' without +CURSOR-MARKER+,
the object in front of +CURSOR-MARKER+, and a form path to that
object."
(labels ((grovel (form last path)
(let ((result-form))
(loop for (car . cdr) on form do
(cond ((eql car +cursor-marker+)
(decf (first path))
(return-from grovel
(values (nreconc result-form cdr)
last
(nreverse path))))
((consp car)
(multiple-value-bind (new-car new-last new-path)
(grovel car last (cons 0 path))
(return-from grovel
(values (nreconc
(cons new-car result-form) cdr)
new-last
new-path))))))
(push car result-form)
(setq last car)
(incf (first path))
finally
(return-from grovel
(values (nreverse result-form) nil nil))))))
(grovel form nil (list 0))))
(defgeneric extract-local-op-arglists (operator args)
(:documentation
"If the form `(OPERATOR ,@ARGS) is a local operator binding form,
return a list of pairs (OP . ARGLIST) for each locally bound op.")
(:method (operator args)
(declare (ignore operator args))
nil)
(:method ((operator (eql 'cl:flet)) args)
(let ((defs (first args))
(body (rest args)))
(t (%collect-op/argl-alist defs)))))
(:method ((operator (eql 'cl:labels)) args)
(destructuring-bind (defs . body) args
(let ((current-def (car (last defs))))
((not (null body))
(extract-local-op-arglists 'cl:flet args))
(t
(let ((def.body (cddr current-def)))
(when def.body
(%collect-op/argl-alist defs)))))))))
MACROLET
(:method ((operator (eql 'cl:macrolet)) args)
(extract-local-op-arglists 'cl:labels args)))
(defun %collect-op/argl-alist (defs)
(setq defs (remove-if-not #'(lambda (x)
(and (consp x) (second x)))
defs))
(loop for (name arglist . nil) in defs
collect (cons name arglist)))
(defun find-immediately-containing-arglist (form)
"Returns the arglist of the subform _immediately_ containing
+CURSOR-MARKER+ in `form'. Notice, however, that +CURSOR-MARKER+ may
be in a nested arglist \(e.g. `(WITH-OPEN-FILE (<here>'\), and the
arglist of the appropriate parent form \(WITH-OPEN-FILE\) will be
returned in that case."
(flet ((try (form-path form arglist)
(let* ((arglist-path (form-path-to-arglist-path form-path
form
arglist))
(argl (apply #'arglist-ref
arglist
arglist-path))
(args (apply #'provided-arguments-ref
(cdr form)
arglist
arglist-path)))
(when (and (arglist-p argl) (listp args))
(values argl args)))))
(multiple-value-bind (form arglist obj form-path)
(find-subform-with-arglist form)
(declare (ignore obj))
(with-available-arglist (arglist) arglist
First try the form the cursor is in ( in case of a normal
(multiple-value-or (try form-path form arglist)
(try (butlast form-path) form arglist)
:not-available)))))
(defun form-path-to-arglist-path (form-path form arglist)
"Convert a form path to an arglist path consisting of arglist
indices."
(labels ((convert (path args arglist)
(if (null path)
nil
(let* ((idx (car path))
(idx* (arglist-index idx args arglist))
(arglist* (and idx* (arglist-ref arglist idx*)))
(args* (and idx* (provided-arguments-ref args
arglist
idx*))))
arglist of DEFUN wo n't contain as much information .
(cond ((null idx*)
nil)
((arglist-p arglist*)
(cons idx* (convert (cdr path) args* arglist*)))
(t
(list idx*)))))))
(convert
(cond ((null form-path) nil)
((equal form-path '(0)) nil)
(t
(destructuring-bind (car . cdr) form-path
(cons (1- car) cdr))))
(cdr form)
arglist)))
(defun arglist-index (provided-argument-index provided-arguments arglist)
"Return the arglist index into `arglist' for the parameter belonging
to the argument (NTH `provided-argument-index' `provided-arguments')."
(let ((positional-args# (positional-args-number arglist))
(arg-index provided-argument-index))
(with-struct (arglist. key-p rest) arglist
(cond
arg-index)
nil)
(assert (arglist.rest arglist))
positional-args#)
(let* ((argument (nth arg-index provided-arguments))
(provided-keys (subseq provided-arguments positional-args#)))
(loop for (key value) on provided-keys by #'cddr
when (eq value argument)
return (match key
(('quote symbol) symbol)
(_ key)))))))))
(defun arglist-ref (arglist &rest indices)
"Returns the parameter in ARGLIST along the INDICIES path. Numbers
represent positional parameters (required, optional), keywords
represent key parameters."
(flet ((ref-positional-arg (arglist index)
(check-type index (integer 0 *))
(with-struct (arglist. provided-args required-args
optional-args rest)
arglist
(loop for args in (list provided-args required-args
(mapcar #'optional-arg.arg-name
optional-args))
for args# = (length args)
if (< index args#)
return (nth index args)
else
do (decf index args#)
finally (return (or rest nil)))))
(ref-keyword-arg (arglist keyword)
not only from the KEYWORD package .
(let ((keyword (match keyword
(('quote symbol) symbol)
(_ keyword))))
(do-decoded-arglist arglist
(&key (kw arg) (when (eq kw keyword)
(return-from ref-keyword-arg arg)))))
nil))
(dolist (index indices)
(assert (arglist-p arglist))
(setq arglist (if (numberp index)
(ref-positional-arg arglist index)
(ref-keyword-arg arglist index))))
arglist))
(defun provided-arguments-ref (provided-args arglist &rest indices)
"Returns the argument in PROVIDED-ARGUMENT along the INDICES path
relative to ARGLIST."
(check-type arglist arglist)
(flet ((ref (provided-args arglist index)
(if (numberp index)
(nth index provided-args)
(let ((provided-keys (subseq provided-args
(positional-args-number arglist))))
(loop for (key value) on provided-keys
when (eq key index)
return value)))))
(dolist (idx indices)
(setq provided-args (ref provided-args arglist idx))
(setq arglist (arglist-ref arglist idx)))
provided-args))
(defun positional-args-number (arglist)
(+ (length (arglist.provided-args arglist))
(length (arglist.required-args arglist))
(length (arglist.optional-args arglist))))
(defun parse-raw-form (raw-form)
"Parse a RAW-FORM into a Lisp form. I.e. substitute strings by
symbols if already interned. For strings not already interned, use
ARGLIST-DUMMY."
(unless (null raw-form)
(loop for element in raw-form
collect (etypecase element
(string (read-conversatively element))
(list (parse-raw-form element))
(symbol (prog1 element
(assert (eq element +cursor-marker+))))))))
(defun read-conversatively (string)
"Tries to find the symbol that's represented by STRING.
If it can't, this either means that STRING does not represent a
symbol, or that the symbol behind STRING would have to be freshly
interned. Because this function is supposed to be called from the
automatic arglist display stuff from Slime, interning freshly
symbols is a big no-no.
In such a case (that no symbol could be found), an object of type
ARGLIST-DUMMY is returned instead, which works as a placeholder
datum for subsequent logics to rely on."
(let* ((string (string-left-trim '(#\Space #\Tab #\Newline) string))
(length (length string))
(type (cond ((zerop length) nil)
((eql (aref string 0) #\')
:quoted-symbol)
((search "#'" string :end2 (min length 2))
:sharpquoted-symbol)
((char= (char string 0) (char string (1- length))
#\")
:string)
(t
:symbol))))
(multiple-value-bind (symbol found?)
(case type
(:symbol (parse-symbol string))
(:quoted-symbol (parse-symbol (subseq string 1)))
(:sharpquoted-symbol (parse-symbol (subseq string 2)))
(:string (values string t))
(t (values string nil)))
(if found?
(ecase type
(:symbol symbol)
(:quoted-symbol `(quote ,symbol))
(:sharpquoted-symbol `(function ,symbol))
(:string (if (> length 1)
(subseq string 1 (1- length))
string)))
(make-arglist-dummy string)))))
(defun test-print-arglist ()
(flet ((test (arglist &rest strings)
(let* ((*package* (find-package :micros))
(actual (decoded-arglist-to-string
(decode-arglist arglist)
:print-right-margin 1000)))
(unless (loop for string in strings
thereis (string= actual string))
(warn "Test failed: ~S => ~S~% Expected: ~A"
arglist actual
(if (cdr strings)
(format nil "One of: ~{~S~^, ~}" strings)
(format nil "~S" (first strings))))))))
(test '(function cons) "(function cons)")
(test '(quote cons) "(quote cons)")
(test '(&key (function #'+))
"(&key (function #'+))" "(&key (function (function +)))")
(test '(&whole x y z) "(y z)")
(test '(x &aux y z) "(x)")
(test '(x &environment env y) "(x y)")
(test '(&key ((function f))) "(&key ((function ..)))")
(test
'(eval-when (&any :compile-toplevel :load-toplevel :execute) &body body)
"(eval-when (&any :compile-toplevel :load-toplevel :execute) &body body)")
(test '(declare (optimize &any (speed 1) (safety 1)))
"(declare (optimize &any (speed 1) (safety 1)))")))
(defun test-arglist-ref ()
(macrolet ((soft-assert (form)
`(unless ,form
(warn "Assertion failed: ~S~%" ',form))))
(let ((sample (decode-arglist '(x &key ((:k (y z)))))))
(soft-assert (eq (arglist-ref sample 0) 'x))
(soft-assert (eq (arglist-ref sample :k 0) 'y))
(soft-assert (eq (arglist-ref sample :k 1) 'z))
(soft-assert (eq (provided-arguments-ref '(a :k (b c)) sample 0)
'a))
(soft-assert (eq (provided-arguments-ref '(a :k (b c)) sample :k 0)
'b))
(soft-assert (eq (provided-arguments-ref '(a :k (b c)) sample :k 1)
'c)))))
(test-print-arglist)
(test-arglist-ref)
|
b22ed5e83c66a48b67f01d89f1044a55e512fa2e992fd95aac95ce4666dc7028 | alakahakai/hackerrank | common-divisors.hs |
Common Divisors
-divisors
Author : < >
Date : June 8th , 2015
Common Divisors
-divisors
Author: Ray Qiu <>
Date: June 8th, 2015
-}
{-# OPTIONS -O2 #-}
import Control.Applicative (liftA)
import Control.Monad (forM_)
import qualified Data.Map as M
import qualified Data.Set as S
import System.IO
divisors :: Int -> [Int]
divisors n = foldr (\x xs -> if n `mod` x == 0
then if x /= n `div` x
then x:(n `div` x):xs
else x:xs
else xs) []
[1..(floor . sqrt . fromIntegral) n]
main :: IO ()
main = do
n <- liftA (\x -> read x :: Int) getLine
forM_ [1..n] $ \_ -> do
[l, m] <- liftA (map (\x -> read x :: Int)) (liftA words getLine)
let s1 = S.fromList (divisors l)
s2 = S.fromList (divisors m)
print . length . S.toList $ S.intersection s1 s2
| null | https://raw.githubusercontent.com/alakahakai/hackerrank/465d17107bbe402daf750651bb57cf092305acf9/fp/common-divisors.hs | haskell | # OPTIONS -O2 # |
Common Divisors
-divisors
Author : < >
Date : June 8th , 2015
Common Divisors
-divisors
Author: Ray Qiu <>
Date: June 8th, 2015
-}
import Control.Applicative (liftA)
import Control.Monad (forM_)
import qualified Data.Map as M
import qualified Data.Set as S
import System.IO
divisors :: Int -> [Int]
divisors n = foldr (\x xs -> if n `mod` x == 0
then if x /= n `div` x
then x:(n `div` x):xs
else x:xs
else xs) []
[1..(floor . sqrt . fromIntegral) n]
main :: IO ()
main = do
n <- liftA (\x -> read x :: Int) getLine
forM_ [1..n] $ \_ -> do
[l, m] <- liftA (map (\x -> read x :: Int)) (liftA words getLine)
let s1 = S.fromList (divisors l)
s2 = S.fromList (divisors m)
print . length . S.toList $ S.intersection s1 s2
|
8e55056fe416ec48cabfc9d642825d70671f4a307ebb55eb6d96d38519d386bc | jeffshrager/biobike | special-slots.lisp | -*- Package : frames ; mode : lisp ; base : 10 ; Syntax : Common - Lisp ; -*-
(in-package :frames)
;;; +=========================================================================+
| Copyright ( c ) 2002 , 2003 , 2004 JP , , |
;;; | |
;;; | Permission is hereby granted, free of charge, to any person obtaining |
;;; | a copy of this software and associated documentation files (the |
| " Software " ) , to deal in the Software without restriction , including |
;;; | without limitation the rights to use, copy, modify, merge, publish, |
| distribute , sublicense , and/or sell copies of the Software , and to |
| permit persons to whom the Software is furnished to do so , subject to |
;;; | the following conditions: |
;;; | |
;;; | The above copyright notice and this permission notice shall be included |
| in all copies or substantial portions of the Software . |
;;; | |
| THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND , |
;;; | EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF |
;;; | MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. |
;;; | IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY |
| CLAIM , DAMAGES OR OTHER LIABILITY , WHETHER IN AN ACTION OF CONTRACT , |
;;; | TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE |
;;; | SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. |
;;; +=========================================================================+
(defslot #$putDemons :set-valued? t)
(defslot #$addDemons :set-valued? t)
(defslot #$getter)
(defslot #$computedSlot)
(defslot #$inverse :applicable-to #$Slot)
(defslot #$inheritsThrough)
(defslot #$instanceOf)
(defslot #$HTMLGenerator)
(def-computed-slot (#$accessorFn frame slot)
we need to make a symbol so setf can work
(let ((accessor-symbol
(intern (one-string (slotv frame #$fName) "-ACCESSOR") :frames))
(accessor (lambda (target-frame) (slotv target-frame frame)))
(mutator-symbol
(intern (one-string (slotv frame #$fName) "-MUTATOR") :frames))
(mutator
(lambda (target-frame new-val)
(setf (slotv target-frame frame) new-val))))
(setf (symbol-function accessor-symbol) accessor)
(setf (symbol-function mutator-symbol) mutator)
necessary to use eval because defsetf is defined as a macro
;; and there is no functional equivalent
(eval `(defsetf ,accessor-symbol ,mutator-symbol))
accessor-symbol))
(def-inverse-slot #$subClasses #$isA)
(def-inverse-slot #$parts #$partOf)
(def-transitive-slot #$allIsA #$isA)
(def-transitive-slot #$allSubclasses #$subclasses)
(def-transitive-slot #$allParts #$subclasses)
(def-transitive-slot #$allPartOf #$partOf)
;;; Redefine fname to be a computed slot
(def-computed-slot (#$fName frame slot) (gensym-and-intern frame))
| null | https://raw.githubusercontent.com/jeffshrager/biobike/5313ec1fe8e82c21430d645e848ecc0386436f57/BioLisp/Frames/special-slots.lisp | lisp | mode : lisp ; base : 10 ; Syntax : Common - Lisp ; -*-
+=========================================================================+
| |
| Permission is hereby granted, free of charge, to any person obtaining |
| a copy of this software and associated documentation files (the |
| without limitation the rights to use, copy, modify, merge, publish, |
| the following conditions: |
| |
| The above copyright notice and this permission notice shall be included |
| |
| EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF |
| MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. |
| IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY |
| TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE |
| SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. |
+=========================================================================+
and there is no functional equivalent
Redefine fname to be a computed slot |
(in-package :frames)
| Copyright ( c ) 2002 , 2003 , 2004 JP , , |
| " Software " ) , to deal in the Software without restriction , including |
| distribute , sublicense , and/or sell copies of the Software , and to |
| permit persons to whom the Software is furnished to do so , subject to |
| in all copies or substantial portions of the Software . |
| THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND , |
| CLAIM , DAMAGES OR OTHER LIABILITY , WHETHER IN AN ACTION OF CONTRACT , |
(defslot #$putDemons :set-valued? t)
(defslot #$addDemons :set-valued? t)
(defslot #$getter)
(defslot #$computedSlot)
(defslot #$inverse :applicable-to #$Slot)
(defslot #$inheritsThrough)
(defslot #$instanceOf)
(defslot #$HTMLGenerator)
(def-computed-slot (#$accessorFn frame slot)
we need to make a symbol so setf can work
(let ((accessor-symbol
(intern (one-string (slotv frame #$fName) "-ACCESSOR") :frames))
(accessor (lambda (target-frame) (slotv target-frame frame)))
(mutator-symbol
(intern (one-string (slotv frame #$fName) "-MUTATOR") :frames))
(mutator
(lambda (target-frame new-val)
(setf (slotv target-frame frame) new-val))))
(setf (symbol-function accessor-symbol) accessor)
(setf (symbol-function mutator-symbol) mutator)
necessary to use eval because defsetf is defined as a macro
(eval `(defsetf ,accessor-symbol ,mutator-symbol))
accessor-symbol))
(def-inverse-slot #$subClasses #$isA)
(def-inverse-slot #$parts #$partOf)
(def-transitive-slot #$allIsA #$isA)
(def-transitive-slot #$allSubclasses #$subclasses)
(def-transitive-slot #$allParts #$subclasses)
(def-transitive-slot #$allPartOf #$partOf)
(def-computed-slot (#$fName frame slot) (gensym-and-intern frame))
|
82c5ce6fcdc0a76d27084c12d41602dcdb35918032df44986d4e0298c24dff64 | angavrilov/cl-linux-debug | patches.lisp | (in-package :asdf)
(let ((cg (find-system :cffi-grovel)))
(unless (system-source-file cg)
(%set-system-source-file
(pathname (directory-namestring
(merge-pathnames #P"mk-runtime/"
(system-definition-pathname :cl-linux-debug))))
cg)))
(in-package :elf)
#| Patch the ELF library. The original implementation of the
function is massively inefficient. |#
(defun name-symbols (sec)
"Assign names to the symbols contained in SEC."
(when (member (type sec) '(:symtab :dynsym))
(with-slots (elf sh type) sec
(let* ((name-sec (nth (link sh) (sections elf)))
(tab (data name-sec)))
(mapcar (lambda (sym)
(setf (sym-name sym)
(coerce (loop for idx from (name sym)
for code = (aref tab idx)
until (equal code 0)
collect (code-char code))
'string)))
(data sec))))))
| null | https://raw.githubusercontent.com/angavrilov/cl-linux-debug/879da2dcd14918bb8ffab003e934f4b01fba12ff/patches.lisp | lisp | Patch the ELF library. The original implementation of the
function is massively inefficient. | (in-package :asdf)
(let ((cg (find-system :cffi-grovel)))
(unless (system-source-file cg)
(%set-system-source-file
(pathname (directory-namestring
(merge-pathnames #P"mk-runtime/"
(system-definition-pathname :cl-linux-debug))))
cg)))
(in-package :elf)
(defun name-symbols (sec)
"Assign names to the symbols contained in SEC."
(when (member (type sec) '(:symtab :dynsym))
(with-slots (elf sh type) sec
(let* ((name-sec (nth (link sh) (sections elf)))
(tab (data name-sec)))
(mapcar (lambda (sym)
(setf (sym-name sym)
(coerce (loop for idx from (name sym)
for code = (aref tab idx)
until (equal code 0)
collect (code-char code))
'string)))
(data sec))))))
|
182cb2094b02547bfff1472fd7d88ae742cfa468bd359d6c8fac7c1c6a97c6eb | Clojure2D/clojure2d-examples | ray.clj | (ns rt4.the-next-week.ch07a.ray
(:require [fastmath.vector :as v]
[fastmath.core :as m]))
(set! *warn-on-reflection* true)
(set! *unchecked-math* :warn-on-boxed)
(m/use-primitive-operators)
(defprotocol RayProto
(at [ray t]))
(defrecord Ray [origin direction ^double time]
RayProto
(at [_ t] (v/add origin (v/mult direction t))))
(defn ray
([m] (map->Ray (merge {:time 0.0} m)))
([origin direction] (->Ray origin direction 0.0))
([origin direction time] (->Ray origin direction time)))
| null | https://raw.githubusercontent.com/Clojure2D/clojure2d-examples/ead92d6f17744b91070e6308157364ad4eab8a1b/src/rt4/the_next_week/ch07a/ray.clj | clojure | (ns rt4.the-next-week.ch07a.ray
(:require [fastmath.vector :as v]
[fastmath.core :as m]))
(set! *warn-on-reflection* true)
(set! *unchecked-math* :warn-on-boxed)
(m/use-primitive-operators)
(defprotocol RayProto
(at [ray t]))
(defrecord Ray [origin direction ^double time]
RayProto
(at [_ t] (v/add origin (v/mult direction t))))
(defn ray
([m] (map->Ray (merge {:time 0.0} m)))
([origin direction] (->Ray origin direction 0.0))
([origin direction time] (->Ray origin direction time)))
|
|
937d94ffc31316ac22dc3683c7bb76f54aeb4f6a77263085ee612b05bfe5dcc7 | lichtblau/CommonQt | t5.lisp | ;;; -*- show-trailing-whitespace: t; indent-tabs-mode: nil -*-
;;; -t3.html
(defpackage :qt-tutorial-5
(:use :cl :qt)
(:export #:main))
(in-package :qt-tutorial-5)
(named-readtables:in-readtable :qt)
(defvar *qapp*)
(defclass my-widget ()
()
(:metaclass qt-class)
(:qt-superclass "QWidget"))
(defmethod initialize-instance :after ((instance my-widget) &key parent)
(if parent
(new instance parent)
(new instance))
(#_setFixedSize instance 200 120)
(let ((quit (#_new QPushButton "Quit" instance))
(lcd (#_new QLCDNumber 2))
(slider (#_new QSlider (#_Horizontal "Qt"))))
(#_setFont quit (#_new QFont "Times" 18 (#_Bold "QFont")))
(#_setSegmentStyle lcd (#_Filled "QLCDNumber"))
(#_setRange slider 0 99)
(#_setValue slider 0)
(#_connect "QObject"
quit (QSIGNAL "clicked()")
*qapp* (QSLOT "quit()"))
(#_connect "QObject"
slider (QSIGNAL "valueChanged(int)")
lcd (QSLOT "display(int)"))
(let ((layout (#_new QVBoxLayout)))
(#_addWidget layout quit)
(#_addWidget layout lcd)
(#_addWidget layout slider)
(#_setLayout instance layout))))
(defun main ()
(setf *qapp* (make-qapplication))
(let ((widget (make-instance 'my-widget)))
(#_show widget)
(unwind-protect
(#_exec *qapp*)
(#_hide widget))))
| null | https://raw.githubusercontent.com/lichtblau/CommonQt/fa14472594b2b2b34695ec3fff6f858a03ec5813/tutorial/old/t5.lisp | lisp | -*- show-trailing-whitespace: t; indent-tabs-mode: nil -*-
-t3.html |
(defpackage :qt-tutorial-5
(:use :cl :qt)
(:export #:main))
(in-package :qt-tutorial-5)
(named-readtables:in-readtable :qt)
(defvar *qapp*)
(defclass my-widget ()
()
(:metaclass qt-class)
(:qt-superclass "QWidget"))
(defmethod initialize-instance :after ((instance my-widget) &key parent)
(if parent
(new instance parent)
(new instance))
(#_setFixedSize instance 200 120)
(let ((quit (#_new QPushButton "Quit" instance))
(lcd (#_new QLCDNumber 2))
(slider (#_new QSlider (#_Horizontal "Qt"))))
(#_setFont quit (#_new QFont "Times" 18 (#_Bold "QFont")))
(#_setSegmentStyle lcd (#_Filled "QLCDNumber"))
(#_setRange slider 0 99)
(#_setValue slider 0)
(#_connect "QObject"
quit (QSIGNAL "clicked()")
*qapp* (QSLOT "quit()"))
(#_connect "QObject"
slider (QSIGNAL "valueChanged(int)")
lcd (QSLOT "display(int)"))
(let ((layout (#_new QVBoxLayout)))
(#_addWidget layout quit)
(#_addWidget layout lcd)
(#_addWidget layout slider)
(#_setLayout instance layout))))
(defun main ()
(setf *qapp* (make-qapplication))
(let ((widget (make-instance 'my-widget)))
(#_show widget)
(unwind-protect
(#_exec *qapp*)
(#_hide widget))))
|
09e14e10545b9411edb9c9332e04c179bd0d0c3242651a564aa6905d99a2dcf4 | gnuvince/ocaml-tiger | lexer.mli | exception LexerError of (Src_pos.t * string)
val lex_tiger : Lexing.lexbuf -> Parser.token
| null | https://raw.githubusercontent.com/gnuvince/ocaml-tiger/42e39cb0d48cf3100fbfb7e51aa88a71e04ec6a4/lexer.mli | ocaml | exception LexerError of (Src_pos.t * string)
val lex_tiger : Lexing.lexbuf -> Parser.token
|
|
37f232407795d9912ff99c9eb7fc52021667949de51f24900f675056464553df | ocaml/merlin | path.ml | module A = struct
type a = int
end
open A
let x = (5 : a)
| null | https://raw.githubusercontent.com/ocaml/merlin/e576bc75f11323ec8489d2e58a701264f5a7fe0e/tests/test-dirs/outline.t/path.ml | ocaml | module A = struct
type a = int
end
open A
let x = (5 : a)
|
|
89f13f4c195dcab36153960933c679df0761d42a09b40ac4a800ca40d22fe450 | reasonml/reason | knownMlIssues.ml | (* [x] fixed *)
type t2 =
int * int (* attributed to entire type not binding *)
type color =
| Red of int (* After red *)
| Black of int (* After black *)
| Green of int (* Does not remain here *)
let blahCurriedX x =
function
| Red 10
| Black 20
| Green 10 -> 1 (* After or pattern green *)
| Red x -> 0 (* After red *)
| Black x -> 0 (* After black *)
After second green
(* On next line after blahCurriedX def *)
EOL comments wrap because other elements break first ( in this example
" mutable " causes breaks . We either need :
1 . To prevent wrapping of anything inside of eol comments attachments .
2 . eol comments .
"mutable" causes breaks. We either need:
1. To prevent wrapping of anything inside of eol comments attachments.
2. Losslessly wrap eol comments.
*)
(* This example illustrates the above issue, but isn't een idempotent due to the issue. *)
(* type cfg = { *)
(* node_id : int ref; *)
node_list : int list ref ;
name_pdesc_tbl : ( int , ( int , int ) ) Hashtbl.t ; ( * * Map proc name to procdesc
mutable priority_set : ( int , int ) ( * * set of function names to be analyzed first
(* } *)
(* *)
(* *)
| null | https://raw.githubusercontent.com/reasonml/reason/daa11255cb4716ce1c370925251021bd6e3bd974/formatTest/typeCheckedTests/input/knownMlIssues.ml | ocaml | [x] fixed
attributed to entire type not binding
After red
After black
Does not remain here
After or pattern green
After red
After black
On next line after blahCurriedX def
This example illustrates the above issue, but isn't een idempotent due to the issue.
type cfg = {
node_id : int ref;
}
| type t2 =
type color =
let blahCurriedX x =
function
| Red 10
| Black 20
After second green
EOL comments wrap because other elements break first ( in this example
" mutable " causes breaks . We either need :
1 . To prevent wrapping of anything inside of eol comments attachments .
2 . eol comments .
"mutable" causes breaks. We either need:
1. To prevent wrapping of anything inside of eol comments attachments.
2. Losslessly wrap eol comments.
*)
node_list : int list ref ;
name_pdesc_tbl : ( int , ( int , int ) ) Hashtbl.t ; ( * * Map proc name to procdesc
mutable priority_set : ( int , int ) ( * * set of function names to be analyzed first
|
9464c1c4826d5dd98ad3ee03ac655f5f8143649dcb668b08d4f4e64014be55d9 | gas2serra/cldk | event-handler.lisp | (in-package :cldk-internals)
;;; event handler
(defclass event-handler (display-driver-callback-handler)
((cur-x :initform nil
:reader event-handler-cur-x)
(cur-y :initform nil
:reader event-handler-cur-y)
(cur-root-x :initform nil
:reader event-handler-cur-root-x)
(cur-root-y :initform nil
:reader event-handler-cur-root-y)
(modifiers :initform 0
:reader event-handler-modifiers)
(pressed-buttons :initform 0
:reader event-handler-pressed-buttons)))
(defgeneric handle-button-event (handler kind pointer button
window timestamp)
(:method ((handler event-handler) kind pointer button
window timestamp)
)
(:method :before ((handler event-handler) kind pointer button
window timestamp)
(with-slots (pressed-buttons modifiers) handler
(when (eql kind :release)
(setf pressed-buttons (logxor button pressed-buttons)))))
(:method :after ((handler event-handler) kind pointer button
window timestamp)
(with-slots (pressed-buttons modifiers) handler
(when (eql kind :press)
(setf pressed-buttons (logior button pressed-buttons))))))
(defgeneric handle-scroll-event (handler pointer dx dy
window timestamp)
(:method ((handler event-handler) pointer dx dy window timestamp)
))
(defgeneric handle-motion-event (handler pointer x y
root-x root-y
window timestamp)
(:method ((handler event-handler) pointer x y
root-x root-y window timestamp)
)
(:method :after ((handler event-handler) pointer x y
root-x root-y window timestamp)
(with-slots (cur-x cur-y cur-root-x cur-root-y) handler
(setf cur-x x
cur-y y
cur-root-x root-x
cur-root-y root-y))))
(defgeneric handle-key-event (handler kind keyname character modifiers
window timestamp)
(:method ((handler event-handler) kind keyname character modifiers
window timestamp)
)
(:method :before ((handler event-handler) kind keyname character mmodifiers
window timestamp)
(with-slots (modifiers) handler
(setf modifiers mmodifiers))))
(defgeneric handle-enter-event (handler pointer x y root-x root-y win time)
(:method ((handler event-handler) pointer
x y root-x root-y
window timestamp)
)
(:method :before ((handler event-handler) pointer x y
root-x root-y window timestamp)
(with-slots (cur-x cur-y cur-root-x cur-root-y) handler
(setf cur-x x
cur-y y
cur-root-x root-x
cur-root-y root-y))))
(defgeneric handle-leave-event (handler pointer win time)
(:method ((handler event-handler) pointer
window timestamp)
)
(:method :after ((handler event-handler) pointer
window timestamp)
(with-slots (cur-x cur-y cur-root-x cur-root-y) handler
(setf cur-x nil
cur-y nil
cur-root-x nil
cur-root-y nil))))
(defgeneric handle-configure-event (handler win x y w h time)
(:method ((handler event-handler) win x y w h time)
))
(defgeneric handle-repaint-event (handler win x y w h time)
(:method ((handler event-handler) win x y w h time)
))
(defgeneric handle-destroy-event (handler win time)
(:method ((handler event-handler) win time)
))
(defgeneric handle-wm-delete-event (handler win time)
(:method ((handler event-handler) win time)
))
;;;
;;; pretty print
;;;
(defun button2keyword (button)
(let ((button-mapping #.(vector :left
:middle
:right
:x1
:x2)))
(dotimes (i 9)
(when (logbitp i button)
(return (aref button-mapping i))))))
(defun buttons2keywords (button)
(let ((button-mapping #.(vector :left
:middle
:right
:x1
:x2))
(ks nil))
(dotimes (i 9)
(when (logbitp i button)
(setf ks (cons (aref button-mapping i) ks))))
ks))
(defun modifiers2keywords (button)
(let ((button-mapping #.(vector :shift
:control
:meta
:super
:hyper
:alt))
(ks nil))
(dotimes (i 6)
(when (logbitp (+ 8 i) button)
(setf ks (cons (aref button-mapping i) ks))))
ks))
;;;
;;; log event handler
;;;
(defparameter *events-to-log-list* '(:delete :repaint :configure
:enter-leave :button :scroll :motion :key
:modifiers))
(defclass log-event-handler (event-handler)
((to-log :initform :all
:accessor event-handler-events-to-log)))
(defmethod handle-button-event ((handler log-event-handler) kind
pointer button win timestamp)
(with-slots (to-log cur-x cur-y cur-root-x cur-root-y) handler
(when (or (eql to-log :all) (member :button to-log))
(log:info "win:~A k:~A p:~A b:~A p:~A[~A]" win kind pointer
(list button (button2keyword button))
(list cur-x cur-y) (list cur-root-x cur-root-y))
(when (or (eql to-log :all) (member :modifiers to-log))
(with-slots (modifiers pressed-buttons) handler
(log:info "keys:~A buts:~A"
(modifiers2keywords modifiers)
(buttons2keywords pressed-buttons)))))))
(defmethod handle-scroll-event ((handler log-event-handler) pointer dx dy
win timestamp)
(with-slots (to-log) handler
(when (or (eql to-log :all) (member :scroll to-log))
(log:info "win:~A p:~A w:~A" win pointer
(list dx dy))
(when (or (eql to-log :all) (member :modifiers to-log))
(with-slots (modifiers pressed-buttons) handler
(log:info "keys:~A buts:~A"
(modifiers2keywords modifiers)
(buttons2keywords pressed-buttons)))))))
(defmethod handle-motion-event ((handler log-event-handler) pointer x y
root-x root-y
win timestamp)
(with-slots (to-log) handler
(when (or (eql to-log :all) (member :motion to-log))
(log:info "win:~A p:~A p:~A[~A]" win pointer
(list x y) (list root-x root-y))
(when (and (listp to-log) (member :modifiers to-log))
(with-slots (modifiers pressed-buttons) handler
(log:info "keys:~A buts:~A"
(modifiers2keywords modifiers)
(buttons2keywords pressed-buttons)))))))
(defmethod handle-key-event ((handler log-event-handler) kind
keyname character modifiers
win timestamp)
(with-slots (to-log) handler
(when (or (eql to-log :all) (member :key to-log))
(log:info "win:~A k:~A name:~A char:~A mod:~A" win kind keyname character
(list modifiers (modifiers2keywords modifiers)))
(when (or (eql to-log :all) (member :modifiers to-log))
(with-slots (modifiers pressed-buttons) handler
(log:info "keys:~A buts:~A"
(modifiers2keywords modifiers)
(buttons2keywords pressed-buttons)))))))
(defmethod handle-enter-event ((handler log-event-handler) pointer
x y x-root y-root
win timestamp)
(with-slots (to-log cur-x cur-y cur-root-x cur-root-y) handler
(when (or (eql to-log :all) (member :enter-leave to-log))
(log:info "win:~A p:~A p:~A[~A]" win pointer
(list cur-x cur-y) (list cur-root-x cur-root-y)))))
(defmethod handle-leave-event ((handler log-event-handler) pointer
win timestamp)
(with-slots (to-log cur-x cur-y cur-root-x cur-root-y) handler
(when (or (eql to-log :all) (member :enter-leave to-log))
(log:info "win:~A p:~A p:~A[~A]" win pointer
(list cur-x cur-y) (list cur-root-x cur-root-y)))))
(defmethod handle-configure-event ((handler log-event-handler) win x y w h
timestamp)
(with-slots (to-log) handler
(when (or (eql to-log :all) (member :configure to-log))
(log:info "win:~A x:~A y:~A w:~A h:~A" win x y w h))))
(defmethod handle-repaint-event ((handler log-event-handler) win x y w h
timestamp)
(with-slots (to-log) handler
(when (or (eql to-log :all) (member :repaint to-log))
(log:info "win:~A x:~A y:~A w:~A h:~A" win x y w h))))
(defmethod handle-wm-delete-event ((handler log-event-handler) win timestamp)
(with-slots (to-log) handler
(when (or (eql to-log :all) (member :delete to-log))
(log:info "win:~A" win))))
(setf *default-event-handler* (make-instance 'event-handler))
;;;
;;;
;;;
(defmacro <e- (kernel fn &rest args)
`(within-user-mode (,kernel :block-p nil)
(funcall ,fn (event-handler ,kernel) ,@args)))
(defmethod driver-cb-window-configuration-event ((handler event-handler) kernel win x y width height time)
(check-kernel-mode)
(<e- kernel #'handle-configure-event win x y width height time))
(defmethod driver-cb-repaint-event ((handler event-handler) kernel win x y width height time)
(check-kernel-mode)
(<e- kernel #'handle-repaint-event win x y width height time))
(defmethod driver-cb-scroll-event ((handler event-handler) kernel pointer dx dy win timestamp)
(check-kernel-mode)
(<e- kernel #'handle-scroll-event pointer dx dy win timestamp))
(defmethod driver-cb-button-event ((handler event-handler) kernel kind pointer button win timestamp)
(check-kernel-mode)
(<e- kernel #'handle-button-event kind pointer button win timestamp))
(defmethod driver-cb-motion-event ((handler event-handler) kernel pointer x y root-x root-y
win timestamp)
(check-kernel-mode)
(<e- kernel #'handle-motion-event pointer x y root-x root-y
win timestamp))
(defmethod driver-cb-key-event ((handler event-handler) kernel kind keyname character modifiers
win timestamp)
(check-kernel-mode)
(<e- kernel #'handle-key-event kind keyname character modifiers
win timestamp))
(defmethod driver-cb-enter-event ((handler event-handler) kernel pointer x y root-x root-y win time)
(check-kernel-mode)
(<e- kernel #'handle-enter-event pointer x y root-x root-y win time))
(defmethod driver-cb-leave-event ((handler event-handler) kernel pointer win time)
(check-kernel-mode)
(<e- kernel #'handle-leave-event pointer win time))
(defmethod driver-cb-wm-delete-event ((handler event-handler) kernel win time)
(check-kernel-mode)
(<e- kernel #'handle-wm-delete-event win time))
| null | https://raw.githubusercontent.com/gas2serra/cldk/63c8322aedac44249ff8f28cd4f5f59a48ab1441/Core/mirror/event-handler.lisp | lisp | event handler
pretty print
log event handler
| (in-package :cldk-internals)
(defclass event-handler (display-driver-callback-handler)
((cur-x :initform nil
:reader event-handler-cur-x)
(cur-y :initform nil
:reader event-handler-cur-y)
(cur-root-x :initform nil
:reader event-handler-cur-root-x)
(cur-root-y :initform nil
:reader event-handler-cur-root-y)
(modifiers :initform 0
:reader event-handler-modifiers)
(pressed-buttons :initform 0
:reader event-handler-pressed-buttons)))
(defgeneric handle-button-event (handler kind pointer button
window timestamp)
(:method ((handler event-handler) kind pointer button
window timestamp)
)
(:method :before ((handler event-handler) kind pointer button
window timestamp)
(with-slots (pressed-buttons modifiers) handler
(when (eql kind :release)
(setf pressed-buttons (logxor button pressed-buttons)))))
(:method :after ((handler event-handler) kind pointer button
window timestamp)
(with-slots (pressed-buttons modifiers) handler
(when (eql kind :press)
(setf pressed-buttons (logior button pressed-buttons))))))
(defgeneric handle-scroll-event (handler pointer dx dy
window timestamp)
(:method ((handler event-handler) pointer dx dy window timestamp)
))
(defgeneric handle-motion-event (handler pointer x y
root-x root-y
window timestamp)
(:method ((handler event-handler) pointer x y
root-x root-y window timestamp)
)
(:method :after ((handler event-handler) pointer x y
root-x root-y window timestamp)
(with-slots (cur-x cur-y cur-root-x cur-root-y) handler
(setf cur-x x
cur-y y
cur-root-x root-x
cur-root-y root-y))))
(defgeneric handle-key-event (handler kind keyname character modifiers
window timestamp)
(:method ((handler event-handler) kind keyname character modifiers
window timestamp)
)
(:method :before ((handler event-handler) kind keyname character mmodifiers
window timestamp)
(with-slots (modifiers) handler
(setf modifiers mmodifiers))))
(defgeneric handle-enter-event (handler pointer x y root-x root-y win time)
(:method ((handler event-handler) pointer
x y root-x root-y
window timestamp)
)
(:method :before ((handler event-handler) pointer x y
root-x root-y window timestamp)
(with-slots (cur-x cur-y cur-root-x cur-root-y) handler
(setf cur-x x
cur-y y
cur-root-x root-x
cur-root-y root-y))))
(defgeneric handle-leave-event (handler pointer win time)
(:method ((handler event-handler) pointer
window timestamp)
)
(:method :after ((handler event-handler) pointer
window timestamp)
(with-slots (cur-x cur-y cur-root-x cur-root-y) handler
(setf cur-x nil
cur-y nil
cur-root-x nil
cur-root-y nil))))
(defgeneric handle-configure-event (handler win x y w h time)
(:method ((handler event-handler) win x y w h time)
))
(defgeneric handle-repaint-event (handler win x y w h time)
(:method ((handler event-handler) win x y w h time)
))
(defgeneric handle-destroy-event (handler win time)
(:method ((handler event-handler) win time)
))
(defgeneric handle-wm-delete-event (handler win time)
(:method ((handler event-handler) win time)
))
(defun button2keyword (button)
(let ((button-mapping #.(vector :left
:middle
:right
:x1
:x2)))
(dotimes (i 9)
(when (logbitp i button)
(return (aref button-mapping i))))))
(defun buttons2keywords (button)
(let ((button-mapping #.(vector :left
:middle
:right
:x1
:x2))
(ks nil))
(dotimes (i 9)
(when (logbitp i button)
(setf ks (cons (aref button-mapping i) ks))))
ks))
(defun modifiers2keywords (button)
(let ((button-mapping #.(vector :shift
:control
:meta
:super
:hyper
:alt))
(ks nil))
(dotimes (i 6)
(when (logbitp (+ 8 i) button)
(setf ks (cons (aref button-mapping i) ks))))
ks))
(defparameter *events-to-log-list* '(:delete :repaint :configure
:enter-leave :button :scroll :motion :key
:modifiers))
(defclass log-event-handler (event-handler)
((to-log :initform :all
:accessor event-handler-events-to-log)))
(defmethod handle-button-event ((handler log-event-handler) kind
pointer button win timestamp)
(with-slots (to-log cur-x cur-y cur-root-x cur-root-y) handler
(when (or (eql to-log :all) (member :button to-log))
(log:info "win:~A k:~A p:~A b:~A p:~A[~A]" win kind pointer
(list button (button2keyword button))
(list cur-x cur-y) (list cur-root-x cur-root-y))
(when (or (eql to-log :all) (member :modifiers to-log))
(with-slots (modifiers pressed-buttons) handler
(log:info "keys:~A buts:~A"
(modifiers2keywords modifiers)
(buttons2keywords pressed-buttons)))))))
(defmethod handle-scroll-event ((handler log-event-handler) pointer dx dy
win timestamp)
(with-slots (to-log) handler
(when (or (eql to-log :all) (member :scroll to-log))
(log:info "win:~A p:~A w:~A" win pointer
(list dx dy))
(when (or (eql to-log :all) (member :modifiers to-log))
(with-slots (modifiers pressed-buttons) handler
(log:info "keys:~A buts:~A"
(modifiers2keywords modifiers)
(buttons2keywords pressed-buttons)))))))
(defmethod handle-motion-event ((handler log-event-handler) pointer x y
root-x root-y
win timestamp)
(with-slots (to-log) handler
(when (or (eql to-log :all) (member :motion to-log))
(log:info "win:~A p:~A p:~A[~A]" win pointer
(list x y) (list root-x root-y))
(when (and (listp to-log) (member :modifiers to-log))
(with-slots (modifiers pressed-buttons) handler
(log:info "keys:~A buts:~A"
(modifiers2keywords modifiers)
(buttons2keywords pressed-buttons)))))))
(defmethod handle-key-event ((handler log-event-handler) kind
keyname character modifiers
win timestamp)
(with-slots (to-log) handler
(when (or (eql to-log :all) (member :key to-log))
(log:info "win:~A k:~A name:~A char:~A mod:~A" win kind keyname character
(list modifiers (modifiers2keywords modifiers)))
(when (or (eql to-log :all) (member :modifiers to-log))
(with-slots (modifiers pressed-buttons) handler
(log:info "keys:~A buts:~A"
(modifiers2keywords modifiers)
(buttons2keywords pressed-buttons)))))))
(defmethod handle-enter-event ((handler log-event-handler) pointer
x y x-root y-root
win timestamp)
(with-slots (to-log cur-x cur-y cur-root-x cur-root-y) handler
(when (or (eql to-log :all) (member :enter-leave to-log))
(log:info "win:~A p:~A p:~A[~A]" win pointer
(list cur-x cur-y) (list cur-root-x cur-root-y)))))
(defmethod handle-leave-event ((handler log-event-handler) pointer
win timestamp)
(with-slots (to-log cur-x cur-y cur-root-x cur-root-y) handler
(when (or (eql to-log :all) (member :enter-leave to-log))
(log:info "win:~A p:~A p:~A[~A]" win pointer
(list cur-x cur-y) (list cur-root-x cur-root-y)))))
(defmethod handle-configure-event ((handler log-event-handler) win x y w h
timestamp)
(with-slots (to-log) handler
(when (or (eql to-log :all) (member :configure to-log))
(log:info "win:~A x:~A y:~A w:~A h:~A" win x y w h))))
(defmethod handle-repaint-event ((handler log-event-handler) win x y w h
timestamp)
(with-slots (to-log) handler
(when (or (eql to-log :all) (member :repaint to-log))
(log:info "win:~A x:~A y:~A w:~A h:~A" win x y w h))))
(defmethod handle-wm-delete-event ((handler log-event-handler) win timestamp)
(with-slots (to-log) handler
(when (or (eql to-log :all) (member :delete to-log))
(log:info "win:~A" win))))
(setf *default-event-handler* (make-instance 'event-handler))
(defmacro <e- (kernel fn &rest args)
`(within-user-mode (,kernel :block-p nil)
(funcall ,fn (event-handler ,kernel) ,@args)))
(defmethod driver-cb-window-configuration-event ((handler event-handler) kernel win x y width height time)
(check-kernel-mode)
(<e- kernel #'handle-configure-event win x y width height time))
(defmethod driver-cb-repaint-event ((handler event-handler) kernel win x y width height time)
(check-kernel-mode)
(<e- kernel #'handle-repaint-event win x y width height time))
(defmethod driver-cb-scroll-event ((handler event-handler) kernel pointer dx dy win timestamp)
(check-kernel-mode)
(<e- kernel #'handle-scroll-event pointer dx dy win timestamp))
(defmethod driver-cb-button-event ((handler event-handler) kernel kind pointer button win timestamp)
(check-kernel-mode)
(<e- kernel #'handle-button-event kind pointer button win timestamp))
(defmethod driver-cb-motion-event ((handler event-handler) kernel pointer x y root-x root-y
win timestamp)
(check-kernel-mode)
(<e- kernel #'handle-motion-event pointer x y root-x root-y
win timestamp))
(defmethod driver-cb-key-event ((handler event-handler) kernel kind keyname character modifiers
win timestamp)
(check-kernel-mode)
(<e- kernel #'handle-key-event kind keyname character modifiers
win timestamp))
(defmethod driver-cb-enter-event ((handler event-handler) kernel pointer x y root-x root-y win time)
(check-kernel-mode)
(<e- kernel #'handle-enter-event pointer x y root-x root-y win time))
(defmethod driver-cb-leave-event ((handler event-handler) kernel pointer win time)
(check-kernel-mode)
(<e- kernel #'handle-leave-event pointer win time))
(defmethod driver-cb-wm-delete-event ((handler event-handler) kernel win time)
(check-kernel-mode)
(<e- kernel #'handle-wm-delete-event win time))
|
0270805fbdf73c26103b8b7bd886cea71e41f350992a948437a5c61817ca7171 | cram2/cram | ode.lisp | Regression test ODE for GSLL , automatically generated
;;
Copyright 2009
Distributed under the terms of the GNU General Public License
;;
;; This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation , either version 3 of the License , or
;; (at your option) any later version.
;;
;; This program is distributed in the hope that it will be useful,
;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
;; GNU General Public License for more details.
;;
You should have received a copy of the GNU General Public License
;; along with this program. If not, see </>.
(in-package :gsl)
(LISP-UNIT:DEFINE-TEST ODE
(LISP-UNIT::ASSERT-NUMERICAL-EQUAL
(LIST 495 1.0d0 -1.4568657425802234d0 -11.547345633897558d0)
(MULTIPLE-VALUE-LIST (INTEGRATE-VANDERPOL 1.0d0 1.d-4 +STEP-RK2+ NIL)))
(LISP-UNIT::ASSERT-NUMERICAL-EQUAL
(LIST 40 1.0d0 -1.4568569264026898d0 -11.547449151779395d0)
(MULTIPLE-VALUE-LIST (INTEGRATE-VANDERPOL 1.0d0 1.d-4 +STEP-RK4+ NIL)))
(LISP-UNIT::ASSERT-NUMERICAL-EQUAL
(LIST 35 1.0d0 -1.456874342553472d0 -11.547250693698407d0)
(MULTIPLE-VALUE-LIST
(INTEGRATE-VANDERPOL 1.0d0 1.d-4 +STEP-RKF45+ NIL)))
(LISP-UNIT::ASSERT-NUMERICAL-EQUAL
(LIST 27 1.0d0 -1.4568588825970334d0 -11.547432342449643d0)
(MULTIPLE-VALUE-LIST
(INTEGRATE-VANDERPOL 1.0d0 1.d-4 +STEP-RKCK+ NIL)))
(LISP-UNIT::ASSERT-NUMERICAL-EQUAL
(LIST 16 1.0d0 -1.4568622636249005d0 -11.547385179410822d0)
(MULTIPLE-VALUE-LIST
(INTEGRATE-VANDERPOL 1.0d0 1.d-4 +STEP-RK8PD+ NIL)))
(LISP-UNIT::ASSERT-NUMERICAL-EQUAL
(LIST 359 1.0d0 -1.4569507371916566d0 -11.546406519788615d0)
(MULTIPLE-VALUE-LIST
(INTEGRATE-VANDERPOL 1.0d0 1.d-4 +STEP-RK2IMP+ NIL)))
(LISP-UNIT::ASSERT-NUMERICAL-EQUAL
(LIST 40 1.0d0 -1.4568644436344684d0 -11.547361181933427d0)
(MULTIPLE-VALUE-LIST
(INTEGRATE-VANDERPOL 1.0d0 1.d-4 +STEP-RK4IMP+ NIL)))
(LISP-UNIT::ASSERT-NUMERICAL-EQUAL
(LIST 9 1.0d0 -1.4568620806209944d0 -11.547387321938151d0)
(MULTIPLE-VALUE-LIST
(INTEGRATE-VANDERPOL 1.0d0 1.d-4 +STEP-BSIMP+ NIL)))
(LISP-UNIT::ASSERT-NUMERICAL-EQUAL
(LIST 11176 1.0d0 -1.459959741392502d0 -11.510866371379606d0)
(MULTIPLE-VALUE-LIST
(LET ((*MAX-ITER* 12000))
(INTEGRATE-VANDERPOL 1.0d0 1.d-4 +STEP-GEAR1+ NIL))))
(LISP-UNIT::ASSERT-NUMERICAL-EQUAL
(LIST 52 1.0d0 -1.4568645170220367d0 -11.54736019525012d0)
(MULTIPLE-VALUE-LIST
(INTEGRATE-VANDERPOL 1.0d0 1.d-4 +STEP-GEAR2+ NIL))))
| null | https://raw.githubusercontent.com/cram2/cram/dcb73031ee944d04215bbff9e98b9e8c210ef6c5/cram_3rdparty/gsll/src/tests/ode.lisp | lisp |
This program is free software: you can redistribute it and/or modify
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
along with this program. If not, see </>. | Regression test ODE for GSLL , automatically generated
Copyright 2009
Distributed under the terms of the GNU General Public License
it under the terms of the GNU General Public License as published by
the Free Software Foundation , either version 3 of the License , or
You should have received a copy of the GNU General Public License
(in-package :gsl)
(LISP-UNIT:DEFINE-TEST ODE
(LISP-UNIT::ASSERT-NUMERICAL-EQUAL
(LIST 495 1.0d0 -1.4568657425802234d0 -11.547345633897558d0)
(MULTIPLE-VALUE-LIST (INTEGRATE-VANDERPOL 1.0d0 1.d-4 +STEP-RK2+ NIL)))
(LISP-UNIT::ASSERT-NUMERICAL-EQUAL
(LIST 40 1.0d0 -1.4568569264026898d0 -11.547449151779395d0)
(MULTIPLE-VALUE-LIST (INTEGRATE-VANDERPOL 1.0d0 1.d-4 +STEP-RK4+ NIL)))
(LISP-UNIT::ASSERT-NUMERICAL-EQUAL
(LIST 35 1.0d0 -1.456874342553472d0 -11.547250693698407d0)
(MULTIPLE-VALUE-LIST
(INTEGRATE-VANDERPOL 1.0d0 1.d-4 +STEP-RKF45+ NIL)))
(LISP-UNIT::ASSERT-NUMERICAL-EQUAL
(LIST 27 1.0d0 -1.4568588825970334d0 -11.547432342449643d0)
(MULTIPLE-VALUE-LIST
(INTEGRATE-VANDERPOL 1.0d0 1.d-4 +STEP-RKCK+ NIL)))
(LISP-UNIT::ASSERT-NUMERICAL-EQUAL
(LIST 16 1.0d0 -1.4568622636249005d0 -11.547385179410822d0)
(MULTIPLE-VALUE-LIST
(INTEGRATE-VANDERPOL 1.0d0 1.d-4 +STEP-RK8PD+ NIL)))
(LISP-UNIT::ASSERT-NUMERICAL-EQUAL
(LIST 359 1.0d0 -1.4569507371916566d0 -11.546406519788615d0)
(MULTIPLE-VALUE-LIST
(INTEGRATE-VANDERPOL 1.0d0 1.d-4 +STEP-RK2IMP+ NIL)))
(LISP-UNIT::ASSERT-NUMERICAL-EQUAL
(LIST 40 1.0d0 -1.4568644436344684d0 -11.547361181933427d0)
(MULTIPLE-VALUE-LIST
(INTEGRATE-VANDERPOL 1.0d0 1.d-4 +STEP-RK4IMP+ NIL)))
(LISP-UNIT::ASSERT-NUMERICAL-EQUAL
(LIST 9 1.0d0 -1.4568620806209944d0 -11.547387321938151d0)
(MULTIPLE-VALUE-LIST
(INTEGRATE-VANDERPOL 1.0d0 1.d-4 +STEP-BSIMP+ NIL)))
(LISP-UNIT::ASSERT-NUMERICAL-EQUAL
(LIST 11176 1.0d0 -1.459959741392502d0 -11.510866371379606d0)
(MULTIPLE-VALUE-LIST
(LET ((*MAX-ITER* 12000))
(INTEGRATE-VANDERPOL 1.0d0 1.d-4 +STEP-GEAR1+ NIL))))
(LISP-UNIT::ASSERT-NUMERICAL-EQUAL
(LIST 52 1.0d0 -1.4568645170220367d0 -11.54736019525012d0)
(MULTIPLE-VALUE-LIST
(INTEGRATE-VANDERPOL 1.0d0 1.d-4 +STEP-GEAR2+ NIL))))
|
566bb5dc9141fa24d31234e348f6e2822893eb3df7bf2649a1bb1ba3d0744fa1 | ocaml/ocaml | warning16.ml | (* TEST
* expect
*)
let foo ?x = ()
[%%expect{|
Line 1, characters 9-10:
1 | let foo ?x = ()
^
Warning 16 [unerasable-optional-argument]: this optional argument cannot be erased.
val foo : ?x:'a -> unit = <fun>
|}]
let foo ?x ~y = ()
[%%expect{|
Line 1, characters 9-10:
1 | let foo ?x ~y = ()
^
Warning 16 [unerasable-optional-argument]: this optional argument cannot be erased.
val foo : ?x:'a -> y:'b -> unit = <fun>
|}]
let foo ?x () = ()
[%%expect{|
val foo : ?x:'a -> unit -> unit = <fun>
|}]
let foo ?x ~y () = ()
[%%expect{|
val foo : ?x:'a -> y:'b -> unit -> unit = <fun>
|}]
class bar ?x = object end
[%%expect{|
Line 1, characters 11-12:
1 | class bar ?x = object end
^
Warning 16 [unerasable-optional-argument]: this optional argument cannot be erased.
class bar : ?x:'a -> object end
|}]
class bar ?x ~y = object end
[%%expect{|
Line 1, characters 11-12:
1 | class bar ?x ~y = object end
^
Warning 16 [unerasable-optional-argument]: this optional argument cannot be erased.
class bar : ?x:'a -> y:'b -> object end
|}]
class bar ?x () = object end
[%%expect{|
class bar : ?x:'a -> unit -> object end
|}]
class foo ?x ~y () = object end
[%%expect{|
class foo : ?x:'a -> y:'b -> unit -> object end
|}]
| null | https://raw.githubusercontent.com/ocaml/ocaml/d71ea3d089ae3c338b8b6e2fb7beb08908076c7a/testsuite/tests/typing-warnings/warning16.ml | ocaml | TEST
* expect
| let foo ?x = ()
[%%expect{|
Line 1, characters 9-10:
1 | let foo ?x = ()
^
Warning 16 [unerasable-optional-argument]: this optional argument cannot be erased.
val foo : ?x:'a -> unit = <fun>
|}]
let foo ?x ~y = ()
[%%expect{|
Line 1, characters 9-10:
1 | let foo ?x ~y = ()
^
Warning 16 [unerasable-optional-argument]: this optional argument cannot be erased.
val foo : ?x:'a -> y:'b -> unit = <fun>
|}]
let foo ?x () = ()
[%%expect{|
val foo : ?x:'a -> unit -> unit = <fun>
|}]
let foo ?x ~y () = ()
[%%expect{|
val foo : ?x:'a -> y:'b -> unit -> unit = <fun>
|}]
class bar ?x = object end
[%%expect{|
Line 1, characters 11-12:
1 | class bar ?x = object end
^
Warning 16 [unerasable-optional-argument]: this optional argument cannot be erased.
class bar : ?x:'a -> object end
|}]
class bar ?x ~y = object end
[%%expect{|
Line 1, characters 11-12:
1 | class bar ?x ~y = object end
^
Warning 16 [unerasable-optional-argument]: this optional argument cannot be erased.
class bar : ?x:'a -> y:'b -> object end
|}]
class bar ?x () = object end
[%%expect{|
class bar : ?x:'a -> unit -> object end
|}]
class foo ?x ~y () = object end
[%%expect{|
class foo : ?x:'a -> y:'b -> unit -> object end
|}]
|
161434a00f2a7c4ebd3c5e11022ad18b2ca98dbef54e757eca5387fda3bae6f8 | ChicagoBoss/ChicagoBoss | boss_env.erl | %%-------------------------------------------------------------------
@author
ChicagoBoss Team and contributors , see file in root directory
%% @end
This file is part of ChicagoBoss project .
See file in root directory
%% for license information, see LICENSE file in root directory
%% @end
%% @doc
%%-------------------------------------------------------------------
-module(boss_env).
-export([boss_env/0, setup_boss_env/0, get_env/2, get_env/3]).
-export([master_node/0, is_master_node/0, is_developing_app/1]).
-export([router_adapter/0, cache_adapter/0, session_adapter/0, mq_adapter/0]).
-spec boss_env() -> any().
boss_env() ->
case get(boss_environment) of
undefined -> setup_boss_env();
Val -> Val
end.
-spec setup_boss_env() -> types:execution_mode().
setup_boss_env() ->
case boss_load:module_is_loaded(reloader) of
true -> put(boss_environment, development), development;
false -> put(boss_environment, production), production
end.
-spec get_env(atom(),atom(),any()) -> any().
get_env(App, Key, Default) when is_atom(App), is_atom(Key) ->
case application:get_env(App, Key) of
{ok, Val} -> Val;
_ -> Default
end.
-spec get_env(atom(), any()) -> any().
get_env(Key, Default) when is_atom(Key) ->
get_env(boss, Key, Default).
-spec master_node() -> any().
master_node() ->
case boss_env:get_env(master_node, erlang:node()) of
MasterNode when is_list(MasterNode) ->
list_to_atom(MasterNode);
MasterNode -> MasterNode
end.
-spec is_master_node() -> boolean().
is_master_node() ->
master_node() =:= erlang:node().
-spec is_developing_app(types:application()) -> boolean().
is_developing_app(AppName) ->
BossEnv = boss_env:boss_env(),
DevelopingApp = boss_env:get_env(developing_app, undefined),
AppName =:= DevelopingApp andalso BossEnv =:= development.
-spec router_adapter() -> atom().
router_adapter() ->
get_env(router_adapter, boss_router).
-spec cache_adapter() -> atom().
cache_adapter() ->
get_env(cache_adapter, memcached_bin).
-spec session_adapter() -> atom().
session_adapter() ->
get_env(session_adapter, mock).
-spec mq_adapter() -> atom().
mq_adapter() ->
get_env(mq_adapter, tinymq).
| null | https://raw.githubusercontent.com/ChicagoBoss/ChicagoBoss/113bac70c2f835c1e99c757170fd38abf09f5da2/src/boss/boss_env.erl | erlang | -------------------------------------------------------------------
@end
for license information, see LICENSE file in root directory
@end
@doc
------------------------------------------------------------------- | @author
ChicagoBoss Team and contributors , see file in root directory
This file is part of ChicagoBoss project .
See file in root directory
-module(boss_env).
-export([boss_env/0, setup_boss_env/0, get_env/2, get_env/3]).
-export([master_node/0, is_master_node/0, is_developing_app/1]).
-export([router_adapter/0, cache_adapter/0, session_adapter/0, mq_adapter/0]).
-spec boss_env() -> any().
boss_env() ->
case get(boss_environment) of
undefined -> setup_boss_env();
Val -> Val
end.
-spec setup_boss_env() -> types:execution_mode().
setup_boss_env() ->
case boss_load:module_is_loaded(reloader) of
true -> put(boss_environment, development), development;
false -> put(boss_environment, production), production
end.
-spec get_env(atom(),atom(),any()) -> any().
get_env(App, Key, Default) when is_atom(App), is_atom(Key) ->
case application:get_env(App, Key) of
{ok, Val} -> Val;
_ -> Default
end.
-spec get_env(atom(), any()) -> any().
get_env(Key, Default) when is_atom(Key) ->
get_env(boss, Key, Default).
-spec master_node() -> any().
master_node() ->
case boss_env:get_env(master_node, erlang:node()) of
MasterNode when is_list(MasterNode) ->
list_to_atom(MasterNode);
MasterNode -> MasterNode
end.
-spec is_master_node() -> boolean().
is_master_node() ->
master_node() =:= erlang:node().
-spec is_developing_app(types:application()) -> boolean().
is_developing_app(AppName) ->
BossEnv = boss_env:boss_env(),
DevelopingApp = boss_env:get_env(developing_app, undefined),
AppName =:= DevelopingApp andalso BossEnv =:= development.
-spec router_adapter() -> atom().
router_adapter() ->
get_env(router_adapter, boss_router).
-spec cache_adapter() -> atom().
cache_adapter() ->
get_env(cache_adapter, memcached_bin).
-spec session_adapter() -> atom().
session_adapter() ->
get_env(session_adapter, mock).
-spec mq_adapter() -> atom().
mq_adapter() ->
get_env(mq_adapter, tinymq).
|
368c58821a6a4108e23a44aa634301a5e3f081d89102331102cb9f06454a6829 | lemonidas/Alan-Compiler | AlanString.ml | open Error
explode - implode functions
let explode s =
let rec expl i l =
if i < 0 then l else
expl (i - 1) (s.[i] :: l) in
expl (String.length s - 1) []
let implode l =
let result = String.create (List.length l) in
let rec imp i = function
| [] -> result
| c :: l -> result.[i] <- c; imp (i + 1) l in
imp 0 l
(* Functions for parsing hex characters *)
let is_hex ch =
((ch >= '0' && ch <= '9') ||
(ch >= 'a' && ch <= 'f') ||
(ch >= 'A' && ch <= 'Z'))
let get_hex_value x =
if (x>='0' && x<='9')
then Char.code x - Char.code '0'
else if (x>='A' && x <= 'F')
then Char.code x - Char.code 'A' + 10
else Char.code x - Char.code 'a' + 10
let parse_hex str =
let h1 = get_hex_value str.[2] in
let h2 = get_hex_value str.[3] in
Char.chr (h1*16+h2)
(* Takes a string and returns it without escape characters *)
let de_escape str =
let length = String.length str in
let rec loop i acc=
if (i < length)
then (
match str.[i] with
|'\\' -> (
match str.[i+1] with
|'n' -> loop (i+2) ('\n'::acc)
|'r' -> loop (i+2) ('\r'::acc)
|'t' -> loop (i+2) ('\t'::acc)
|'0' -> loop (i+2) ((Char.chr 0)::acc)
|'\'' -> loop (i+2) ('\''::acc)
|'"' -> loop (i+2) ('"'::acc)
|'x' ->
if ((is_hex str.[i+2]) && (is_hex str.[i+3]))
then
let h1 = get_hex_value str.[i+2] in
let h2 = get_hex_value str.[i+3] in
loop (i+4) ((Char.chr (h1*16+h2))::acc)
else (
error "Invalid escape sequence";
loop (i+5) acc
)
|_ -> error "Invalid escape sequence";
loop (i+2) acc
)
|_ -> loop (i+1) (str.[i]::acc)
)
else implode (List.rev acc)
in loop 0 []
(* Handle escape sequences for Final Code Creation *)
let handle_escapes str =
let char_list = explode str in
let base = List.rev (explode "\tdb '") in
let rec delete_empty_strings char_list acc =
match char_list with
| [] -> implode acc
| ('\n'::'\''::'\''::' '::'b'::'d'::'\t'::t) ->
delete_empty_strings t acc
| (h::t) ->
delete_empty_strings t (h::acc) in
let rec parse_char_list acc lst =
match lst with
| [] ->
let tail_lst = List.rev (explode "'\n\tdb 0\n") in
delete_empty_strings (tail_lst@acc) []
| ('\\'::'t'::t) ->
let to_add = List.rev (explode "'\n\tdb 9\n\tdb '") in
parse_char_list (to_add @ acc) t
| ('\\'::'n'::t) ->
let to_add = List.rev (explode "'\n\tdb 10\n\tdb '") in
parse_char_list (to_add @ acc) t
| ('\\'::'r'::t) ->
let to_add = List.rev (explode "'\n\tdb 13\n\tdb '") in
parse_char_list (to_add @ acc) t
| ('\\'::'0'::t) ->
let to_add = List.rev (explode "'\n\tdb 0\n\tdb '") in
parse_char_list (to_add @ acc) t
| ('\\'::'\\'::t) ->
let to_add = List.rev (explode "'\n\tdb \\\n\tdb '") in
parse_char_list (to_add @ acc) t
| ('\\'::'\''::t) ->
let to_add = List.rev (explode "'\n\tdb 39\n\tdb '") in
parse_char_list (to_add @ acc) t
| ('\\'::'"'::t) ->
let to_add = List.rev (explode "'\n\tdb 34\n\tdb '") in
parse_char_list (to_add @ acc) t
| ('\\'::'x'::n1::n2::t) ->
let code = (get_hex_value n1 * 16 + get_hex_value n2) in
let to_add_str = Printf.sprintf "'\n\tdb %d\n\tdb '" code in
let to_add = List.rev (explode to_add_str) in
parse_char_list (to_add @ acc) t
| (h::t) ->
parse_char_list (h::acc) t in
parse_char_list base char_list
| null | https://raw.githubusercontent.com/lemonidas/Alan-Compiler/bbedcbf91028d45a2e26839790df2a1347e8bc52/AlanString.ml | ocaml | Functions for parsing hex characters
Takes a string and returns it without escape characters
Handle escape sequences for Final Code Creation | open Error
explode - implode functions
let explode s =
let rec expl i l =
if i < 0 then l else
expl (i - 1) (s.[i] :: l) in
expl (String.length s - 1) []
let implode l =
let result = String.create (List.length l) in
let rec imp i = function
| [] -> result
| c :: l -> result.[i] <- c; imp (i + 1) l in
imp 0 l
let is_hex ch =
((ch >= '0' && ch <= '9') ||
(ch >= 'a' && ch <= 'f') ||
(ch >= 'A' && ch <= 'Z'))
let get_hex_value x =
if (x>='0' && x<='9')
then Char.code x - Char.code '0'
else if (x>='A' && x <= 'F')
then Char.code x - Char.code 'A' + 10
else Char.code x - Char.code 'a' + 10
let parse_hex str =
let h1 = get_hex_value str.[2] in
let h2 = get_hex_value str.[3] in
Char.chr (h1*16+h2)
let de_escape str =
let length = String.length str in
let rec loop i acc=
if (i < length)
then (
match str.[i] with
|'\\' -> (
match str.[i+1] with
|'n' -> loop (i+2) ('\n'::acc)
|'r' -> loop (i+2) ('\r'::acc)
|'t' -> loop (i+2) ('\t'::acc)
|'0' -> loop (i+2) ((Char.chr 0)::acc)
|'\'' -> loop (i+2) ('\''::acc)
|'"' -> loop (i+2) ('"'::acc)
|'x' ->
if ((is_hex str.[i+2]) && (is_hex str.[i+3]))
then
let h1 = get_hex_value str.[i+2] in
let h2 = get_hex_value str.[i+3] in
loop (i+4) ((Char.chr (h1*16+h2))::acc)
else (
error "Invalid escape sequence";
loop (i+5) acc
)
|_ -> error "Invalid escape sequence";
loop (i+2) acc
)
|_ -> loop (i+1) (str.[i]::acc)
)
else implode (List.rev acc)
in loop 0 []
let handle_escapes str =
let char_list = explode str in
let base = List.rev (explode "\tdb '") in
let rec delete_empty_strings char_list acc =
match char_list with
| [] -> implode acc
| ('\n'::'\''::'\''::' '::'b'::'d'::'\t'::t) ->
delete_empty_strings t acc
| (h::t) ->
delete_empty_strings t (h::acc) in
let rec parse_char_list acc lst =
match lst with
| [] ->
let tail_lst = List.rev (explode "'\n\tdb 0\n") in
delete_empty_strings (tail_lst@acc) []
| ('\\'::'t'::t) ->
let to_add = List.rev (explode "'\n\tdb 9\n\tdb '") in
parse_char_list (to_add @ acc) t
| ('\\'::'n'::t) ->
let to_add = List.rev (explode "'\n\tdb 10\n\tdb '") in
parse_char_list (to_add @ acc) t
| ('\\'::'r'::t) ->
let to_add = List.rev (explode "'\n\tdb 13\n\tdb '") in
parse_char_list (to_add @ acc) t
| ('\\'::'0'::t) ->
let to_add = List.rev (explode "'\n\tdb 0\n\tdb '") in
parse_char_list (to_add @ acc) t
| ('\\'::'\\'::t) ->
let to_add = List.rev (explode "'\n\tdb \\\n\tdb '") in
parse_char_list (to_add @ acc) t
| ('\\'::'\''::t) ->
let to_add = List.rev (explode "'\n\tdb 39\n\tdb '") in
parse_char_list (to_add @ acc) t
| ('\\'::'"'::t) ->
let to_add = List.rev (explode "'\n\tdb 34\n\tdb '") in
parse_char_list (to_add @ acc) t
| ('\\'::'x'::n1::n2::t) ->
let code = (get_hex_value n1 * 16 + get_hex_value n2) in
let to_add_str = Printf.sprintf "'\n\tdb %d\n\tdb '" code in
let to_add = List.rev (explode to_add_str) in
parse_char_list (to_add @ acc) t
| (h::t) ->
parse_char_list (h::acc) t in
parse_char_list base char_list
|
e8b242ee84e577d2ea2d45f98d1a5f3e5466c0efa77628f0579370f4339cd9ea | abdulapopoola/SICPBook | 3.01.scm | #lang planet neil/sicp
(define (make-accumulator value)
(lambda (new-value)
(begin (set! value (+ value new-value))
value)))
(define A (make-accumulator 5))
(A 10)
(A 10)
(A -20)
(define x (A 0))
| null | https://raw.githubusercontent.com/abdulapopoola/SICPBook/c8a0228ebf66d9c1ddc5ef1fcc1d05d8684f090a/Chapter%203/3.1/3.01.scm | scheme | #lang planet neil/sicp
(define (make-accumulator value)
(lambda (new-value)
(begin (set! value (+ value new-value))
value)))
(define A (make-accumulator 5))
(A 10)
(A 10)
(A -20)
(define x (A 0))
|
|
141284ca46d9f4425d634f0fc8cf3415c732785252f353b2822eb1a471b09d37 | pa-ba/compdata | Matching.hs | {-# LANGUAGE FlexibleContexts #-}
# LANGUAGE GADTs #
# LANGUAGE MultiParamTypeClasses #
--------------------------------------------------------------------------------
-- |
-- Module : Data.Comp.Matching
Copyright : ( c ) 2010 - 2011
-- License : BSD3
Maintainer : < >
-- Stability : experimental
Portability : non - portable ( GHC Extensions )
--
-- This module implements matching of contexts or terms with variables againts terms
--
--------------------------------------------------------------------------------
module Data.Comp.Matching
(
matchCxt,
matchTerm,
module Data.Comp.Variables
) where
import Data.Comp.Equality
import Data.Comp.Term
import Data.Comp.Variables
import Data.Foldable
import Data.Map (Map)
import qualified Data.Map as Map
import Data.Traversable
import Prelude hiding (all, mapM, mapM_)
{-| This is an auxiliary function for implementing 'matchCxt'. It behaves
similarly as 'match' but is oblivious to non-linearity. Therefore, the
substitution that is returned maps holes to non-empty lists of terms
(resp. contexts in general). This substitution is only a matching
substitution if all elements in each list of the substitution's range
are equal. -}
matchCxt' :: (Ord v, EqF f, Functor f, Foldable f)
=> Context f v -> Cxt h f a -> Maybe (Map v [Cxt h f a])
matchCxt' (Hole v) t = Just $ Map.singleton v [t]
matchCxt' (Term s) (Term t) = do
eqs <- eqMod s t
substs <- mapM (uncurry matchCxt') eqs
return $ Map.unionsWith (++) substs
matchCxt' Term {} Hole {} = Nothing
| This function takes a context @c@ as the first argument and tries
to match it against the term @t@ ( or in general a context with holes
in @a@ ) . The context @c@ matches the term @t@ if there is a
/matching substitution/ @s@ that maps holes to terms ( resp . contexts in general )
such that if the holes in the context @c@ are replaced according to
the substitution @s@ , the term @t@ is obtained . Note that the context
@c@ might be non - linear , i.e. has multiple holes that are
equal . According to the above definition this means that holes with
equal holes have to be instantiated by equal terms !
to match it against the term @t@ (or in general a context with holes
in @a@). The context @c@ matches the term @t@ if there is a
/matching substitution/ @s@ that maps holes to terms (resp. contexts in general)
such that if the holes in the context @c@ are replaced according to
the substitution @s@, the term @t@ is obtained. Note that the context
@c@ might be non-linear, i.e. has multiple holes that are
equal. According to the above definition this means that holes with
equal holes have to be instantiated by equal terms! -}
matchCxt :: (Ord v,EqF f, Eq (Cxt h f a), Functor f, Foldable f)
=> Context f v -> Cxt h f a -> Maybe (CxtSubst h a f v)
matchCxt c1 c2 = do
res <- matchCxt' c1 c2
let insts = Map.elems res
mapM_ checkEq insts
return $ Map.map head res
where checkEq [] = Nothing
checkEq (c : cs)
| all (== c) cs = Just ()
| otherwise = Nothing
{-| This function is similar to 'matchCxt' but instead of a context it
matches a term with variables against a context. -}
matchTerm :: (Ord v, EqF f, Eq (Cxt h f a) , Traversable f, HasVars f v)
=> Term f -> Cxt h f a -> Maybe (CxtSubst h a f v)
matchTerm t = matchCxt (varsToHoles t)
| null | https://raw.githubusercontent.com/pa-ba/compdata/5783d0e11129097e045cabba61643114b154e3f2/src/Data/Comp/Matching.hs | haskell | # LANGUAGE FlexibleContexts #
------------------------------------------------------------------------------
|
Module : Data.Comp.Matching
License : BSD3
Stability : experimental
This module implements matching of contexts or terms with variables againts terms
------------------------------------------------------------------------------
| This is an auxiliary function for implementing 'matchCxt'. It behaves
similarly as 'match' but is oblivious to non-linearity. Therefore, the
substitution that is returned maps holes to non-empty lists of terms
(resp. contexts in general). This substitution is only a matching
substitution if all elements in each list of the substitution's range
are equal.
| This function is similar to 'matchCxt' but instead of a context it
matches a term with variables against a context. | # LANGUAGE GADTs #
# LANGUAGE MultiParamTypeClasses #
Copyright : ( c ) 2010 - 2011
Maintainer : < >
Portability : non - portable ( GHC Extensions )
module Data.Comp.Matching
(
matchCxt,
matchTerm,
module Data.Comp.Variables
) where
import Data.Comp.Equality
import Data.Comp.Term
import Data.Comp.Variables
import Data.Foldable
import Data.Map (Map)
import qualified Data.Map as Map
import Data.Traversable
import Prelude hiding (all, mapM, mapM_)
matchCxt' :: (Ord v, EqF f, Functor f, Foldable f)
=> Context f v -> Cxt h f a -> Maybe (Map v [Cxt h f a])
matchCxt' (Hole v) t = Just $ Map.singleton v [t]
matchCxt' (Term s) (Term t) = do
eqs <- eqMod s t
substs <- mapM (uncurry matchCxt') eqs
return $ Map.unionsWith (++) substs
matchCxt' Term {} Hole {} = Nothing
| This function takes a context @c@ as the first argument and tries
to match it against the term @t@ ( or in general a context with holes
in @a@ ) . The context @c@ matches the term @t@ if there is a
/matching substitution/ @s@ that maps holes to terms ( resp . contexts in general )
such that if the holes in the context @c@ are replaced according to
the substitution @s@ , the term @t@ is obtained . Note that the context
@c@ might be non - linear , i.e. has multiple holes that are
equal . According to the above definition this means that holes with
equal holes have to be instantiated by equal terms !
to match it against the term @t@ (or in general a context with holes
in @a@). The context @c@ matches the term @t@ if there is a
/matching substitution/ @s@ that maps holes to terms (resp. contexts in general)
such that if the holes in the context @c@ are replaced according to
the substitution @s@, the term @t@ is obtained. Note that the context
@c@ might be non-linear, i.e. has multiple holes that are
equal. According to the above definition this means that holes with
equal holes have to be instantiated by equal terms! -}
matchCxt :: (Ord v,EqF f, Eq (Cxt h f a), Functor f, Foldable f)
=> Context f v -> Cxt h f a -> Maybe (CxtSubst h a f v)
matchCxt c1 c2 = do
res <- matchCxt' c1 c2
let insts = Map.elems res
mapM_ checkEq insts
return $ Map.map head res
where checkEq [] = Nothing
checkEq (c : cs)
| all (== c) cs = Just ()
| otherwise = Nothing
matchTerm :: (Ord v, EqF f, Eq (Cxt h f a) , Traversable f, HasVars f v)
=> Term f -> Cxt h f a -> Maybe (CxtSubst h a f v)
matchTerm t = matchCxt (varsToHoles t)
|
7683947781357df984f5663faeee8005b8b99c0e7f04f62ff1c1a476731c20d1 | mokus0/polynomial | NumInstance.hs | module Bench.NumInstance where
import Criterion
numInstanceTests :: [Benchmark]
numInstanceTests = []
| null | https://raw.githubusercontent.com/mokus0/polynomial/42fde2c9a72f449eeda4d534acfe64b8e92b5c27/bench/src/Bench/NumInstance.hs | haskell | module Bench.NumInstance where
import Criterion
numInstanceTests :: [Benchmark]
numInstanceTests = []
|
|
4c2fb0c6808a0816f616c5d5857baa731a6372934491989e397b1b9dbb5c674c | ghc/ghc | Types.hs | # LANGUAGE CPP #
# LANGUAGE DerivingStrategies #
# LANGUAGE GeneralizedNewtypeDeriving #
# LANGUAGE NoImplicitPrelude #
# LANGUAGE Trustworthy #
{-# OPTIONS_GHC -Wno-unused-binds #-}
-- XXX -Wno-unused-binds stops us warning about unused constructors,
-- but really we should just remove them if we don't want them
-----------------------------------------------------------------------------
-- |
Module : Foreign . C.Types
Copyright : ( c ) The FFI task force 2001
-- License : BSD-style (see the file libraries/base/LICENSE)
--
Maintainer :
-- Stability : provisional
-- Portability : portable
--
Mapping of C types to corresponding types .
--
-----------------------------------------------------------------------------
#include <ghcplatform.h>
module Foreign.C.Types
( -- * Representations of C types
$ ctypes
* * # platform # Platform differences
-- | This module contains platform specific information about types.
-- __/As such, the types presented on this page reflect the/__
-- __/platform on which the documentation was generated and may/__
-- __/not coincide with the types on your platform./__
-- ** Integral types
-- | These types are represented as @newtype@s of
-- types in "Data.Int" and "Data.Word", and are instances of
' Prelude . Eq ' , ' Prelude . ' , ' Prelude . ' , ' Prelude . Read ' ,
' Prelude . Show ' , ' Prelude . ' , ' Data . Typeable . ' ,
' Storable ' , ' Prelude . Bounded ' , ' Prelude . Real ' , ' Prelude . Integral '
-- and 'Bits'.
CChar(..), CSChar(..), CUChar(..)
, CShort(..), CUShort(..), CInt(..), CUInt(..)
, CLong(..), CULong(..)
, CPtrdiff(..), CSize(..), CWchar(..), CSigAtomic(..)
, CLLong(..), CULLong(..), CBool(..)
, CIntPtr(..), CUIntPtr(..), CIntMax(..), CUIntMax(..)
-- ** Numeric types
-- | These types are represented as @newtype@s of basic
-- foreign types, and are instances of
' Prelude . Eq ' , ' Prelude . ' , ' Prelude . ' , ' Prelude . Read ' ,
' Prelude . Show ' , ' Prelude . ' , ' Data . Typeable . ' and
-- 'Storable'.
, CClock(..), CTime(..), CUSeconds(..), CSUSeconds(..)
extracted from CTime , because we do n't want this comment in
the language reports :
| To convert ' CTime ' to ' Data . Time . UTCTime ' , use the following :
--
-- > \t -> posixSecondsToUTCTime (realToFrac t :: POSIXTime)
--
-- ** Floating types
-- | These types are represented as @newtype@s of
' Prelude . Float ' and ' Prelude . Double ' , and are instances of
' Prelude . Eq ' , ' Prelude . ' , ' Prelude . ' , ' Prelude . Read ' ,
' Prelude . Show ' , ' Prelude . ' , ' Data . Typeable . ' , ' ' ,
' Prelude . Real ' , ' Prelude . Fractional ' , ' Prelude . Floating ' ,
' Prelude . RealFrac ' and ' Prelude . RealFloat ' . That does mean
that ( respectively ` CDouble ` 's ) instances of
' Prelude . Eq ' , ' Prelude . ' , ' Prelude . ' and
' Prelude . Fractional ' are as badly behaved as ` Prelude . Float ` 's
-- (respectively `Prelude.Double`'s).
, CFloat(..), CDouble(..)
XXX GHC does n't support CLDouble yet
, ( .. )
-- See Note [Exporting constructors of marshallable foreign types]
-- in Foreign.Ptr for why the constructors for these newtypes are
-- exported.
-- ** Other types
Instances of : and
, CFile, CFpos, CJmpBuf
) where
import Foreign.Storable
import Data.Bits ( Bits(..), FiniteBits(..) )
import Data.Int ( Int8, Int16, Int32, Int64 )
import Data.Word ( Word8, Word16, Word32, Word64 )
import GHC.Base
import GHC.Float
import GHC.Enum
import GHC.Real
import GHC.Show
import GHC.Read
import GHC.Num
import GHC.Ix
#include "HsBaseConfig.h"
#include "CTypes.h"
-- | Haskell type representing the C @char@ type.
/(The concrete types of " Foreign . C.Types#platform " are platform - specific.)/
INTEGRAL_TYPE(CChar,"char",HTYPE_CHAR)
| Haskell type representing the C @signed char@ type .
/(The concrete types of " Foreign . C.Types#platform " are platform - specific.)/
INTEGRAL_TYPE(CSChar,"signed char",HTYPE_SIGNED_CHAR)
-- | Haskell type representing the C @unsigned char@ type.
/(The concrete types of " Foreign . C.Types#platform " are platform - specific.)/
INTEGRAL_TYPE(CUChar,"unsigned char",HTYPE_UNSIGNED_CHAR)
-- | Haskell type representing the C @short@ type.
/(The concrete types of " Foreign . C.Types#platform " are platform - specific.)/
INTEGRAL_TYPE(CShort,"short",HTYPE_SHORT)
-- | Haskell type representing the C @unsigned short@ type.
/(The concrete types of " Foreign . C.Types#platform " are platform - specific.)/
INTEGRAL_TYPE(CUShort,"unsigned short",HTYPE_UNSIGNED_SHORT)
-- | Haskell type representing the C @int@ type.
/(The concrete types of " Foreign . C.Types#platform " are platform - specific.)/
INTEGRAL_TYPE(CInt,"int",HTYPE_INT)
-- | Haskell type representing the C @unsigned int@ type.
/(The concrete types of " Foreign . C.Types#platform " are platform - specific.)/
INTEGRAL_TYPE(CUInt,"unsigned int",HTYPE_UNSIGNED_INT)
-- | Haskell type representing the C @long@ type.
/(The concrete types of " Foreign . C.Types#platform " are platform - specific.)/
INTEGRAL_TYPE(CLong,"long",HTYPE_LONG)
-- | Haskell type representing the C @unsigned long@ type.
/(The concrete types of " Foreign . C.Types#platform " are platform - specific.)/
INTEGRAL_TYPE(CULong,"unsigned long",HTYPE_UNSIGNED_LONG)
-- | Haskell type representing the C @long long@ type.
/(The concrete types of " Foreign . C.Types#platform " are platform - specific.)/
INTEGRAL_TYPE(CLLong,"long long",HTYPE_LONG_LONG)
| Haskell type representing the C @unsigned long long@ type .
/(The concrete types of " Foreign . C.Types#platform " are platform - specific.)/
INTEGRAL_TYPE(CULLong,"unsigned long long",HTYPE_UNSIGNED_LONG_LONG)
-- | Haskell type representing the C @bool@ type.
/(The concrete types of " Foreign . C.Types#platform " are platform - specific.)/
--
@since 4.10.0.0
INTEGRAL_TYPE(CBool,"bool",HTYPE_BOOL)
-- | Haskell type representing the C @float@ type.
/(The concrete types of " Foreign . C.Types#platform " are platform - specific.)/
FLOATING_TYPE(CFloat,"float",HTYPE_FLOAT)
-- | Haskell type representing the C @double@ type.
/(The concrete types of " Foreign . C.Types#platform " are platform - specific.)/
FLOATING_TYPE(CDouble,"double",HTYPE_DOUBLE)
XXX GHC does n't support CLDouble yet
# RULES
" realToFrac / a->CFloat " realToFrac = \x - > CFloat ( realToFrac x )
" realToFrac / a->CDouble " realToFrac = \x - > CDouble ( realToFrac x )
" realToFrac / CFloat->a " realToFrac = \(CFloat x ) - > realToFrac x
" realToFrac / CDouble->a " realToFrac ) - > realToFrac x
#
"realToFrac/a->CFloat" realToFrac = \x -> CFloat (realToFrac x)
"realToFrac/a->CDouble" realToFrac = \x -> CDouble (realToFrac x)
"realToFrac/CFloat->a" realToFrac = \(CFloat x) -> realToFrac x
"realToFrac/CDouble->a" realToFrac = \(CDouble x) -> realToFrac x
#-}
GHC does n't support CLDouble yet
-- "realToFrac/a->CLDouble" realToFrac = \x -> CLDouble (realToFrac x)
-- "realToFrac/CLDouble->a" realToFrac = \(CLDouble x) -> realToFrac x
| Haskell type representing the C @ptrdiff_t@ type .
/(The concrete types of " Foreign . C.Types#platform " are platform - specific.)/
INTEGRAL_TYPE(CPtrdiff,"ptrdiff_t",HTYPE_PTRDIFF_T)
-- | Haskell type representing the C @size_t@ type.
/(The concrete types of " Foreign . C.Types#platform " are platform - specific.)/
INTEGRAL_TYPE(CSize,"size_t",HTYPE_SIZE_T)
-- | Haskell type representing the C @wchar_t@ type.
/(The concrete types of " Foreign . C.Types#platform " are platform - specific.)/
INTEGRAL_TYPE(CWchar,"wchar_t",HTYPE_WCHAR_T)
#if defined(HTYPE_SIG_ATOMIC_T)
-- | Haskell type representing the C @sig_atomic_t@ type.
/(The concrete types of " Foreign . C.Types#platform " are platform - specific.)/
See Note [ Lack of signals on wasm32 - wasi ] .
INTEGRAL_TYPE(CSigAtomic,"sig_atomic_t",HTYPE_SIG_ATOMIC_T)
#else
newtype CSigAtomic = CSigAtomic Int32
deriving newtype (Read, Show, ARITHMETIC_CLASSES, INTEGRAL_CLASSES, Ix)
#endif
| Haskell type representing the C @clock_t@ type .
/(The concrete types of " Foreign . C.Types#platform " are platform - specific.)/
ARITHMETIC_TYPE(CClock,"clock_t",HTYPE_CLOCK_T)
| Haskell type representing the C @time_t@ type .
/(The concrete types of " Foreign . C.Types#platform " are platform - specific.)/
ARITHMETIC_TYPE(CTime,"time_t",HTYPE_TIME_T)
| Haskell type representing the C @useconds_t@ type .
/(The concrete types of " Foreign . C.Types#platform " are platform - specific.)/
--
@since 4.4.0.0
ARITHMETIC_TYPE(CUSeconds,"useconds_t",HTYPE_USECONDS_T)
-- | Haskell type representing the C @suseconds_t@ type.
/(The concrete types of " Foreign . C.Types#platform " are platform - specific.)/
--
@since 4.4.0.0
ARITHMETIC_TYPE(CSUSeconds,"suseconds_t",HTYPE_SUSECONDS_T)
FIXME : Implement and provide instances for Eq and
-- | Haskell type representing the C @FILE@ type.
/(The concrete types of " Foreign . C.Types#platform " are platform - specific.)/
data CFile = CFile
| Haskell type representing the C @fpos_t@ type .
/(The concrete types of " Foreign . C.Types#platform " are platform - specific.)/
data CFpos = CFpos
-- | Haskell type representing the C @jmp_buf@ type.
/(The concrete types of " Foreign . C.Types#platform " are platform - specific.)/
data CJmpBuf = CJmpBuf
INTEGRAL_TYPE(CIntPtr,"intptr_t",HTYPE_INTPTR_T)
INTEGRAL_TYPE(CUIntPtr,"uintptr_t",HTYPE_UINTPTR_T)
INTEGRAL_TYPE(CIntMax,"intmax_t",HTYPE_INTMAX_T)
INTEGRAL_TYPE(CUIntMax,"uintmax_t",HTYPE_UINTMAX_T)
-- C99 types which are still missing include:
-- wint_t, wctrans_t, wctype_t
$ ctypes
These types are needed to accurately represent C function prototypes ,
in order to access C library interfaces in Haskell . The system
is not required to represent those types exactly as C does , but the
following guarantees are provided concerning a type @CT@
representing a C type @t@ :
* If a C function prototype has @t@ as an argument or result type , the
use of @CT@ in the corresponding position in a foreign declaration
permits the program to access the full range of values encoded
by the C type ; and conversely , any value for @CT@ has a valid
representation in C.
* ' ( ' Prelude.undefined ' : : CT)@ will yield the same value as
@sizeof ( t)@ in C.
* @'alignment ' ( ' Prelude.undefined ' : : CT)@ matches the alignment
constraint enforced by the C implementation for
* The members ' peek ' and ' poke ' of the ' Storable ' class map all values
of @CT@ to the corresponding value of @t@ and vice versa .
* When an instance of ' Prelude . Bounded ' is defined for @CT@ , the values
of ' Prelude.minBound ' and ' Prelude.maxBound ' coincide with @t_MIN@
and @t_MAX@ in C.
* When an instance of ' Prelude . ' or ' Prelude . ' is defined for @CT@ ,
the predicates defined by the type class implement the same relation
as the corresponding predicate in C on
* When an instance of ' Prelude . ' , ' Prelude . Read ' , ' Prelude . Integral ' ,
' Prelude . Fractional ' , ' Prelude . Floating ' , ' Prelude . RealFrac ' , or
' Prelude . RealFloat ' is defined for @CT@ , the arithmetic operations
defined by the type class implement the same function as the
corresponding arithmetic operations ( if available ) in C on
* When an instance of ' Bits ' is defined for @CT@ , the bitwise operation
defined by the type class implement the same function as the
corresponding bitwise operation in C on
These types are needed to accurately represent C function prototypes,
in order to access C library interfaces in Haskell. The Haskell system
is not required to represent those types exactly as C does, but the
following guarantees are provided concerning a Haskell type @CT@
representing a C type @t@:
* If a C function prototype has @t@ as an argument or result type, the
use of @CT@ in the corresponding position in a foreign declaration
permits the Haskell program to access the full range of values encoded
by the C type; and conversely, any Haskell value for @CT@ has a valid
representation in C.
* @'sizeOf' ('Prelude.undefined' :: CT)@ will yield the same value as
@sizeof (t)@ in C.
* @'alignment' ('Prelude.undefined' :: CT)@ matches the alignment
constraint enforced by the C implementation for @t@.
* The members 'peek' and 'poke' of the 'Storable' class map all values
of @CT@ to the corresponding value of @t@ and vice versa.
* When an instance of 'Prelude.Bounded' is defined for @CT@, the values
of 'Prelude.minBound' and 'Prelude.maxBound' coincide with @t_MIN@
and @t_MAX@ in C.
* When an instance of 'Prelude.Eq' or 'Prelude.Ord' is defined for @CT@,
the predicates defined by the type class implement the same relation
as the corresponding predicate in C on @t@.
* When an instance of 'Prelude.Num', 'Prelude.Read', 'Prelude.Integral',
'Prelude.Fractional', 'Prelude.Floating', 'Prelude.RealFrac', or
'Prelude.RealFloat' is defined for @CT@, the arithmetic operations
defined by the type class implement the same function as the
corresponding arithmetic operations (if available) in C on @t@.
* When an instance of 'Bits' is defined for @CT@, the bitwise operation
defined by the type class implement the same function as the
corresponding bitwise operation in C on @t@.
-}
| null | https://raw.githubusercontent.com/ghc/ghc/93f0e3c49cea484bd6e838892ff8702ec51f34c3/libraries/base/Foreign/C/Types.hs | haskell | # OPTIONS_GHC -Wno-unused-binds #
XXX -Wno-unused-binds stops us warning about unused constructors,
but really we should just remove them if we don't want them
---------------------------------------------------------------------------
|
License : BSD-style (see the file libraries/base/LICENSE)
Stability : provisional
Portability : portable
---------------------------------------------------------------------------
* Representations of C types
| This module contains platform specific information about types.
__/As such, the types presented on this page reflect the/__
__/platform on which the documentation was generated and may/__
__/not coincide with the types on your platform./__
** Integral types
| These types are represented as @newtype@s of
types in "Data.Int" and "Data.Word", and are instances of
and 'Bits'.
** Numeric types
| These types are represented as @newtype@s of basic
foreign types, and are instances of
'Storable'.
> \t -> posixSecondsToUTCTime (realToFrac t :: POSIXTime)
** Floating types
| These types are represented as @newtype@s of
(respectively `Prelude.Double`'s).
See Note [Exporting constructors of marshallable foreign types]
in Foreign.Ptr for why the constructors for these newtypes are
exported.
** Other types
| Haskell type representing the C @char@ type.
| Haskell type representing the C @unsigned char@ type.
| Haskell type representing the C @short@ type.
| Haskell type representing the C @unsigned short@ type.
| Haskell type representing the C @int@ type.
| Haskell type representing the C @unsigned int@ type.
| Haskell type representing the C @long@ type.
| Haskell type representing the C @unsigned long@ type.
| Haskell type representing the C @long long@ type.
| Haskell type representing the C @bool@ type.
| Haskell type representing the C @float@ type.
| Haskell type representing the C @double@ type.
"realToFrac/a->CLDouble" realToFrac = \x -> CLDouble (realToFrac x)
"realToFrac/CLDouble->a" realToFrac = \(CLDouble x) -> realToFrac x
| Haskell type representing the C @size_t@ type.
| Haskell type representing the C @wchar_t@ type.
| Haskell type representing the C @sig_atomic_t@ type.
| Haskell type representing the C @suseconds_t@ type.
| Haskell type representing the C @FILE@ type.
| Haskell type representing the C @jmp_buf@ type.
C99 types which are still missing include:
wint_t, wctrans_t, wctype_t | # LANGUAGE CPP #
# LANGUAGE DerivingStrategies #
# LANGUAGE GeneralizedNewtypeDeriving #
# LANGUAGE NoImplicitPrelude #
# LANGUAGE Trustworthy #
Module : Foreign . C.Types
Copyright : ( c ) The FFI task force 2001
Maintainer :
Mapping of C types to corresponding types .
#include <ghcplatform.h>
module Foreign.C.Types
$ ctypes
* * # platform # Platform differences
' Prelude . Eq ' , ' Prelude . ' , ' Prelude . ' , ' Prelude . Read ' ,
' Prelude . Show ' , ' Prelude . ' , ' Data . Typeable . ' ,
' Storable ' , ' Prelude . Bounded ' , ' Prelude . Real ' , ' Prelude . Integral '
CChar(..), CSChar(..), CUChar(..)
, CShort(..), CUShort(..), CInt(..), CUInt(..)
, CLong(..), CULong(..)
, CPtrdiff(..), CSize(..), CWchar(..), CSigAtomic(..)
, CLLong(..), CULLong(..), CBool(..)
, CIntPtr(..), CUIntPtr(..), CIntMax(..), CUIntMax(..)
' Prelude . Eq ' , ' Prelude . ' , ' Prelude . ' , ' Prelude . Read ' ,
' Prelude . Show ' , ' Prelude . ' , ' Data . Typeable . ' and
, CClock(..), CTime(..), CUSeconds(..), CSUSeconds(..)
extracted from CTime , because we do n't want this comment in
the language reports :
| To convert ' CTime ' to ' Data . Time . UTCTime ' , use the following :
' Prelude . Float ' and ' Prelude . Double ' , and are instances of
' Prelude . Eq ' , ' Prelude . ' , ' Prelude . ' , ' Prelude . Read ' ,
' Prelude . Show ' , ' Prelude . ' , ' Data . Typeable . ' , ' ' ,
' Prelude . Real ' , ' Prelude . Fractional ' , ' Prelude . Floating ' ,
' Prelude . RealFrac ' and ' Prelude . RealFloat ' . That does mean
that ( respectively ` CDouble ` 's ) instances of
' Prelude . Eq ' , ' Prelude . ' , ' Prelude . ' and
' Prelude . Fractional ' are as badly behaved as ` Prelude . Float ` 's
, CFloat(..), CDouble(..)
XXX GHC does n't support CLDouble yet
, ( .. )
Instances of : and
, CFile, CFpos, CJmpBuf
) where
import Foreign.Storable
import Data.Bits ( Bits(..), FiniteBits(..) )
import Data.Int ( Int8, Int16, Int32, Int64 )
import Data.Word ( Word8, Word16, Word32, Word64 )
import GHC.Base
import GHC.Float
import GHC.Enum
import GHC.Real
import GHC.Show
import GHC.Read
import GHC.Num
import GHC.Ix
#include "HsBaseConfig.h"
#include "CTypes.h"
/(The concrete types of " Foreign . C.Types#platform " are platform - specific.)/
INTEGRAL_TYPE(CChar,"char",HTYPE_CHAR)
| Haskell type representing the C @signed char@ type .
/(The concrete types of " Foreign . C.Types#platform " are platform - specific.)/
INTEGRAL_TYPE(CSChar,"signed char",HTYPE_SIGNED_CHAR)
/(The concrete types of " Foreign . C.Types#platform " are platform - specific.)/
INTEGRAL_TYPE(CUChar,"unsigned char",HTYPE_UNSIGNED_CHAR)
/(The concrete types of " Foreign . C.Types#platform " are platform - specific.)/
INTEGRAL_TYPE(CShort,"short",HTYPE_SHORT)
/(The concrete types of " Foreign . C.Types#platform " are platform - specific.)/
INTEGRAL_TYPE(CUShort,"unsigned short",HTYPE_UNSIGNED_SHORT)
/(The concrete types of " Foreign . C.Types#platform " are platform - specific.)/
INTEGRAL_TYPE(CInt,"int",HTYPE_INT)
/(The concrete types of " Foreign . C.Types#platform " are platform - specific.)/
INTEGRAL_TYPE(CUInt,"unsigned int",HTYPE_UNSIGNED_INT)
/(The concrete types of " Foreign . C.Types#platform " are platform - specific.)/
INTEGRAL_TYPE(CLong,"long",HTYPE_LONG)
/(The concrete types of " Foreign . C.Types#platform " are platform - specific.)/
INTEGRAL_TYPE(CULong,"unsigned long",HTYPE_UNSIGNED_LONG)
/(The concrete types of " Foreign . C.Types#platform " are platform - specific.)/
INTEGRAL_TYPE(CLLong,"long long",HTYPE_LONG_LONG)
| Haskell type representing the C @unsigned long long@ type .
/(The concrete types of " Foreign . C.Types#platform " are platform - specific.)/
INTEGRAL_TYPE(CULLong,"unsigned long long",HTYPE_UNSIGNED_LONG_LONG)
/(The concrete types of " Foreign . C.Types#platform " are platform - specific.)/
@since 4.10.0.0
INTEGRAL_TYPE(CBool,"bool",HTYPE_BOOL)
/(The concrete types of " Foreign . C.Types#platform " are platform - specific.)/
FLOATING_TYPE(CFloat,"float",HTYPE_FLOAT)
/(The concrete types of " Foreign . C.Types#platform " are platform - specific.)/
FLOATING_TYPE(CDouble,"double",HTYPE_DOUBLE)
XXX GHC does n't support CLDouble yet
# RULES
" realToFrac / a->CFloat " realToFrac = \x - > CFloat ( realToFrac x )
" realToFrac / a->CDouble " realToFrac = \x - > CDouble ( realToFrac x )
" realToFrac / CFloat->a " realToFrac = \(CFloat x ) - > realToFrac x
" realToFrac / CDouble->a " realToFrac ) - > realToFrac x
#
"realToFrac/a->CFloat" realToFrac = \x -> CFloat (realToFrac x)
"realToFrac/a->CDouble" realToFrac = \x -> CDouble (realToFrac x)
"realToFrac/CFloat->a" realToFrac = \(CFloat x) -> realToFrac x
"realToFrac/CDouble->a" realToFrac = \(CDouble x) -> realToFrac x
#-}
GHC does n't support CLDouble yet
| Haskell type representing the C @ptrdiff_t@ type .
/(The concrete types of " Foreign . C.Types#platform " are platform - specific.)/
INTEGRAL_TYPE(CPtrdiff,"ptrdiff_t",HTYPE_PTRDIFF_T)
/(The concrete types of " Foreign . C.Types#platform " are platform - specific.)/
INTEGRAL_TYPE(CSize,"size_t",HTYPE_SIZE_T)
/(The concrete types of " Foreign . C.Types#platform " are platform - specific.)/
INTEGRAL_TYPE(CWchar,"wchar_t",HTYPE_WCHAR_T)
#if defined(HTYPE_SIG_ATOMIC_T)
/(The concrete types of " Foreign . C.Types#platform " are platform - specific.)/
See Note [ Lack of signals on wasm32 - wasi ] .
INTEGRAL_TYPE(CSigAtomic,"sig_atomic_t",HTYPE_SIG_ATOMIC_T)
#else
newtype CSigAtomic = CSigAtomic Int32
deriving newtype (Read, Show, ARITHMETIC_CLASSES, INTEGRAL_CLASSES, Ix)
#endif
| Haskell type representing the C @clock_t@ type .
/(The concrete types of " Foreign . C.Types#platform " are platform - specific.)/
ARITHMETIC_TYPE(CClock,"clock_t",HTYPE_CLOCK_T)
| Haskell type representing the C @time_t@ type .
/(The concrete types of " Foreign . C.Types#platform " are platform - specific.)/
ARITHMETIC_TYPE(CTime,"time_t",HTYPE_TIME_T)
| Haskell type representing the C @useconds_t@ type .
/(The concrete types of " Foreign . C.Types#platform " are platform - specific.)/
@since 4.4.0.0
ARITHMETIC_TYPE(CUSeconds,"useconds_t",HTYPE_USECONDS_T)
/(The concrete types of " Foreign . C.Types#platform " are platform - specific.)/
@since 4.4.0.0
ARITHMETIC_TYPE(CSUSeconds,"suseconds_t",HTYPE_SUSECONDS_T)
FIXME : Implement and provide instances for Eq and
/(The concrete types of " Foreign . C.Types#platform " are platform - specific.)/
data CFile = CFile
| Haskell type representing the C @fpos_t@ type .
/(The concrete types of " Foreign . C.Types#platform " are platform - specific.)/
data CFpos = CFpos
/(The concrete types of " Foreign . C.Types#platform " are platform - specific.)/
data CJmpBuf = CJmpBuf
INTEGRAL_TYPE(CIntPtr,"intptr_t",HTYPE_INTPTR_T)
INTEGRAL_TYPE(CUIntPtr,"uintptr_t",HTYPE_UINTPTR_T)
INTEGRAL_TYPE(CIntMax,"intmax_t",HTYPE_INTMAX_T)
INTEGRAL_TYPE(CUIntMax,"uintmax_t",HTYPE_UINTMAX_T)
$ ctypes
These types are needed to accurately represent C function prototypes ,
in order to access C library interfaces in Haskell . The system
is not required to represent those types exactly as C does , but the
following guarantees are provided concerning a type @CT@
representing a C type @t@ :
* If a C function prototype has @t@ as an argument or result type , the
use of @CT@ in the corresponding position in a foreign declaration
permits the program to access the full range of values encoded
by the C type ; and conversely , any value for @CT@ has a valid
representation in C.
* ' ( ' Prelude.undefined ' : : CT)@ will yield the same value as
@sizeof ( t)@ in C.
* @'alignment ' ( ' Prelude.undefined ' : : CT)@ matches the alignment
constraint enforced by the C implementation for
* The members ' peek ' and ' poke ' of the ' Storable ' class map all values
of @CT@ to the corresponding value of @t@ and vice versa .
* When an instance of ' Prelude . Bounded ' is defined for @CT@ , the values
of ' Prelude.minBound ' and ' Prelude.maxBound ' coincide with @t_MIN@
and @t_MAX@ in C.
* When an instance of ' Prelude . ' or ' Prelude . ' is defined for @CT@ ,
the predicates defined by the type class implement the same relation
as the corresponding predicate in C on
* When an instance of ' Prelude . ' , ' Prelude . Read ' , ' Prelude . Integral ' ,
' Prelude . Fractional ' , ' Prelude . Floating ' , ' Prelude . RealFrac ' , or
' Prelude . RealFloat ' is defined for @CT@ , the arithmetic operations
defined by the type class implement the same function as the
corresponding arithmetic operations ( if available ) in C on
* When an instance of ' Bits ' is defined for @CT@ , the bitwise operation
defined by the type class implement the same function as the
corresponding bitwise operation in C on
These types are needed to accurately represent C function prototypes,
in order to access C library interfaces in Haskell. The Haskell system
is not required to represent those types exactly as C does, but the
following guarantees are provided concerning a Haskell type @CT@
representing a C type @t@:
* If a C function prototype has @t@ as an argument or result type, the
use of @CT@ in the corresponding position in a foreign declaration
permits the Haskell program to access the full range of values encoded
by the C type; and conversely, any Haskell value for @CT@ has a valid
representation in C.
* @'sizeOf' ('Prelude.undefined' :: CT)@ will yield the same value as
@sizeof (t)@ in C.
* @'alignment' ('Prelude.undefined' :: CT)@ matches the alignment
constraint enforced by the C implementation for @t@.
* The members 'peek' and 'poke' of the 'Storable' class map all values
of @CT@ to the corresponding value of @t@ and vice versa.
* When an instance of 'Prelude.Bounded' is defined for @CT@, the values
of 'Prelude.minBound' and 'Prelude.maxBound' coincide with @t_MIN@
and @t_MAX@ in C.
* When an instance of 'Prelude.Eq' or 'Prelude.Ord' is defined for @CT@,
the predicates defined by the type class implement the same relation
as the corresponding predicate in C on @t@.
* When an instance of 'Prelude.Num', 'Prelude.Read', 'Prelude.Integral',
'Prelude.Fractional', 'Prelude.Floating', 'Prelude.RealFrac', or
'Prelude.RealFloat' is defined for @CT@, the arithmetic operations
defined by the type class implement the same function as the
corresponding arithmetic operations (if available) in C on @t@.
* When an instance of 'Bits' is defined for @CT@, the bitwise operation
defined by the type class implement the same function as the
corresponding bitwise operation in C on @t@.
-}
|
91547792d5e9ff62157d874e7b8ad83c0c4033a00dda4d2b1484c5c918cd6119 | bobzhang/ocaml-book | type_equal.ml | open Format
(** functor can only be modules
input is a type-constructor
output is a module type as well
*)
module type Equal = sig
type fst
type snd
module Coerce (S:sig type 'a f end) : sig
val f: fst S.f -> snd S.f
end
end
type ('a,'b)equal = (module Equal with type fst = 'a and type snd = 'b)
module Refl : Equal = struct
type fst
type snd = fst
module Coerce (S:sig type 'a f end) = struct
let f x = x
end
end
(** parameterize over type is fine
parameterize over (type constructor) requires functor
functor, functor also has a signature.
type declaration appears both in
module definition and module type definition
mdoule type declaration appears both in
module defintion and module type definition
we can use functor to calculate types....
It's kinda type-level computation. Fw
*)
let refl (type a) =
(module struct
type fst = a
type snd = a
module Coerce (S:sig type 'a f end) = struct
let f x = x
end
end : Equal with type fst = a and type snd = a)
let a x = x
| null | https://raw.githubusercontent.com/bobzhang/ocaml-book/09a575b0d1fedfce565ecb9a0ae9cf0df37fdc75/code/types/type_equal.ml | ocaml | * functor can only be modules
input is a type-constructor
output is a module type as well
* parameterize over type is fine
parameterize over (type constructor) requires functor
functor, functor also has a signature.
type declaration appears both in
module definition and module type definition
mdoule type declaration appears both in
module defintion and module type definition
we can use functor to calculate types....
It's kinda type-level computation. Fw
| open Format
module type Equal = sig
type fst
type snd
module Coerce (S:sig type 'a f end) : sig
val f: fst S.f -> snd S.f
end
end
type ('a,'b)equal = (module Equal with type fst = 'a and type snd = 'b)
module Refl : Equal = struct
type fst
type snd = fst
module Coerce (S:sig type 'a f end) = struct
let f x = x
end
end
let refl (type a) =
(module struct
type fst = a
type snd = a
module Coerce (S:sig type 'a f end) = struct
let f x = x
end
end : Equal with type fst = a and type snd = a)
let a x = x
|
5302d2f8c1e2842b4a074d2b7eb9ebda71eab86d73a62818fe8ea5406ba4a258 | arichiardi/replumb | load_test.cljs | (ns replumb.load-test
(:require [cljs.test :refer-macros [deftest is]]
[replumb.load :refer [file-paths-for-load-fn file-paths]]))
(deftest paths-without-ext
(is (empty? (file-paths-for-load-fn [] true "temp")) "If empty src-paths and :macros true, file-paths-for-load-fn should return empty vector")
(is (empty? (file-paths-for-load-fn [] false "temp")) "If empty src-paths and :macros false, file-paths-for-load-fn should return empty vector")
(let [src-paths ["src1/foo" "src2/" "src3/foo/bar"]
file "core"
cljs-files (map #(str % (when-not (= "/" (last %)) "/") file ".cljs") src-paths)
cljc-files (map #(str % (when-not (= "/" (last %)) "/") file ".cljc") src-paths)
clj-files (map #(str % (when-not (= "/" (last %)) "/") file ".clj") src-paths)
js-files (map #(str % (when-not (= "/" (last %)) "/") file ".js") src-paths)]
(let [files (into [] (file-paths-for-load-fn src-paths false file))]
(is (= 9 (count files)) "With 3 paths and :macros false, file-paths-for-load-fn should try 9 files")
(is (= cljs-files (subvec files 0 3)) "When :macros false, file-paths-for-load-fn should try .cljs files first")
(is (= cljc-files (subvec files 3 6)) "When :macros false, file-paths-for-load-fn should try .cljc files second")
(is (= js-files (subvec files 6)) "When :macros false, file-paths-for-load-fn should try .js files third"))
(let [files (into [] (file-paths-for-load-fn src-paths true file))]
(is (= 6 (count files)) "With 3 paths and :macros true, file-paths-for-load-fn should try 6 files")
(is (= clj-files (subvec files 0 3)) "When :macros true, file-paths-for-load-fn should try .clj files first")
(is (= cljc-files (subvec files 3)) "When :macros true, file-paths-for-load-fn should try .cljc files second"))))
(deftest paths-with-ext
(is (empty? (file-paths [] "temp.clj")) "If src-paths is empty, file-paths-for-load-fn should return empty vector")
(let [src-paths ["src1/foo" "src2/" "src3/foo/bar"]
file "baz.clj"
expected-path (map #(str % (when-not (= "/" (last %)) "/") file) src-paths)
files (into [] (file-paths src-paths file))]
(is (= expected-path files) "The fn file-paths (remember it does not add extension), should return the expected 3 files")))
| null | https://raw.githubusercontent.com/arichiardi/replumb/dde2228f2e364c3bafdf6585bb1bc1c27a3e336c/test/cljs/replumb/load_test.cljs | clojure | (ns replumb.load-test
(:require [cljs.test :refer-macros [deftest is]]
[replumb.load :refer [file-paths-for-load-fn file-paths]]))
(deftest paths-without-ext
(is (empty? (file-paths-for-load-fn [] true "temp")) "If empty src-paths and :macros true, file-paths-for-load-fn should return empty vector")
(is (empty? (file-paths-for-load-fn [] false "temp")) "If empty src-paths and :macros false, file-paths-for-load-fn should return empty vector")
(let [src-paths ["src1/foo" "src2/" "src3/foo/bar"]
file "core"
cljs-files (map #(str % (when-not (= "/" (last %)) "/") file ".cljs") src-paths)
cljc-files (map #(str % (when-not (= "/" (last %)) "/") file ".cljc") src-paths)
clj-files (map #(str % (when-not (= "/" (last %)) "/") file ".clj") src-paths)
js-files (map #(str % (when-not (= "/" (last %)) "/") file ".js") src-paths)]
(let [files (into [] (file-paths-for-load-fn src-paths false file))]
(is (= 9 (count files)) "With 3 paths and :macros false, file-paths-for-load-fn should try 9 files")
(is (= cljs-files (subvec files 0 3)) "When :macros false, file-paths-for-load-fn should try .cljs files first")
(is (= cljc-files (subvec files 3 6)) "When :macros false, file-paths-for-load-fn should try .cljc files second")
(is (= js-files (subvec files 6)) "When :macros false, file-paths-for-load-fn should try .js files third"))
(let [files (into [] (file-paths-for-load-fn src-paths true file))]
(is (= 6 (count files)) "With 3 paths and :macros true, file-paths-for-load-fn should try 6 files")
(is (= clj-files (subvec files 0 3)) "When :macros true, file-paths-for-load-fn should try .clj files first")
(is (= cljc-files (subvec files 3)) "When :macros true, file-paths-for-load-fn should try .cljc files second"))))
(deftest paths-with-ext
(is (empty? (file-paths [] "temp.clj")) "If src-paths is empty, file-paths-for-load-fn should return empty vector")
(let [src-paths ["src1/foo" "src2/" "src3/foo/bar"]
file "baz.clj"
expected-path (map #(str % (when-not (= "/" (last %)) "/") file) src-paths)
files (into [] (file-paths src-paths file))]
(is (= expected-path files) "The fn file-paths (remember it does not add extension), should return the expected 3 files")))
|
|
56ff3cedf53981d1367e9248c45ded87ff5d8dc602c2b41bee30404897b579a1 | kumarshantanu/calfpath | type.cljc | Copyright ( c ) . All rights reserved .
; The use and distribution terms for this software are covered by the
; Eclipse Public License 1.0 (-1.0.php)
; which can be found in the file LICENSE at the root of this distribution.
; By using this software in any fashion, you are agreeing to be bound by
; the terms of this license.
; You must not remove this notice, or any other, from this software.
(ns calfpath.type
"Type related arifacts.")
(defprotocol IRouteMatcher
(-parse-uri-template [this uri-template])
(-get-static-uri-template [this uri-pattern-tokens] "Return URI token(s) if static URI template, nil otherwise")
(-initialize-request [this request params-key])
(-static-uri-partial-match [this request static-tokens params-key])
(-static-uri-full-match [this request static-tokens params-key])
(-dynamic-uri-partial-match [this request uri-template params-key])
(-dynamic-uri-full-match [this request uri-template params-key]))
| null | https://raw.githubusercontent.com/kumarshantanu/calfpath/e923ad59106661cd66389cf94954b47558799d00/src/calfpath/type.cljc | clojure | The use and distribution terms for this software are covered by the
Eclipse Public License 1.0 (-1.0.php)
which can be found in the file LICENSE at the root of this distribution.
By using this software in any fashion, you are agreeing to be bound by
the terms of this license.
You must not remove this notice, or any other, from this software. | Copyright ( c ) . All rights reserved .
(ns calfpath.type
"Type related arifacts.")
(defprotocol IRouteMatcher
(-parse-uri-template [this uri-template])
(-get-static-uri-template [this uri-pattern-tokens] "Return URI token(s) if static URI template, nil otherwise")
(-initialize-request [this request params-key])
(-static-uri-partial-match [this request static-tokens params-key])
(-static-uri-full-match [this request static-tokens params-key])
(-dynamic-uri-partial-match [this request uri-template params-key])
(-dynamic-uri-full-match [this request uri-template params-key]))
|
70ef1e402e81b6839172747d3b348d67c38b5d8394cb4f27397869aba921d7f6 | clojure-interop/google-cloud-clients | core.clj | (ns com.google.cloud.scheduler.v1beta1.stub.core
(:refer-clojure :only [require comment defn ->])
(:import ))
(require '[com.google.cloud.scheduler.v1beta1.stub.CloudSchedulerStub])
(require '[com.google.cloud.scheduler.v1beta1.stub.CloudSchedulerStubSettings$Builder])
(require '[com.google.cloud.scheduler.v1beta1.stub.CloudSchedulerStubSettings])
(require '[com.google.cloud.scheduler.v1beta1.stub.GrpcCloudSchedulerCallableFactory])
(require '[com.google.cloud.scheduler.v1beta1.stub.GrpcCloudSchedulerStub])
| null | https://raw.githubusercontent.com/clojure-interop/google-cloud-clients/80852d0496057c22f9cdc86d6f9ffc0fa3cd7904/com.google.cloud.scheduler/src/com/google/cloud/scheduler/v1beta1/stub/core.clj | clojure | (ns com.google.cloud.scheduler.v1beta1.stub.core
(:refer-clojure :only [require comment defn ->])
(:import ))
(require '[com.google.cloud.scheduler.v1beta1.stub.CloudSchedulerStub])
(require '[com.google.cloud.scheduler.v1beta1.stub.CloudSchedulerStubSettings$Builder])
(require '[com.google.cloud.scheduler.v1beta1.stub.CloudSchedulerStubSettings])
(require '[com.google.cloud.scheduler.v1beta1.stub.GrpcCloudSchedulerCallableFactory])
(require '[com.google.cloud.scheduler.v1beta1.stub.GrpcCloudSchedulerStub])
|
|
40a729c59e6e7ad6bbee80e53cd155f9532c55bc422a8b29885b2f91d6efe34b | lread/test-doc-blocks | process.clj | (ns ^:no-doc lread.test-doc-blocks.impl.process
(:require [clojure.set :as cset]
[clojure.string :as string]
[lread.test-doc-blocks.impl.amalg-ns :as amalg-ns]
[lread.test-doc-blocks.impl.body-prep :as body-prep]
[lread.test-doc-blocks.impl.inline-ns :as inline-ns]
[lread.test-doc-blocks.impl.test-body :as test-body]))
(defn- throw-with-block-context [action cause {:keys [doc-filename line-no header]}]
(throw (ex-info (format (string/join "\n" ["Unable to %s"
"While processing code block from:"
" file: %s"
" line: %d"
" under header: %s"])
action doc-filename line-no header)
{} cause)))
(defn- reader-wrap-block-text
"Return block with `:block-text` wrapped in reader conditional, if requested."
[{:keys [block-text test-doc-blocks/reader-cond] :as block}]
(if reader-cond
(assoc block :block-text (format "#?(%s\n(do\n%s\n))" reader-cond block-text))
block))
(defn- prep-block-for-conversion-to-test
"Return block with new `:prepped-block-text`"
[block]
(try
(assoc block :prepped-block-text (body-prep/prep-block-for-conversion-to-test (:block-text block)))
(catch Throwable e
(throw-with-block-context "prep block for conversion to test" e block)) ) )
(defn- find-inline-ns-forms
"Return block with a string vector of `:ns-forms` found in `:prepped-block-text`"
[block]
(try
(assoc block :ns-forms (inline-ns/find-forms (:prepped-block-text block)))
(catch Throwable e
(throw-with-block-context "find inline namespace forms" e block))))
(defn- remove-inline-ns-forms
"Return block with `:prepped-block-text` absent of inline ns forms"
[block]
(try
(update block :prepped-block-text inline-ns/remove-forms)
(catch Throwable e
(throw-with-block-context "remove inline namespace forms" e block))))
(defn- create-test-body
"Return block with new `:test-body`"
[block]
(try
(assoc block :test-body (test-body/to-test-body (:prepped-block-text block)))
(catch Throwable e
(throw-with-block-context "create test body" e block))))
(defn- restructure-to-tests
"Return blocks restructured to tests"
[blocks]
(->> blocks
(map #(update % :test-doc-blocks/test-ns str))
(sort-by (juxt :test-doc-blocks/test-ns :test-doc-blocks/platform :doc-filename :line-no))
(group-by (juxt :test-doc-blocks/test-ns :test-doc-blocks/platform))
(map (fn [[[test-ns platform] tests]] {:test-ns test-ns :platform platform :tests tests}))))
(defn- amalg-ns-refs [tests]
{:imports (amalg-ns/amalg-imports (mapcat #(get-in % [:ns-forms :imports]) tests))
:requires (amalg-ns/amalg-requires (mapcat #(get-in % [:ns-forms :requires]) tests))
:refer-clojures (amalg-ns/amalg-refer-clojures (mapcat #(get-in % [:ns-forms :refer-clojures]) tests))})
(defn- amalgamate-ns-refs
"Returns test def `t` with new `:ns-refs-amalg`"
[t]
(try
(assoc t :ns-refs-amalg (amalg-ns-refs (:tests t)))
(catch Throwable e
(throw (ex-info (format "unable to amalgamate inline namespace refs for test namespace %s" (:test-ns t))
{} e)))))
(defn- unwrap-quoted [coll]
(map #(if (and (list? %)
(= 'quote (first %)))
(second %)
%) coll))
(defn- ensure-one-refer-clojures-per-namespace-platform
"Returns `t` if valid, throws if not."
[t]
(let [r (-> t :ns-refs-amalg :refer-clojures)
plat-refs (->> r
(reduce-kv (fn [m platform refs]
(if (= :default platform)
(assoc m platform refs)
(assoc m platform (cset/union (:default r) refs))))
{})
(sort-by key)
for consistent error order reporting : default first
errors (keep (fn [[platform refs]]
(when (> (count refs) 1)
(format "Expected only one unique refer-clojure per target test namespace per platform, but found target-ns %s, platform %s to have %d active occurrences: %s"
(:test-ns t) platform (count refs) (vec refs))))
plat-refs)]
(if (seq errors)
fail fast on first error for now
(throw (ex-info (first errors) {}))
t)))
(defn- summarize-refs [refs]
{:default (->> refs :default vec (sort-by str) vec)
:reader-cond (->> (dissoc refs :default)
(map (fn [[k v]] [k v]))
(sort-by first)
(mapcat (fn [[platform elems]] (concat [platform] [(vec (sort-by str elems))]))))})
(defn- summarize-refer-clojures [refer-clojures]
(-> (reduce-kv (fn [m platform refs]
(let [refs (some->> refs first rest (concat [:refer-clojure]) unwrap-quoted seq)]
(if (= :default platform)
(assoc m :default refs)
(assoc-in m [:reader-cond platform] refs))))
{}
refer-clojures)
(update :reader-cond #(->> (sort-by key %)
(mapcat identity)))))
(defn- massage-ns-refs
"Returns `t` with new `:ns-refs` massaged for easy writing."
[t]
(let [arefs (:ns-refs-amalg t)
ns-refs {:refer-clojures (summarize-refer-clojures (:refer-clojures arefs))
:requires (summarize-refs (:requires arefs))
:imports (summarize-refs (:imports arefs))}]
(assoc t :ns-refs ns-refs)))
(defn convert-to-tests
"Takes parsed input [{block}...] and preps for output to
[{:test-doc-blocks/test-ns ns1
:tests [{block}...]
:ns-refs [[boo.ya :as ya]...]}]"
[parsed]
(->> parsed
(remove :test-doc-blocks/skip)
(map reader-wrap-block-text)
(map prep-block-for-conversion-to-test)
(map find-inline-ns-forms)
(map remove-inline-ns-forms)
(map create-test-body)
restructure-to-tests
(map amalgamate-ns-refs)
(map ensure-one-refer-clojures-per-namespace-platform)
(map massage-ns-refs)))
(comment
(->> (group-by (juxt :a :b) [{:a 1 :b 2 :c 3}
{:a 1 :b 3 :c 4}
{:a 2 :b 1 :c 5}])
(map (fn [[[test-ns platform] tests]] {:test-ns test-ns :platform platform :tests tests})))
(reduce-kv (fn [m k v]
(assoc m k (count v)))
{} {:a #{1 2} :b #{} :c #{}})
)
| null | https://raw.githubusercontent.com/lread/test-doc-blocks/3ec9020c51e3b69408120a11df228e6416c453a9/src/lread/test_doc_blocks/impl/process.clj | clojure | (ns ^:no-doc lread.test-doc-blocks.impl.process
(:require [clojure.set :as cset]
[clojure.string :as string]
[lread.test-doc-blocks.impl.amalg-ns :as amalg-ns]
[lread.test-doc-blocks.impl.body-prep :as body-prep]
[lread.test-doc-blocks.impl.inline-ns :as inline-ns]
[lread.test-doc-blocks.impl.test-body :as test-body]))
(defn- throw-with-block-context [action cause {:keys [doc-filename line-no header]}]
(throw (ex-info (format (string/join "\n" ["Unable to %s"
"While processing code block from:"
" file: %s"
" line: %d"
" under header: %s"])
action doc-filename line-no header)
{} cause)))
(defn- reader-wrap-block-text
"Return block with `:block-text` wrapped in reader conditional, if requested."
[{:keys [block-text test-doc-blocks/reader-cond] :as block}]
(if reader-cond
(assoc block :block-text (format "#?(%s\n(do\n%s\n))" reader-cond block-text))
block))
(defn- prep-block-for-conversion-to-test
"Return block with new `:prepped-block-text`"
[block]
(try
(assoc block :prepped-block-text (body-prep/prep-block-for-conversion-to-test (:block-text block)))
(catch Throwable e
(throw-with-block-context "prep block for conversion to test" e block)) ) )
(defn- find-inline-ns-forms
"Return block with a string vector of `:ns-forms` found in `:prepped-block-text`"
[block]
(try
(assoc block :ns-forms (inline-ns/find-forms (:prepped-block-text block)))
(catch Throwable e
(throw-with-block-context "find inline namespace forms" e block))))
(defn- remove-inline-ns-forms
"Return block with `:prepped-block-text` absent of inline ns forms"
[block]
(try
(update block :prepped-block-text inline-ns/remove-forms)
(catch Throwable e
(throw-with-block-context "remove inline namespace forms" e block))))
(defn- create-test-body
"Return block with new `:test-body`"
[block]
(try
(assoc block :test-body (test-body/to-test-body (:prepped-block-text block)))
(catch Throwable e
(throw-with-block-context "create test body" e block))))
(defn- restructure-to-tests
"Return blocks restructured to tests"
[blocks]
(->> blocks
(map #(update % :test-doc-blocks/test-ns str))
(sort-by (juxt :test-doc-blocks/test-ns :test-doc-blocks/platform :doc-filename :line-no))
(group-by (juxt :test-doc-blocks/test-ns :test-doc-blocks/platform))
(map (fn [[[test-ns platform] tests]] {:test-ns test-ns :platform platform :tests tests}))))
(defn- amalg-ns-refs [tests]
{:imports (amalg-ns/amalg-imports (mapcat #(get-in % [:ns-forms :imports]) tests))
:requires (amalg-ns/amalg-requires (mapcat #(get-in % [:ns-forms :requires]) tests))
:refer-clojures (amalg-ns/amalg-refer-clojures (mapcat #(get-in % [:ns-forms :refer-clojures]) tests))})
(defn- amalgamate-ns-refs
"Returns test def `t` with new `:ns-refs-amalg`"
[t]
(try
(assoc t :ns-refs-amalg (amalg-ns-refs (:tests t)))
(catch Throwable e
(throw (ex-info (format "unable to amalgamate inline namespace refs for test namespace %s" (:test-ns t))
{} e)))))
(defn- unwrap-quoted [coll]
(map #(if (and (list? %)
(= 'quote (first %)))
(second %)
%) coll))
(defn- ensure-one-refer-clojures-per-namespace-platform
"Returns `t` if valid, throws if not."
[t]
(let [r (-> t :ns-refs-amalg :refer-clojures)
plat-refs (->> r
(reduce-kv (fn [m platform refs]
(if (= :default platform)
(assoc m platform refs)
(assoc m platform (cset/union (:default r) refs))))
{})
(sort-by key)
for consistent error order reporting : default first
errors (keep (fn [[platform refs]]
(when (> (count refs) 1)
(format "Expected only one unique refer-clojure per target test namespace per platform, but found target-ns %s, platform %s to have %d active occurrences: %s"
(:test-ns t) platform (count refs) (vec refs))))
plat-refs)]
(if (seq errors)
fail fast on first error for now
(throw (ex-info (first errors) {}))
t)))
(defn- summarize-refs [refs]
{:default (->> refs :default vec (sort-by str) vec)
:reader-cond (->> (dissoc refs :default)
(map (fn [[k v]] [k v]))
(sort-by first)
(mapcat (fn [[platform elems]] (concat [platform] [(vec (sort-by str elems))]))))})
(defn- summarize-refer-clojures [refer-clojures]
(-> (reduce-kv (fn [m platform refs]
(let [refs (some->> refs first rest (concat [:refer-clojure]) unwrap-quoted seq)]
(if (= :default platform)
(assoc m :default refs)
(assoc-in m [:reader-cond platform] refs))))
{}
refer-clojures)
(update :reader-cond #(->> (sort-by key %)
(mapcat identity)))))
(defn- massage-ns-refs
"Returns `t` with new `:ns-refs` massaged for easy writing."
[t]
(let [arefs (:ns-refs-amalg t)
ns-refs {:refer-clojures (summarize-refer-clojures (:refer-clojures arefs))
:requires (summarize-refs (:requires arefs))
:imports (summarize-refs (:imports arefs))}]
(assoc t :ns-refs ns-refs)))
(defn convert-to-tests
"Takes parsed input [{block}...] and preps for output to
[{:test-doc-blocks/test-ns ns1
:tests [{block}...]
:ns-refs [[boo.ya :as ya]...]}]"
[parsed]
(->> parsed
(remove :test-doc-blocks/skip)
(map reader-wrap-block-text)
(map prep-block-for-conversion-to-test)
(map find-inline-ns-forms)
(map remove-inline-ns-forms)
(map create-test-body)
restructure-to-tests
(map amalgamate-ns-refs)
(map ensure-one-refer-clojures-per-namespace-platform)
(map massage-ns-refs)))
(comment
(->> (group-by (juxt :a :b) [{:a 1 :b 2 :c 3}
{:a 1 :b 3 :c 4}
{:a 2 :b 1 :c 5}])
(map (fn [[[test-ns platform] tests]] {:test-ns test-ns :platform platform :tests tests})))
(reduce-kv (fn [m k v]
(assoc m k (count v)))
{} {:a #{1 2} :b #{} :c #{}})
)
|
|
41f5897a57aba705af917c899b80da588f30ba132c0fadb5436ce5fb86d0234a | appleshan/cl-http | test.lisp | -*- Mode : lisp ; Syntax : ansi - common - lisp ; Base : 10 ; Package : cl - user ; -*-
(in-package "CL-USER")
;;; simplest of tests, to load the parse and parse a document
#+(and mcl (not CL-HTTP))
(load "entwicklung@paz:sourceServer:lisp:xml:define-system.lisp")
#+(and (not mcl) (not cl-http))
(load "d:\\Source\\Lisp\\Xml\\define-system.lisp")
;; minimum system
#+mcl
(register-system-definition :xparser "entwicklung@paz:sourceServer:lisp:xml:sysdcl.lisp")
#-mcl
(register-system-definition :xparser "d:\\Source\\Lisp\\Xml\\sysdcl.lisp")
;; utils
; (execute-system-operations :xutil '(:compile))
;; xml parser
;(execute-system-operations :xqdm '(:load))
;(execute-system-operations :xqdm '(:compile))
;(execute-system-operations :xparser '(:load))
;(execute-system-operations :xparser '(:compile))
(execute-system-operations :xparser '(:compile :load))
;; extended to include xml paths
(register-system-definition :xpath "entwicklung@paz:sourceServer:lisp:xml:sysdcl.lisp")
( execute - system - operations : ' (: load ) )
( execute - system - operations : ' (: compile ) )
(execute-system-operations :xpath '(:compile :load))
;; extended to include xml query
(register-system-definition :xquery "entwicklung@paz:sourceServer:lisp:xml:sysdcl.lisp")
;(execute-system-operations :xquery '(:load))
;(execute-system-operations :xquery '(:compile))
(execute-system-operations :xquery '(:compile :load))
;; _really_ simple tests
;; w/o namespaces
(xmlp:document-parser "<test attr='1234'>asdf</test>")
;; with namespaces
(xmlp:document-parser "<ns:test attr='1234' xmlns:ns='ns1'>asdf</ns:test>")
;; for a simple document
(time (xmlp:document-parser "file"))
;;(inspect *)
:EOF
| null | https://raw.githubusercontent.com/appleshan/cl-http/a7ec6bf51e260e9bb69d8e180a103daf49aa0ac2/contrib/janderson/xml-2001-10-03/tests/test.lisp | lisp | Syntax : ansi - common - lisp ; Base : 10 ; Package : cl - user ; -*-
simplest of tests, to load the parse and parse a document
minimum system
utils
(execute-system-operations :xutil '(:compile))
xml parser
(execute-system-operations :xqdm '(:load))
(execute-system-operations :xqdm '(:compile))
(execute-system-operations :xparser '(:load))
(execute-system-operations :xparser '(:compile))
extended to include xml paths
extended to include xml query
(execute-system-operations :xquery '(:load))
(execute-system-operations :xquery '(:compile))
_really_ simple tests
w/o namespaces
with namespaces
for a simple document
(inspect *) |
(in-package "CL-USER")
#+(and mcl (not CL-HTTP))
(load "entwicklung@paz:sourceServer:lisp:xml:define-system.lisp")
#+(and (not mcl) (not cl-http))
(load "d:\\Source\\Lisp\\Xml\\define-system.lisp")
#+mcl
(register-system-definition :xparser "entwicklung@paz:sourceServer:lisp:xml:sysdcl.lisp")
#-mcl
(register-system-definition :xparser "d:\\Source\\Lisp\\Xml\\sysdcl.lisp")
(execute-system-operations :xparser '(:compile :load))
(register-system-definition :xpath "entwicklung@paz:sourceServer:lisp:xml:sysdcl.lisp")
( execute - system - operations : ' (: load ) )
( execute - system - operations : ' (: compile ) )
(execute-system-operations :xpath '(:compile :load))
(register-system-definition :xquery "entwicklung@paz:sourceServer:lisp:xml:sysdcl.lisp")
(execute-system-operations :xquery '(:compile :load))
(xmlp:document-parser "<test attr='1234'>asdf</test>")
(xmlp:document-parser "<ns:test attr='1234' xmlns:ns='ns1'>asdf</ns:test>")
(time (xmlp:document-parser "file"))
:EOF
|
63aa2099dbe156fcccf2f74fc197a94784ecba6f793ee4f7e7b0aef5f1ff6248 | darkleaf/publicator | types.clj | (ns publicator.persistence.types
(:require
[jdbc.proto])
(:import
[org.postgresql.jdbc PgArray]
[org.postgresql.util PGobject]
[java.sql Timestamp]
[java.time Instant]
[java.util Collection]))
(extend-protocol jdbc.proto/ISQLResultSetReadColumn
PGobject
(from-sql-type [this _conn _metadata _i]
(let [type (.getType this)
value (.getValue this)]
(case type
"xid" (bigint value)
:else this)))
PgArray
(from-sql-type [this _conn metadata i]
(let [column-name (.getColumnName metadata i)
arr (.getArray this)]
(cond
(re-matches #".+-ids" column-name) (set arr)
:else (vec arr))))
Timestamp
(from-sql-type [this _conn _metadata _i]
(.toInstant this)))
(extend-protocol jdbc.proto/ISQLType
Instant
(set-stmt-parameter! [self conn stmt index]
(let [sql-val (Timestamp/from self)]
(.setObject stmt index sql-val)))
Collection
(set-stmt-parameter! [self conn stmt index]
(let [scalar-type (-> stmt
.getParameterMetaData
(.getParameterTypeName index)
(subs 1))
sql-val (.createArrayOf conn scalar-type (to-array self))]
(.setObject stmt index sql-val))))
| null | https://raw.githubusercontent.com/darkleaf/publicator/e07eee93d8f3d9c07a15d574619d5ea59c00f87d/persistence/src/publicator/persistence/types.clj | clojure | (ns publicator.persistence.types
(:require
[jdbc.proto])
(:import
[org.postgresql.jdbc PgArray]
[org.postgresql.util PGobject]
[java.sql Timestamp]
[java.time Instant]
[java.util Collection]))
(extend-protocol jdbc.proto/ISQLResultSetReadColumn
PGobject
(from-sql-type [this _conn _metadata _i]
(let [type (.getType this)
value (.getValue this)]
(case type
"xid" (bigint value)
:else this)))
PgArray
(from-sql-type [this _conn metadata i]
(let [column-name (.getColumnName metadata i)
arr (.getArray this)]
(cond
(re-matches #".+-ids" column-name) (set arr)
:else (vec arr))))
Timestamp
(from-sql-type [this _conn _metadata _i]
(.toInstant this)))
(extend-protocol jdbc.proto/ISQLType
Instant
(set-stmt-parameter! [self conn stmt index]
(let [sql-val (Timestamp/from self)]
(.setObject stmt index sql-val)))
Collection
(set-stmt-parameter! [self conn stmt index]
(let [scalar-type (-> stmt
.getParameterMetaData
(.getParameterTypeName index)
(subs 1))
sql-val (.createArrayOf conn scalar-type (to-array self))]
(.setObject stmt index sql-val))))
|
|
ee001bfafe25574eb8e6c73d253edbbe22db0a4c4713b9788e7c65ccc587551a | haskell-game/tiny-games-hs | hexescape.hs | #!/usr/bin/env stack
-- stack script --resolver lts-20 --package grid,random
import Import;c=putStrLn;n=4;u=pure;v z=randomRIO(0,z);main=do{let{gH=
hexHexGrid n};let{aC=indices gH\\[(0,0)]};e<-(aC!!)<$>v (length aC-1);(_,_,h)<-
g(gH,e)(head(centre gH),False,100);if h<=0then c"✝"else c"🪜"};m p=do{mapM_(c.(
\(k,r)->([k..n]>>" ")++((mC r p)=<<[2..n+k])))(zip([1..n-1]++[n, n-1..1])[1..])
};g(w,e)(p,s,h)|p==e||h<=0=u(p,True,h)|True=do{m p;d::Int<-v 10;;let{nh=h-d};
let{mO=neighbours w p};c.show$zip[1..](map(\x->head$directionTo w p x)$mO);
i<-read<$>getLine;c$"You have "++show nh++"hp";g(w,e)(mO!!(i-1),False,nh)};
mC r (a,b) c|(n-r)==b&&(if r<=n then(c-1-n)else(c-1)-n+(r-n))==a="⬢ "|True="⬡ "
-- ^10 ------------------------------------------------------------------ 80> --
hackage-10 - 80 / hexescape ( nevrome ) .
Copyright 2023 ,
SPDX - License - Identifier : CC - BY-4.0
You are in room ⬢ . Select the next , adjacent room ⬡ you want to explore with a
number between 1 and 6 ( + Enter ) . Search for the exit 🪜 , before you run out of
healthpoints ( hp ) and die ✝ .
Uses the unicode characters ✝ , 🪜 , ⬡ and ⬢ , so it may not look right with all
fonts / machines .
Copyright 2023, Clemens Schmid
SPDX-License-Identifier: CC-BY-4.0
You are in room ⬢. Select the next, adjacent room ⬡ you want to explore with a
number between 1 and 6 (+ Enter). Search for the exit 🪜, before you run out of
healthpoints (hp) and die ✝.
Uses the unicode characters ✝, 🪜, ⬡ and ⬢, so it may not look right with all
fonts/machines.
-} | null | https://raw.githubusercontent.com/haskell-game/tiny-games-hs/fe407ed6f920717ce3e725483b39a05596b1cf11/hackage/hexescape/hexescape.hs | haskell | stack script --resolver lts-20 --package grid,random
^10 ------------------------------------------------------------------ 80> -- | #!/usr/bin/env stack
import Import;c=putStrLn;n=4;u=pure;v z=randomRIO(0,z);main=do{let{gH=
hexHexGrid n};let{aC=indices gH\\[(0,0)]};e<-(aC!!)<$>v (length aC-1);(_,_,h)<-
g(gH,e)(head(centre gH),False,100);if h<=0then c"✝"else c"🪜"};m p=do{mapM_(c.(
\(k,r)->([k..n]>>" ")++((mC r p)=<<[2..n+k])))(zip([1..n-1]++[n, n-1..1])[1..])
};g(w,e)(p,s,h)|p==e||h<=0=u(p,True,h)|True=do{m p;d::Int<-v 10;;let{nh=h-d};
let{mO=neighbours w p};c.show$zip[1..](map(\x->head$directionTo w p x)$mO);
i<-read<$>getLine;c$"You have "++show nh++"hp";g(w,e)(mO!!(i-1),False,nh)};
mC r (a,b) c|(n-r)==b&&(if r<=n then(c-1-n)else(c-1)-n+(r-n))==a="⬢ "|True="⬡ "
hackage-10 - 80 / hexescape ( nevrome ) .
Copyright 2023 ,
SPDX - License - Identifier : CC - BY-4.0
You are in room ⬢ . Select the next , adjacent room ⬡ you want to explore with a
number between 1 and 6 ( + Enter ) . Search for the exit 🪜 , before you run out of
healthpoints ( hp ) and die ✝ .
Uses the unicode characters ✝ , 🪜 , ⬡ and ⬢ , so it may not look right with all
fonts / machines .
Copyright 2023, Clemens Schmid
SPDX-License-Identifier: CC-BY-4.0
You are in room ⬢. Select the next, adjacent room ⬡ you want to explore with a
number between 1 and 6 (+ Enter). Search for the exit 🪜, before you run out of
healthpoints (hp) and die ✝.
Uses the unicode characters ✝, 🪜, ⬡ and ⬢, so it may not look right with all
fonts/machines.
-} |
a98de1c5ad67972cce1b57d1aeb94cd560b2f5f58f9c0618c5e566b0b9cf5cb9 | yesodweb/yesod | Message.hs | {-# LANGUAGE OverloadedStrings #-}
module Yesod.Auth.Message
( AuthMessage (..)
, defaultMessage
-- * All languages
, englishMessage
, portugueseMessage
, swedishMessage
, germanMessage
, frenchMessage
, norwegianBokmålMessage
, japaneseMessage
, finnishMessage
, chineseMessage
, croatianMessage
, spanishMessage
, czechMessage
, russianMessage
, dutchMessage
, danishMessage
, koreanMessage
) where
import Data.Monoid (mappend, (<>))
import Data.Text (Text)
data AuthMessage =
NoOpenID
| LoginOpenID
| LoginGoogle
| LoginYahoo
| Email
| UserName
| IdentifierNotFound Text
| Password
| Register
| RegisterLong
| EnterEmail
| ConfirmationEmailSentTitle
| ConfirmationEmailSent Text
| AddressVerified
| EmailVerifiedChangePass
| EmailVerified
| InvalidKeyTitle
| InvalidKey
| InvalidEmailPass
| BadSetPass
| SetPassTitle
| SetPass
| NewPass
| ConfirmPass
| PassMismatch
| PassUpdated
| Facebook
| LoginViaEmail
| InvalidLogin
| NowLoggedIn
| LoginTitle
| PleaseProvideUsername
| PleaseProvidePassword
| NoIdentifierProvided
| InvalidEmailAddress
| PasswordResetTitle
| ProvideIdentifier
| SendPasswordResetEmail
| PasswordResetPrompt
| CurrentPassword
| InvalidUsernamePass
| Logout
| LogoutTitle
| AuthError
# DEPRECATED Logout " Please , use LogoutTitle instead . " #
# DEPRECATED AddressVerified " Please , use instead . " #
-- | Defaults to 'englishMessage'.
defaultMessage :: AuthMessage -> Text
defaultMessage = englishMessage
englishMessage :: AuthMessage -> Text
englishMessage NoOpenID = "No OpenID identifier found"
englishMessage LoginOpenID = "Log in via OpenID"
englishMessage LoginGoogle = "Log in via Google"
englishMessage LoginYahoo = "Log in via Yahoo"
englishMessage Email = "Email"
englishMessage UserName = "User name"
englishMessage Password = "Password"
englishMessage CurrentPassword = "Current Password"
englishMessage Register = "Register"
englishMessage RegisterLong = "Register a new account"
englishMessage EnterEmail = "Enter your e-mail address below, and a confirmation e-mail will be sent to you."
englishMessage ConfirmationEmailSentTitle = "Confirmation e-mail sent"
englishMessage (ConfirmationEmailSent email) =
"A confirmation e-mail has been sent to " `Data.Monoid.mappend`
email `mappend`
"."
englishMessage AddressVerified = "Email address verified, please set a new password"
englishMessage EmailVerifiedChangePass = "Email address verified, please set a new password"
englishMessage EmailVerified = "Email address verified"
englishMessage InvalidKeyTitle = "Invalid verification key"
englishMessage InvalidKey = "I'm sorry, but that was an invalid verification key."
englishMessage InvalidEmailPass = "Invalid email/password combination"
englishMessage BadSetPass = "You must be logged in to set a password"
englishMessage SetPassTitle = "Set password"
englishMessage SetPass = "Set a new password"
englishMessage NewPass = "New password"
englishMessage ConfirmPass = "Confirm"
englishMessage PassMismatch = "Passwords did not match, please try again"
englishMessage PassUpdated = "Password updated"
englishMessage Facebook = "Log in with Facebook"
englishMessage LoginViaEmail = "Log in via email"
englishMessage InvalidLogin = "Invalid login"
englishMessage NowLoggedIn = "You are now logged in"
englishMessage LoginTitle = "Log In"
englishMessage PleaseProvideUsername = "Please fill in your username"
englishMessage PleaseProvidePassword = "Please fill in your password"
englishMessage NoIdentifierProvided = "No email/username provided"
englishMessage InvalidEmailAddress = "Invalid email address provided"
englishMessage PasswordResetTitle = "Password Reset"
englishMessage ProvideIdentifier = "Email or Username"
englishMessage SendPasswordResetEmail = "Send password reset email"
englishMessage PasswordResetPrompt = "Enter your e-mail address or username below, and a password reset e-mail will be sent to you."
englishMessage InvalidUsernamePass = "Invalid username/password combination"
englishMessage (IdentifierNotFound ident) = "Login not found: " `mappend` ident
englishMessage Logout = "Log Out"
englishMessage LogoutTitle = "Log Out"
FIXME by Google Translate
portugueseMessage :: AuthMessage -> Text
portugueseMessage NoOpenID = "Nenhum identificador OpenID encontrado"
portugueseMessage LoginOpenID = "Entrar via OpenID"
portugueseMessage LoginGoogle = "Entrar via Google"
portugueseMessage LoginYahoo = "Entrar via Yahoo"
portugueseMessage Email = "E-mail"
FIXME by Google Translate " user name "
portugueseMessage Password = "Senha"
portugueseMessage CurrentPassword = "Palavra de passe"
portugueseMessage Register = "Registrar"
portugueseMessage RegisterLong = "Registrar uma nova conta"
portugueseMessage EnterEmail = "Por favor digite seu endereço de e-mail abaixo e um e-mail de confirmação será enviado para você."
portugueseMessage ConfirmationEmailSentTitle = "E-mail de confirmação enviado"
portugueseMessage (ConfirmationEmailSent email) =
"Um e-mail de confirmação foi enviado para " `mappend`
email `mappend`
"."
portugueseMessage AddressVerified = "Endereço verificado, por favor entre com uma nova senha"
portugueseMessage EmailVerifiedChangePass = "Endereço verificado, por favor entre com uma nova senha"
portugueseMessage EmailVerified = "Endereço verificado"
portugueseMessage InvalidKeyTitle = "Chave de verificação inválida"
portugueseMessage InvalidKey = "Por favor nos desculpe, mas essa é uma chave de verificação inválida."
portugueseMessage InvalidEmailPass = "E-mail e/ou senha inválidos"
portugueseMessage BadSetPass = "Você deve entrar para definir uma senha"
portugueseMessage SetPassTitle = "Definir senha"
portugueseMessage SetPass = "Definir uma nova senha"
portugueseMessage NewPass = "Nova senha"
portugueseMessage ConfirmPass = "Confirmar"
portugueseMessage PassMismatch = "Senhas não conferem, por favor tente novamente"
portugueseMessage PassUpdated = "Senhas alteradas"
portugueseMessage Facebook = "Entrar via Facebook"
portugueseMessage LoginViaEmail = "Entrar via e-mail"
portugueseMessage InvalidLogin = "Informações de login inválidas"
portugueseMessage NowLoggedIn = "Você acaba de entrar no site com sucesso!"
portugueseMessage LoginTitle = "Entrar no site"
portugueseMessage PleaseProvideUsername = "Por favor digite seu nome de usuário"
portugueseMessage PleaseProvidePassword = "Por favor digite sua senha"
portugueseMessage NoIdentifierProvided = "Nenhum e-mail ou nome de usuário informado"
portugueseMessage InvalidEmailAddress = "Endereço de e-mail inválido informado"
portugueseMessage PasswordResetTitle = "Resetar senha"
portugueseMessage ProvideIdentifier = "E-mail ou nome de usuário"
portugueseMessage SendPasswordResetEmail = "Enviar e-mail para resetar senha"
portugueseMessage PasswordResetPrompt = "Insira seu endereço de e-mail ou nome de usuário abaixo. Um e-mail para resetar sua senha será enviado para você."
portugueseMessage InvalidUsernamePass = "Nome de usuário ou senha inválidos"
TODO
portugueseMessage i@(IdentifierNotFound _) = englishMessage i
FIXME by Google Translate
FIXME by Google Translate
FIXME by Google Translate
spanishMessage :: AuthMessage -> Text
spanishMessage NoOpenID = "No se encuentra el identificador OpenID"
spanishMessage LoginOpenID = "Entrar utilizando OpenID"
spanishMessage LoginGoogle = "Entrar utilizando Google"
spanishMessage LoginYahoo = "Entrar utilizando Yahoo"
spanishMessage Email = "Correo electrónico"
spanishMessage UserName = "Nombre de Usuario"
spanishMessage Password = "Contraseña"
spanishMessage CurrentPassword = "Contraseña actual"
spanishMessage Register = "Registrarse"
spanishMessage RegisterLong = "Registrar una nueva cuenta"
spanishMessage EnterEmail = "Coloque su dirección de correo electrónico, y un correo de confirmación le será enviado a su cuenta."
spanishMessage ConfirmationEmailSentTitle = "La confirmación de correo ha sido enviada"
spanishMessage (ConfirmationEmailSent email) =
"Una confirmación de correo electrónico ha sido enviada a " `mappend`
email `mappend`
"."
spanishMessage AddressVerified = "Dirección verificada, por favor introduzca una contraseña"
spanishMessage EmailVerifiedChangePass = "Dirección verificada, por favor introduzca una contraseña"
spanishMessage EmailVerified = "Dirección verificada"
spanishMessage InvalidKeyTitle = "Clave de verificación invalida"
spanishMessage InvalidKey = "Lo sentimos, pero esa clave de verificación es inválida."
spanishMessage InvalidEmailPass = "La combinación cuenta de correo/contraseña es inválida"
spanishMessage BadSetPass = "Debe acceder a la aplicación para modificar la contraseña"
spanishMessage SetPassTitle = "Modificar contraseña"
spanishMessage SetPass = "Actualizar nueva contraseña"
spanishMessage NewPass = "Nueva contraseña"
spanishMessage ConfirmPass = "Confirmar"
spanishMessage PassMismatch = "Las contraseñas no coinciden, inténtelo de nuevo"
spanishMessage PassUpdated = "Contraseña actualizada"
spanishMessage Facebook = "Entrar mediante Facebook"
spanishMessage LoginViaEmail = "Entrar mediante una cuenta de correo"
spanishMessage InvalidLogin = "Login inválido"
spanishMessage NowLoggedIn = "Usted ha ingresado al sitio"
spanishMessage LoginTitle = "Log In"
spanishMessage PleaseProvideUsername = "Por favor escriba su nombre de usuario"
spanishMessage PleaseProvidePassword = "Por favor escriba su contraseña"
spanishMessage NoIdentifierProvided = "No ha indicado una cuenta de correo/nombre de usuario"
spanishMessage InvalidEmailAddress = "La cuenta de correo es inválida"
spanishMessage PasswordResetTitle = "Actualización de contraseña"
spanishMessage ProvideIdentifier = "Cuenta de correo o nombre de usuario"
spanishMessage SendPasswordResetEmail = "Enviar correo de actualización de contraseña"
spanishMessage PasswordResetPrompt = "Escriba su cuenta de correo o nombre de usuario, y una confirmación de actualización de contraseña será enviada a su cuenta de correo."
spanishMessage InvalidUsernamePass = "Combinación de nombre de usuario/contraseña invalida"
TODO
spanishMessage i@(IdentifierNotFound _) = englishMessage i
FIXME by Google Translate
FIXME by Google Translate
FIXME by Google Translate
swedishMessage :: AuthMessage -> Text
swedishMessage NoOpenID = "Fann ej OpenID identifierare"
swedishMessage LoginOpenID = "Logga in via OpenID"
swedishMessage LoginGoogle = "Logga in via Google"
swedishMessage LoginYahoo = "Logga in via Yahoo"
swedishMessage Email = "Epost"
FIXME by Google Translate " user name "
swedishMessage Password = "Lösenord"
swedishMessage CurrentPassword = "Current password"
swedishMessage Register = "Registrera"
swedishMessage RegisterLong = "Registrera ett nytt konto"
swedishMessage EnterEmail = "Skriv in din epost nedan så kommer ett konfirmationsmail skickas till adressen."
swedishMessage ConfirmationEmailSentTitle = "Konfirmationsmail skickat"
swedishMessage (ConfirmationEmailSent email) =
"Ett konfirmationsmeddelande har skickats till" `mappend`
email `mappend`
"."
swedishMessage AddressVerified = "Adress verifierad, vänligen välj nytt lösenord"
swedishMessage EmailVerifiedChangePass = "Adress verifierad, vänligen välj nytt lösenord"
swedishMessage EmailVerified = "Adress verifierad"
swedishMessage InvalidKeyTitle = "Ogiltig verifikationsnyckel"
swedishMessage InvalidKey = "Tyvärr, du angav en ogiltig verifimationsnyckel."
swedishMessage InvalidEmailPass = "Ogiltig epost/lösenord kombination"
swedishMessage BadSetPass = "Du måste vara inloggad för att ange ett lösenord"
swedishMessage SetPassTitle = "Ange lösenord"
swedishMessage SetPass = "Ange nytt lösenord"
swedishMessage NewPass = "Nytt lösenord"
swedishMessage ConfirmPass = "Godkänn"
swedishMessage PassMismatch = "Lösenorden matcha ej, vänligen försök igen"
swedishMessage PassUpdated = "Lösenord updaterades"
swedishMessage Facebook = "Logga in med Facebook"
swedishMessage LoginViaEmail = "Logga in via epost"
swedishMessage InvalidLogin = "Ogiltigt login"
swedishMessage NowLoggedIn = "Du är nu inloggad"
swedishMessage LoginTitle = "Logga in"
swedishMessage PleaseProvideUsername = "Vänligen fyll i användarnamn"
swedishMessage PleaseProvidePassword = "Vänligen fyll i lösenord"
swedishMessage NoIdentifierProvided = "Emailadress eller användarnamn saknas"
swedishMessage InvalidEmailAddress = "Ogiltig emailadress angiven"
swedishMessage PasswordResetTitle = "Återställning av lösenord"
swedishMessage ProvideIdentifier = "Epost eller användarnamn"
swedishMessage SendPasswordResetEmail = "Skicka email för återställning av lösenord"
swedishMessage PasswordResetPrompt = "Skriv in din emailadress eller användarnamn nedan och " `mappend`
"ett email för återställning av lösenord kommmer att skickas till dig."
swedishMessage InvalidUsernamePass = "Ogiltig kombination av användarnamn och lösenord"
TODO
swedishMessage i@(IdentifierNotFound _) = englishMessage i
FIXME by Google Translate
FIXME by Google Translate
FIXME by Google Translate
germanMessage :: AuthMessage -> Text
germanMessage NoOpenID = "Kein OpenID-Identifier gefunden"
germanMessage LoginOpenID = "Login via OpenID"
germanMessage LoginGoogle = "Login via Google"
germanMessage LoginYahoo = "Login via Yahoo"
germanMessage Email = "E-Mail"
germanMessage UserName = "Benutzername"
germanMessage Password = "Passwort"
germanMessage CurrentPassword = "Aktuelles Passwort"
germanMessage Register = "Registrieren"
germanMessage RegisterLong = "Neuen Account registrieren"
germanMessage EnterEmail = "Bitte die E-Mail Adresse angeben, eine Bestätigungsmail wird verschickt."
germanMessage ConfirmationEmailSentTitle = "Bestätigung verschickt."
germanMessage (ConfirmationEmailSent email) =
"Eine Bestätigung wurde an " `mappend`
email `mappend`
" versandt."
germanMessage AddressVerified = "Adresse bestätigt, bitte neues Passwort angeben"
germanMessage EmailVerifiedChangePass = "Adresse bestätigt, bitte neues Passwort angeben"
germanMessage EmailVerified = "Adresse bestätigt"
germanMessage InvalidKeyTitle = "Ungültiger Bestätigungsschlüssel"
germanMessage InvalidKey = "Das war leider ein ungültiger Bestätigungsschlüssel"
germanMessage InvalidEmailPass = "Ungültiger Nutzername oder Passwort"
germanMessage BadSetPass = "Um das Passwort zu ändern muss man eingeloggt sein"
germanMessage SetPassTitle = "Passwort angeben"
germanMessage SetPass = "Neues Passwort angeben"
germanMessage NewPass = "Neues Passwort"
germanMessage ConfirmPass = "Bestätigen"
germanMessage PassMismatch = "Die Passwörter stimmen nicht überein"
germanMessage PassUpdated = "Passwort überschrieben"
germanMessage Facebook = "Login über Facebook"
germanMessage LoginViaEmail = "Login via E-Mail"
germanMessage InvalidLogin = "Ungültiger Login"
germanMessage NowLoggedIn = "Login erfolgreich"
germanMessage LoginTitle = "Anmelden"
germanMessage PleaseProvideUsername = "Bitte Nutzername angeben"
germanMessage PleaseProvidePassword = "Bitte Passwort angeben"
germanMessage NoIdentifierProvided = "Keine E-Mail-Adresse oder kein Nutzername angegeben"
germanMessage InvalidEmailAddress = "Unzulässiger E-Mail-Anbieter"
germanMessage PasswordResetTitle = "Passwort zurücksetzen"
germanMessage ProvideIdentifier = "E-Mail-Adresse oder Nutzername"
germanMessage SendPasswordResetEmail = "E-Mail zusenden um Passwort zurückzusetzen"
germanMessage PasswordResetPrompt = "Nach Einhabe der E-Mail-Adresse oder des Nutzernamen wird eine E-Mail zugesendet mit welcher das Passwort zurückgesetzt werden kann."
germanMessage InvalidUsernamePass = "Ungültige Kombination aus Nutzername und Passwort"
TODO
germanMessage Logout = "Abmelden"
germanMessage LogoutTitle = "Abmelden"
germanMessage AuthError = "Fehler beim Anmelden"
frenchMessage :: AuthMessage -> Text
frenchMessage NoOpenID = "Aucun fournisseur OpenID n'a été trouvé"
frenchMessage LoginOpenID = "Se connecter avec OpenID"
frenchMessage LoginGoogle = "Se connecter avec Google"
frenchMessage LoginYahoo = "Se connecter avec Yahoo"
frenchMessage Email = "Adresse électronique"
FIXME by Google Translate " user name "
frenchMessage Password = "Mot de passe"
frenchMessage CurrentPassword = "Mot de passe actuel"
frenchMessage Register = "S'inscrire"
frenchMessage RegisterLong = "Créer un compte"
frenchMessage EnterEmail = "Entrez ci-dessous votre adresse électronique, et un message de confirmation vous sera envoyé"
frenchMessage ConfirmationEmailSentTitle = "Message de confirmation"
frenchMessage (ConfirmationEmailSent email) =
"Un message de confirmation a été envoyé à " `mappend`
email `mappend`
"."
frenchMessage AddressVerified = "Votre adresse électronique a été validée, merci de choisir un nouveau mot de passe."
frenchMessage EmailVerifiedChangePass = "Votre adresse électronique a été validée, merci de choisir un nouveau mot de passe."
frenchMessage EmailVerified = "Votre adresse électronique a été validée"
frenchMessage InvalidKeyTitle = "Clef de validation incorrecte"
frenchMessage InvalidKey = "Désolé, mais cette clef de validation est incorrecte"
frenchMessage InvalidEmailPass = "La combinaison de ce mot de passe et de cette adresse électronique n'existe pas."
frenchMessage BadSetPass = "Vous devez être connecté pour choisir un mot de passe"
frenchMessage SetPassTitle = "Changer de mot de passe"
frenchMessage SetPass = "Choisir un nouveau mot de passe"
frenchMessage NewPass = "Nouveau mot de passe"
frenchMessage ConfirmPass = "Confirmation du mot de passe"
frenchMessage PassMismatch = "Le deux mots de passe sont différents, veuillez les corriger"
frenchMessage PassUpdated = "Le mot de passe a bien été changé"
frenchMessage Facebook = "Se connecter avec Facebook"
frenchMessage LoginViaEmail = "Se connecter avec une adresse électronique"
frenchMessage InvalidLogin = "Nom d'utilisateur incorrect"
frenchMessage NowLoggedIn = "Vous êtes maintenant connecté"
frenchMessage LoginTitle = "Se connecter"
frenchMessage PleaseProvideUsername = "Veuillez fournir votre nom d'utilisateur"
frenchMessage PleaseProvidePassword = "Veuillez fournir votre mot de passe"
frenchMessage NoIdentifierProvided = "Adresse électronique/nom d'utilisateur non spécifié"
frenchMessage InvalidEmailAddress = "Adresse électronique spécifiée invalide"
frenchMessage PasswordResetTitle = "Réinitialisation du mot de passe"
frenchMessage ProvideIdentifier = "Adresse électronique ou nom d'utilisateur"
frenchMessage SendPasswordResetEmail = "Envoi d'un courriel pour réinitialiser le mot de passe"
frenchMessage PasswordResetPrompt = "Entrez votre courriel ou votre nom d'utilisateur ci-dessous, et vous recevrez un message électronique pour réinitialiser votre mot de passe."
frenchMessage InvalidUsernamePass = "La combinaison de ce mot de passe et de ce nom d'utilisateur n'existe pas."
frenchMessage (IdentifierNotFound ident) = "Nom d'utilisateur introuvable: " `mappend` ident
frenchMessage Logout = "Déconnexion"
frenchMessage LogoutTitle = "Déconnexion"
FIXME by Google Translate
norwegianBokmålMessage :: AuthMessage -> Text
norwegianBokmålMessage NoOpenID = "Ingen OpenID-identifiserer funnet"
norwegianBokmålMessage LoginOpenID = "Logg inn med OpenID"
norwegianBokmålMessage LoginGoogle = "Logg inn med Google"
norwegianBokmålMessage LoginYahoo = "Logg inn med Yahoo"
norwegianBokmålMessage Email = "E-post"
FIXME by Google Translate " user name "
norwegianBokmålMessage Password = "Passord"
norwegianBokmålMessage CurrentPassword = "Current password"
norwegianBokmålMessage Register = "Registrer"
norwegianBokmålMessage RegisterLong = "Registrer en ny konto"
norwegianBokmålMessage EnterEmail = "Skriv inn e-postadressen din nedenfor og en e-postkonfirmasjon vil bli sendt."
norwegianBokmålMessage ConfirmationEmailSentTitle = "E-postkonfirmasjon sendt."
norwegianBokmålMessage (ConfirmationEmailSent email) =
"En e-postkonfirmasjon har blitt sendt til " `mappend`
email `mappend`
"."
norwegianBokmålMessage AddressVerified = "Adresse verifisert, vennligst sett et nytt passord."
norwegianBokmålMessage EmailVerifiedChangePass = "Adresse verifisert, vennligst sett et nytt passord."
norwegianBokmålMessage EmailVerified = "Adresse verifisert"
norwegianBokmålMessage InvalidKeyTitle = "Ugyldig verifiseringsnøkkel"
norwegianBokmålMessage InvalidKey = "Beklager, men det var en ugyldig verifiseringsnøkkel."
norwegianBokmålMessage InvalidEmailPass = "Ugyldig e-post/passord-kombinasjon"
norwegianBokmålMessage BadSetPass = "Du må være logget inn for å sette et passord."
norwegianBokmålMessage SetPassTitle = "Sett passord"
norwegianBokmålMessage SetPass = "Sett et nytt passord"
norwegianBokmålMessage NewPass = "Nytt passord"
norwegianBokmålMessage ConfirmPass = "Bekreft"
norwegianBokmålMessage PassMismatch = "Passordene stemte ikke overens, vennligst prøv igjen"
norwegianBokmålMessage PassUpdated = "Passord oppdatert"
norwegianBokmålMessage Facebook = "Logg inn med Facebook"
norwegianBokmålMessage LoginViaEmail = "Logg inn med e-post"
norwegianBokmålMessage InvalidLogin = "Ugyldig innlogging"
norwegianBokmålMessage NowLoggedIn = "Du er nå logget inn"
norwegianBokmålMessage LoginTitle = "Logg inn"
norwegianBokmålMessage PleaseProvideUsername = "Vennligst fyll inn ditt brukernavn"
norwegianBokmålMessage PleaseProvidePassword = "Vennligst fyll inn ditt passord"
norwegianBokmålMessage NoIdentifierProvided = "No email/username provided"
norwegianBokmålMessage InvalidEmailAddress = "Invalid email address provided"
norwegianBokmålMessage PasswordResetTitle = "Password Reset"
norwegianBokmålMessage ProvideIdentifier = "Email or Username"
norwegianBokmålMessage SendPasswordResetEmail = "Send password reset email"
norwegianBokmålMessage PasswordResetPrompt = "Enter your e-mail address or username below, and a password reset e-mail will be sent to you."
norwegianBokmålMessage InvalidUsernamePass = "Invalid username/password combination"
TODO
norwegianBokmålMessage i@(IdentifierNotFound _) = englishMessage i
FIXME by Google Translate
FIXME by Google Translate
FIXME by Google Translate
japaneseMessage :: AuthMessage -> Text
japaneseMessage NoOpenID = "OpenID識別子がありません"
japaneseMessage LoginOpenID = "OpenIDでログイン"
japaneseMessage LoginGoogle = "Googleでログイン"
japaneseMessage LoginYahoo = "Yahooでログイン"
japaneseMessage Email = "Eメール"
FIXME by Google Translate " user name "
japaneseMessage Password = "パスワード"
japaneseMessage CurrentPassword = "現在のパスワード"
japaneseMessage Register = "登録"
japaneseMessage RegisterLong = "新規アカウント登録"
japaneseMessage EnterEmail = "メールアドレスを入力してください。確認メールが送られます"
japaneseMessage ConfirmationEmailSentTitle = "確認メールを送信しました"
japaneseMessage (ConfirmationEmailSent email) =
"確認メールを " `mappend`
email `mappend`
" に送信しました"
japaneseMessage AddressVerified = "アドレスは認証されました。新しいパスワードを設定してください"
japaneseMessage EmailVerifiedChangePass = "アドレスは認証されました。新しいパスワードを設定してください"
japaneseMessage EmailVerified = "アドレスは認証されました"
japaneseMessage InvalidKeyTitle = "認証キーが無効です"
japaneseMessage InvalidKey = "申し訳ありません。無効な認証キーです"
japaneseMessage InvalidEmailPass = "メールアドレスまたはパスワードが無効です"
japaneseMessage BadSetPass = "パスワードを設定するためには、ログインしてください"
japaneseMessage SetPassTitle = "パスワードの設定"
japaneseMessage SetPass = "新しいパスワードを設定する"
japaneseMessage NewPass = "新しいパスワード"
japaneseMessage ConfirmPass = "確認"
japaneseMessage PassMismatch = "パスワードが合いません。もう一度試してください"
japaneseMessage PassUpdated = "パスワードは更新されました"
japaneseMessage Facebook = "Facebookでログイン"
japaneseMessage LoginViaEmail = "Eメールでログイン"
japaneseMessage InvalidLogin = "無効なログインです"
japaneseMessage NowLoggedIn = "ログインしました"
japaneseMessage LoginTitle = "ログイン"
japaneseMessage PleaseProvideUsername = "ユーザ名を入力してください"
japaneseMessage PleaseProvidePassword = "パスワードを入力してください"
japaneseMessage NoIdentifierProvided = "メールアドレス/ユーザ名が入力されていません"
japaneseMessage InvalidEmailAddress = "メールアドレスが無効です"
japaneseMessage PasswordResetTitle = "パスワードの再設定"
japaneseMessage ProvideIdentifier = "メールアドレスまたはユーザ名"
japaneseMessage SendPasswordResetEmail = "パスワード再設定用メールの送信"
japaneseMessage PasswordResetPrompt = "以下にメールアドレスまたはユーザ名を入力してください。パスワードを再設定するためのメールが送信されます。"
japaneseMessage InvalidUsernamePass = "ユーザ名とパスワードの組み合わせが間違っています"
japaneseMessage (IdentifierNotFound ident) =
ident `mappend` "は登録されていません"
FIXME by Google Translate
FIXME by Google Translate
FIXME by Google Translate
finnishMessage :: AuthMessage -> Text
finnishMessage NoOpenID = "OpenID-tunnistetta ei löydy"
finnishMessage LoginOpenID = "Kirjaudu OpenID-tilillä"
finnishMessage LoginGoogle = "Kirjaudu Google-tilillä"
finnishMessage LoginYahoo = "Kirjaudu Yahoo-tilillä"
finnishMessage Email = "Sähköposti"
FIXME by Google Translate " user name "
finnishMessage Password = "Salasana"
finnishMessage CurrentPassword = "Current password"
finnishMessage Register = "Luo uusi"
finnishMessage RegisterLong = "Luo uusi tili"
finnishMessage EnterEmail = "Kirjoita alle sähköpostiosoitteesi, johon vahvistussähköposti lähetetään."
finnishMessage ConfirmationEmailSentTitle = "Vahvistussähköposti lähetetty."
finnishMessage (ConfirmationEmailSent email) =
"Vahvistussähköposti on lähetty osoitteeseen " `mappend`
email `mappend`
"."
finnishMessage AddressVerified = "Sähköpostiosoite vahvistettu. Anna uusi salasana"
finnishMessage EmailVerifiedChangePass = "Sähköpostiosoite vahvistettu. Anna uusi salasana"
finnishMessage EmailVerified = "Sähköpostiosoite vahvistettu"
finnishMessage InvalidKeyTitle = "Virheellinen varmistusavain"
finnishMessage InvalidKey = "Valitettavasti varmistusavain on virheellinen."
finnishMessage InvalidEmailPass = "Virheellinen sähköposti tai salasana."
finnishMessage BadSetPass = "Kirjaudu ensin sisään asettaaksesi salasanan"
finnishMessage SetPassTitle = "Salasanan asettaminen"
finnishMessage SetPass = "Aseta uusi salasana"
finnishMessage NewPass = "Uusi salasana"
finnishMessage ConfirmPass = "Vahvista"
finnishMessage PassMismatch = "Salasanat eivät täsmää"
finnishMessage PassUpdated = "Salasana vaihdettu"
finnishMessage Facebook = "Kirjaudu Facebook-tilillä"
finnishMessage LoginViaEmail = "Kirjaudu sähköpostitilillä"
finnishMessage InvalidLogin = "Kirjautuminen epäonnistui"
finnishMessage NowLoggedIn = "Olet nyt kirjautunut sisään"
finnishMessage LoginTitle = "Kirjautuminen"
finnishMessage PleaseProvideUsername = "Käyttäjänimi puuttuu"
finnishMessage PleaseProvidePassword = "Salasana puuttuu"
finnishMessage NoIdentifierProvided = "Sähköpostiosoite/käyttäjänimi puuttuu"
finnishMessage InvalidEmailAddress = "Annettu sähköpostiosoite ei kelpaa"
finnishMessage PasswordResetTitle = "Uuden salasanan tilaaminen"
finnishMessage ProvideIdentifier = "Sähköpostiosoite tai käyttäjänimi"
finnishMessage SendPasswordResetEmail = "Lähetä uusi salasana sähköpostitse"
finnishMessage PasswordResetPrompt = "Anna sähköpostiosoitteesi tai käyttäjätunnuksesi alla, niin lähetämme uuden salasanan sähköpostitse."
finnishMessage InvalidUsernamePass = "Virheellinen käyttäjänimi tai salasana."
TODO
finnishMessage i@(IdentifierNotFound _) = englishMessage i
FIXME by Google Translate
FIXME by Google Translate
FIXME by Google Translate
chineseMessage :: AuthMessage -> Text
chineseMessage NoOpenID = "无效的OpenID"
chineseMessage LoginOpenID = "用OpenID登录"
chineseMessage LoginGoogle = "用Google帐户登录"
chineseMessage LoginYahoo = "用Yahoo帐户登录"
chineseMessage Email = "邮箱"
chineseMessage UserName = "用户名"
chineseMessage Password = "密码"
chineseMessage CurrentPassword = "当前密码"
chineseMessage Register = "注册"
chineseMessage RegisterLong = "注册新帐户"
chineseMessage EnterEmail = "输入你的邮箱地址,你将收到一封确认邮件。"
chineseMessage ConfirmationEmailSentTitle = "确认邮件已发送"
chineseMessage (ConfirmationEmailSent email) =
"确认邮件已发送至 " `mappend`
email `mappend`
"."
chineseMessage AddressVerified = "地址验证成功,请设置新密码"
chineseMessage EmailVerifiedChangePass = "地址验证成功,请设置新密码"
chineseMessage EmailVerified = "地址验证成功"
chineseMessage InvalidKeyTitle = "无效的验证码"
chineseMessage InvalidKey = "对不起,验证码无效。"
chineseMessage InvalidEmailPass = "无效的邮箱/密码组合"
chineseMessage BadSetPass = "你需要登录才能设置密码"
chineseMessage SetPassTitle = "设置密码"
chineseMessage SetPass = "设置新密码"
chineseMessage NewPass = "新密码"
chineseMessage ConfirmPass = "确认"
chineseMessage PassMismatch = "密码不匹配,请重新输入"
chineseMessage PassUpdated = "密码更新成功"
chineseMessage Facebook = "用Facebook帐户登录"
chineseMessage LoginViaEmail = "用邮箱登录"
chineseMessage InvalidLogin = "登录失败"
chineseMessage NowLoggedIn = "登录成功"
chineseMessage LoginTitle = "登录"
chineseMessage PleaseProvideUsername = "请输入用户名"
chineseMessage PleaseProvidePassword = "请输入密码"
chineseMessage NoIdentifierProvided = "缺少邮箱/用户名"
chineseMessage InvalidEmailAddress = "无效的邮箱地址"
chineseMessage PasswordResetTitle = "重置密码"
chineseMessage ProvideIdentifier = "邮箱或用户名"
chineseMessage SendPasswordResetEmail = "发送密码重置邮件"
chineseMessage PasswordResetPrompt = "输入你的邮箱地址或用户名,你将收到一封密码重置邮件。"
chineseMessage InvalidUsernamePass = "无效的用户名/密码组合"
chineseMessage (IdentifierNotFound ident) = "邮箱/用户名不存在: " `mappend` ident
chineseMessage Logout = "注销"
chineseMessage LogoutTitle = "注销"
chineseMessage AuthError = "验证错误"
czechMessage :: AuthMessage -> Text
czechMessage NoOpenID = "Nebyl nalezen identifikátor OpenID"
czechMessage LoginOpenID = "Přihlásit přes OpenID"
czechMessage LoginGoogle = "Přihlásit přes Google"
czechMessage LoginYahoo = "Přihlásit přes Yahoo"
czechMessage Email = "E-mail"
czechMessage UserName = "Uživatelské jméno"
czechMessage Password = "Heslo"
czechMessage CurrentPassword = "Current password"
czechMessage Register = "Registrovat"
czechMessage RegisterLong = "Zaregistrovat nový účet"
czechMessage EnterEmail = "Níže zadejte svou e-mailovou adresu a bude vám poslán potvrzovací e-mail."
czechMessage ConfirmationEmailSentTitle = "Potvrzovací e-mail odeslán"
czechMessage (ConfirmationEmailSent email) =
"Potvrzovací e-mail byl odeslán na " `mappend` email `mappend` "."
czechMessage AddressVerified = "Adresa byla ověřena, prosím nastavte si nové heslo"
czechMessage EmailVerifiedChangePass = "Adresa byla ověřena, prosím nastavte si nové heslo"
czechMessage EmailVerified = "Adresa byla ověřena"
czechMessage InvalidKeyTitle = "Neplatný ověřovací klíč"
czechMessage InvalidKey = "Bohužel, ověřovací klíč je neplatný."
czechMessage InvalidEmailPass = "Neplatná kombinace e-mail/heslo"
czechMessage BadSetPass = "Pro nastavení hesla je vyžadováno přihlášení"
czechMessage SetPassTitle = "Nastavit heslo"
czechMessage SetPass = "Nastavit nové heslo"
czechMessage NewPass = "Nové heslo"
czechMessage ConfirmPass = "Potvrdit"
czechMessage PassMismatch = "Hesla si neodpovídají, zkuste to znovu"
czechMessage PassUpdated = "Heslo aktualizováno"
czechMessage Facebook = "Přihlásit přes Facebook"
czechMessage LoginViaEmail = "Přihlásit přes e-mail"
czechMessage InvalidLogin = "Neplatné přihlášení"
czechMessage NowLoggedIn = "Přihlášení proběhlo úspěšně"
czechMessage LoginTitle = "Přihlásit"
czechMessage PleaseProvideUsername = "Prosím, zadejte svoje uživatelské jméno"
czechMessage PleaseProvidePassword = "Prosím, zadejte svoje heslo"
czechMessage NoIdentifierProvided = "Nebyl poskytnut žádný e-mail nebo uživatelské jméno"
czechMessage InvalidEmailAddress = "Zadaná e-mailová adresa je neplatná"
czechMessage PasswordResetTitle = "Obnovení hesla"
czechMessage ProvideIdentifier = "E-mail nebo uživatelské jméno"
czechMessage SendPasswordResetEmail = "Poslat e-mail pro obnovení hesla"
czechMessage PasswordResetPrompt = "Zadejte svou e-mailovou adresu nebo uživatelské jméno a bude vám poslán email pro obnovení hesla."
czechMessage InvalidUsernamePass = "Neplatná kombinace uživatelského jména a hesla"
TODO
czechMessage i@(IdentifierNotFound _) = englishMessage i
FIXME by Google Translate
FIXME by Google Translate
FIXME by Google Translate
- mail – это фактическое сокращение словосочетания electronic mail ,
для русского перевода так же использовано : эл.почта
russianMessage :: AuthMessage -> Text
russianMessage NoOpenID = "Идентификатор OpenID не найден"
russianMessage LoginOpenID = "Вход с помощью OpenID"
russianMessage LoginGoogle = "Вход с помощью Google"
russianMessage LoginYahoo = "Вход с помощью Yahoo"
russianMessage Email = "Эл.почта"
russianMessage UserName = "Имя пользователя"
russianMessage Password = "Пароль"
russianMessage CurrentPassword = "Старый пароль"
russianMessage Register = "Регистрация"
russianMessage RegisterLong = "Создать учётную запись"
russianMessage EnterEmail = "Введите свой адрес эл.почты ниже, вам будет отправлено письмо для подтверждения."
russianMessage ConfirmationEmailSentTitle = "Письмо для подтверждения отправлено"
russianMessage (ConfirmationEmailSent email) =
"Письмо для подтверждения было отправлено на адрес " `mappend`
email `mappend`
"."
russianMessage AddressVerified = "Адрес подтверждён. Пожалуйста, установите новый пароль."
russianMessage EmailVerifiedChangePass = "Адрес подтверждён. Пожалуйста, установите новый пароль."
russianMessage EmailVerified = "Адрес подтверждён"
russianMessage InvalidKeyTitle = "Неверный ключ подтверждения"
russianMessage InvalidKey = "Извините, но ключ подтверждения оказался недействительным."
russianMessage InvalidEmailPass = "Неверное сочетание эл.почты и пароля"
russianMessage BadSetPass = "Чтобы изменить пароль, необходимо выполнить вход"
russianMessage SetPassTitle = "Установить пароль"
russianMessage SetPass = "Установить новый пароль"
russianMessage NewPass = "Новый пароль"
russianMessage ConfirmPass = "Подтверждение пароля"
russianMessage PassMismatch = "Пароли не совпадают, повторите снова"
russianMessage PassUpdated = "Пароль обновлён"
russianMessage Facebook = "Войти с помощью Facebook"
russianMessage LoginViaEmail = "Войти по адресу эл.почты"
russianMessage InvalidLogin = "Неверный логин"
russianMessage NowLoggedIn = "Вход выполнен"
russianMessage LoginTitle = "Войти"
russianMessage PleaseProvideUsername = "Пожалуйста, введите ваше имя пользователя"
russianMessage PleaseProvidePassword = "Пожалуйста, введите ваш пароль"
russianMessage NoIdentifierProvided = "Не указан адрес эл.почты/имя пользователя"
russianMessage InvalidEmailAddress = "Указан неверный адрес эл.почты"
russianMessage PasswordResetTitle = "Сброс пароля"
russianMessage ProvideIdentifier = "Имя пользователя или эл.почта"
russianMessage SendPasswordResetEmail = "Отправить письмо для сброса пароля"
russianMessage PasswordResetPrompt = "Введите адрес эл.почты или ваше имя пользователя ниже, вам будет отправлено письмо для сброса пароля."
russianMessage InvalidUsernamePass = "Неверное сочетание имени пользователя и пароля"
russianMessage (IdentifierNotFound ident) = "Логин не найден: " `mappend` ident
russianMessage Logout = "Выйти"
russianMessage LogoutTitle = "Выйти"
russianMessage AuthError = "Ошибка аутентификации"
dutchMessage :: AuthMessage -> Text
dutchMessage NoOpenID = "Geen OpenID identificator gevonden"
dutchMessage LoginOpenID = "Inloggen via OpenID"
dutchMessage LoginGoogle = "Inloggen via Google"
dutchMessage LoginYahoo = "Inloggen via Yahoo"
dutchMessage Email = "E-mail"
dutchMessage UserName = "Gebruikersnaam"
dutchMessage Password = "Wachtwoord"
dutchMessage CurrentPassword = "Huidig wachtwoord"
dutchMessage Register = "Registreren"
dutchMessage RegisterLong = "Registreer een nieuw account"
dutchMessage EnterEmail = "Voer uw e-mailadres hieronder in, er zal een bevestigings-e-mail naar u worden verzonden."
dutchMessage ConfirmationEmailSentTitle = "Bevestigings-e-mail verzonden"
dutchMessage (ConfirmationEmailSent email) =
"Een bevestigings-e-mail is verzonden naar " `mappend`
email `mappend`
"."
dutchMessage AddressVerified = "Adres geverifieerd, stel alstublieft een nieuwe wachtwoord in"
dutchMessage EmailVerifiedChangePass = "Adres geverifieerd, stel alstublieft een nieuwe wachtwoord in"
dutchMessage EmailVerified = "Adres geverifieerd"
dutchMessage InvalidKeyTitle = "Ongeldig verificatietoken"
dutchMessage InvalidKey = "Dat was helaas een ongeldig verificatietoken."
dutchMessage InvalidEmailPass = "Ongeldige e-mailadres/wachtwoord combinatie"
dutchMessage BadSetPass = "U moet ingelogd zijn om een nieuwe wachtwoord in te stellen"
dutchMessage SetPassTitle = "Wachtwoord instellen"
dutchMessage SetPass = "Een nieuwe wachtwoord instellen"
dutchMessage NewPass = "Nieuw wachtwoord"
dutchMessage ConfirmPass = "Bevestig"
dutchMessage PassMismatch = "Wachtwoorden kwamen niet overeen, probeer het alstublieft nog eens"
dutchMessage PassUpdated = "Wachtwoord geüpdatet"
dutchMessage Facebook = "Inloggen met Facebook"
dutchMessage LoginViaEmail = "Inloggen via e-mail"
dutchMessage InvalidLogin = "Ongeldige inloggegevens"
dutchMessage NowLoggedIn = "U bent nu ingelogd"
dutchMessage LoginTitle = "Inloggen"
dutchMessage PleaseProvideUsername = "Voer alstublieft uw gebruikersnaam in"
dutchMessage PleaseProvidePassword = "Voer alstublieft uw wachtwoord in"
dutchMessage NoIdentifierProvided = "Geen e-mailadres/gebruikersnaam opgegeven"
dutchMessage InvalidEmailAddress = "Ongeldig e-mailadres opgegeven"
dutchMessage PasswordResetTitle = "Wachtwoord wijzigen"
dutchMessage ProvideIdentifier = "E-mailadres of gebruikersnaam"
dutchMessage SendPasswordResetEmail = "Stuur een wachtwoord reset e-mail"
dutchMessage PasswordResetPrompt = "Voer uw e-mailadres of gebruikersnaam hieronder in, er zal een e-mail naar u worden verzonden waarmee u uw wachtwoord kunt wijzigen."
dutchMessage InvalidUsernamePass = "Ongeldige gebruikersnaam/wachtwoord combinatie"
dutchMessage (IdentifierNotFound ident) = "Inloggegevens niet gevonden: " `mappend` ident
dutchMessage Logout = "Uitloggen"
dutchMessage LogoutTitle = "Uitloggen"
dutchMessage AuthError = "Verificatiefout"
croatianMessage :: AuthMessage -> Text
croatianMessage NoOpenID = "Nije pronađen OpenID identifikator"
croatianMessage LoginOpenID = "Prijava uz OpenID"
croatianMessage LoginGoogle = "Prijava uz Google"
croatianMessage LoginYahoo = "Prijava uz Yahoo"
croatianMessage Facebook = "Prijava uz Facebook"
croatianMessage LoginViaEmail = "Prijava putem e-pošte"
croatianMessage Email = "E-pošta"
croatianMessage UserName = "Korisničko ime"
croatianMessage Password = "Lozinka"
croatianMessage CurrentPassword = "Current Password"
croatianMessage Register = "Registracija"
croatianMessage RegisterLong = "Registracija novog računa"
croatianMessage EnterEmail = "Dolje unesite adresu e-pošte, pa ćemo vam poslati e-poruku za potvrdu."
croatianMessage PasswordResetPrompt = "Dolje unesite adresu e-pošte ili korisničko ime, pa ćemo vam poslati e-poruku za potvrdu."
croatianMessage ConfirmationEmailSentTitle = "E-poruka za potvrdu"
croatianMessage (ConfirmationEmailSent email) = "E-poruka za potvrdu poslana je na adresu " <> email <> "."
croatianMessage AddressVerified = "Adresa ovjerena, postavite novu lozinku"
croatianMessage EmailVerifiedChangePass = "Adresa ovjerena, postavite novu lozinku"
croatianMessage EmailVerified = "Adresa ovjerena"
croatianMessage InvalidKeyTitle = "Ključ za ovjeru nije valjan"
croatianMessage InvalidKey = "Nažalost, taj ključ za ovjeru nije valjan."
croatianMessage InvalidEmailPass = "Kombinacija e-pošte i lozinke nije valjana"
croatianMessage InvalidUsernamePass = "Kombinacija korisničkog imena i lozinke nije valjana"
croatianMessage BadSetPass = "Za postavljanje lozinke morate biti prijavljeni"
croatianMessage SetPassTitle = "Postavi lozinku"
croatianMessage SetPass = "Postavite novu lozinku"
croatianMessage NewPass = "Nova lozinka"
croatianMessage ConfirmPass = "Potvrda lozinke"
croatianMessage PassMismatch = "Lozinke se ne podudaraju, pokušajte ponovo"
croatianMessage PassUpdated = "Lozinka ažurirana"
croatianMessage InvalidLogin = "Prijava nije valjana"
croatianMessage NowLoggedIn = "Sada ste prijavljeni u"
croatianMessage LoginTitle = "Prijava"
croatianMessage PleaseProvideUsername = "Unesite korisničko ime"
croatianMessage PleaseProvidePassword = "Unesite lozinku"
croatianMessage NoIdentifierProvided = "Nisu dani e-pošta/korisničko ime"
croatianMessage InvalidEmailAddress = "Dana adresa e-pošte nije valjana"
croatianMessage PasswordResetTitle = "Poništavanje lozinke"
croatianMessage ProvideIdentifier = "E-pošta ili korisničko ime"
croatianMessage SendPasswordResetEmail = "Pošalji e-poruku za poništavanje lozinke"
croatianMessage (IdentifierNotFound ident) = "Korisničko ime/e-pošta nisu pronađeni: " <> ident
croatianMessage Logout = "Odjava"
croatianMessage LogoutTitle = "Odjava"
croatianMessage AuthError = "Pogreška provjere autentičnosti"
danishMessage :: AuthMessage -> Text
danishMessage NoOpenID = "Mangler OpenID identifier"
danishMessage LoginOpenID = "Login med OpenID"
danishMessage LoginGoogle = "Login med Google"
danishMessage LoginYahoo = "Login med Yahoo"
danishMessage Email = "E-mail"
danishMessage UserName = "Brugernavn"
danishMessage Password = "Kodeord"
danishMessage CurrentPassword = "Nuværende kodeord"
danishMessage Register = "Opret"
danishMessage RegisterLong = "Opret en ny konto"
danishMessage EnterEmail = "Indtast din e-mailadresse nedenfor og en bekræftelsesmail vil blive sendt til dig."
danishMessage ConfirmationEmailSentTitle = "Bekræftelsesmail sendt"
danishMessage (ConfirmationEmailSent email) =
"En bekræftelsesmail er sendt til " `mappend`
email `mappend`
"."
danishMessage AddressVerified = "Adresse bekræftet, sæt venligst et nyt kodeord"
danishMessage EmailVerifiedChangePass = "Adresse bekræftet, sæt venligst et nyt kodeord"
danishMessage EmailVerified = "Adresse bekræftet"
danishMessage InvalidKeyTitle = "Ugyldig verifikationsnøgle"
danishMessage InvalidKey = "Beklager, det var en ugyldigt verifikationsnøgle."
danishMessage InvalidEmailPass = "Ugyldigt e-mail/kodeord"
danishMessage BadSetPass = "Du skal være logget ind for at sætte et kodeord"
danishMessage SetPassTitle = "Sæt kodeord"
danishMessage SetPass = "Sæt et nyt kodeord"
danishMessage NewPass = "Nyt kodeord"
danishMessage ConfirmPass = "Bekræft"
danishMessage PassMismatch = "Kodeordne var forskellige, prøv venligst igen"
danishMessage PassUpdated = "Kodeord opdateret"
danishMessage Facebook = "Login med Facebook"
danishMessage LoginViaEmail = "Login med e-mail"
danishMessage InvalidLogin = "Ugyldigt login"
danishMessage NowLoggedIn = "Du er nu logget ind"
danishMessage LoginTitle = "Log ind"
danishMessage PleaseProvideUsername = "Indtast venligst dit brugernavn"
danishMessage PleaseProvidePassword = "Indtasy venligst dit kodeord"
danishMessage NoIdentifierProvided = "Mangler e-mail/username"
danishMessage InvalidEmailAddress = "Ugyldig e-mailadresse indtastet"
danishMessage PasswordResetTitle = "Nulstilning af kodeord"
danishMessage ProvideIdentifier = "E-mail eller brugernavn"
danishMessage SendPasswordResetEmail = "Send kodeordsnulstillingsmail"
danishMessage PasswordResetPrompt = "Indtast din e-mailadresse eller dit brugernavn nedenfor, så bliver en kodeordsnulstilningsmail sendt til dig."
danishMessage InvalidUsernamePass = "Ugyldigt brugernavn/kodeord"
danishMessage (IdentifierNotFound ident) = "Brugernavn findes ikke: " `mappend` ident
danishMessage Logout = "Log ud"
danishMessage LogoutTitle = "Log ud"
danishMessage AuthError = "Fejl ved bekræftelse af identitet"
koreanMessage :: AuthMessage -> Text
koreanMessage NoOpenID = "OpenID ID가 없습니다"
koreanMessage LoginOpenID = "OpenID로 로그인"
koreanMessage LoginGoogle = "Google로 로그인"
koreanMessage LoginYahoo = "Yahoo로 로그인"
koreanMessage Email = "이메일"
koreanMessage UserName = "사용자 이름"
koreanMessage Password = "비밀번호"
koreanMessage CurrentPassword = "현재 비밀번호"
koreanMessage Register = "등록"
koreanMessage RegisterLong = "새 계정 등록"
koreanMessage EnterEmail = "이메일 주소를 아래에 입력하시면 확인 이메일이 발송됩니다."
koreanMessage ConfirmationEmailSentTitle = "확인 이메일을 보냈습니다"
koreanMessage (ConfirmationEmailSent email) =
"확인 이메일을 " `mappend`
email `mappend`
"에 보냈습니다."
koreanMessage AddressVerified = "주소가 인증되었습니다. 새 비밀번호를 설정하세요."
koreanMessage EmailVerifiedChangePass = "주소가 인증되었습니다. 새 비밀번호를 설정하세요."
koreanMessage EmailVerified = "주소가 인증되었습니다"
koreanMessage InvalidKeyTitle = "인증키가 잘못되었습니다"
koreanMessage InvalidKey = "죄송합니다. 잘못된 인증키입니다."
koreanMessage InvalidEmailPass = "이메일 주소나 비밀번호가 잘못되었습니다"
koreanMessage BadSetPass = "비밀번호를 설정하기 위해서는 로그인해야 합니다"
koreanMessage SetPassTitle = "비밀번호 설정"
koreanMessage SetPass = "새 비밀번호 설정"
koreanMessage NewPass = "새 비밀번호"
koreanMessage ConfirmPass = "확인"
koreanMessage PassMismatch = "비밀번호가 맞지 않습니다. 다시 시도해주세요."
koreanMessage PassUpdated = "비밀번호가 업데이트 되었습니다"
koreanMessage Facebook = "Facebook으로 로그인"
koreanMessage LoginViaEmail = "이메일로"
koreanMessage InvalidLogin = "잘못된 로그인입니다"
koreanMessage NowLoggedIn = "로그인했습니다"
koreanMessage LoginTitle = "로그인"
koreanMessage PleaseProvideUsername = "사용자 이름을 입력하세요"
koreanMessage PleaseProvidePassword = "비밀번호를 입력하세요"
koreanMessage NoIdentifierProvided = "이메일 주소나 사용자 이름이 입력되어 있지 않습니다"
koreanMessage InvalidEmailAddress = "이메일 주소가 잘못되었습니다"
koreanMessage PasswordResetTitle = "비밀번호 변경"
koreanMessage ProvideIdentifier = "이메일 주소나 사용자 이름"
koreanMessage SendPasswordResetEmail = "비밀번호 재설정 이메일 보내기"
koreanMessage PasswordResetPrompt = "이메일 주소나 사용자 이름을 아래에 입력하시면 비밀번호 재설정 이메일이 발송됩니다."
koreanMessage InvalidUsernamePass = "사용자 이름이나 비밀번호가 잘못되었습니다"
koreanMessage (IdentifierNotFound ident) = ident `mappend` "는 등록되어 있지 않습니다"
koreanMessage Logout = "로그아웃"
koreanMessage LogoutTitle = "로그아웃"
koreanMessage AuthError = "인증오류"
| null | https://raw.githubusercontent.com/yesodweb/yesod/f30f96ee41feef9562b1880ed5a3dc9dfa81d0b1/yesod-auth/Yesod/Auth/Message.hs | haskell | # LANGUAGE OverloadedStrings #
* All languages
| Defaults to 'englishMessage'. | module Yesod.Auth.Message
( AuthMessage (..)
, defaultMessage
, englishMessage
, portugueseMessage
, swedishMessage
, germanMessage
, frenchMessage
, norwegianBokmålMessage
, japaneseMessage
, finnishMessage
, chineseMessage
, croatianMessage
, spanishMessage
, czechMessage
, russianMessage
, dutchMessage
, danishMessage
, koreanMessage
) where
import Data.Monoid (mappend, (<>))
import Data.Text (Text)
data AuthMessage =
NoOpenID
| LoginOpenID
| LoginGoogle
| LoginYahoo
| Email
| UserName
| IdentifierNotFound Text
| Password
| Register
| RegisterLong
| EnterEmail
| ConfirmationEmailSentTitle
| ConfirmationEmailSent Text
| AddressVerified
| EmailVerifiedChangePass
| EmailVerified
| InvalidKeyTitle
| InvalidKey
| InvalidEmailPass
| BadSetPass
| SetPassTitle
| SetPass
| NewPass
| ConfirmPass
| PassMismatch
| PassUpdated
| Facebook
| LoginViaEmail
| InvalidLogin
| NowLoggedIn
| LoginTitle
| PleaseProvideUsername
| PleaseProvidePassword
| NoIdentifierProvided
| InvalidEmailAddress
| PasswordResetTitle
| ProvideIdentifier
| SendPasswordResetEmail
| PasswordResetPrompt
| CurrentPassword
| InvalidUsernamePass
| Logout
| LogoutTitle
| AuthError
# DEPRECATED Logout " Please , use LogoutTitle instead . " #
# DEPRECATED AddressVerified " Please , use instead . " #
defaultMessage :: AuthMessage -> Text
defaultMessage = englishMessage
englishMessage :: AuthMessage -> Text
englishMessage NoOpenID = "No OpenID identifier found"
englishMessage LoginOpenID = "Log in via OpenID"
englishMessage LoginGoogle = "Log in via Google"
englishMessage LoginYahoo = "Log in via Yahoo"
englishMessage Email = "Email"
englishMessage UserName = "User name"
englishMessage Password = "Password"
englishMessage CurrentPassword = "Current Password"
englishMessage Register = "Register"
englishMessage RegisterLong = "Register a new account"
englishMessage EnterEmail = "Enter your e-mail address below, and a confirmation e-mail will be sent to you."
englishMessage ConfirmationEmailSentTitle = "Confirmation e-mail sent"
englishMessage (ConfirmationEmailSent email) =
"A confirmation e-mail has been sent to " `Data.Monoid.mappend`
email `mappend`
"."
englishMessage AddressVerified = "Email address verified, please set a new password"
englishMessage EmailVerifiedChangePass = "Email address verified, please set a new password"
englishMessage EmailVerified = "Email address verified"
englishMessage InvalidKeyTitle = "Invalid verification key"
englishMessage InvalidKey = "I'm sorry, but that was an invalid verification key."
englishMessage InvalidEmailPass = "Invalid email/password combination"
englishMessage BadSetPass = "You must be logged in to set a password"
englishMessage SetPassTitle = "Set password"
englishMessage SetPass = "Set a new password"
englishMessage NewPass = "New password"
englishMessage ConfirmPass = "Confirm"
englishMessage PassMismatch = "Passwords did not match, please try again"
englishMessage PassUpdated = "Password updated"
englishMessage Facebook = "Log in with Facebook"
englishMessage LoginViaEmail = "Log in via email"
englishMessage InvalidLogin = "Invalid login"
englishMessage NowLoggedIn = "You are now logged in"
englishMessage LoginTitle = "Log In"
englishMessage PleaseProvideUsername = "Please fill in your username"
englishMessage PleaseProvidePassword = "Please fill in your password"
englishMessage NoIdentifierProvided = "No email/username provided"
englishMessage InvalidEmailAddress = "Invalid email address provided"
englishMessage PasswordResetTitle = "Password Reset"
englishMessage ProvideIdentifier = "Email or Username"
englishMessage SendPasswordResetEmail = "Send password reset email"
englishMessage PasswordResetPrompt = "Enter your e-mail address or username below, and a password reset e-mail will be sent to you."
englishMessage InvalidUsernamePass = "Invalid username/password combination"
englishMessage (IdentifierNotFound ident) = "Login not found: " `mappend` ident
englishMessage Logout = "Log Out"
englishMessage LogoutTitle = "Log Out"
FIXME by Google Translate
portugueseMessage :: AuthMessage -> Text
portugueseMessage NoOpenID = "Nenhum identificador OpenID encontrado"
portugueseMessage LoginOpenID = "Entrar via OpenID"
portugueseMessage LoginGoogle = "Entrar via Google"
portugueseMessage LoginYahoo = "Entrar via Yahoo"
portugueseMessage Email = "E-mail"
FIXME by Google Translate " user name "
portugueseMessage Password = "Senha"
portugueseMessage CurrentPassword = "Palavra de passe"
portugueseMessage Register = "Registrar"
portugueseMessage RegisterLong = "Registrar uma nova conta"
portugueseMessage EnterEmail = "Por favor digite seu endereço de e-mail abaixo e um e-mail de confirmação será enviado para você."
portugueseMessage ConfirmationEmailSentTitle = "E-mail de confirmação enviado"
portugueseMessage (ConfirmationEmailSent email) =
"Um e-mail de confirmação foi enviado para " `mappend`
email `mappend`
"."
portugueseMessage AddressVerified = "Endereço verificado, por favor entre com uma nova senha"
portugueseMessage EmailVerifiedChangePass = "Endereço verificado, por favor entre com uma nova senha"
portugueseMessage EmailVerified = "Endereço verificado"
portugueseMessage InvalidKeyTitle = "Chave de verificação inválida"
portugueseMessage InvalidKey = "Por favor nos desculpe, mas essa é uma chave de verificação inválida."
portugueseMessage InvalidEmailPass = "E-mail e/ou senha inválidos"
portugueseMessage BadSetPass = "Você deve entrar para definir uma senha"
portugueseMessage SetPassTitle = "Definir senha"
portugueseMessage SetPass = "Definir uma nova senha"
portugueseMessage NewPass = "Nova senha"
portugueseMessage ConfirmPass = "Confirmar"
portugueseMessage PassMismatch = "Senhas não conferem, por favor tente novamente"
portugueseMessage PassUpdated = "Senhas alteradas"
portugueseMessage Facebook = "Entrar via Facebook"
portugueseMessage LoginViaEmail = "Entrar via e-mail"
portugueseMessage InvalidLogin = "Informações de login inválidas"
portugueseMessage NowLoggedIn = "Você acaba de entrar no site com sucesso!"
portugueseMessage LoginTitle = "Entrar no site"
portugueseMessage PleaseProvideUsername = "Por favor digite seu nome de usuário"
portugueseMessage PleaseProvidePassword = "Por favor digite sua senha"
portugueseMessage NoIdentifierProvided = "Nenhum e-mail ou nome de usuário informado"
portugueseMessage InvalidEmailAddress = "Endereço de e-mail inválido informado"
portugueseMessage PasswordResetTitle = "Resetar senha"
portugueseMessage ProvideIdentifier = "E-mail ou nome de usuário"
portugueseMessage SendPasswordResetEmail = "Enviar e-mail para resetar senha"
portugueseMessage PasswordResetPrompt = "Insira seu endereço de e-mail ou nome de usuário abaixo. Um e-mail para resetar sua senha será enviado para você."
portugueseMessage InvalidUsernamePass = "Nome de usuário ou senha inválidos"
TODO
portugueseMessage i@(IdentifierNotFound _) = englishMessage i
FIXME by Google Translate
FIXME by Google Translate
FIXME by Google Translate
spanishMessage :: AuthMessage -> Text
spanishMessage NoOpenID = "No se encuentra el identificador OpenID"
spanishMessage LoginOpenID = "Entrar utilizando OpenID"
spanishMessage LoginGoogle = "Entrar utilizando Google"
spanishMessage LoginYahoo = "Entrar utilizando Yahoo"
spanishMessage Email = "Correo electrónico"
spanishMessage UserName = "Nombre de Usuario"
spanishMessage Password = "Contraseña"
spanishMessage CurrentPassword = "Contraseña actual"
spanishMessage Register = "Registrarse"
spanishMessage RegisterLong = "Registrar una nueva cuenta"
spanishMessage EnterEmail = "Coloque su dirección de correo electrónico, y un correo de confirmación le será enviado a su cuenta."
spanishMessage ConfirmationEmailSentTitle = "La confirmación de correo ha sido enviada"
spanishMessage (ConfirmationEmailSent email) =
"Una confirmación de correo electrónico ha sido enviada a " `mappend`
email `mappend`
"."
spanishMessage AddressVerified = "Dirección verificada, por favor introduzca una contraseña"
spanishMessage EmailVerifiedChangePass = "Dirección verificada, por favor introduzca una contraseña"
spanishMessage EmailVerified = "Dirección verificada"
spanishMessage InvalidKeyTitle = "Clave de verificación invalida"
spanishMessage InvalidKey = "Lo sentimos, pero esa clave de verificación es inválida."
spanishMessage InvalidEmailPass = "La combinación cuenta de correo/contraseña es inválida"
spanishMessage BadSetPass = "Debe acceder a la aplicación para modificar la contraseña"
spanishMessage SetPassTitle = "Modificar contraseña"
spanishMessage SetPass = "Actualizar nueva contraseña"
spanishMessage NewPass = "Nueva contraseña"
spanishMessage ConfirmPass = "Confirmar"
spanishMessage PassMismatch = "Las contraseñas no coinciden, inténtelo de nuevo"
spanishMessage PassUpdated = "Contraseña actualizada"
spanishMessage Facebook = "Entrar mediante Facebook"
spanishMessage LoginViaEmail = "Entrar mediante una cuenta de correo"
spanishMessage InvalidLogin = "Login inválido"
spanishMessage NowLoggedIn = "Usted ha ingresado al sitio"
spanishMessage LoginTitle = "Log In"
spanishMessage PleaseProvideUsername = "Por favor escriba su nombre de usuario"
spanishMessage PleaseProvidePassword = "Por favor escriba su contraseña"
spanishMessage NoIdentifierProvided = "No ha indicado una cuenta de correo/nombre de usuario"
spanishMessage InvalidEmailAddress = "La cuenta de correo es inválida"
spanishMessage PasswordResetTitle = "Actualización de contraseña"
spanishMessage ProvideIdentifier = "Cuenta de correo o nombre de usuario"
spanishMessage SendPasswordResetEmail = "Enviar correo de actualización de contraseña"
spanishMessage PasswordResetPrompt = "Escriba su cuenta de correo o nombre de usuario, y una confirmación de actualización de contraseña será enviada a su cuenta de correo."
spanishMessage InvalidUsernamePass = "Combinación de nombre de usuario/contraseña invalida"
TODO
spanishMessage i@(IdentifierNotFound _) = englishMessage i
FIXME by Google Translate
FIXME by Google Translate
FIXME by Google Translate
swedishMessage :: AuthMessage -> Text
swedishMessage NoOpenID = "Fann ej OpenID identifierare"
swedishMessage LoginOpenID = "Logga in via OpenID"
swedishMessage LoginGoogle = "Logga in via Google"
swedishMessage LoginYahoo = "Logga in via Yahoo"
swedishMessage Email = "Epost"
FIXME by Google Translate " user name "
swedishMessage Password = "Lösenord"
swedishMessage CurrentPassword = "Current password"
swedishMessage Register = "Registrera"
swedishMessage RegisterLong = "Registrera ett nytt konto"
swedishMessage EnterEmail = "Skriv in din epost nedan så kommer ett konfirmationsmail skickas till adressen."
swedishMessage ConfirmationEmailSentTitle = "Konfirmationsmail skickat"
swedishMessage (ConfirmationEmailSent email) =
"Ett konfirmationsmeddelande har skickats till" `mappend`
email `mappend`
"."
swedishMessage AddressVerified = "Adress verifierad, vänligen välj nytt lösenord"
swedishMessage EmailVerifiedChangePass = "Adress verifierad, vänligen välj nytt lösenord"
swedishMessage EmailVerified = "Adress verifierad"
swedishMessage InvalidKeyTitle = "Ogiltig verifikationsnyckel"
swedishMessage InvalidKey = "Tyvärr, du angav en ogiltig verifimationsnyckel."
swedishMessage InvalidEmailPass = "Ogiltig epost/lösenord kombination"
swedishMessage BadSetPass = "Du måste vara inloggad för att ange ett lösenord"
swedishMessage SetPassTitle = "Ange lösenord"
swedishMessage SetPass = "Ange nytt lösenord"
swedishMessage NewPass = "Nytt lösenord"
swedishMessage ConfirmPass = "Godkänn"
swedishMessage PassMismatch = "Lösenorden matcha ej, vänligen försök igen"
swedishMessage PassUpdated = "Lösenord updaterades"
swedishMessage Facebook = "Logga in med Facebook"
swedishMessage LoginViaEmail = "Logga in via epost"
swedishMessage InvalidLogin = "Ogiltigt login"
swedishMessage NowLoggedIn = "Du är nu inloggad"
swedishMessage LoginTitle = "Logga in"
swedishMessage PleaseProvideUsername = "Vänligen fyll i användarnamn"
swedishMessage PleaseProvidePassword = "Vänligen fyll i lösenord"
swedishMessage NoIdentifierProvided = "Emailadress eller användarnamn saknas"
swedishMessage InvalidEmailAddress = "Ogiltig emailadress angiven"
swedishMessage PasswordResetTitle = "Återställning av lösenord"
swedishMessage ProvideIdentifier = "Epost eller användarnamn"
swedishMessage SendPasswordResetEmail = "Skicka email för återställning av lösenord"
swedishMessage PasswordResetPrompt = "Skriv in din emailadress eller användarnamn nedan och " `mappend`
"ett email för återställning av lösenord kommmer att skickas till dig."
swedishMessage InvalidUsernamePass = "Ogiltig kombination av användarnamn och lösenord"
TODO
swedishMessage i@(IdentifierNotFound _) = englishMessage i
FIXME by Google Translate
FIXME by Google Translate
FIXME by Google Translate
germanMessage :: AuthMessage -> Text
germanMessage NoOpenID = "Kein OpenID-Identifier gefunden"
germanMessage LoginOpenID = "Login via OpenID"
germanMessage LoginGoogle = "Login via Google"
germanMessage LoginYahoo = "Login via Yahoo"
germanMessage Email = "E-Mail"
germanMessage UserName = "Benutzername"
germanMessage Password = "Passwort"
germanMessage CurrentPassword = "Aktuelles Passwort"
germanMessage Register = "Registrieren"
germanMessage RegisterLong = "Neuen Account registrieren"
germanMessage EnterEmail = "Bitte die E-Mail Adresse angeben, eine Bestätigungsmail wird verschickt."
germanMessage ConfirmationEmailSentTitle = "Bestätigung verschickt."
germanMessage (ConfirmationEmailSent email) =
"Eine Bestätigung wurde an " `mappend`
email `mappend`
" versandt."
germanMessage AddressVerified = "Adresse bestätigt, bitte neues Passwort angeben"
germanMessage EmailVerifiedChangePass = "Adresse bestätigt, bitte neues Passwort angeben"
germanMessage EmailVerified = "Adresse bestätigt"
germanMessage InvalidKeyTitle = "Ungültiger Bestätigungsschlüssel"
germanMessage InvalidKey = "Das war leider ein ungültiger Bestätigungsschlüssel"
germanMessage InvalidEmailPass = "Ungültiger Nutzername oder Passwort"
germanMessage BadSetPass = "Um das Passwort zu ändern muss man eingeloggt sein"
germanMessage SetPassTitle = "Passwort angeben"
germanMessage SetPass = "Neues Passwort angeben"
germanMessage NewPass = "Neues Passwort"
germanMessage ConfirmPass = "Bestätigen"
germanMessage PassMismatch = "Die Passwörter stimmen nicht überein"
germanMessage PassUpdated = "Passwort überschrieben"
germanMessage Facebook = "Login über Facebook"
germanMessage LoginViaEmail = "Login via E-Mail"
germanMessage InvalidLogin = "Ungültiger Login"
germanMessage NowLoggedIn = "Login erfolgreich"
germanMessage LoginTitle = "Anmelden"
germanMessage PleaseProvideUsername = "Bitte Nutzername angeben"
germanMessage PleaseProvidePassword = "Bitte Passwort angeben"
germanMessage NoIdentifierProvided = "Keine E-Mail-Adresse oder kein Nutzername angegeben"
germanMessage InvalidEmailAddress = "Unzulässiger E-Mail-Anbieter"
germanMessage PasswordResetTitle = "Passwort zurücksetzen"
germanMessage ProvideIdentifier = "E-Mail-Adresse oder Nutzername"
germanMessage SendPasswordResetEmail = "E-Mail zusenden um Passwort zurückzusetzen"
germanMessage PasswordResetPrompt = "Nach Einhabe der E-Mail-Adresse oder des Nutzernamen wird eine E-Mail zugesendet mit welcher das Passwort zurückgesetzt werden kann."
germanMessage InvalidUsernamePass = "Ungültige Kombination aus Nutzername und Passwort"
TODO
germanMessage Logout = "Abmelden"
germanMessage LogoutTitle = "Abmelden"
germanMessage AuthError = "Fehler beim Anmelden"
frenchMessage :: AuthMessage -> Text
frenchMessage NoOpenID = "Aucun fournisseur OpenID n'a été trouvé"
frenchMessage LoginOpenID = "Se connecter avec OpenID"
frenchMessage LoginGoogle = "Se connecter avec Google"
frenchMessage LoginYahoo = "Se connecter avec Yahoo"
frenchMessage Email = "Adresse électronique"
FIXME by Google Translate " user name "
frenchMessage Password = "Mot de passe"
frenchMessage CurrentPassword = "Mot de passe actuel"
frenchMessage Register = "S'inscrire"
frenchMessage RegisterLong = "Créer un compte"
frenchMessage EnterEmail = "Entrez ci-dessous votre adresse électronique, et un message de confirmation vous sera envoyé"
frenchMessage ConfirmationEmailSentTitle = "Message de confirmation"
frenchMessage (ConfirmationEmailSent email) =
"Un message de confirmation a été envoyé à " `mappend`
email `mappend`
"."
frenchMessage AddressVerified = "Votre adresse électronique a été validée, merci de choisir un nouveau mot de passe."
frenchMessage EmailVerifiedChangePass = "Votre adresse électronique a été validée, merci de choisir un nouveau mot de passe."
frenchMessage EmailVerified = "Votre adresse électronique a été validée"
frenchMessage InvalidKeyTitle = "Clef de validation incorrecte"
frenchMessage InvalidKey = "Désolé, mais cette clef de validation est incorrecte"
frenchMessage InvalidEmailPass = "La combinaison de ce mot de passe et de cette adresse électronique n'existe pas."
frenchMessage BadSetPass = "Vous devez être connecté pour choisir un mot de passe"
frenchMessage SetPassTitle = "Changer de mot de passe"
frenchMessage SetPass = "Choisir un nouveau mot de passe"
frenchMessage NewPass = "Nouveau mot de passe"
frenchMessage ConfirmPass = "Confirmation du mot de passe"
frenchMessage PassMismatch = "Le deux mots de passe sont différents, veuillez les corriger"
frenchMessage PassUpdated = "Le mot de passe a bien été changé"
frenchMessage Facebook = "Se connecter avec Facebook"
frenchMessage LoginViaEmail = "Se connecter avec une adresse électronique"
frenchMessage InvalidLogin = "Nom d'utilisateur incorrect"
frenchMessage NowLoggedIn = "Vous êtes maintenant connecté"
frenchMessage LoginTitle = "Se connecter"
frenchMessage PleaseProvideUsername = "Veuillez fournir votre nom d'utilisateur"
frenchMessage PleaseProvidePassword = "Veuillez fournir votre mot de passe"
frenchMessage NoIdentifierProvided = "Adresse électronique/nom d'utilisateur non spécifié"
frenchMessage InvalidEmailAddress = "Adresse électronique spécifiée invalide"
frenchMessage PasswordResetTitle = "Réinitialisation du mot de passe"
frenchMessage ProvideIdentifier = "Adresse électronique ou nom d'utilisateur"
frenchMessage SendPasswordResetEmail = "Envoi d'un courriel pour réinitialiser le mot de passe"
frenchMessage PasswordResetPrompt = "Entrez votre courriel ou votre nom d'utilisateur ci-dessous, et vous recevrez un message électronique pour réinitialiser votre mot de passe."
frenchMessage InvalidUsernamePass = "La combinaison de ce mot de passe et de ce nom d'utilisateur n'existe pas."
frenchMessage (IdentifierNotFound ident) = "Nom d'utilisateur introuvable: " `mappend` ident
frenchMessage Logout = "Déconnexion"
frenchMessage LogoutTitle = "Déconnexion"
FIXME by Google Translate
norwegianBokmålMessage :: AuthMessage -> Text
norwegianBokmålMessage NoOpenID = "Ingen OpenID-identifiserer funnet"
norwegianBokmålMessage LoginOpenID = "Logg inn med OpenID"
norwegianBokmålMessage LoginGoogle = "Logg inn med Google"
norwegianBokmålMessage LoginYahoo = "Logg inn med Yahoo"
norwegianBokmålMessage Email = "E-post"
FIXME by Google Translate " user name "
norwegianBokmålMessage Password = "Passord"
norwegianBokmålMessage CurrentPassword = "Current password"
norwegianBokmålMessage Register = "Registrer"
norwegianBokmålMessage RegisterLong = "Registrer en ny konto"
norwegianBokmålMessage EnterEmail = "Skriv inn e-postadressen din nedenfor og en e-postkonfirmasjon vil bli sendt."
norwegianBokmålMessage ConfirmationEmailSentTitle = "E-postkonfirmasjon sendt."
norwegianBokmålMessage (ConfirmationEmailSent email) =
"En e-postkonfirmasjon har blitt sendt til " `mappend`
email `mappend`
"."
norwegianBokmålMessage AddressVerified = "Adresse verifisert, vennligst sett et nytt passord."
norwegianBokmålMessage EmailVerifiedChangePass = "Adresse verifisert, vennligst sett et nytt passord."
norwegianBokmålMessage EmailVerified = "Adresse verifisert"
norwegianBokmålMessage InvalidKeyTitle = "Ugyldig verifiseringsnøkkel"
norwegianBokmålMessage InvalidKey = "Beklager, men det var en ugyldig verifiseringsnøkkel."
norwegianBokmålMessage InvalidEmailPass = "Ugyldig e-post/passord-kombinasjon"
norwegianBokmålMessage BadSetPass = "Du må være logget inn for å sette et passord."
norwegianBokmålMessage SetPassTitle = "Sett passord"
norwegianBokmålMessage SetPass = "Sett et nytt passord"
norwegianBokmålMessage NewPass = "Nytt passord"
norwegianBokmålMessage ConfirmPass = "Bekreft"
norwegianBokmålMessage PassMismatch = "Passordene stemte ikke overens, vennligst prøv igjen"
norwegianBokmålMessage PassUpdated = "Passord oppdatert"
norwegianBokmålMessage Facebook = "Logg inn med Facebook"
norwegianBokmålMessage LoginViaEmail = "Logg inn med e-post"
norwegianBokmålMessage InvalidLogin = "Ugyldig innlogging"
norwegianBokmålMessage NowLoggedIn = "Du er nå logget inn"
norwegianBokmålMessage LoginTitle = "Logg inn"
norwegianBokmålMessage PleaseProvideUsername = "Vennligst fyll inn ditt brukernavn"
norwegianBokmålMessage PleaseProvidePassword = "Vennligst fyll inn ditt passord"
norwegianBokmålMessage NoIdentifierProvided = "No email/username provided"
norwegianBokmålMessage InvalidEmailAddress = "Invalid email address provided"
norwegianBokmålMessage PasswordResetTitle = "Password Reset"
norwegianBokmålMessage ProvideIdentifier = "Email or Username"
norwegianBokmålMessage SendPasswordResetEmail = "Send password reset email"
norwegianBokmålMessage PasswordResetPrompt = "Enter your e-mail address or username below, and a password reset e-mail will be sent to you."
norwegianBokmålMessage InvalidUsernamePass = "Invalid username/password combination"
TODO
norwegianBokmålMessage i@(IdentifierNotFound _) = englishMessage i
FIXME by Google Translate
FIXME by Google Translate
FIXME by Google Translate
japaneseMessage :: AuthMessage -> Text
japaneseMessage NoOpenID = "OpenID識別子がありません"
japaneseMessage LoginOpenID = "OpenIDでログイン"
japaneseMessage LoginGoogle = "Googleでログイン"
japaneseMessage LoginYahoo = "Yahooでログイン"
japaneseMessage Email = "Eメール"
FIXME by Google Translate " user name "
japaneseMessage Password = "パスワード"
japaneseMessage CurrentPassword = "現在のパスワード"
japaneseMessage Register = "登録"
japaneseMessage RegisterLong = "新規アカウント登録"
japaneseMessage EnterEmail = "メールアドレスを入力してください。確認メールが送られます"
japaneseMessage ConfirmationEmailSentTitle = "確認メールを送信しました"
japaneseMessage (ConfirmationEmailSent email) =
"確認メールを " `mappend`
email `mappend`
" に送信しました"
japaneseMessage AddressVerified = "アドレスは認証されました。新しいパスワードを設定してください"
japaneseMessage EmailVerifiedChangePass = "アドレスは認証されました。新しいパスワードを設定してください"
japaneseMessage EmailVerified = "アドレスは認証されました"
japaneseMessage InvalidKeyTitle = "認証キーが無効です"
japaneseMessage InvalidKey = "申し訳ありません。無効な認証キーです"
japaneseMessage InvalidEmailPass = "メールアドレスまたはパスワードが無効です"
japaneseMessage BadSetPass = "パスワードを設定するためには、ログインしてください"
japaneseMessage SetPassTitle = "パスワードの設定"
japaneseMessage SetPass = "新しいパスワードを設定する"
japaneseMessage NewPass = "新しいパスワード"
japaneseMessage ConfirmPass = "確認"
japaneseMessage PassMismatch = "パスワードが合いません。もう一度試してください"
japaneseMessage PassUpdated = "パスワードは更新されました"
japaneseMessage Facebook = "Facebookでログイン"
japaneseMessage LoginViaEmail = "Eメールでログイン"
japaneseMessage InvalidLogin = "無効なログインです"
japaneseMessage NowLoggedIn = "ログインしました"
japaneseMessage LoginTitle = "ログイン"
japaneseMessage PleaseProvideUsername = "ユーザ名を入力してください"
japaneseMessage PleaseProvidePassword = "パスワードを入力してください"
japaneseMessage NoIdentifierProvided = "メールアドレス/ユーザ名が入力されていません"
japaneseMessage InvalidEmailAddress = "メールアドレスが無効です"
japaneseMessage PasswordResetTitle = "パスワードの再設定"
japaneseMessage ProvideIdentifier = "メールアドレスまたはユーザ名"
japaneseMessage SendPasswordResetEmail = "パスワード再設定用メールの送信"
japaneseMessage PasswordResetPrompt = "以下にメールアドレスまたはユーザ名を入力してください。パスワードを再設定するためのメールが送信されます。"
japaneseMessage InvalidUsernamePass = "ユーザ名とパスワードの組み合わせが間違っています"
japaneseMessage (IdentifierNotFound ident) =
ident `mappend` "は登録されていません"
FIXME by Google Translate
FIXME by Google Translate
FIXME by Google Translate
finnishMessage :: AuthMessage -> Text
finnishMessage NoOpenID = "OpenID-tunnistetta ei löydy"
finnishMessage LoginOpenID = "Kirjaudu OpenID-tilillä"
finnishMessage LoginGoogle = "Kirjaudu Google-tilillä"
finnishMessage LoginYahoo = "Kirjaudu Yahoo-tilillä"
finnishMessage Email = "Sähköposti"
FIXME by Google Translate " user name "
finnishMessage Password = "Salasana"
finnishMessage CurrentPassword = "Current password"
finnishMessage Register = "Luo uusi"
finnishMessage RegisterLong = "Luo uusi tili"
finnishMessage EnterEmail = "Kirjoita alle sähköpostiosoitteesi, johon vahvistussähköposti lähetetään."
finnishMessage ConfirmationEmailSentTitle = "Vahvistussähköposti lähetetty."
finnishMessage (ConfirmationEmailSent email) =
"Vahvistussähköposti on lähetty osoitteeseen " `mappend`
email `mappend`
"."
finnishMessage AddressVerified = "Sähköpostiosoite vahvistettu. Anna uusi salasana"
finnishMessage EmailVerifiedChangePass = "Sähköpostiosoite vahvistettu. Anna uusi salasana"
finnishMessage EmailVerified = "Sähköpostiosoite vahvistettu"
finnishMessage InvalidKeyTitle = "Virheellinen varmistusavain"
finnishMessage InvalidKey = "Valitettavasti varmistusavain on virheellinen."
finnishMessage InvalidEmailPass = "Virheellinen sähköposti tai salasana."
finnishMessage BadSetPass = "Kirjaudu ensin sisään asettaaksesi salasanan"
finnishMessage SetPassTitle = "Salasanan asettaminen"
finnishMessage SetPass = "Aseta uusi salasana"
finnishMessage NewPass = "Uusi salasana"
finnishMessage ConfirmPass = "Vahvista"
finnishMessage PassMismatch = "Salasanat eivät täsmää"
finnishMessage PassUpdated = "Salasana vaihdettu"
finnishMessage Facebook = "Kirjaudu Facebook-tilillä"
finnishMessage LoginViaEmail = "Kirjaudu sähköpostitilillä"
finnishMessage InvalidLogin = "Kirjautuminen epäonnistui"
finnishMessage NowLoggedIn = "Olet nyt kirjautunut sisään"
finnishMessage LoginTitle = "Kirjautuminen"
finnishMessage PleaseProvideUsername = "Käyttäjänimi puuttuu"
finnishMessage PleaseProvidePassword = "Salasana puuttuu"
finnishMessage NoIdentifierProvided = "Sähköpostiosoite/käyttäjänimi puuttuu"
finnishMessage InvalidEmailAddress = "Annettu sähköpostiosoite ei kelpaa"
finnishMessage PasswordResetTitle = "Uuden salasanan tilaaminen"
finnishMessage ProvideIdentifier = "Sähköpostiosoite tai käyttäjänimi"
finnishMessage SendPasswordResetEmail = "Lähetä uusi salasana sähköpostitse"
finnishMessage PasswordResetPrompt = "Anna sähköpostiosoitteesi tai käyttäjätunnuksesi alla, niin lähetämme uuden salasanan sähköpostitse."
finnishMessage InvalidUsernamePass = "Virheellinen käyttäjänimi tai salasana."
TODO
finnishMessage i@(IdentifierNotFound _) = englishMessage i
FIXME by Google Translate
FIXME by Google Translate
FIXME by Google Translate
chineseMessage :: AuthMessage -> Text
chineseMessage NoOpenID = "无效的OpenID"
chineseMessage LoginOpenID = "用OpenID登录"
chineseMessage LoginGoogle = "用Google帐户登录"
chineseMessage LoginYahoo = "用Yahoo帐户登录"
chineseMessage Email = "邮箱"
chineseMessage UserName = "用户名"
chineseMessage Password = "密码"
chineseMessage CurrentPassword = "当前密码"
chineseMessage Register = "注册"
chineseMessage RegisterLong = "注册新帐户"
chineseMessage EnterEmail = "输入你的邮箱地址,你将收到一封确认邮件。"
chineseMessage ConfirmationEmailSentTitle = "确认邮件已发送"
chineseMessage (ConfirmationEmailSent email) =
"确认邮件已发送至 " `mappend`
email `mappend`
"."
chineseMessage AddressVerified = "地址验证成功,请设置新密码"
chineseMessage EmailVerifiedChangePass = "地址验证成功,请设置新密码"
chineseMessage EmailVerified = "地址验证成功"
chineseMessage InvalidKeyTitle = "无效的验证码"
chineseMessage InvalidKey = "对不起,验证码无效。"
chineseMessage InvalidEmailPass = "无效的邮箱/密码组合"
chineseMessage BadSetPass = "你需要登录才能设置密码"
chineseMessage SetPassTitle = "设置密码"
chineseMessage SetPass = "设置新密码"
chineseMessage NewPass = "新密码"
chineseMessage ConfirmPass = "确认"
chineseMessage PassMismatch = "密码不匹配,请重新输入"
chineseMessage PassUpdated = "密码更新成功"
chineseMessage Facebook = "用Facebook帐户登录"
chineseMessage LoginViaEmail = "用邮箱登录"
chineseMessage InvalidLogin = "登录失败"
chineseMessage NowLoggedIn = "登录成功"
chineseMessage LoginTitle = "登录"
chineseMessage PleaseProvideUsername = "请输入用户名"
chineseMessage PleaseProvidePassword = "请输入密码"
chineseMessage NoIdentifierProvided = "缺少邮箱/用户名"
chineseMessage InvalidEmailAddress = "无效的邮箱地址"
chineseMessage PasswordResetTitle = "重置密码"
chineseMessage ProvideIdentifier = "邮箱或用户名"
chineseMessage SendPasswordResetEmail = "发送密码重置邮件"
chineseMessage PasswordResetPrompt = "输入你的邮箱地址或用户名,你将收到一封密码重置邮件。"
chineseMessage InvalidUsernamePass = "无效的用户名/密码组合"
chineseMessage (IdentifierNotFound ident) = "邮箱/用户名不存在: " `mappend` ident
chineseMessage Logout = "注销"
chineseMessage LogoutTitle = "注销"
chineseMessage AuthError = "验证错误"
czechMessage :: AuthMessage -> Text
czechMessage NoOpenID = "Nebyl nalezen identifikátor OpenID"
czechMessage LoginOpenID = "Přihlásit přes OpenID"
czechMessage LoginGoogle = "Přihlásit přes Google"
czechMessage LoginYahoo = "Přihlásit přes Yahoo"
czechMessage Email = "E-mail"
czechMessage UserName = "Uživatelské jméno"
czechMessage Password = "Heslo"
czechMessage CurrentPassword = "Current password"
czechMessage Register = "Registrovat"
czechMessage RegisterLong = "Zaregistrovat nový účet"
czechMessage EnterEmail = "Níže zadejte svou e-mailovou adresu a bude vám poslán potvrzovací e-mail."
czechMessage ConfirmationEmailSentTitle = "Potvrzovací e-mail odeslán"
czechMessage (ConfirmationEmailSent email) =
"Potvrzovací e-mail byl odeslán na " `mappend` email `mappend` "."
czechMessage AddressVerified = "Adresa byla ověřena, prosím nastavte si nové heslo"
czechMessage EmailVerifiedChangePass = "Adresa byla ověřena, prosím nastavte si nové heslo"
czechMessage EmailVerified = "Adresa byla ověřena"
czechMessage InvalidKeyTitle = "Neplatný ověřovací klíč"
czechMessage InvalidKey = "Bohužel, ověřovací klíč je neplatný."
czechMessage InvalidEmailPass = "Neplatná kombinace e-mail/heslo"
czechMessage BadSetPass = "Pro nastavení hesla je vyžadováno přihlášení"
czechMessage SetPassTitle = "Nastavit heslo"
czechMessage SetPass = "Nastavit nové heslo"
czechMessage NewPass = "Nové heslo"
czechMessage ConfirmPass = "Potvrdit"
czechMessage PassMismatch = "Hesla si neodpovídají, zkuste to znovu"
czechMessage PassUpdated = "Heslo aktualizováno"
czechMessage Facebook = "Přihlásit přes Facebook"
czechMessage LoginViaEmail = "Přihlásit přes e-mail"
czechMessage InvalidLogin = "Neplatné přihlášení"
czechMessage NowLoggedIn = "Přihlášení proběhlo úspěšně"
czechMessage LoginTitle = "Přihlásit"
czechMessage PleaseProvideUsername = "Prosím, zadejte svoje uživatelské jméno"
czechMessage PleaseProvidePassword = "Prosím, zadejte svoje heslo"
czechMessage NoIdentifierProvided = "Nebyl poskytnut žádný e-mail nebo uživatelské jméno"
czechMessage InvalidEmailAddress = "Zadaná e-mailová adresa je neplatná"
czechMessage PasswordResetTitle = "Obnovení hesla"
czechMessage ProvideIdentifier = "E-mail nebo uživatelské jméno"
czechMessage SendPasswordResetEmail = "Poslat e-mail pro obnovení hesla"
czechMessage PasswordResetPrompt = "Zadejte svou e-mailovou adresu nebo uživatelské jméno a bude vám poslán email pro obnovení hesla."
czechMessage InvalidUsernamePass = "Neplatná kombinace uživatelského jména a hesla"
TODO
czechMessage i@(IdentifierNotFound _) = englishMessage i
FIXME by Google Translate
FIXME by Google Translate
FIXME by Google Translate
- mail – это фактическое сокращение словосочетания electronic mail ,
для русского перевода так же использовано : эл.почта
russianMessage :: AuthMessage -> Text
russianMessage NoOpenID = "Идентификатор OpenID не найден"
russianMessage LoginOpenID = "Вход с помощью OpenID"
russianMessage LoginGoogle = "Вход с помощью Google"
russianMessage LoginYahoo = "Вход с помощью Yahoo"
russianMessage Email = "Эл.почта"
russianMessage UserName = "Имя пользователя"
russianMessage Password = "Пароль"
russianMessage CurrentPassword = "Старый пароль"
russianMessage Register = "Регистрация"
russianMessage RegisterLong = "Создать учётную запись"
russianMessage EnterEmail = "Введите свой адрес эл.почты ниже, вам будет отправлено письмо для подтверждения."
russianMessage ConfirmationEmailSentTitle = "Письмо для подтверждения отправлено"
russianMessage (ConfirmationEmailSent email) =
"Письмо для подтверждения было отправлено на адрес " `mappend`
email `mappend`
"."
russianMessage AddressVerified = "Адрес подтверждён. Пожалуйста, установите новый пароль."
russianMessage EmailVerifiedChangePass = "Адрес подтверждён. Пожалуйста, установите новый пароль."
russianMessage EmailVerified = "Адрес подтверждён"
russianMessage InvalidKeyTitle = "Неверный ключ подтверждения"
russianMessage InvalidKey = "Извините, но ключ подтверждения оказался недействительным."
russianMessage InvalidEmailPass = "Неверное сочетание эл.почты и пароля"
russianMessage BadSetPass = "Чтобы изменить пароль, необходимо выполнить вход"
russianMessage SetPassTitle = "Установить пароль"
russianMessage SetPass = "Установить новый пароль"
russianMessage NewPass = "Новый пароль"
russianMessage ConfirmPass = "Подтверждение пароля"
russianMessage PassMismatch = "Пароли не совпадают, повторите снова"
russianMessage PassUpdated = "Пароль обновлён"
russianMessage Facebook = "Войти с помощью Facebook"
russianMessage LoginViaEmail = "Войти по адресу эл.почты"
russianMessage InvalidLogin = "Неверный логин"
russianMessage NowLoggedIn = "Вход выполнен"
russianMessage LoginTitle = "Войти"
russianMessage PleaseProvideUsername = "Пожалуйста, введите ваше имя пользователя"
russianMessage PleaseProvidePassword = "Пожалуйста, введите ваш пароль"
russianMessage NoIdentifierProvided = "Не указан адрес эл.почты/имя пользователя"
russianMessage InvalidEmailAddress = "Указан неверный адрес эл.почты"
russianMessage PasswordResetTitle = "Сброс пароля"
russianMessage ProvideIdentifier = "Имя пользователя или эл.почта"
russianMessage SendPasswordResetEmail = "Отправить письмо для сброса пароля"
russianMessage PasswordResetPrompt = "Введите адрес эл.почты или ваше имя пользователя ниже, вам будет отправлено письмо для сброса пароля."
russianMessage InvalidUsernamePass = "Неверное сочетание имени пользователя и пароля"
russianMessage (IdentifierNotFound ident) = "Логин не найден: " `mappend` ident
russianMessage Logout = "Выйти"
russianMessage LogoutTitle = "Выйти"
russianMessage AuthError = "Ошибка аутентификации"
dutchMessage :: AuthMessage -> Text
dutchMessage NoOpenID = "Geen OpenID identificator gevonden"
dutchMessage LoginOpenID = "Inloggen via OpenID"
dutchMessage LoginGoogle = "Inloggen via Google"
dutchMessage LoginYahoo = "Inloggen via Yahoo"
dutchMessage Email = "E-mail"
dutchMessage UserName = "Gebruikersnaam"
dutchMessage Password = "Wachtwoord"
dutchMessage CurrentPassword = "Huidig wachtwoord"
dutchMessage Register = "Registreren"
dutchMessage RegisterLong = "Registreer een nieuw account"
dutchMessage EnterEmail = "Voer uw e-mailadres hieronder in, er zal een bevestigings-e-mail naar u worden verzonden."
dutchMessage ConfirmationEmailSentTitle = "Bevestigings-e-mail verzonden"
dutchMessage (ConfirmationEmailSent email) =
"Een bevestigings-e-mail is verzonden naar " `mappend`
email `mappend`
"."
dutchMessage AddressVerified = "Adres geverifieerd, stel alstublieft een nieuwe wachtwoord in"
dutchMessage EmailVerifiedChangePass = "Adres geverifieerd, stel alstublieft een nieuwe wachtwoord in"
dutchMessage EmailVerified = "Adres geverifieerd"
dutchMessage InvalidKeyTitle = "Ongeldig verificatietoken"
dutchMessage InvalidKey = "Dat was helaas een ongeldig verificatietoken."
dutchMessage InvalidEmailPass = "Ongeldige e-mailadres/wachtwoord combinatie"
dutchMessage BadSetPass = "U moet ingelogd zijn om een nieuwe wachtwoord in te stellen"
dutchMessage SetPassTitle = "Wachtwoord instellen"
dutchMessage SetPass = "Een nieuwe wachtwoord instellen"
dutchMessage NewPass = "Nieuw wachtwoord"
dutchMessage ConfirmPass = "Bevestig"
dutchMessage PassMismatch = "Wachtwoorden kwamen niet overeen, probeer het alstublieft nog eens"
dutchMessage PassUpdated = "Wachtwoord geüpdatet"
dutchMessage Facebook = "Inloggen met Facebook"
dutchMessage LoginViaEmail = "Inloggen via e-mail"
dutchMessage InvalidLogin = "Ongeldige inloggegevens"
dutchMessage NowLoggedIn = "U bent nu ingelogd"
dutchMessage LoginTitle = "Inloggen"
dutchMessage PleaseProvideUsername = "Voer alstublieft uw gebruikersnaam in"
dutchMessage PleaseProvidePassword = "Voer alstublieft uw wachtwoord in"
dutchMessage NoIdentifierProvided = "Geen e-mailadres/gebruikersnaam opgegeven"
dutchMessage InvalidEmailAddress = "Ongeldig e-mailadres opgegeven"
dutchMessage PasswordResetTitle = "Wachtwoord wijzigen"
dutchMessage ProvideIdentifier = "E-mailadres of gebruikersnaam"
dutchMessage SendPasswordResetEmail = "Stuur een wachtwoord reset e-mail"
dutchMessage PasswordResetPrompt = "Voer uw e-mailadres of gebruikersnaam hieronder in, er zal een e-mail naar u worden verzonden waarmee u uw wachtwoord kunt wijzigen."
dutchMessage InvalidUsernamePass = "Ongeldige gebruikersnaam/wachtwoord combinatie"
dutchMessage (IdentifierNotFound ident) = "Inloggegevens niet gevonden: " `mappend` ident
dutchMessage Logout = "Uitloggen"
dutchMessage LogoutTitle = "Uitloggen"
dutchMessage AuthError = "Verificatiefout"
croatianMessage :: AuthMessage -> Text
croatianMessage NoOpenID = "Nije pronađen OpenID identifikator"
croatianMessage LoginOpenID = "Prijava uz OpenID"
croatianMessage LoginGoogle = "Prijava uz Google"
croatianMessage LoginYahoo = "Prijava uz Yahoo"
croatianMessage Facebook = "Prijava uz Facebook"
croatianMessage LoginViaEmail = "Prijava putem e-pošte"
croatianMessage Email = "E-pošta"
croatianMessage UserName = "Korisničko ime"
croatianMessage Password = "Lozinka"
croatianMessage CurrentPassword = "Current Password"
croatianMessage Register = "Registracija"
croatianMessage RegisterLong = "Registracija novog računa"
croatianMessage EnterEmail = "Dolje unesite adresu e-pošte, pa ćemo vam poslati e-poruku za potvrdu."
croatianMessage PasswordResetPrompt = "Dolje unesite adresu e-pošte ili korisničko ime, pa ćemo vam poslati e-poruku za potvrdu."
croatianMessage ConfirmationEmailSentTitle = "E-poruka za potvrdu"
croatianMessage (ConfirmationEmailSent email) = "E-poruka za potvrdu poslana je na adresu " <> email <> "."
croatianMessage AddressVerified = "Adresa ovjerena, postavite novu lozinku"
croatianMessage EmailVerifiedChangePass = "Adresa ovjerena, postavite novu lozinku"
croatianMessage EmailVerified = "Adresa ovjerena"
croatianMessage InvalidKeyTitle = "Ključ za ovjeru nije valjan"
croatianMessage InvalidKey = "Nažalost, taj ključ za ovjeru nije valjan."
croatianMessage InvalidEmailPass = "Kombinacija e-pošte i lozinke nije valjana"
croatianMessage InvalidUsernamePass = "Kombinacija korisničkog imena i lozinke nije valjana"
croatianMessage BadSetPass = "Za postavljanje lozinke morate biti prijavljeni"
croatianMessage SetPassTitle = "Postavi lozinku"
croatianMessage SetPass = "Postavite novu lozinku"
croatianMessage NewPass = "Nova lozinka"
croatianMessage ConfirmPass = "Potvrda lozinke"
croatianMessage PassMismatch = "Lozinke se ne podudaraju, pokušajte ponovo"
croatianMessage PassUpdated = "Lozinka ažurirana"
croatianMessage InvalidLogin = "Prijava nije valjana"
croatianMessage NowLoggedIn = "Sada ste prijavljeni u"
croatianMessage LoginTitle = "Prijava"
croatianMessage PleaseProvideUsername = "Unesite korisničko ime"
croatianMessage PleaseProvidePassword = "Unesite lozinku"
croatianMessage NoIdentifierProvided = "Nisu dani e-pošta/korisničko ime"
croatianMessage InvalidEmailAddress = "Dana adresa e-pošte nije valjana"
croatianMessage PasswordResetTitle = "Poništavanje lozinke"
croatianMessage ProvideIdentifier = "E-pošta ili korisničko ime"
croatianMessage SendPasswordResetEmail = "Pošalji e-poruku za poništavanje lozinke"
croatianMessage (IdentifierNotFound ident) = "Korisničko ime/e-pošta nisu pronađeni: " <> ident
croatianMessage Logout = "Odjava"
croatianMessage LogoutTitle = "Odjava"
croatianMessage AuthError = "Pogreška provjere autentičnosti"
danishMessage :: AuthMessage -> Text
danishMessage NoOpenID = "Mangler OpenID identifier"
danishMessage LoginOpenID = "Login med OpenID"
danishMessage LoginGoogle = "Login med Google"
danishMessage LoginYahoo = "Login med Yahoo"
danishMessage Email = "E-mail"
danishMessage UserName = "Brugernavn"
danishMessage Password = "Kodeord"
danishMessage CurrentPassword = "Nuværende kodeord"
danishMessage Register = "Opret"
danishMessage RegisterLong = "Opret en ny konto"
danishMessage EnterEmail = "Indtast din e-mailadresse nedenfor og en bekræftelsesmail vil blive sendt til dig."
danishMessage ConfirmationEmailSentTitle = "Bekræftelsesmail sendt"
danishMessage (ConfirmationEmailSent email) =
"En bekræftelsesmail er sendt til " `mappend`
email `mappend`
"."
danishMessage AddressVerified = "Adresse bekræftet, sæt venligst et nyt kodeord"
danishMessage EmailVerifiedChangePass = "Adresse bekræftet, sæt venligst et nyt kodeord"
danishMessage EmailVerified = "Adresse bekræftet"
danishMessage InvalidKeyTitle = "Ugyldig verifikationsnøgle"
danishMessage InvalidKey = "Beklager, det var en ugyldigt verifikationsnøgle."
danishMessage InvalidEmailPass = "Ugyldigt e-mail/kodeord"
danishMessage BadSetPass = "Du skal være logget ind for at sætte et kodeord"
danishMessage SetPassTitle = "Sæt kodeord"
danishMessage SetPass = "Sæt et nyt kodeord"
danishMessage NewPass = "Nyt kodeord"
danishMessage ConfirmPass = "Bekræft"
danishMessage PassMismatch = "Kodeordne var forskellige, prøv venligst igen"
danishMessage PassUpdated = "Kodeord opdateret"
danishMessage Facebook = "Login med Facebook"
danishMessage LoginViaEmail = "Login med e-mail"
danishMessage InvalidLogin = "Ugyldigt login"
danishMessage NowLoggedIn = "Du er nu logget ind"
danishMessage LoginTitle = "Log ind"
danishMessage PleaseProvideUsername = "Indtast venligst dit brugernavn"
danishMessage PleaseProvidePassword = "Indtasy venligst dit kodeord"
danishMessage NoIdentifierProvided = "Mangler e-mail/username"
danishMessage InvalidEmailAddress = "Ugyldig e-mailadresse indtastet"
danishMessage PasswordResetTitle = "Nulstilning af kodeord"
danishMessage ProvideIdentifier = "E-mail eller brugernavn"
danishMessage SendPasswordResetEmail = "Send kodeordsnulstillingsmail"
danishMessage PasswordResetPrompt = "Indtast din e-mailadresse eller dit brugernavn nedenfor, så bliver en kodeordsnulstilningsmail sendt til dig."
danishMessage InvalidUsernamePass = "Ugyldigt brugernavn/kodeord"
danishMessage (IdentifierNotFound ident) = "Brugernavn findes ikke: " `mappend` ident
danishMessage Logout = "Log ud"
danishMessage LogoutTitle = "Log ud"
danishMessage AuthError = "Fejl ved bekræftelse af identitet"
koreanMessage :: AuthMessage -> Text
koreanMessage NoOpenID = "OpenID ID가 없습니다"
koreanMessage LoginOpenID = "OpenID로 로그인"
koreanMessage LoginGoogle = "Google로 로그인"
koreanMessage LoginYahoo = "Yahoo로 로그인"
koreanMessage Email = "이메일"
koreanMessage UserName = "사용자 이름"
koreanMessage Password = "비밀번호"
koreanMessage CurrentPassword = "현재 비밀번호"
koreanMessage Register = "등록"
koreanMessage RegisterLong = "새 계정 등록"
koreanMessage EnterEmail = "이메일 주소를 아래에 입력하시면 확인 이메일이 발송됩니다."
koreanMessage ConfirmationEmailSentTitle = "확인 이메일을 보냈습니다"
koreanMessage (ConfirmationEmailSent email) =
"확인 이메일을 " `mappend`
email `mappend`
"에 보냈습니다."
koreanMessage AddressVerified = "주소가 인증되었습니다. 새 비밀번호를 설정하세요."
koreanMessage EmailVerifiedChangePass = "주소가 인증되었습니다. 새 비밀번호를 설정하세요."
koreanMessage EmailVerified = "주소가 인증되었습니다"
koreanMessage InvalidKeyTitle = "인증키가 잘못되었습니다"
koreanMessage InvalidKey = "죄송합니다. 잘못된 인증키입니다."
koreanMessage InvalidEmailPass = "이메일 주소나 비밀번호가 잘못되었습니다"
koreanMessage BadSetPass = "비밀번호를 설정하기 위해서는 로그인해야 합니다"
koreanMessage SetPassTitle = "비밀번호 설정"
koreanMessage SetPass = "새 비밀번호 설정"
koreanMessage NewPass = "새 비밀번호"
koreanMessage ConfirmPass = "확인"
koreanMessage PassMismatch = "비밀번호가 맞지 않습니다. 다시 시도해주세요."
koreanMessage PassUpdated = "비밀번호가 업데이트 되었습니다"
koreanMessage Facebook = "Facebook으로 로그인"
koreanMessage LoginViaEmail = "이메일로"
koreanMessage InvalidLogin = "잘못된 로그인입니다"
koreanMessage NowLoggedIn = "로그인했습니다"
koreanMessage LoginTitle = "로그인"
koreanMessage PleaseProvideUsername = "사용자 이름을 입력하세요"
koreanMessage PleaseProvidePassword = "비밀번호를 입력하세요"
koreanMessage NoIdentifierProvided = "이메일 주소나 사용자 이름이 입력되어 있지 않습니다"
koreanMessage InvalidEmailAddress = "이메일 주소가 잘못되었습니다"
koreanMessage PasswordResetTitle = "비밀번호 변경"
koreanMessage ProvideIdentifier = "이메일 주소나 사용자 이름"
koreanMessage SendPasswordResetEmail = "비밀번호 재설정 이메일 보내기"
koreanMessage PasswordResetPrompt = "이메일 주소나 사용자 이름을 아래에 입력하시면 비밀번호 재설정 이메일이 발송됩니다."
koreanMessage InvalidUsernamePass = "사용자 이름이나 비밀번호가 잘못되었습니다"
koreanMessage (IdentifierNotFound ident) = ident `mappend` "는 등록되어 있지 않습니다"
koreanMessage Logout = "로그아웃"
koreanMessage LogoutTitle = "로그아웃"
koreanMessage AuthError = "인증오류"
|
e13e7ba7e59e4567fb86a68eccfd0b35ce4cfa6f98a54df83fbb856e9f6b4fe0 | YoshikuniJujo/test_haskell | Shaderc.hs | # LANGUAGE BlockArguments #
# LANGUAGE TypeApplications , ScopedTypeVariables #
{-# LANGUAGE DataKinds, KindSignatures #-}
# LANGUAGE ViewPatterns #
# LANGUAGE GeneralizedNewtypeDeriving #
# OPTIONS_GHC -Wall -fno - warn - tabs #
module Shaderc where
import Foreign.Storable
import Control.Monad.Cont
import Data.String
import qualified Data.ByteString as BS
import Shaderc.Exception
import Shaderc.EnumAuto
import qualified Shaderc.Core as C
import qualified Shaderc.Middle as M
import qualified Shaderc.CompileOptions as CompileOptions
import qualified Shaderc.CompilationResult.Core as CompilationResult
newtype Spv (sknd :: ShaderKind) = Spv BS.ByteString
deriving (Show, IsString)
compileIntoSpv :: forall ud sknd . (Storable ud, SpvShaderKind sknd) =>
BS.ByteString -> BS.ByteString -> BS.ByteString ->
CompileOptions.T ud -> IO (Spv sknd)
compileIntoSpv src ifnm epnm opts = ($ pure) $ runContT do
cmp <- lift C.compilerInitialize
rslt <- M.compileIntoSpv cmp src (shaderKind @sknd) ifnm epnm opts
lift $ throwUnlessSuccess rslt
lift do cspv <- CompilationResult.getBytes rslt
(fromIntegral -> cspvln) <- CompilationResult.getLength rslt
spv <- BS.packCStringLen (cspv, cspvln)
CompilationResult.release rslt
C.compilerRelease cmp
pure $ Spv spv
defaultCompileOptions :: CompileOptions.T ()
defaultCompileOptions = CompileOptions.T {
CompileOptions.tMacroDefinitions = [],
CompileOptions.tSourceLanguage = Nothing,
CompileOptions.tGenerateDebugInfo = False,
CompileOptions.tOptimizationLevel = Nothing,
CompileOptions.tForcedVersionProfile = Nothing,
CompileOptions.tIncludeCallbacks = Nothing }
| null | https://raw.githubusercontent.com/YoshikuniJujo/test_haskell/20de2cb05eff3b570b30fbdc4273cdd636f914be/themes/gui/vulkan/try-shaderc/src/Shaderc.hs | haskell | # LANGUAGE DataKinds, KindSignatures # | # LANGUAGE BlockArguments #
# LANGUAGE TypeApplications , ScopedTypeVariables #
# LANGUAGE ViewPatterns #
# LANGUAGE GeneralizedNewtypeDeriving #
# OPTIONS_GHC -Wall -fno - warn - tabs #
module Shaderc where
import Foreign.Storable
import Control.Monad.Cont
import Data.String
import qualified Data.ByteString as BS
import Shaderc.Exception
import Shaderc.EnumAuto
import qualified Shaderc.Core as C
import qualified Shaderc.Middle as M
import qualified Shaderc.CompileOptions as CompileOptions
import qualified Shaderc.CompilationResult.Core as CompilationResult
newtype Spv (sknd :: ShaderKind) = Spv BS.ByteString
deriving (Show, IsString)
compileIntoSpv :: forall ud sknd . (Storable ud, SpvShaderKind sknd) =>
BS.ByteString -> BS.ByteString -> BS.ByteString ->
CompileOptions.T ud -> IO (Spv sknd)
compileIntoSpv src ifnm epnm opts = ($ pure) $ runContT do
cmp <- lift C.compilerInitialize
rslt <- M.compileIntoSpv cmp src (shaderKind @sknd) ifnm epnm opts
lift $ throwUnlessSuccess rslt
lift do cspv <- CompilationResult.getBytes rslt
(fromIntegral -> cspvln) <- CompilationResult.getLength rslt
spv <- BS.packCStringLen (cspv, cspvln)
CompilationResult.release rslt
C.compilerRelease cmp
pure $ Spv spv
defaultCompileOptions :: CompileOptions.T ()
defaultCompileOptions = CompileOptions.T {
CompileOptions.tMacroDefinitions = [],
CompileOptions.tSourceLanguage = Nothing,
CompileOptions.tGenerateDebugInfo = False,
CompileOptions.tOptimizationLevel = Nothing,
CompileOptions.tForcedVersionProfile = Nothing,
CompileOptions.tIncludeCallbacks = Nothing }
|
9ecc6db04dbfa99e57a1841d8f4fdc10adc571d9212a27d3ffc304843a2c57a5 | xmonad/xmonad-contrib | Circle.hs | # LANGUAGE FlexibleInstances , MultiParamTypeClasses #
-----------------------------------------------------------------------------
-- |
-- Module : XMonad.Layout.Circle
-- Description : An elliptical, overlapping layout.
Copyright : ( c )
-- License : BSD-style (see LICENSE)
--
Maintainer : < >
-- Stability : unstable
-- Portability : unportable
--
Circle is an elliptical , overlapping layout , by
--
-----------------------------------------------------------------------------
module XMonad.Layout.Circle (
-- * Usage
-- $usage
Circle (..)
) where -- actually it's an ellipse
import XMonad.Prelude
import XMonad
import XMonad.StackSet (integrate, peek)
-- $usage
-- You can use this module with the following in your @~\/.xmonad\/xmonad.hs@:
--
> import XMonad . Layout . Circle
--
Then edit your @layoutHook@ by adding the Circle layout :
--
-- > myLayout = Circle ||| Full ||| etc..
-- > main = xmonad def { layoutHook = myLayout }
--
-- For more detailed instructions on editing the layoutHook see
-- <#customizing-xmonad the tutorial> and
-- "XMonad.Doc.Extending#Editing_the_layout_hook".
data Circle a = Circle deriving ( Read, Show )
instance LayoutClass Circle Window where
doLayout Circle r s = do layout <- raiseFocus $ circleLayout r $ integrate s
return (layout, Nothing)
circleLayout :: Rectangle -> [a] -> [(a, Rectangle)]
circleLayout _ [] = []
circleLayout r (w:ws) = master : rest
where master = (w, center r)
rest = zip ws $ map (satellite r) [0, pi * 2 / fromIntegral (length ws) ..]
raiseFocus :: [(Window, Rectangle)] -> X [(Window, Rectangle)]
raiseFocus xs = do focused <- withWindowSet (return . peek)
return $ case find ((== focused) . Just . fst) xs of
Just x -> x : delete x xs
Nothing -> xs
center :: Rectangle -> Rectangle
center (Rectangle sx sy sw sh) = Rectangle x y w h
where s = sqrt 2 :: Double
w = round (fromIntegral sw / s)
h = round (fromIntegral sh / s)
x = sx + fromIntegral (sw - w) `div` 2
y = sy + fromIntegral (sh - h) `div` 2
satellite :: Rectangle -> Double -> Rectangle
satellite (Rectangle sx sy sw sh) a = Rectangle (sx + round (rx + rx * cos a))
(sy + round (ry + ry * sin a))
w h
where rx = fromIntegral (sw - w) / 2
ry = fromIntegral (sh - h) / 2
w = sw * 10 `div` 25
h = sh * 10 `div` 25
| null | https://raw.githubusercontent.com/xmonad/xmonad-contrib/571d017b8259340971db1736eedc992a54e9022c/XMonad/Layout/Circle.hs | haskell | ---------------------------------------------------------------------------
|
Module : XMonad.Layout.Circle
Description : An elliptical, overlapping layout.
License : BSD-style (see LICENSE)
Stability : unstable
Portability : unportable
---------------------------------------------------------------------------
* Usage
$usage
actually it's an ellipse
$usage
You can use this module with the following in your @~\/.xmonad\/xmonad.hs@:
> myLayout = Circle ||| Full ||| etc..
> main = xmonad def { layoutHook = myLayout }
For more detailed instructions on editing the layoutHook see
<#customizing-xmonad the tutorial> and
"XMonad.Doc.Extending#Editing_the_layout_hook". | # LANGUAGE FlexibleInstances , MultiParamTypeClasses #
Copyright : ( c )
Maintainer : < >
Circle is an elliptical , overlapping layout , by
module XMonad.Layout.Circle (
Circle (..)
import XMonad.Prelude
import XMonad
import XMonad.StackSet (integrate, peek)
> import XMonad . Layout . Circle
Then edit your @layoutHook@ by adding the Circle layout :
data Circle a = Circle deriving ( Read, Show )
instance LayoutClass Circle Window where
doLayout Circle r s = do layout <- raiseFocus $ circleLayout r $ integrate s
return (layout, Nothing)
circleLayout :: Rectangle -> [a] -> [(a, Rectangle)]
circleLayout _ [] = []
circleLayout r (w:ws) = master : rest
where master = (w, center r)
rest = zip ws $ map (satellite r) [0, pi * 2 / fromIntegral (length ws) ..]
raiseFocus :: [(Window, Rectangle)] -> X [(Window, Rectangle)]
raiseFocus xs = do focused <- withWindowSet (return . peek)
return $ case find ((== focused) . Just . fst) xs of
Just x -> x : delete x xs
Nothing -> xs
center :: Rectangle -> Rectangle
center (Rectangle sx sy sw sh) = Rectangle x y w h
where s = sqrt 2 :: Double
w = round (fromIntegral sw / s)
h = round (fromIntegral sh / s)
x = sx + fromIntegral (sw - w) `div` 2
y = sy + fromIntegral (sh - h) `div` 2
satellite :: Rectangle -> Double -> Rectangle
satellite (Rectangle sx sy sw sh) a = Rectangle (sx + round (rx + rx * cos a))
(sy + round (ry + ry * sin a))
w h
where rx = fromIntegral (sw - w) / 2
ry = fromIntegral (sh - h) / 2
w = sw * 10 `div` 25
h = sh * 10 `div` 25
|
62dbdc33608c469e0491eba3ef04b68e229b2cf8d0e7c2f2f34b62301abc5c7b | macchiato-framework/examples | middleware.cljs | (ns dirac-example.middleware
(:require
[macchiato.middleware.defaults :as defaults]))
(defn wrap-defaults [handler]
(defaults/wrap-defaults handler defaults/site-defaults))
| null | https://raw.githubusercontent.com/macchiato-framework/examples/946bdf1a04f5ef787fc83affdcbf6603bbf29b5c/dirac-example/src/dirac_example/middleware.cljs | clojure | (ns dirac-example.middleware
(:require
[macchiato.middleware.defaults :as defaults]))
(defn wrap-defaults [handler]
(defaults/wrap-defaults handler defaults/site-defaults))
|
|
d0333e762d3205e0f78f8b06562ff6a306d42acbdfe965c6659e09de4f0ab73f | fare/fare-scripts | toggle-touchpad.lisp | ":" ; exec cl-launch -Q -sm fare-scripts/toggle-touchpad "$0" "$@"
;; -*- lisp -*-
;; Based on #Software_toggle
;; Use the UI preferences to add a keyboard shortcut that invokes this script.
;; To avoid the slow startup time of lisp as a script, better dump an image with:
;; cl-launch -o ~/bin/x64/toggle-touchpad -d ! -l clisp \
;; -s optima.ppcre -s inferior-shell -E toggle-touchpad::main -L toggle-touchpad.lisp
;; Or use make-multi.sh to create a multi-call binary that includes toggle-touchpad support.
(uiop:define-package :fare-scripts/toggle-touchpad
(:use :cl :fare-utils :uiop :inferior-shell
:optima :optima.ppcre :cl-scripting)
(:export #:help #:get-touchpad-id #:device-enabled-p
#:toggle-device #:disable-device #:enable-device))
(in-package :fare-scripts/toggle-touchpad)
(defun get-touchpad-id ()
(dolist (line (run/lines '(xinput list)))
(match line
((ppcre "(TouchPad|\\sSYNA.*|Synaptics\\s.*|SynPS/2 Synaptics TouchPad)\\s+id\=([0-9]{1,2})\\s+" _ x)
(return (values (parse-integer x)))))))
(defun device-enabled-p (&optional (id (get-touchpad-id)))
(dolist (line (run/lines `(xinput list-props ,id)))
(match line
((ppcre "Device Enabled\\s+[():0-9]+\\s+([01])" x) (return (equal x "1"))))))
(defun toggle-device (&optional (id (get-touchpad-id)) (on :toggle))
(let ((state (ecase on
((:toggle) (not (device-enabled-p id)))
((nil t) on))))
(run `(xinput ,(if state 'enable 'disable) ,id)))
(success))
(defun enable-device (&optional (id (get-touchpad-id)))
(toggle-device id t))
(defun disable-device (&optional (id (get-touchpad-id)))
(toggle-device id nil))
(defun help (&optional (output *standard-output*))
(format output "toggle-touchpad functions: ~{~(~A~)~^ ~}~%"
(package-functions :fare-scripts/toggle-touchpad))
(success))
TODO : use command - line - arguments , or
(cond
((null argv) (toggle-device))
((eql (first-char (first argv)) #\() (eval (first argv)))
(t (if-let (fun (package-function :fare-scripts/toggle-touchpad
(standard-case-symbol-name (first argv))))
(apply 'run-command fun (rest argv))
(progn
(format *error-output* "Bad toggle-touchpad command: ~A~%" (first argv))
(help *error-output*)
(quit 2))))))
| null | https://raw.githubusercontent.com/fare/fare-scripts/fee32edbbe4ca486e63922d94305027a8b5603a5/toggle-touchpad.lisp | lisp | exec cl-launch -Q -sm fare-scripts/toggle-touchpad "$0" "$@"
-*- lisp -*-
Based on #Software_toggle
Use the UI preferences to add a keyboard shortcut that invokes this script.
To avoid the slow startup time of lisp as a script, better dump an image with:
cl-launch -o ~/bin/x64/toggle-touchpad -d ! -l clisp \
-s optima.ppcre -s inferior-shell -E toggle-touchpad::main -L toggle-touchpad.lisp
Or use make-multi.sh to create a multi-call binary that includes toggle-touchpad support. |
(uiop:define-package :fare-scripts/toggle-touchpad
(:use :cl :fare-utils :uiop :inferior-shell
:optima :optima.ppcre :cl-scripting)
(:export #:help #:get-touchpad-id #:device-enabled-p
#:toggle-device #:disable-device #:enable-device))
(in-package :fare-scripts/toggle-touchpad)
(defun get-touchpad-id ()
(dolist (line (run/lines '(xinput list)))
(match line
((ppcre "(TouchPad|\\sSYNA.*|Synaptics\\s.*|SynPS/2 Synaptics TouchPad)\\s+id\=([0-9]{1,2})\\s+" _ x)
(return (values (parse-integer x)))))))
(defun device-enabled-p (&optional (id (get-touchpad-id)))
(dolist (line (run/lines `(xinput list-props ,id)))
(match line
((ppcre "Device Enabled\\s+[():0-9]+\\s+([01])" x) (return (equal x "1"))))))
(defun toggle-device (&optional (id (get-touchpad-id)) (on :toggle))
(let ((state (ecase on
((:toggle) (not (device-enabled-p id)))
((nil t) on))))
(run `(xinput ,(if state 'enable 'disable) ,id)))
(success))
(defun enable-device (&optional (id (get-touchpad-id)))
(toggle-device id t))
(defun disable-device (&optional (id (get-touchpad-id)))
(toggle-device id nil))
(defun help (&optional (output *standard-output*))
(format output "toggle-touchpad functions: ~{~(~A~)~^ ~}~%"
(package-functions :fare-scripts/toggle-touchpad))
(success))
TODO : use command - line - arguments , or
(cond
((null argv) (toggle-device))
((eql (first-char (first argv)) #\() (eval (first argv)))
(t (if-let (fun (package-function :fare-scripts/toggle-touchpad
(standard-case-symbol-name (first argv))))
(apply 'run-command fun (rest argv))
(progn
(format *error-output* "Bad toggle-touchpad command: ~A~%" (first argv))
(help *error-output*)
(quit 2))))))
|
161f3c9757c9e2e2a537a3d9f620046d73aaedbcddeac0a1da689c75e8789dc1 | rizo/snowflake-os | printtyp.ml | (***********************************************************************)
(* *)
(* Objective Caml *)
(* *)
and , projet Cristal , INRIA Rocquencourt
(* *)
Copyright 1996 Institut National de Recherche en Informatique et
en Automatique . All rights reserved . This file is distributed
under the terms of the Q Public License version 1.0 .
(* *)
(***********************************************************************)
$ Id$
(* Printing functions *)
open Misc
open Ctype
open Format
open Longident
open Path
open Asttypes
open Types
open Btype
open Outcometree
(* Print a long identifier *)
let rec longident ppf = function
| Lident s -> fprintf ppf "%s" s
| Ldot(p, s) -> fprintf ppf "%a.%s" longident p s
| Lapply(p1, p2) -> fprintf ppf "%a(%a)" longident p1 longident p2
(* Print an identifier *)
let ident ppf id = fprintf ppf "%s" (Ident.name id)
(* Print a path *)
let ident_pervasive = Ident.create_persistent "Pervasives"
let rec tree_of_path = function
| Pident id ->
Oide_ident (Ident.name id)
| Pdot(Pident id, s, pos) when Ident.same id ident_pervasive ->
Oide_ident s
| Pdot(p, s, pos) ->
Oide_dot (tree_of_path p, s)
| Papply(p1, p2) ->
Oide_apply (tree_of_path p1, tree_of_path p2)
let rec path ppf = function
| Pident id ->
ident ppf id
| Pdot(Pident id, s, pos) when Ident.same id ident_pervasive ->
fprintf ppf "%s" s
| Pdot(p, s, pos) ->
fprintf ppf "%a.%s" path p s
| Papply(p1, p2) ->
fprintf ppf "%a(%a)" path p1 path p2
(* Print a recursive annotation *)
let tree_of_rec = function
| Trec_not -> Orec_not
| Trec_first -> Orec_first
| Trec_next -> Orec_next
(* Print a raw type expression, with sharing *)
let raw_list pr ppf = function
[] -> fprintf ppf "[]"
| a :: l ->
fprintf ppf "@[<1>[%a%t]@]" pr a
(fun ppf -> List.iter (fun x -> fprintf ppf ";@,%a" pr x) l)
let rec safe_kind_repr v = function
Fvar {contents=Some k} ->
if List.memq k v then "Fvar loop" else
safe_kind_repr (k::v) k
| Fvar _ -> "Fvar None"
| Fpresent -> "Fpresent"
| Fabsent -> "Fabsent"
let rec safe_commu_repr v = function
Cok -> "Cok"
| Cunknown -> "Cunknown"
| Clink r ->
if List.memq r v then "Clink loop" else
safe_commu_repr (r::v) !r
let rec safe_repr v = function
{desc = Tlink t} when not (List.memq t v) ->
safe_repr (t::v) t
| t -> t
let rec list_of_memo = function
Mnil -> []
| Mcons (priv, p, t1, t2, rem) -> p :: list_of_memo rem
| Mlink rem -> list_of_memo !rem
let visited = ref []
let rec raw_type ppf ty =
let ty = safe_repr [] ty in
if List.memq ty !visited then fprintf ppf "{id=%d}" ty.id else begin
visited := ty :: !visited;
fprintf ppf "@[<1>{id=%d;level=%d;desc=@,%a}@]" ty.id ty.level
raw_type_desc ty.desc
end
and raw_type_list tl = raw_list raw_type tl
and raw_type_desc ppf = function
Tvar -> fprintf ppf "Tvar"
| Tarrow(l,t1,t2,c) ->
fprintf ppf "@[<hov1>Tarrow(%s,@,%a,@,%a,@,%s)@]"
l raw_type t1 raw_type t2
(safe_commu_repr [] c)
| Ttuple tl ->
fprintf ppf "@[<1>Ttuple@,%a@]" raw_type_list tl
| Tconstr (p, tl, abbrev) ->
fprintf ppf "@[<hov1>Tconstr(@,%a,@,%a,@,%a)@]" path p
raw_type_list tl
(raw_list path) (list_of_memo !abbrev)
| Tobject (t, nm) ->
fprintf ppf "@[<hov1>Tobject(@,%a,@,@[<1>ref%t@])@]" raw_type t
(fun ppf ->
match !nm with None -> fprintf ppf " None"
| Some(p,tl) ->
fprintf ppf "(Some(@,%a,@,%a))" path p raw_type_list tl)
| Tfield (f, k, t1, t2) ->
fprintf ppf "@[<hov1>Tfield(@,%s,@,%s,@,%a,@;<0 -1>%a)@]" f
(safe_kind_repr [] k)
raw_type t1 raw_type t2
| Tnil -> fprintf ppf "Tnil"
| Tlink t -> fprintf ppf "@[<1>Tlink@,%a@]" raw_type t
| Tsubst t -> fprintf ppf "@[<1>Tsubst@,%a@]" raw_type t
| Tunivar -> fprintf ppf "Tunivar"
| Tpoly (t, tl) ->
fprintf ppf "@[<hov1>Tpoly(@,%a,@,%a)@]"
raw_type t
raw_type_list tl
| Tvariant row ->
fprintf ppf
"@[<hov1>{@[%s@,%a;@]@ @[%s@,%a;@]@ %s%b;@ %s%b;@ @[<1>%s%t@]}@]"
"row_fields="
(raw_list (fun ppf (l, f) ->
fprintf ppf "@[%s,@ %a@]" l raw_field f))
row.row_fields
"row_more=" raw_type row.row_more
"row_closed=" row.row_closed
"row_fixed=" row.row_fixed
"row_name="
(fun ppf ->
match row.row_name with None -> fprintf ppf "None"
| Some(p,tl) ->
fprintf ppf "Some(@,%a,@,%a)" path p raw_type_list tl)
| Tpackage (p, _, tl) ->
fprintf ppf "@[<hov1>Tpackage(@,%a@,%a)@]" path p
raw_type_list tl
and raw_field ppf = function
Rpresent None -> fprintf ppf "Rpresent None"
| Rpresent (Some t) -> fprintf ppf "@[<1>Rpresent(Some@,%a)@]" raw_type t
| Reither (c,tl,m,e) ->
fprintf ppf "@[<hov1>Reither(%b,@,%a,@,%b,@,@[<1>ref%t@])@]" c
raw_type_list tl m
(fun ppf ->
match !e with None -> fprintf ppf " None"
| Some f -> fprintf ppf "@,@[<1>(%a)@]" raw_field f)
| Rabsent -> fprintf ppf "Rabsent"
let raw_type_expr ppf t =
visited := [];
raw_type ppf t;
visited := []
(* Print a type expression *)
let names = ref ([] : (type_expr * string) list)
let name_counter = ref 0
let reset_names () = names := []; name_counter := 0
let new_name () =
let name =
if !name_counter < 26
then String.make 1 (Char.chr(97 + !name_counter))
else String.make 1 (Char.chr(97 + !name_counter mod 26)) ^
string_of_int(!name_counter / 26) in
incr name_counter;
name
let name_of_type t =
try List.assq t !names with Not_found ->
let name = new_name () in
names := (t, name) :: !names;
name
let check_name_of_type t = ignore(name_of_type t)
let non_gen_mark sch ty =
if sch && ty.desc = Tvar && ty.level <> generic_level then "_" else ""
let print_name_of_type sch ppf t =
fprintf ppf "'%s%s" (non_gen_mark sch t) (name_of_type t)
let visited_objects = ref ([] : type_expr list)
let aliased = ref ([] : type_expr list)
let delayed = ref ([] : type_expr list)
let add_delayed t =
if not (List.memq t !delayed) then delayed := t :: !delayed
let is_aliased ty = List.memq (proxy ty) !aliased
let add_alias ty =
let px = proxy ty in
if not (is_aliased px) then aliased := px :: !aliased
let aliasable ty =
match ty.desc with Tvar | Tunivar | Tpoly _ -> false | _ -> true
let namable_row row =
row.row_name <> None &&
List.for_all
(fun (_, f) ->
match row_field_repr f with
| Reither(c, l, _, _) ->
row.row_closed && if c then l = [] else List.length l = 1
| _ -> true)
row.row_fields
let rec mark_loops_rec visited ty =
let ty = repr ty in
let px = proxy ty in
if List.memq px visited && aliasable ty then add_alias px else
let visited = px :: visited in
match ty.desc with
| Tvar -> ()
| Tarrow(_, ty1, ty2, _) ->
mark_loops_rec visited ty1; mark_loops_rec visited ty2
| Ttuple tyl -> List.iter (mark_loops_rec visited) tyl
| Tconstr(_, tyl, _) | Tpackage (_, _, tyl) ->
List.iter (mark_loops_rec visited) tyl
| Tvariant row ->
if List.memq px !visited_objects then add_alias px else
begin
let row = row_repr row in
if not (static_row row) then
visited_objects := px :: !visited_objects;
match row.row_name with
| Some(p, tyl) when namable_row row ->
List.iter (mark_loops_rec visited) tyl
| _ ->
iter_row (mark_loops_rec visited) row
end
| Tobject (fi, nm) ->
if List.memq px !visited_objects then add_alias px else
begin
if opened_object ty then
visited_objects := px :: !visited_objects;
begin match !nm with
| None ->
let fields, _ = flatten_fields fi in
List.iter
(fun (_, kind, ty) ->
if field_kind_repr kind = Fpresent then
mark_loops_rec visited ty)
fields
| Some (_, l) ->
List.iter (mark_loops_rec visited) (List.tl l)
end
end
| Tfield(_, kind, ty1, ty2) when field_kind_repr kind = Fpresent ->
mark_loops_rec visited ty1; mark_loops_rec visited ty2
| Tfield(_, _, _, ty2) ->
mark_loops_rec visited ty2
| Tnil -> ()
| Tsubst ty -> mark_loops_rec visited ty
| Tlink _ -> fatal_error "Printtyp.mark_loops_rec (2)"
| Tpoly (ty, tyl) ->
List.iter (fun t -> add_alias t) tyl;
mark_loops_rec visited ty
| Tunivar -> ()
let mark_loops ty =
normalize_type Env.empty ty;
mark_loops_rec [] ty;;
let reset_loop_marks () =
visited_objects := []; aliased := []; delayed := []
let reset () =
reset_names (); reset_loop_marks ()
let reset_and_mark_loops ty =
reset (); mark_loops ty
let reset_and_mark_loops_list tyl =
reset (); List.iter mark_loops tyl
(* Disabled in classic mode when printing an unification error *)
let print_labels = ref true
let print_label ppf l =
if !print_labels && l <> "" || is_optional l then fprintf ppf "%s:" l
let rec tree_of_typexp sch ty =
let ty = repr ty in
let px = proxy ty in
if List.mem_assq px !names && not (List.memq px !delayed) then
let mark = is_non_gen sch ty in
Otyp_var (mark, name_of_type px) else
let pr_typ () =
match ty.desc with
| Tvar ->
Otyp_var (is_non_gen sch ty, name_of_type ty)
| Tarrow(l, ty1, ty2, _) ->
let pr_arrow l ty1 ty2 =
let lab =
if !print_labels && l <> "" || is_optional l then l else ""
in
let t1 =
if is_optional l then
match (repr ty1).desc with
| Tconstr(path, [ty], _)
when Path.same path Predef.path_option ->
tree_of_typexp sch ty
| _ -> Otyp_stuff "<hidden>"
else tree_of_typexp sch ty1 in
Otyp_arrow (lab, t1, tree_of_typexp sch ty2) in
pr_arrow l ty1 ty2
| Ttuple tyl ->
Otyp_tuple (tree_of_typlist sch tyl)
| Tconstr(p, tyl, abbrev) ->
Otyp_constr (tree_of_path p, tree_of_typlist sch tyl)
| Tvariant row ->
let row = row_repr row in
let fields =
if row.row_closed then
List.filter (fun (_, f) -> row_field_repr f <> Rabsent)
row.row_fields
else row.row_fields in
let present =
List.filter
(fun (_, f) ->
match row_field_repr f with
| Rpresent _ -> true
| _ -> false)
fields in
let all_present = List.length present = List.length fields in
begin match row.row_name with
| Some(p, tyl) when namable_row row ->
let id = tree_of_path p in
let args = tree_of_typlist sch tyl in
if row.row_closed && all_present then
Otyp_constr (id, args)
else
let non_gen = is_non_gen sch px in
let tags =
if all_present then None else Some (List.map fst present) in
Otyp_variant (non_gen, Ovar_name(tree_of_path p, args),
row.row_closed, tags)
| _ ->
let non_gen =
not (row.row_closed && all_present) && is_non_gen sch px in
let fields = List.map (tree_of_row_field sch) fields in
let tags =
if all_present then None else Some (List.map fst present) in
Otyp_variant (non_gen, Ovar_fields fields, row.row_closed, tags)
end
| Tobject (fi, nm) ->
tree_of_typobject sch fi nm
| Tsubst ty ->
tree_of_typexp sch ty
| Tlink _ | Tnil | Tfield _ ->
fatal_error "Printtyp.tree_of_typexp"
| Tpoly (ty, []) ->
tree_of_typexp sch ty
| Tpoly (ty, tyl) ->
let tyl = List.map repr tyl in
let tyl = List.filter is_aliased tyl in
if tyl = [] then tree_of_typexp sch ty else begin
let old_delayed = !delayed in
List.iter add_delayed tyl;
let tl = List.map name_of_type tyl in
let tr = Otyp_poly (tl, tree_of_typexp sch ty) in
delayed := old_delayed; tr
end
| Tunivar ->
Otyp_var (false, name_of_type ty)
| Tpackage (p, n, tyl) ->
Otyp_module (Path.name p, n, tree_of_typlist sch tyl)
in
if List.memq px !delayed then delayed := List.filter ((!=) px) !delayed;
if is_aliased px && aliasable ty then begin
check_name_of_type px;
Otyp_alias (pr_typ (), name_of_type px) end
else pr_typ ()
and tree_of_row_field sch (l, f) =
match row_field_repr f with
| Rpresent None | Reither(true, [], _, _) -> (l, false, [])
| Rpresent(Some ty) -> (l, false, [tree_of_typexp sch ty])
| Reither(c, tyl, _, _) ->
contradiction : un constructeur constant qui a un argument
then (l, true, tree_of_typlist sch tyl)
else (l, false, tree_of_typlist sch tyl)
| Rabsent -> (l, false, [] (* une erreur, en fait *))
and tree_of_typlist sch tyl =
List.map (tree_of_typexp sch) tyl
and tree_of_typobject sch fi nm =
begin match !nm with
| None ->
let pr_fields fi =
let (fields, rest) = flatten_fields fi in
let present_fields =
List.fold_right
(fun (n, k, t) l ->
match field_kind_repr k with
| Fpresent -> (n, t) :: l
| _ -> l)
fields [] in
let sorted_fields =
Sort.list (fun (n, _) (n', _) -> n <= n') present_fields in
tree_of_typfields sch rest sorted_fields in
let (fields, rest) = pr_fields fi in
Otyp_object (fields, rest)
| Some (p, ty :: tyl) ->
let non_gen = is_non_gen sch (repr ty) in
let args = tree_of_typlist sch tyl in
Otyp_class (non_gen, tree_of_path p, args)
| _ ->
fatal_error "Printtyp.tree_of_typobject"
end
and is_non_gen sch ty =
sch && ty.desc = Tvar && ty.level <> generic_level
and tree_of_typfields sch rest = function
| [] ->
let rest =
match rest.desc with
| Tvar | Tunivar -> Some (is_non_gen sch rest)
| Tconstr _ -> Some false
| Tnil -> None
| _ -> fatal_error "typfields (1)"
in
([], rest)
| (s, t) :: l ->
let field = (s, tree_of_typexp sch t) in
let (fields, rest) = tree_of_typfields sch rest l in
(field :: fields, rest)
let typexp sch prio ppf ty =
!Oprint.out_type ppf (tree_of_typexp sch ty)
let type_expr ppf ty = typexp false 0 ppf ty
and type_sch ppf ty = typexp true 0 ppf ty
and type_scheme ppf ty = reset_and_mark_loops ty; typexp true 0 ppf ty
(* Maxence *)
let type_scheme_max ?(b_reset_names=true) ppf ty =
if b_reset_names then reset_names () ;
typexp true 0 ppf ty
let tree_of_type_scheme ty = reset_and_mark_loops ty; tree_of_typexp true ty
Print one type declaration
let tree_of_constraints params =
List.fold_right
(fun ty list ->
let ty' = unalias ty in
if proxy ty != proxy ty' then
let tr = tree_of_typexp true ty in
(tr, tree_of_typexp true ty') :: list
else list)
params []
let filter_params tyl =
let params =
List.fold_left
(fun tyl ty ->
let ty = repr ty in
if List.memq ty tyl then Btype.newgenty (Tsubst ty) :: tyl
else ty :: tyl)
[] tyl
in List.rev params
let string_of_mutable = function
| Immutable -> ""
| Mutable -> "mutable "
let rec tree_of_type_decl id decl =
reset();
let params = filter_params decl.type_params in
List.iter add_alias params;
List.iter mark_loops params;
List.iter check_name_of_type (List.map proxy params);
let ty_manifest =
match decl.type_manifest with
| None -> None
| Some ty ->
let ty =
(* Special hack to hide variant name *)
match repr ty with {desc=Tvariant row} ->
let row = row_repr row in
begin match row.row_name with
Some (Pident id', _) when Ident.same id id' ->
newgenty (Tvariant {row with row_name = None})
| _ -> ty
end
| _ -> ty
in
mark_loops ty;
Some ty
in
begin match decl.type_kind with
| Type_abstract -> ()
| Type_variant [] -> ()
| Type_variant cstrs ->
List.iter (fun (_, args) -> List.iter mark_loops args) cstrs
| Type_record(l, rep) ->
List.iter (fun (_, _, ty) -> mark_loops ty) l
end;
let type_param =
function
| Otyp_var (_, id) -> id
| _ -> "?"
in
let type_defined decl =
let abstr =
match decl.type_kind with
Type_abstract ->
begin match decl.type_manifest with
None -> true
| Some ty -> has_constr_row ty
end
| Type_variant _ | Type_record(_,_) ->
decl.type_private = Private
in
let vari =
List.map2
(fun ty (co,cn,ct) ->
if abstr || (repr ty).desc <> Tvar then (co,cn) else (true,true))
decl.type_params decl.type_variance
in
(Ident.name id,
List.map2 (fun ty cocn -> type_param (tree_of_typexp false ty), cocn)
params vari)
in
let tree_of_manifest ty1 =
match ty_manifest with
| None -> ty1
| Some ty -> Otyp_manifest (tree_of_typexp false ty, ty1)
in
let (name, args) = type_defined decl in
let constraints = tree_of_constraints params in
let ty, priv =
match decl.type_kind with
| Type_abstract ->
begin match ty_manifest with
| None -> (Otyp_abstract, Public)
| Some ty ->
tree_of_typexp false ty, decl.type_private
end
| Type_variant cstrs ->
tree_of_manifest (Otyp_sum (List.map tree_of_constructor cstrs)),
decl.type_private
| Type_record(lbls, rep) ->
tree_of_manifest (Otyp_record (List.map tree_of_label lbls)),
decl.type_private
in
(name, args, ty, priv, constraints)
and tree_of_constructor (name, args) =
(name, tree_of_typlist false args)
and tree_of_label (name, mut, arg) =
(name, mut = Mutable, tree_of_typexp false arg)
let tree_of_type_declaration id decl rs =
Osig_type (tree_of_type_decl id decl, tree_of_rec rs)
let type_declaration id ppf decl =
!Oprint.out_sig_item ppf (tree_of_type_declaration id decl Trec_first)
(* Print an exception declaration *)
let tree_of_exception_declaration id decl =
reset_and_mark_loops_list decl;
let tyl = tree_of_typlist false decl in
Osig_exception (Ident.name id, tyl)
let exception_declaration id ppf decl =
!Oprint.out_sig_item ppf (tree_of_exception_declaration id decl)
(* Print a value declaration *)
let tree_of_value_description id decl =
let id = Ident.name id in
let ty = tree_of_type_scheme decl.val_type in
let prims =
match decl.val_kind with
| Val_prim p -> Primitive.description_list p
| _ -> []
in
Osig_value (id, ty, prims)
let value_description id ppf decl =
!Oprint.out_sig_item ppf (tree_of_value_description id decl)
(* Print a class type *)
let class_var sch ppf l (m, t) =
fprintf ppf
"@ @[<2>val %s%s :@ %a@]" (string_of_mutable m) l (typexp sch 0) t
let method_type (_, kind, ty) =
match field_kind_repr kind, repr ty with
Fpresent, {desc=Tpoly(ty, _)} -> ty
| _ , ty -> ty
let tree_of_metho sch concrete csil (lab, kind, ty) =
if lab <> dummy_method then begin
let kind = field_kind_repr kind in
let priv = kind <> Fpresent in
let virt = not (Concr.mem lab concrete) in
let ty = method_type (lab, kind, ty) in
Ocsg_method (lab, priv, virt, tree_of_typexp sch ty) :: csil
end
else csil
let rec prepare_class_type params = function
| Tcty_constr (p, tyl, cty) ->
let sty = Ctype.self_type cty in
if List.memq (proxy sty) !visited_objects
|| List.exists (fun ty -> (repr ty).desc <> Tvar) params
|| List.exists (deep_occur sty) tyl
then prepare_class_type params cty
else List.iter mark_loops tyl
| Tcty_signature sign ->
let sty = repr sign.cty_self in
(* Self may have a name *)
let px = proxy sty in
if List.memq px !visited_objects then add_alias sty
else visited_objects := px :: !visited_objects;
let (fields, _) =
Ctype.flatten_fields (Ctype.object_fields sign.cty_self)
in
List.iter (fun met -> mark_loops (method_type met)) fields;
Vars.iter (fun _ (_, _, ty) -> mark_loops ty) sign.cty_vars
| Tcty_fun (_, ty, cty) ->
mark_loops ty;
prepare_class_type params cty
let rec tree_of_class_type sch params =
function
| Tcty_constr (p', tyl, cty) ->
let sty = Ctype.self_type cty in
if List.memq (proxy sty) !visited_objects
|| List.exists (fun ty -> (repr ty).desc <> Tvar) params
then
tree_of_class_type sch params cty
else
Octy_constr (tree_of_path p', tree_of_typlist true tyl)
| Tcty_signature sign ->
let sty = repr sign.cty_self in
let self_ty =
if is_aliased sty then
Some (Otyp_var (false, name_of_type (proxy sty)))
else None
in
let (fields, _) =
Ctype.flatten_fields (Ctype.object_fields sign.cty_self)
in
let csil = [] in
let csil =
List.fold_left
(fun csil (ty1, ty2) -> Ocsg_constraint (ty1, ty2) :: csil)
csil (tree_of_constraints params)
in
let all_vars =
Vars.fold (fun l (m, v, t) all -> (l, m, v, t) :: all) sign.cty_vars []
in
Consequence of PR#3607 : order of Map.fold has changed !
let all_vars = List.rev all_vars in
let csil =
List.fold_left
(fun csil (l, m, v, t) ->
Ocsg_value (l, m = Mutable, v = Virtual, tree_of_typexp sch t)
:: csil)
csil all_vars
in
let csil =
List.fold_left (tree_of_metho sch sign.cty_concr) csil fields
in
Octy_signature (self_ty, List.rev csil)
| Tcty_fun (l, ty, cty) ->
let lab = if !print_labels && l <> "" || is_optional l then l else "" in
let ty =
if is_optional l then
match (repr ty).desc with
| Tconstr(path, [ty], _) when Path.same path Predef.path_option -> ty
| _ -> newconstr (Path.Pident(Ident.create "<hidden>")) []
else ty in
let tr = tree_of_typexp sch ty in
Octy_fun (lab, tr, tree_of_class_type sch params cty)
let class_type ppf cty =
reset ();
prepare_class_type [] cty;
!Oprint.out_class_type ppf (tree_of_class_type false [] cty)
let tree_of_class_param param variance =
(match tree_of_typexp true param with
Otyp_var (_, s) -> s
| _ -> "?"),
if (repr param).desc = Tvar then (true, true) else variance
let tree_of_class_params params =
let tyl = tree_of_typlist true params in
List.map (function Otyp_var (_, s) -> s | _ -> "?") tyl
let tree_of_class_declaration id cl rs =
let params = filter_params cl.cty_params in
reset ();
List.iter add_alias params;
prepare_class_type params cl.cty_type;
let sty = self_type cl.cty_type in
List.iter mark_loops params;
List.iter check_name_of_type (List.map proxy params);
if is_aliased sty then check_name_of_type (proxy sty);
let vir_flag = cl.cty_new = None in
Osig_class
(vir_flag, Ident.name id,
List.map2 tree_of_class_param params cl.cty_variance,
tree_of_class_type true params cl.cty_type,
tree_of_rec rs)
let class_declaration id ppf cl =
!Oprint.out_sig_item ppf (tree_of_class_declaration id cl Trec_first)
let tree_of_cltype_declaration id cl rs =
let params = List.map repr cl.clty_params in
reset ();
List.iter add_alias params;
prepare_class_type params cl.clty_type;
let sty = self_type cl.clty_type in
List.iter mark_loops params;
List.iter check_name_of_type (List.map proxy params);
if is_aliased sty then check_name_of_type (proxy sty);
let sign = Ctype.signature_of_class_type cl.clty_type in
let virt =
let (fields, _) =
Ctype.flatten_fields (Ctype.object_fields sign.cty_self) in
List.exists
(fun (lab, _, ty) ->
not (lab = dummy_method || Concr.mem lab sign.cty_concr))
fields
|| Vars.fold (fun _ (_,vr,_) b -> vr = Virtual || b) sign.cty_vars false
in
Osig_class_type
(virt, Ident.name id,
List.map2 tree_of_class_param params cl.clty_variance,
tree_of_class_type true params cl.clty_type,
tree_of_rec rs)
let cltype_declaration id ppf cl =
!Oprint.out_sig_item ppf (tree_of_cltype_declaration id cl Trec_first)
(* Print a module type *)
let rec tree_of_modtype = function
| Tmty_ident p ->
Omty_ident (tree_of_path p)
| Tmty_signature sg ->
Omty_signature (tree_of_signature sg)
| Tmty_functor(param, ty_arg, ty_res) ->
Omty_functor
(Ident.name param, tree_of_modtype ty_arg, tree_of_modtype ty_res)
and tree_of_signature = function
| [] -> []
| Tsig_value(id, decl) :: rem ->
tree_of_value_description id decl :: tree_of_signature rem
| Tsig_type(id, _, _) :: rem when is_row_name (Ident.name id) ->
tree_of_signature rem
| Tsig_type(id, decl, rs) :: rem ->
Osig_type(tree_of_type_decl id decl, tree_of_rec rs) ::
tree_of_signature rem
| Tsig_exception(id, decl) :: rem ->
tree_of_exception_declaration id decl :: tree_of_signature rem
| Tsig_module(id, mty, rs) :: rem ->
Osig_module (Ident.name id, tree_of_modtype mty, tree_of_rec rs) ::
tree_of_signature rem
| Tsig_modtype(id, decl) :: rem ->
tree_of_modtype_declaration id decl :: tree_of_signature rem
| Tsig_class(id, decl, rs) :: ctydecl :: tydecl1 :: tydecl2 :: rem ->
tree_of_class_declaration id decl rs :: tree_of_signature rem
| Tsig_cltype(id, decl, rs) :: tydecl1 :: tydecl2 :: rem ->
tree_of_cltype_declaration id decl rs :: tree_of_signature rem
| _ ->
assert false
and tree_of_modtype_declaration id decl =
let mty =
match decl with
| Tmodtype_abstract -> Omty_abstract
| Tmodtype_manifest mty -> tree_of_modtype mty
in
Osig_modtype (Ident.name id, mty)
let tree_of_module id mty rs =
Osig_module (Ident.name id, tree_of_modtype mty, tree_of_rec rs)
let modtype ppf mty = !Oprint.out_module_type ppf (tree_of_modtype mty)
let modtype_declaration id ppf decl =
!Oprint.out_sig_item ppf (tree_of_modtype_declaration id decl)
Print a signature body ( used by -i when compiling a .ml )
let print_signature ppf tree =
fprintf ppf "@[<v>%a@]" !Oprint.out_signature tree
let signature ppf sg =
fprintf ppf "%a" print_signature (tree_of_signature sg)
(* Print an unification error *)
let type_expansion t ppf t' =
if t == t' then type_expr ppf t else
let t' = if proxy t == proxy t' then unalias t' else t' in
fprintf ppf "@[<2>%a@ =@ %a@]" type_expr t type_expr t'
let rec trace fst txt ppf = function
| (t1, t1') :: (t2, t2') :: rem ->
if not fst then fprintf ppf "@,";
fprintf ppf "@[Type@;<1 2>%a@ %s@;<1 2>%a@] %a"
(type_expansion t1) t1' txt (type_expansion t2) t2'
(trace false txt) rem
| _ -> ()
let rec filter_trace = function
| (t1, t1') :: (t2, t2') :: rem ->
let rem' = filter_trace rem in
if t1 == t1' && t2 == t2'
then rem'
else (t1, t1') :: (t2, t2') :: rem'
| _ -> []
(* Hide variant name and var, to force printing the expanded type *)
let hide_variant_name t =
match repr t with
| {desc = Tvariant row} as t when (row_repr row).row_name <> None ->
newty2 t.level
(Tvariant {(row_repr row) with row_name = None;
row_more = newty2 (row_more row).level Tvar})
| _ -> t
let prepare_expansion (t, t') =
let t' = hide_variant_name t' in
mark_loops t; if t != t' then mark_loops t';
(t, t')
let may_prepare_expansion compact (t, t') =
match (repr t').desc with
Tvariant _ | Tobject _ when compact ->
mark_loops t; (t, t)
| _ -> prepare_expansion (t, t')
let print_tags ppf fields =
match fields with [] -> ()
| (t, _) :: fields ->
fprintf ppf "`%s" t;
List.iter (fun (t, _) -> fprintf ppf ",@ `%s" t) fields
let has_explanation unif t3 t4 =
match t3.desc, t4.desc with
Tfield _, _ | _, Tfield _
| Tunivar, Tvar | Tvar, Tunivar
| Tvariant _, Tvariant _ -> true
| Tconstr (p, _, _), Tvar | Tvar, Tconstr (p, _, _) ->
unif && min t3.level t4.level < Path.binding_time p
| _ -> false
let rec mismatch unif = function
(_, t) :: (_, t') :: rem ->
begin match mismatch unif rem with
Some _ as m -> m
| None ->
if has_explanation unif t t' then Some(t,t') else None
end
| [] -> None
| _ -> assert false
let explanation unif t3 t4 ppf =
match t3.desc, t4.desc with
| Tfield _, Tvar | Tvar, Tfield _ ->
fprintf ppf "@,Self type cannot escape its class"
| Tconstr (p, _, _), Tvar
when unif && t4.level < Path.binding_time p ->
fprintf ppf
"@,@[The type constructor@;<1 2>%a@ would escape its scope@]"
path p
| Tvar, Tconstr (p, _, _)
when unif && t3.level < Path.binding_time p ->
fprintf ppf
"@,@[The type constructor@;<1 2>%a@ would escape its scope@]"
path p
| Tvar, Tunivar | Tunivar, Tvar ->
fprintf ppf "@,The universal variable %a would escape its scope"
type_expr (if t3.desc = Tunivar then t3 else t4)
| Tfield (lab, _, _, _), _
| _, Tfield (lab, _, _, _) when lab = dummy_method ->
fprintf ppf
"@,Self type cannot be unified with a closed object type"
| Tfield (l, _, _, _), Tfield (l', _, _, _) when l = l' ->
fprintf ppf "@,Types for method %s are incompatible" l
| _, Tfield (l, _, _, _) ->
fprintf ppf
"@,@[The first object type has no method %s@]" l
| Tfield (l, _, _, _), _ ->
fprintf ppf
"@,@[The second object type has no method %s@]" l
| Tvariant row1, Tvariant row2 ->
let row1 = row_repr row1 and row2 = row_repr row2 in
begin match
row1.row_fields, row1.row_closed, row2.row_fields, row2.row_closed with
| [], true, [], true ->
fprintf ppf "@,These two variant types have no intersection"
| [], true, fields, _ ->
fprintf ppf
"@,@[The first variant type does not allow tag(s)@ @[<hov>%a@]@]"
print_tags fields
| fields, _, [], true ->
fprintf ppf
"@,@[The second variant type does not allow tag(s)@ @[<hov>%a@]@]"
print_tags fields
| [l1,_], true, [l2,_], true when l1 = l2 ->
fprintf ppf "@,Types for tag `%s are incompatible" l1
| _ -> ()
end
| _ -> ()
let explanation unif mis ppf =
match mis with
None -> ()
| Some (t3, t4) -> explanation unif t3 t4 ppf
let unification_error unif tr txt1 ppf txt2 =
reset ();
let tr = List.map (fun (t, t') -> (t, hide_variant_name t')) tr in
let mis = mismatch unif tr in
match tr with
| [] | _ :: [] -> assert false
| t1 :: t2 :: tr ->
try
let tr = filter_trace tr in
let t1, t1' = may_prepare_expansion (tr = []) t1
and t2, t2' = may_prepare_expansion (tr = []) t2 in
print_labels := not !Clflags.classic;
let tr = List.map prepare_expansion tr in
fprintf ppf
"@[<v>\
@[%t@;<1 2>%a@ \
%t@;<1 2>%a\
@]%a%t\
@]"
txt1 (type_expansion t1) t1'
txt2 (type_expansion t2) t2'
(trace false "is not compatible with type") tr
(explanation unif mis);
print_labels := true
with exn ->
print_labels := true;
raise exn
let report_unification_error ppf tr txt1 txt2 =
unification_error true tr txt1 ppf txt2;;
let trace fst txt ppf tr =
print_labels := not !Clflags.classic;
try match tr with
t1 :: t2 :: tr' ->
if fst then trace fst txt ppf (t1 :: t2 :: filter_trace tr')
else trace fst txt ppf (filter_trace tr);
print_labels := true
| _ -> ()
with exn ->
print_labels := true;
raise exn
let report_subtyping_error ppf tr1 txt1 tr2 =
reset ();
let tr1 = List.map prepare_expansion tr1
and tr2 = List.map prepare_expansion tr2 in
trace true txt1 ppf tr1;
if tr2 = [] then () else
let mis = mismatch true tr2 in
trace false "is not compatible with type" ppf tr2;
explanation true mis ppf
| null | https://raw.githubusercontent.com/rizo/snowflake-os/51df43d9ba715532d325e8880d3b8b2c589cd075/plugins/ocamlopt.opt/typing/printtyp.ml | ocaml | *********************************************************************
Objective Caml
*********************************************************************
Printing functions
Print a long identifier
Print an identifier
Print a path
Print a recursive annotation
Print a raw type expression, with sharing
Print a type expression
Disabled in classic mode when printing an unification error
une erreur, en fait
Maxence
Special hack to hide variant name
Print an exception declaration
Print a value declaration
Print a class type
Self may have a name
Print a module type
Print an unification error
Hide variant name and var, to force printing the expanded type | and , projet Cristal , INRIA Rocquencourt
Copyright 1996 Institut National de Recherche en Informatique et
en Automatique . All rights reserved . This file is distributed
under the terms of the Q Public License version 1.0 .
$ Id$
open Misc
open Ctype
open Format
open Longident
open Path
open Asttypes
open Types
open Btype
open Outcometree
let rec longident ppf = function
| Lident s -> fprintf ppf "%s" s
| Ldot(p, s) -> fprintf ppf "%a.%s" longident p s
| Lapply(p1, p2) -> fprintf ppf "%a(%a)" longident p1 longident p2
let ident ppf id = fprintf ppf "%s" (Ident.name id)
let ident_pervasive = Ident.create_persistent "Pervasives"
let rec tree_of_path = function
| Pident id ->
Oide_ident (Ident.name id)
| Pdot(Pident id, s, pos) when Ident.same id ident_pervasive ->
Oide_ident s
| Pdot(p, s, pos) ->
Oide_dot (tree_of_path p, s)
| Papply(p1, p2) ->
Oide_apply (tree_of_path p1, tree_of_path p2)
let rec path ppf = function
| Pident id ->
ident ppf id
| Pdot(Pident id, s, pos) when Ident.same id ident_pervasive ->
fprintf ppf "%s" s
| Pdot(p, s, pos) ->
fprintf ppf "%a.%s" path p s
| Papply(p1, p2) ->
fprintf ppf "%a(%a)" path p1 path p2
let tree_of_rec = function
| Trec_not -> Orec_not
| Trec_first -> Orec_first
| Trec_next -> Orec_next
let raw_list pr ppf = function
[] -> fprintf ppf "[]"
| a :: l ->
fprintf ppf "@[<1>[%a%t]@]" pr a
(fun ppf -> List.iter (fun x -> fprintf ppf ";@,%a" pr x) l)
let rec safe_kind_repr v = function
Fvar {contents=Some k} ->
if List.memq k v then "Fvar loop" else
safe_kind_repr (k::v) k
| Fvar _ -> "Fvar None"
| Fpresent -> "Fpresent"
| Fabsent -> "Fabsent"
let rec safe_commu_repr v = function
Cok -> "Cok"
| Cunknown -> "Cunknown"
| Clink r ->
if List.memq r v then "Clink loop" else
safe_commu_repr (r::v) !r
let rec safe_repr v = function
{desc = Tlink t} when not (List.memq t v) ->
safe_repr (t::v) t
| t -> t
let rec list_of_memo = function
Mnil -> []
| Mcons (priv, p, t1, t2, rem) -> p :: list_of_memo rem
| Mlink rem -> list_of_memo !rem
let visited = ref []
let rec raw_type ppf ty =
let ty = safe_repr [] ty in
if List.memq ty !visited then fprintf ppf "{id=%d}" ty.id else begin
visited := ty :: !visited;
fprintf ppf "@[<1>{id=%d;level=%d;desc=@,%a}@]" ty.id ty.level
raw_type_desc ty.desc
end
and raw_type_list tl = raw_list raw_type tl
and raw_type_desc ppf = function
Tvar -> fprintf ppf "Tvar"
| Tarrow(l,t1,t2,c) ->
fprintf ppf "@[<hov1>Tarrow(%s,@,%a,@,%a,@,%s)@]"
l raw_type t1 raw_type t2
(safe_commu_repr [] c)
| Ttuple tl ->
fprintf ppf "@[<1>Ttuple@,%a@]" raw_type_list tl
| Tconstr (p, tl, abbrev) ->
fprintf ppf "@[<hov1>Tconstr(@,%a,@,%a,@,%a)@]" path p
raw_type_list tl
(raw_list path) (list_of_memo !abbrev)
| Tobject (t, nm) ->
fprintf ppf "@[<hov1>Tobject(@,%a,@,@[<1>ref%t@])@]" raw_type t
(fun ppf ->
match !nm with None -> fprintf ppf " None"
| Some(p,tl) ->
fprintf ppf "(Some(@,%a,@,%a))" path p raw_type_list tl)
| Tfield (f, k, t1, t2) ->
fprintf ppf "@[<hov1>Tfield(@,%s,@,%s,@,%a,@;<0 -1>%a)@]" f
(safe_kind_repr [] k)
raw_type t1 raw_type t2
| Tnil -> fprintf ppf "Tnil"
| Tlink t -> fprintf ppf "@[<1>Tlink@,%a@]" raw_type t
| Tsubst t -> fprintf ppf "@[<1>Tsubst@,%a@]" raw_type t
| Tunivar -> fprintf ppf "Tunivar"
| Tpoly (t, tl) ->
fprintf ppf "@[<hov1>Tpoly(@,%a,@,%a)@]"
raw_type t
raw_type_list tl
| Tvariant row ->
fprintf ppf
"@[<hov1>{@[%s@,%a;@]@ @[%s@,%a;@]@ %s%b;@ %s%b;@ @[<1>%s%t@]}@]"
"row_fields="
(raw_list (fun ppf (l, f) ->
fprintf ppf "@[%s,@ %a@]" l raw_field f))
row.row_fields
"row_more=" raw_type row.row_more
"row_closed=" row.row_closed
"row_fixed=" row.row_fixed
"row_name="
(fun ppf ->
match row.row_name with None -> fprintf ppf "None"
| Some(p,tl) ->
fprintf ppf "Some(@,%a,@,%a)" path p raw_type_list tl)
| Tpackage (p, _, tl) ->
fprintf ppf "@[<hov1>Tpackage(@,%a@,%a)@]" path p
raw_type_list tl
and raw_field ppf = function
Rpresent None -> fprintf ppf "Rpresent None"
| Rpresent (Some t) -> fprintf ppf "@[<1>Rpresent(Some@,%a)@]" raw_type t
| Reither (c,tl,m,e) ->
fprintf ppf "@[<hov1>Reither(%b,@,%a,@,%b,@,@[<1>ref%t@])@]" c
raw_type_list tl m
(fun ppf ->
match !e with None -> fprintf ppf " None"
| Some f -> fprintf ppf "@,@[<1>(%a)@]" raw_field f)
| Rabsent -> fprintf ppf "Rabsent"
let raw_type_expr ppf t =
visited := [];
raw_type ppf t;
visited := []
let names = ref ([] : (type_expr * string) list)
let name_counter = ref 0
let reset_names () = names := []; name_counter := 0
let new_name () =
let name =
if !name_counter < 26
then String.make 1 (Char.chr(97 + !name_counter))
else String.make 1 (Char.chr(97 + !name_counter mod 26)) ^
string_of_int(!name_counter / 26) in
incr name_counter;
name
let name_of_type t =
try List.assq t !names with Not_found ->
let name = new_name () in
names := (t, name) :: !names;
name
let check_name_of_type t = ignore(name_of_type t)
let non_gen_mark sch ty =
if sch && ty.desc = Tvar && ty.level <> generic_level then "_" else ""
let print_name_of_type sch ppf t =
fprintf ppf "'%s%s" (non_gen_mark sch t) (name_of_type t)
let visited_objects = ref ([] : type_expr list)
let aliased = ref ([] : type_expr list)
let delayed = ref ([] : type_expr list)
let add_delayed t =
if not (List.memq t !delayed) then delayed := t :: !delayed
let is_aliased ty = List.memq (proxy ty) !aliased
let add_alias ty =
let px = proxy ty in
if not (is_aliased px) then aliased := px :: !aliased
let aliasable ty =
match ty.desc with Tvar | Tunivar | Tpoly _ -> false | _ -> true
let namable_row row =
row.row_name <> None &&
List.for_all
(fun (_, f) ->
match row_field_repr f with
| Reither(c, l, _, _) ->
row.row_closed && if c then l = [] else List.length l = 1
| _ -> true)
row.row_fields
let rec mark_loops_rec visited ty =
let ty = repr ty in
let px = proxy ty in
if List.memq px visited && aliasable ty then add_alias px else
let visited = px :: visited in
match ty.desc with
| Tvar -> ()
| Tarrow(_, ty1, ty2, _) ->
mark_loops_rec visited ty1; mark_loops_rec visited ty2
| Ttuple tyl -> List.iter (mark_loops_rec visited) tyl
| Tconstr(_, tyl, _) | Tpackage (_, _, tyl) ->
List.iter (mark_loops_rec visited) tyl
| Tvariant row ->
if List.memq px !visited_objects then add_alias px else
begin
let row = row_repr row in
if not (static_row row) then
visited_objects := px :: !visited_objects;
match row.row_name with
| Some(p, tyl) when namable_row row ->
List.iter (mark_loops_rec visited) tyl
| _ ->
iter_row (mark_loops_rec visited) row
end
| Tobject (fi, nm) ->
if List.memq px !visited_objects then add_alias px else
begin
if opened_object ty then
visited_objects := px :: !visited_objects;
begin match !nm with
| None ->
let fields, _ = flatten_fields fi in
List.iter
(fun (_, kind, ty) ->
if field_kind_repr kind = Fpresent then
mark_loops_rec visited ty)
fields
| Some (_, l) ->
List.iter (mark_loops_rec visited) (List.tl l)
end
end
| Tfield(_, kind, ty1, ty2) when field_kind_repr kind = Fpresent ->
mark_loops_rec visited ty1; mark_loops_rec visited ty2
| Tfield(_, _, _, ty2) ->
mark_loops_rec visited ty2
| Tnil -> ()
| Tsubst ty -> mark_loops_rec visited ty
| Tlink _ -> fatal_error "Printtyp.mark_loops_rec (2)"
| Tpoly (ty, tyl) ->
List.iter (fun t -> add_alias t) tyl;
mark_loops_rec visited ty
| Tunivar -> ()
let mark_loops ty =
normalize_type Env.empty ty;
mark_loops_rec [] ty;;
let reset_loop_marks () =
visited_objects := []; aliased := []; delayed := []
let reset () =
reset_names (); reset_loop_marks ()
let reset_and_mark_loops ty =
reset (); mark_loops ty
let reset_and_mark_loops_list tyl =
reset (); List.iter mark_loops tyl
let print_labels = ref true
let print_label ppf l =
if !print_labels && l <> "" || is_optional l then fprintf ppf "%s:" l
let rec tree_of_typexp sch ty =
let ty = repr ty in
let px = proxy ty in
if List.mem_assq px !names && not (List.memq px !delayed) then
let mark = is_non_gen sch ty in
Otyp_var (mark, name_of_type px) else
let pr_typ () =
match ty.desc with
| Tvar ->
Otyp_var (is_non_gen sch ty, name_of_type ty)
| Tarrow(l, ty1, ty2, _) ->
let pr_arrow l ty1 ty2 =
let lab =
if !print_labels && l <> "" || is_optional l then l else ""
in
let t1 =
if is_optional l then
match (repr ty1).desc with
| Tconstr(path, [ty], _)
when Path.same path Predef.path_option ->
tree_of_typexp sch ty
| _ -> Otyp_stuff "<hidden>"
else tree_of_typexp sch ty1 in
Otyp_arrow (lab, t1, tree_of_typexp sch ty2) in
pr_arrow l ty1 ty2
| Ttuple tyl ->
Otyp_tuple (tree_of_typlist sch tyl)
| Tconstr(p, tyl, abbrev) ->
Otyp_constr (tree_of_path p, tree_of_typlist sch tyl)
| Tvariant row ->
let row = row_repr row in
let fields =
if row.row_closed then
List.filter (fun (_, f) -> row_field_repr f <> Rabsent)
row.row_fields
else row.row_fields in
let present =
List.filter
(fun (_, f) ->
match row_field_repr f with
| Rpresent _ -> true
| _ -> false)
fields in
let all_present = List.length present = List.length fields in
begin match row.row_name with
| Some(p, tyl) when namable_row row ->
let id = tree_of_path p in
let args = tree_of_typlist sch tyl in
if row.row_closed && all_present then
Otyp_constr (id, args)
else
let non_gen = is_non_gen sch px in
let tags =
if all_present then None else Some (List.map fst present) in
Otyp_variant (non_gen, Ovar_name(tree_of_path p, args),
row.row_closed, tags)
| _ ->
let non_gen =
not (row.row_closed && all_present) && is_non_gen sch px in
let fields = List.map (tree_of_row_field sch) fields in
let tags =
if all_present then None else Some (List.map fst present) in
Otyp_variant (non_gen, Ovar_fields fields, row.row_closed, tags)
end
| Tobject (fi, nm) ->
tree_of_typobject sch fi nm
| Tsubst ty ->
tree_of_typexp sch ty
| Tlink _ | Tnil | Tfield _ ->
fatal_error "Printtyp.tree_of_typexp"
| Tpoly (ty, []) ->
tree_of_typexp sch ty
| Tpoly (ty, tyl) ->
let tyl = List.map repr tyl in
let tyl = List.filter is_aliased tyl in
if tyl = [] then tree_of_typexp sch ty else begin
let old_delayed = !delayed in
List.iter add_delayed tyl;
let tl = List.map name_of_type tyl in
let tr = Otyp_poly (tl, tree_of_typexp sch ty) in
delayed := old_delayed; tr
end
| Tunivar ->
Otyp_var (false, name_of_type ty)
| Tpackage (p, n, tyl) ->
Otyp_module (Path.name p, n, tree_of_typlist sch tyl)
in
if List.memq px !delayed then delayed := List.filter ((!=) px) !delayed;
if is_aliased px && aliasable ty then begin
check_name_of_type px;
Otyp_alias (pr_typ (), name_of_type px) end
else pr_typ ()
and tree_of_row_field sch (l, f) =
match row_field_repr f with
| Rpresent None | Reither(true, [], _, _) -> (l, false, [])
| Rpresent(Some ty) -> (l, false, [tree_of_typexp sch ty])
| Reither(c, tyl, _, _) ->
contradiction : un constructeur constant qui a un argument
then (l, true, tree_of_typlist sch tyl)
else (l, false, tree_of_typlist sch tyl)
and tree_of_typlist sch tyl =
List.map (tree_of_typexp sch) tyl
and tree_of_typobject sch fi nm =
begin match !nm with
| None ->
let pr_fields fi =
let (fields, rest) = flatten_fields fi in
let present_fields =
List.fold_right
(fun (n, k, t) l ->
match field_kind_repr k with
| Fpresent -> (n, t) :: l
| _ -> l)
fields [] in
let sorted_fields =
Sort.list (fun (n, _) (n', _) -> n <= n') present_fields in
tree_of_typfields sch rest sorted_fields in
let (fields, rest) = pr_fields fi in
Otyp_object (fields, rest)
| Some (p, ty :: tyl) ->
let non_gen = is_non_gen sch (repr ty) in
let args = tree_of_typlist sch tyl in
Otyp_class (non_gen, tree_of_path p, args)
| _ ->
fatal_error "Printtyp.tree_of_typobject"
end
and is_non_gen sch ty =
sch && ty.desc = Tvar && ty.level <> generic_level
and tree_of_typfields sch rest = function
| [] ->
let rest =
match rest.desc with
| Tvar | Tunivar -> Some (is_non_gen sch rest)
| Tconstr _ -> Some false
| Tnil -> None
| _ -> fatal_error "typfields (1)"
in
([], rest)
| (s, t) :: l ->
let field = (s, tree_of_typexp sch t) in
let (fields, rest) = tree_of_typfields sch rest l in
(field :: fields, rest)
let typexp sch prio ppf ty =
!Oprint.out_type ppf (tree_of_typexp sch ty)
let type_expr ppf ty = typexp false 0 ppf ty
and type_sch ppf ty = typexp true 0 ppf ty
and type_scheme ppf ty = reset_and_mark_loops ty; typexp true 0 ppf ty
let type_scheme_max ?(b_reset_names=true) ppf ty =
if b_reset_names then reset_names () ;
typexp true 0 ppf ty
let tree_of_type_scheme ty = reset_and_mark_loops ty; tree_of_typexp true ty
Print one type declaration
let tree_of_constraints params =
List.fold_right
(fun ty list ->
let ty' = unalias ty in
if proxy ty != proxy ty' then
let tr = tree_of_typexp true ty in
(tr, tree_of_typexp true ty') :: list
else list)
params []
let filter_params tyl =
let params =
List.fold_left
(fun tyl ty ->
let ty = repr ty in
if List.memq ty tyl then Btype.newgenty (Tsubst ty) :: tyl
else ty :: tyl)
[] tyl
in List.rev params
let string_of_mutable = function
| Immutable -> ""
| Mutable -> "mutable "
let rec tree_of_type_decl id decl =
reset();
let params = filter_params decl.type_params in
List.iter add_alias params;
List.iter mark_loops params;
List.iter check_name_of_type (List.map proxy params);
let ty_manifest =
match decl.type_manifest with
| None -> None
| Some ty ->
let ty =
match repr ty with {desc=Tvariant row} ->
let row = row_repr row in
begin match row.row_name with
Some (Pident id', _) when Ident.same id id' ->
newgenty (Tvariant {row with row_name = None})
| _ -> ty
end
| _ -> ty
in
mark_loops ty;
Some ty
in
begin match decl.type_kind with
| Type_abstract -> ()
| Type_variant [] -> ()
| Type_variant cstrs ->
List.iter (fun (_, args) -> List.iter mark_loops args) cstrs
| Type_record(l, rep) ->
List.iter (fun (_, _, ty) -> mark_loops ty) l
end;
let type_param =
function
| Otyp_var (_, id) -> id
| _ -> "?"
in
let type_defined decl =
let abstr =
match decl.type_kind with
Type_abstract ->
begin match decl.type_manifest with
None -> true
| Some ty -> has_constr_row ty
end
| Type_variant _ | Type_record(_,_) ->
decl.type_private = Private
in
let vari =
List.map2
(fun ty (co,cn,ct) ->
if abstr || (repr ty).desc <> Tvar then (co,cn) else (true,true))
decl.type_params decl.type_variance
in
(Ident.name id,
List.map2 (fun ty cocn -> type_param (tree_of_typexp false ty), cocn)
params vari)
in
let tree_of_manifest ty1 =
match ty_manifest with
| None -> ty1
| Some ty -> Otyp_manifest (tree_of_typexp false ty, ty1)
in
let (name, args) = type_defined decl in
let constraints = tree_of_constraints params in
let ty, priv =
match decl.type_kind with
| Type_abstract ->
begin match ty_manifest with
| None -> (Otyp_abstract, Public)
| Some ty ->
tree_of_typexp false ty, decl.type_private
end
| Type_variant cstrs ->
tree_of_manifest (Otyp_sum (List.map tree_of_constructor cstrs)),
decl.type_private
| Type_record(lbls, rep) ->
tree_of_manifest (Otyp_record (List.map tree_of_label lbls)),
decl.type_private
in
(name, args, ty, priv, constraints)
and tree_of_constructor (name, args) =
(name, tree_of_typlist false args)
and tree_of_label (name, mut, arg) =
(name, mut = Mutable, tree_of_typexp false arg)
let tree_of_type_declaration id decl rs =
Osig_type (tree_of_type_decl id decl, tree_of_rec rs)
let type_declaration id ppf decl =
!Oprint.out_sig_item ppf (tree_of_type_declaration id decl Trec_first)
let tree_of_exception_declaration id decl =
reset_and_mark_loops_list decl;
let tyl = tree_of_typlist false decl in
Osig_exception (Ident.name id, tyl)
let exception_declaration id ppf decl =
!Oprint.out_sig_item ppf (tree_of_exception_declaration id decl)
let tree_of_value_description id decl =
let id = Ident.name id in
let ty = tree_of_type_scheme decl.val_type in
let prims =
match decl.val_kind with
| Val_prim p -> Primitive.description_list p
| _ -> []
in
Osig_value (id, ty, prims)
let value_description id ppf decl =
!Oprint.out_sig_item ppf (tree_of_value_description id decl)
let class_var sch ppf l (m, t) =
fprintf ppf
"@ @[<2>val %s%s :@ %a@]" (string_of_mutable m) l (typexp sch 0) t
let method_type (_, kind, ty) =
match field_kind_repr kind, repr ty with
Fpresent, {desc=Tpoly(ty, _)} -> ty
| _ , ty -> ty
let tree_of_metho sch concrete csil (lab, kind, ty) =
if lab <> dummy_method then begin
let kind = field_kind_repr kind in
let priv = kind <> Fpresent in
let virt = not (Concr.mem lab concrete) in
let ty = method_type (lab, kind, ty) in
Ocsg_method (lab, priv, virt, tree_of_typexp sch ty) :: csil
end
else csil
let rec prepare_class_type params = function
| Tcty_constr (p, tyl, cty) ->
let sty = Ctype.self_type cty in
if List.memq (proxy sty) !visited_objects
|| List.exists (fun ty -> (repr ty).desc <> Tvar) params
|| List.exists (deep_occur sty) tyl
then prepare_class_type params cty
else List.iter mark_loops tyl
| Tcty_signature sign ->
let sty = repr sign.cty_self in
let px = proxy sty in
if List.memq px !visited_objects then add_alias sty
else visited_objects := px :: !visited_objects;
let (fields, _) =
Ctype.flatten_fields (Ctype.object_fields sign.cty_self)
in
List.iter (fun met -> mark_loops (method_type met)) fields;
Vars.iter (fun _ (_, _, ty) -> mark_loops ty) sign.cty_vars
| Tcty_fun (_, ty, cty) ->
mark_loops ty;
prepare_class_type params cty
let rec tree_of_class_type sch params =
function
| Tcty_constr (p', tyl, cty) ->
let sty = Ctype.self_type cty in
if List.memq (proxy sty) !visited_objects
|| List.exists (fun ty -> (repr ty).desc <> Tvar) params
then
tree_of_class_type sch params cty
else
Octy_constr (tree_of_path p', tree_of_typlist true tyl)
| Tcty_signature sign ->
let sty = repr sign.cty_self in
let self_ty =
if is_aliased sty then
Some (Otyp_var (false, name_of_type (proxy sty)))
else None
in
let (fields, _) =
Ctype.flatten_fields (Ctype.object_fields sign.cty_self)
in
let csil = [] in
let csil =
List.fold_left
(fun csil (ty1, ty2) -> Ocsg_constraint (ty1, ty2) :: csil)
csil (tree_of_constraints params)
in
let all_vars =
Vars.fold (fun l (m, v, t) all -> (l, m, v, t) :: all) sign.cty_vars []
in
Consequence of PR#3607 : order of Map.fold has changed !
let all_vars = List.rev all_vars in
let csil =
List.fold_left
(fun csil (l, m, v, t) ->
Ocsg_value (l, m = Mutable, v = Virtual, tree_of_typexp sch t)
:: csil)
csil all_vars
in
let csil =
List.fold_left (tree_of_metho sch sign.cty_concr) csil fields
in
Octy_signature (self_ty, List.rev csil)
| Tcty_fun (l, ty, cty) ->
let lab = if !print_labels && l <> "" || is_optional l then l else "" in
let ty =
if is_optional l then
match (repr ty).desc with
| Tconstr(path, [ty], _) when Path.same path Predef.path_option -> ty
| _ -> newconstr (Path.Pident(Ident.create "<hidden>")) []
else ty in
let tr = tree_of_typexp sch ty in
Octy_fun (lab, tr, tree_of_class_type sch params cty)
let class_type ppf cty =
reset ();
prepare_class_type [] cty;
!Oprint.out_class_type ppf (tree_of_class_type false [] cty)
let tree_of_class_param param variance =
(match tree_of_typexp true param with
Otyp_var (_, s) -> s
| _ -> "?"),
if (repr param).desc = Tvar then (true, true) else variance
let tree_of_class_params params =
let tyl = tree_of_typlist true params in
List.map (function Otyp_var (_, s) -> s | _ -> "?") tyl
let tree_of_class_declaration id cl rs =
let params = filter_params cl.cty_params in
reset ();
List.iter add_alias params;
prepare_class_type params cl.cty_type;
let sty = self_type cl.cty_type in
List.iter mark_loops params;
List.iter check_name_of_type (List.map proxy params);
if is_aliased sty then check_name_of_type (proxy sty);
let vir_flag = cl.cty_new = None in
Osig_class
(vir_flag, Ident.name id,
List.map2 tree_of_class_param params cl.cty_variance,
tree_of_class_type true params cl.cty_type,
tree_of_rec rs)
let class_declaration id ppf cl =
!Oprint.out_sig_item ppf (tree_of_class_declaration id cl Trec_first)
let tree_of_cltype_declaration id cl rs =
let params = List.map repr cl.clty_params in
reset ();
List.iter add_alias params;
prepare_class_type params cl.clty_type;
let sty = self_type cl.clty_type in
List.iter mark_loops params;
List.iter check_name_of_type (List.map proxy params);
if is_aliased sty then check_name_of_type (proxy sty);
let sign = Ctype.signature_of_class_type cl.clty_type in
let virt =
let (fields, _) =
Ctype.flatten_fields (Ctype.object_fields sign.cty_self) in
List.exists
(fun (lab, _, ty) ->
not (lab = dummy_method || Concr.mem lab sign.cty_concr))
fields
|| Vars.fold (fun _ (_,vr,_) b -> vr = Virtual || b) sign.cty_vars false
in
Osig_class_type
(virt, Ident.name id,
List.map2 tree_of_class_param params cl.clty_variance,
tree_of_class_type true params cl.clty_type,
tree_of_rec rs)
let cltype_declaration id ppf cl =
!Oprint.out_sig_item ppf (tree_of_cltype_declaration id cl Trec_first)
let rec tree_of_modtype = function
| Tmty_ident p ->
Omty_ident (tree_of_path p)
| Tmty_signature sg ->
Omty_signature (tree_of_signature sg)
| Tmty_functor(param, ty_arg, ty_res) ->
Omty_functor
(Ident.name param, tree_of_modtype ty_arg, tree_of_modtype ty_res)
and tree_of_signature = function
| [] -> []
| Tsig_value(id, decl) :: rem ->
tree_of_value_description id decl :: tree_of_signature rem
| Tsig_type(id, _, _) :: rem when is_row_name (Ident.name id) ->
tree_of_signature rem
| Tsig_type(id, decl, rs) :: rem ->
Osig_type(tree_of_type_decl id decl, tree_of_rec rs) ::
tree_of_signature rem
| Tsig_exception(id, decl) :: rem ->
tree_of_exception_declaration id decl :: tree_of_signature rem
| Tsig_module(id, mty, rs) :: rem ->
Osig_module (Ident.name id, tree_of_modtype mty, tree_of_rec rs) ::
tree_of_signature rem
| Tsig_modtype(id, decl) :: rem ->
tree_of_modtype_declaration id decl :: tree_of_signature rem
| Tsig_class(id, decl, rs) :: ctydecl :: tydecl1 :: tydecl2 :: rem ->
tree_of_class_declaration id decl rs :: tree_of_signature rem
| Tsig_cltype(id, decl, rs) :: tydecl1 :: tydecl2 :: rem ->
tree_of_cltype_declaration id decl rs :: tree_of_signature rem
| _ ->
assert false
and tree_of_modtype_declaration id decl =
let mty =
match decl with
| Tmodtype_abstract -> Omty_abstract
| Tmodtype_manifest mty -> tree_of_modtype mty
in
Osig_modtype (Ident.name id, mty)
let tree_of_module id mty rs =
Osig_module (Ident.name id, tree_of_modtype mty, tree_of_rec rs)
let modtype ppf mty = !Oprint.out_module_type ppf (tree_of_modtype mty)
let modtype_declaration id ppf decl =
!Oprint.out_sig_item ppf (tree_of_modtype_declaration id decl)
Print a signature body ( used by -i when compiling a .ml )
let print_signature ppf tree =
fprintf ppf "@[<v>%a@]" !Oprint.out_signature tree
let signature ppf sg =
fprintf ppf "%a" print_signature (tree_of_signature sg)
let type_expansion t ppf t' =
if t == t' then type_expr ppf t else
let t' = if proxy t == proxy t' then unalias t' else t' in
fprintf ppf "@[<2>%a@ =@ %a@]" type_expr t type_expr t'
let rec trace fst txt ppf = function
| (t1, t1') :: (t2, t2') :: rem ->
if not fst then fprintf ppf "@,";
fprintf ppf "@[Type@;<1 2>%a@ %s@;<1 2>%a@] %a"
(type_expansion t1) t1' txt (type_expansion t2) t2'
(trace false txt) rem
| _ -> ()
let rec filter_trace = function
| (t1, t1') :: (t2, t2') :: rem ->
let rem' = filter_trace rem in
if t1 == t1' && t2 == t2'
then rem'
else (t1, t1') :: (t2, t2') :: rem'
| _ -> []
let hide_variant_name t =
match repr t with
| {desc = Tvariant row} as t when (row_repr row).row_name <> None ->
newty2 t.level
(Tvariant {(row_repr row) with row_name = None;
row_more = newty2 (row_more row).level Tvar})
| _ -> t
let prepare_expansion (t, t') =
let t' = hide_variant_name t' in
mark_loops t; if t != t' then mark_loops t';
(t, t')
let may_prepare_expansion compact (t, t') =
match (repr t').desc with
Tvariant _ | Tobject _ when compact ->
mark_loops t; (t, t)
| _ -> prepare_expansion (t, t')
let print_tags ppf fields =
match fields with [] -> ()
| (t, _) :: fields ->
fprintf ppf "`%s" t;
List.iter (fun (t, _) -> fprintf ppf ",@ `%s" t) fields
let has_explanation unif t3 t4 =
match t3.desc, t4.desc with
Tfield _, _ | _, Tfield _
| Tunivar, Tvar | Tvar, Tunivar
| Tvariant _, Tvariant _ -> true
| Tconstr (p, _, _), Tvar | Tvar, Tconstr (p, _, _) ->
unif && min t3.level t4.level < Path.binding_time p
| _ -> false
let rec mismatch unif = function
(_, t) :: (_, t') :: rem ->
begin match mismatch unif rem with
Some _ as m -> m
| None ->
if has_explanation unif t t' then Some(t,t') else None
end
| [] -> None
| _ -> assert false
let explanation unif t3 t4 ppf =
match t3.desc, t4.desc with
| Tfield _, Tvar | Tvar, Tfield _ ->
fprintf ppf "@,Self type cannot escape its class"
| Tconstr (p, _, _), Tvar
when unif && t4.level < Path.binding_time p ->
fprintf ppf
"@,@[The type constructor@;<1 2>%a@ would escape its scope@]"
path p
| Tvar, Tconstr (p, _, _)
when unif && t3.level < Path.binding_time p ->
fprintf ppf
"@,@[The type constructor@;<1 2>%a@ would escape its scope@]"
path p
| Tvar, Tunivar | Tunivar, Tvar ->
fprintf ppf "@,The universal variable %a would escape its scope"
type_expr (if t3.desc = Tunivar then t3 else t4)
| Tfield (lab, _, _, _), _
| _, Tfield (lab, _, _, _) when lab = dummy_method ->
fprintf ppf
"@,Self type cannot be unified with a closed object type"
| Tfield (l, _, _, _), Tfield (l', _, _, _) when l = l' ->
fprintf ppf "@,Types for method %s are incompatible" l
| _, Tfield (l, _, _, _) ->
fprintf ppf
"@,@[The first object type has no method %s@]" l
| Tfield (l, _, _, _), _ ->
fprintf ppf
"@,@[The second object type has no method %s@]" l
| Tvariant row1, Tvariant row2 ->
let row1 = row_repr row1 and row2 = row_repr row2 in
begin match
row1.row_fields, row1.row_closed, row2.row_fields, row2.row_closed with
| [], true, [], true ->
fprintf ppf "@,These two variant types have no intersection"
| [], true, fields, _ ->
fprintf ppf
"@,@[The first variant type does not allow tag(s)@ @[<hov>%a@]@]"
print_tags fields
| fields, _, [], true ->
fprintf ppf
"@,@[The second variant type does not allow tag(s)@ @[<hov>%a@]@]"
print_tags fields
| [l1,_], true, [l2,_], true when l1 = l2 ->
fprintf ppf "@,Types for tag `%s are incompatible" l1
| _ -> ()
end
| _ -> ()
let explanation unif mis ppf =
match mis with
None -> ()
| Some (t3, t4) -> explanation unif t3 t4 ppf
let unification_error unif tr txt1 ppf txt2 =
reset ();
let tr = List.map (fun (t, t') -> (t, hide_variant_name t')) tr in
let mis = mismatch unif tr in
match tr with
| [] | _ :: [] -> assert false
| t1 :: t2 :: tr ->
try
let tr = filter_trace tr in
let t1, t1' = may_prepare_expansion (tr = []) t1
and t2, t2' = may_prepare_expansion (tr = []) t2 in
print_labels := not !Clflags.classic;
let tr = List.map prepare_expansion tr in
fprintf ppf
"@[<v>\
@[%t@;<1 2>%a@ \
%t@;<1 2>%a\
@]%a%t\
@]"
txt1 (type_expansion t1) t1'
txt2 (type_expansion t2) t2'
(trace false "is not compatible with type") tr
(explanation unif mis);
print_labels := true
with exn ->
print_labels := true;
raise exn
let report_unification_error ppf tr txt1 txt2 =
unification_error true tr txt1 ppf txt2;;
let trace fst txt ppf tr =
print_labels := not !Clflags.classic;
try match tr with
t1 :: t2 :: tr' ->
if fst then trace fst txt ppf (t1 :: t2 :: filter_trace tr')
else trace fst txt ppf (filter_trace tr);
print_labels := true
| _ -> ()
with exn ->
print_labels := true;
raise exn
let report_subtyping_error ppf tr1 txt1 tr2 =
reset ();
let tr1 = List.map prepare_expansion tr1
and tr2 = List.map prepare_expansion tr2 in
trace true txt1 ppf tr1;
if tr2 = [] then () else
let mis = mismatch true tr2 in
trace false "is not compatible with type" ppf tr2;
explanation true mis ppf
|
75614bb3495a50bec93193eb4915b86a0e6ca744b72945846888d932c42974f3 | ghc/ghc | IfaceToCore.hs |
( c ) The University of Glasgow 2006
( c ) The GRASP / AQUA Project , Glasgow University , 1992 - 1998
Type checking of type signatures in interface files
(c) The University of Glasgow 2006
(c) The GRASP/AQUA Project, Glasgow University, 1992-1998
Type checking of type signatures in interface files
-}
# LANGUAGE NondecreasingIndentation #
# LANGUAGE FlexibleContexts #
# OPTIONS_GHC -Wno - incomplete - record - updates #
# LANGUAGE TupleSections #
# LANGUAGE RecordWildCards #
module GHC.IfaceToCore (
tcLookupImported_maybe,
importDecl, checkWiredInTyCon, tcHiBootIface, typecheckIface,
typecheckWholeCoreBindings,
typecheckIfacesForMerging,
typecheckIfaceForInstantiate,
tcIfaceDecl, tcIfaceDecls,
tcIfaceInst, tcIfaceFamInst, tcIfaceRules,
tcIfaceAnnotations, tcIfaceCompleteMatches,
tcIfaceExpr, -- Desired by HERMIT (#7683)
tcIfaceGlobal,
tcIfaceOneShot, tcTopIfaceBindings,
hydrateCgBreakInfo
) where
import GHC.Prelude
import GHC.ByteCode.Types
import Data.Word
import GHC.Driver.Env
import GHC.Driver.Session
import GHC.Driver.Config.Core.Lint ( initLintConfig )
import GHC.Builtin.Types.Literals(typeNatCoAxiomRules)
import GHC.Builtin.Types
import GHC.Iface.Syntax
import GHC.Iface.Load
import GHC.Iface.Env
import GHC.StgToCmm.Types
import GHC.Runtime.Heap.Layout
import GHC.Tc.Errors.Types
import GHC.Tc.TyCl.Build
import GHC.Tc.Utils.Monad
import GHC.Tc.Utils.TcType
import GHC.Core.Type
import GHC.Core.Coercion
import GHC.Core.Coercion.Axiom
import GHC.Core.FVs
import GHC.Core.TyCo.Rep -- needs to build types & coercions in a knot
import GHC.Core.TyCo.Subst ( substTyCoVars )
import GHC.Core.InstEnv
import GHC.Core.FamInstEnv
import GHC.Core
import GHC.Core.RoughMap( RoughMatchTc(..) )
import GHC.Core.Utils
import GHC.Core.Unfold( calcUnfoldingGuidance )
import GHC.Core.Unfold.Make
import GHC.Core.Lint
import GHC.Core.Make
import GHC.Core.Class
import GHC.Core.TyCon
import GHC.Core.ConLike
import GHC.Core.DataCon
import GHC.Core.Opt.OccurAnal ( occurAnalyseExpr )
import GHC.Core.Ppr
import GHC.Unit.Env
import GHC.Unit.External
import GHC.Unit.Module
import GHC.Unit.Module.ModDetails
import GHC.Unit.Module.ModIface
import GHC.Unit.Home.ModInfo
import GHC.Utils.Outputable
import GHC.Utils.Misc
import GHC.Utils.Panic
import GHC.Utils.Panic.Plain
import GHC.Utils.Constants (debugIsOn)
import GHC.Utils.Logger
import GHC.Data.Bag
import GHC.Data.Maybe
import GHC.Data.FastString
import GHC.Data.List.SetOps
import GHC.Types.Annotations
import GHC.Types.SourceFile
import GHC.Types.SourceText
import GHC.Types.Basic hiding ( SuccessFlag(..) )
import GHC.Types.CompleteMatch
import GHC.Types.SrcLoc
import GHC.Types.TypeEnv
import GHC.Types.Unique.FM
import GHC.Types.Unique.DSet ( mkUniqDSet )
import GHC.Types.Unique.Set ( nonDetEltsUniqSet )
import GHC.Types.Unique.Supply
import GHC.Types.Demand( isDeadEndSig )
import GHC.Types.Literal
import GHC.Types.Var as Var
import GHC.Types.Var.Set
import GHC.Types.Name
import GHC.Types.Name.Env
import GHC.Types.Name.Set
import GHC.Types.Id
import GHC.Types.Id.Make
import GHC.Types.Id.Info
import GHC.Types.Tickish
import GHC.Types.TyThing
import GHC.Types.Error
import GHC.Fingerprint
import qualified GHC.Data.BooleanFormula as BF
import Control.Monad
import GHC.Parser.Annotation
import GHC.Driver.Env.KnotVars
import GHC.Unit.Module.WholeCoreBindings
import Data.IORef
import Data.Foldable
import GHC.Builtin.Names (ioTyConName, rOOT_MAIN)
This module takes
IfaceDecl - > TyThing
IfaceType - > Type
etc
An IfaceDecl is populated with RdrNames , and these are not renamed to
Names before typechecking , because there should be no scope errors etc .
-- For ( b ) consider : f = \$( ... h .... )
-- where h is imported , and calls f via an hi - boot file .
-- This is bad ! But it is not seen as a staging error , because h
-- is indeed imported . We do n't want the type - checker to black - hole
-- when simplifying and compiling the splice !
--
-- Simple solution : discard any unfolding that mentions a variable
-- bound in this module ( and hence not yet processed ) .
-- The discarding happens when forkM finds a type error .
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* *
Type - checking a complete interface
* *
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
Suppose we discover we do n't need to recompile . Then we must type
check the old interface file . This is a bit different to the
incremental type checking we do as we suck in interface files . Instead
we do things similarly as when we are typechecking source decls : we
bring into scope the type envt for the interface all at once , using a
knot . Remember , the decls are n't necessarily in dependency order --
and even if they were , the type decls might be mutually recursive .
Note [ Knot - tying typecheckIface ]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Suppose we are typechecking an interface A.hi , and we come across
a Name for another entity defined in A.hi . How do we get the
' ' , in this case ? There are three cases :
1 ) tcHiBootIface in GHC.IfaceToCore : We 're typechecking an
hi - boot file in preparation of checking if the hs file we 're
building is compatible . In this case , we want all of the
internal TyCons to MATCH the ones that we just constructed
during typechecking : the knot is thus tied through if_rec_types .
2 ) rehydrate in GHC.Driver . Make : We are rehydrating a
mutually recursive cluster of hi files , in order to ensure
that all of the references refer to each other correctly .
In this case , the knot is tied through the HPT passed in ,
which contains all of the interfaces we are in the process
of typechecking .
3 ) genModDetails in GHC.Driver . Main : We are typechecking an
old interface to generate the ModDetails . In this case ,
we do the same thing as ( 2 ) and pass in an HPT with
the HomeModInfo being generated to tie knots .
The upshot is that the CLIENT of this function is responsible
for making sure that the knot is tied correctly . If you do n't ,
then you 'll get a message saying that we could n't load the
declaration you wanted .
BTW , in one - shot mode we never call typecheckIface ; instead ,
loadInterface handles type - checking interface . In that case ,
knots are tied through the EPS . No problem !
This module takes
IfaceDecl -> TyThing
IfaceType -> Type
etc
An IfaceDecl is populated with RdrNames, and these are not renamed to
Names before typechecking, because there should be no scope errors etc.
-- For (b) consider: f = \$(...h....)
-- where h is imported, and calls f via an hi-boot file.
-- This is bad! But it is not seen as a staging error, because h
-- is indeed imported. We don't want the type-checker to black-hole
-- when simplifying and compiling the splice!
--
-- Simple solution: discard any unfolding that mentions a variable
-- bound in this module (and hence not yet processed).
-- The discarding happens when forkM finds a type error.
************************************************************************
* *
Type-checking a complete interface
* *
************************************************************************
Suppose we discover we don't need to recompile. Then we must type
check the old interface file. This is a bit different to the
incremental type checking we do as we suck in interface files. Instead
we do things similarly as when we are typechecking source decls: we
bring into scope the type envt for the interface all at once, using a
knot. Remember, the decls aren't necessarily in dependency order --
and even if they were, the type decls might be mutually recursive.
Note [Knot-tying typecheckIface]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Suppose we are typechecking an interface A.hi, and we come across
a Name for another entity defined in A.hi. How do we get the
'TyCon', in this case? There are three cases:
1) tcHiBootIface in GHC.IfaceToCore: We're typechecking an
hi-boot file in preparation of checking if the hs file we're
building is compatible. In this case, we want all of the
internal TyCons to MATCH the ones that we just constructed
during typechecking: the knot is thus tied through if_rec_types.
2) rehydrate in GHC.Driver.Make: We are rehydrating a
mutually recursive cluster of hi files, in order to ensure
that all of the references refer to each other correctly.
In this case, the knot is tied through the HPT passed in,
which contains all of the interfaces we are in the process
of typechecking.
3) genModDetails in GHC.Driver.Main: We are typechecking an
old interface to generate the ModDetails. In this case,
we do the same thing as (2) and pass in an HPT with
the HomeModInfo being generated to tie knots.
The upshot is that the CLIENT of this function is responsible
for making sure that the knot is tied correctly. If you don't,
then you'll get a message saying that we couldn't load the
declaration you wanted.
BTW, in one-shot mode we never call typecheckIface; instead,
loadInterface handles type-checking interface. In that case,
knots are tied through the EPS. No problem!
-}
-- Clients of this function be careful, see Note [Knot-tying typecheckIface]
typecheckIface :: ModIface -- Get the decls from here
-> IfG ModDetails
typecheckIface iface
= initIfaceLcl (mi_semantic_module iface) (text "typecheckIface") (mi_boot iface) $ do
{ -- Get the right set of decls and rules. If we are compiling without -O
-- we discard pragmas before typechecking, so that we don't "see"
-- information that we shouldn't. From a versioning point of view
-- It's not actually *wrong* to do so, but in fact GHCi is unable
-- to handle unboxed tuples, so it must not see unfoldings.
ignore_prags <- goptM Opt_IgnoreInterfacePragmas
the decls . This is done lazily , so that the knot - tying
-- within this single module works out right. It's the callers
-- job to make sure the knot is tied.
; names_w_things <- tcIfaceDecls ignore_prags (mi_decls iface)
; let type_env = mkNameEnv names_w_things
-- Now do those rules, instances and annotations
; insts <- mapM tcIfaceInst (mi_insts iface)
; fam_insts <- mapM tcIfaceFamInst (mi_fam_insts iface)
; rules <- tcIfaceRules ignore_prags (mi_rules iface)
; anns <- tcIfaceAnnotations (mi_anns iface)
-- Exports
; exports <- ifaceExportNames (mi_exports iface)
; complete_matches <- tcIfaceCompleteMatches (mi_complete_matches iface)
-- Finished
; traceIf (vcat [text "Finished typechecking interface for" <+> ppr (mi_module iface),
Careful ! If we tug on the TyThing thunks too early
-- we'll infinite loop with hs-boot. See #10083 for
-- an example where this would cause non-termination.
text "Type envt:" <+> ppr (map fst names_w_things)])
; return $ ModDetails { md_types = type_env
, md_insts = mkInstEnv insts
, md_fam_insts = fam_insts
, md_rules = rules
, md_anns = anns
, md_exports = exports
, md_complete_matches = complete_matches
}
}
typecheckWholeCoreBindings :: IORef TypeEnv -> WholeCoreBindings -> IfG [CoreBind]
typecheckWholeCoreBindings type_var (WholeCoreBindings tidy_bindings this_mod _) =
initIfaceLcl this_mod (text "typecheckWholeCoreBindings") NotBoot $ do
tcTopIfaceBindings type_var tidy_bindings
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* *
for merging
* *
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
************************************************************************
* *
Typechecking for merging
* *
************************************************************************
-}
-- | Returns true if an 'IfaceDecl' is for @data T@ (an abstract data type)
isAbstractIfaceDecl :: IfaceDecl -> Bool
isAbstractIfaceDecl IfaceData{ ifCons = IfAbstractTyCon {} } = True
isAbstractIfaceDecl IfaceClass{ ifBody = IfAbstractClass } = True
isAbstractIfaceDecl IfaceFamily{ ifFamFlav = IfaceAbstractClosedSynFamilyTyCon } = True
isAbstractIfaceDecl _ = False
ifMaybeRoles :: IfaceDecl -> Maybe [Role]
ifMaybeRoles IfaceData { ifRoles = rs } = Just rs
ifMaybeRoles IfaceSynonym { ifRoles = rs } = Just rs
ifMaybeRoles IfaceClass { ifRoles = rs } = Just rs
ifMaybeRoles _ = Nothing
| Merge two ' IfaceDecl 's together , preferring a non - abstract one . If
both are non - abstract we pick one arbitrarily ( and check for consistency
-- later.)
mergeIfaceDecl :: IfaceDecl -> IfaceDecl -> IfaceDecl
mergeIfaceDecl d1 d2
| isAbstractIfaceDecl d1 = d2 `withRolesFrom` d1
| isAbstractIfaceDecl d2 = d1 `withRolesFrom` d2
| IfaceClass{ ifBody = IfConcreteClass { ifSigs = ops1, ifMinDef = bf1 } } <- d1
, IfaceClass{ ifBody = IfConcreteClass { ifSigs = ops2, ifMinDef = bf2 } } <- d2
= let ops = nonDetNameEnvElts $
plusNameEnv_C mergeIfaceClassOp
(mkNameEnv [ (n, op) | op@(IfaceClassOp n _ _) <- ops1 ])
(mkNameEnv [ (n, op) | op@(IfaceClassOp n _ _) <- ops2 ])
in d1 { ifBody = (ifBody d1) {
ifSigs = ops,
ifMinDef = BF.mkOr [noLocA bf1, noLocA bf2]
}
} `withRolesFrom` d2
-- It doesn't matter; we'll check for consistency later when
-- we merge, see 'mergeSignatures'
| otherwise = d1 `withRolesFrom` d2
-- Note [Role merging]
-- ~~~~~~~~~~~~~~~~~~~
First , why might it be necessary to do a non - trivial role
-- merge? It may rescue a merge that might otherwise fail:
--
-- signature A where
-- type role T nominal representational
-- data T a b
--
-- signature A where
-- type role T representational nominal
-- data T a b
--
-- A module that defines T as representational in both arguments
-- would successfully fill both signatures, so it would be better
-- if we merged the roles of these types in some nontrivial
-- way.
--
-- However, we have to be very careful about how we go about
-- doing this, because role subtyping is *conditional* on
-- the supertype being NOT representationally injective, e.g.,
-- if we have instead:
--
-- signature A where
-- type role T nominal representational
-- data T a b = T a b
--
-- signature A where
-- type role T representational nominal
-- data T a b = T a b
--
Should we merge the definitions of T so that the roles are R / R ( or N / N ) ?
-- Absolutely not: neither resulting type is a subtype of the original
-- types (see Note [Role subtyping]), because data is not representationally
-- injective.
--
-- Thus, merging only occurs when BOTH TyCons in question are
-- representationally injective. If they're not, no merge.
withRolesFrom :: IfaceDecl -> IfaceDecl -> IfaceDecl
d1 `withRolesFrom` d2
| Just roles1 <- ifMaybeRoles d1
, Just roles2 <- ifMaybeRoles d2
, not (isRepInjectiveIfaceDecl d1 || isRepInjectiveIfaceDecl d2)
= d1 { ifRoles = mergeRoles roles1 roles2 }
| otherwise = d1
where
mergeRoles roles1 roles2 = zipWithEqual "mergeRoles" max roles1 roles2
isRepInjectiveIfaceDecl :: IfaceDecl -> Bool
isRepInjectiveIfaceDecl IfaceData{ ifCons = IfDataTyCon{} } = True
isRepInjectiveIfaceDecl IfaceFamily{ ifFamFlav = IfaceDataFamilyTyCon } = True
isRepInjectiveIfaceDecl _ = False
mergeIfaceClassOp :: IfaceClassOp -> IfaceClassOp -> IfaceClassOp
mergeIfaceClassOp op1@(IfaceClassOp _ _ (Just _)) _ = op1
mergeIfaceClassOp _ op2 = op2
| Merge two ' OccEnv 's of ' IfaceDecl 's by ' OccName ' .
mergeIfaceDecls :: OccEnv IfaceDecl -> OccEnv IfaceDecl -> OccEnv IfaceDecl
mergeIfaceDecls = plusOccEnv_C mergeIfaceDecl
-- | This is a very interesting function. Like typecheckIface, we want
to type check an interface file into a ModDetails . However , the use - case
for these ModDetails is different : we want to compare all of the
ModDetails to ensure they define compatible declarations , and then
-- merge them together. So in particular, we have to take a different
strategy for knot - tying : we first speculatively merge the declarations
-- to get the "base" truth for what we believe the types will be
-- (this is "type computation.") Then we read everything in relative
-- to this truth and check for compatibility.
--
-- During the merge process, we may need to nondeterministically
-- pick a particular declaration to use, if multiple signatures define
-- the declaration ('mergeIfaceDecl'). If, for all choices, there
-- are no type synonym cycles in the resulting merged graph, then
-- we can show that our choice cannot matter. Consider the
-- set of entities which the declarations depend on: by assumption
-- of acyclicity, we can assume that these have already been shown to be equal
-- to each other (otherwise merging will fail). Then it must
-- be the case that all candidate declarations here are type-equal
-- (the choice doesn't matter) or there is an inequality (in which
-- case merging will fail.)
--
-- Unfortunately, the choice can matter if there is a cycle. Consider the
-- following merge:
--
-- signature H where { type A = C; type B = A; data C }
-- signature H where { type A = (); data B; type C = B }
--
-- If we pick @type A = C@ as our representative, there will be
-- a cycle and merging will fail. But if we pick @type A = ()@ as
-- our representative, no cycle occurs, and we instead conclude
-- that all of the types are unit. So it seems that we either
-- (a) need a stronger acyclicity check which considers *all*
-- possible choices from a merge, or (b) we must find a selection
-- of declarations which is acyclic, and show that this is always
the " best " choice we could have made ( ezyang conjectures this
-- is the case but does not have a proof). For now this is
-- not implemented.
--
-- It's worth noting that at the moment, a data constructor and a
-- type synonym are never compatible. Consider:
--
-- signature H where { type Int=C; type B = Int; data C = Int}
-- signature H where { export Prelude.Int; data B; type C = B; }
--
This will be rejected , because the reexported Int in the second
-- signature (a proper data type) is never considered equal to a
-- type synonym. Perhaps this should be relaxed, where a type synonym
-- in a signature is considered implemented by a data type declaration
-- which matches the reference of the type synonym.
typecheckIfacesForMerging :: Module -> [ModIface] -> (KnotVars (IORef TypeEnv)) -> IfM lcl (TypeEnv, [ModDetails])
typecheckIfacesForMerging mod ifaces tc_env_vars =
-- cannot be boot (False)
initIfaceLcl mod (text "typecheckIfacesForMerging") NotBoot $ do
ignore_prags <- goptM Opt_IgnoreInterfacePragmas
-- Build the initial environment
NB : Do n't include dfuns here , because we do n't want to
serialize them out . See Note [ rnIfaceNeverExported ] in GHC.Iface . Rename
NB : But coercions are OK , because they will have the right OccName .
let mk_decl_env decls
= mkOccEnv [ (getOccName decl, decl)
| decl <- decls
, case decl of
exclude DFuns
_ -> True ]
decl_envs = map (mk_decl_env . map snd . mi_decls) ifaces
:: [OccEnv IfaceDecl]
decl_env = foldl' mergeIfaceDecls emptyOccEnv decl_envs
:: OccEnv IfaceDecl
-- TODO: change tcIfaceDecls to accept w/o Fingerprint
names_w_things <- tcIfaceDecls ignore_prags (map (\x -> (fingerprint0, x))
(nonDetOccEnvElts decl_env))
let global_type_env = mkNameEnv names_w_things
case lookupKnotVars tc_env_vars mod of
Just tc_env_var -> writeMutVar tc_env_var global_type_env
Nothing -> return ()
OK , now each ModIface using this environment
details <- forM ifaces $ \iface -> do
-- See Note [Resolving never-exported Names] in GHC.IfaceToCore
type_env <- fixM $ \type_env ->
setImplicitEnvM type_env $ do
decls <- tcIfaceDecls ignore_prags (mi_decls iface)
return (mkNameEnv decls)
-- But note that we use this type_env to typecheck references to DFun
-- in 'IfaceInst'
setImplicitEnvM type_env $ do
insts <- mapM tcIfaceInst (mi_insts iface)
fam_insts <- mapM tcIfaceFamInst (mi_fam_insts iface)
rules <- tcIfaceRules ignore_prags (mi_rules iface)
anns <- tcIfaceAnnotations (mi_anns iface)
exports <- ifaceExportNames (mi_exports iface)
complete_matches <- tcIfaceCompleteMatches (mi_complete_matches iface)
return $ ModDetails { md_types = type_env
, md_insts = mkInstEnv insts
, md_fam_insts = fam_insts
, md_rules = rules
, md_anns = anns
, md_exports = exports
, md_complete_matches = complete_matches
}
return (global_type_env, details)
| a signature ' ModIface ' under the assumption that we have
-- instantiated it under some implementation (recorded in 'mi_semantic_module')
-- and want to check if the implementation fills the signature.
--
-- This needs to operate slightly differently than 'typecheckIface'
because ( 1 ) we have a ' NameShape ' , from the exports of the
-- implementing module, which we will use to give our top-level
-- declarations the correct 'Name's even when the implementor
provided them with a reexport , and ( 2 ) we have to deal with
-- DFun silliness (see Note [rnIfaceNeverExported])
typecheckIfaceForInstantiate :: NameShape -> ModIface -> IfM lcl ModDetails
typecheckIfaceForInstantiate nsubst iface =
initIfaceLclWithSubst (mi_semantic_module iface)
(text "typecheckIfaceForInstantiate")
(mi_boot iface) nsubst $ do
ignore_prags <- goptM Opt_IgnoreInterfacePragmas
-- See Note [Resolving never-exported Names] in GHC.IfaceToCore
type_env <- fixM $ \type_env ->
setImplicitEnvM type_env $ do
decls <- tcIfaceDecls ignore_prags (mi_decls iface)
return (mkNameEnv decls)
-- See Note [rnIfaceNeverExported]
setImplicitEnvM type_env $ do
insts <- mapM tcIfaceInst (mi_insts iface)
fam_insts <- mapM tcIfaceFamInst (mi_fam_insts iface)
rules <- tcIfaceRules ignore_prags (mi_rules iface)
anns <- tcIfaceAnnotations (mi_anns iface)
exports <- ifaceExportNames (mi_exports iface)
complete_matches <- tcIfaceCompleteMatches (mi_complete_matches iface)
return $ ModDetails { md_types = type_env
, md_insts = mkInstEnv insts
, md_fam_insts = fam_insts
, md_rules = rules
, md_anns = anns
, md_exports = exports
, md_complete_matches = complete_matches
}
-- Note [Resolving never-exported Names]
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-- For the high-level overview, see
Note [ Handling never - exported under Backpack ]
--
-- As described in 'typecheckIfacesForMerging', the splendid innovation
-- of signature merging is to rewrite all Names in each of the signatures
-- we are merging together to a pre-merged structure; this is the key
-- ingredient that lets us solve some problems when merging type
-- synonyms.
--
-- However, when a 'Name' refers to a NON-exported entity, as is the
case with the DFun of a ClsInst , or a of a type family ,
this strategy causes problems : if we pick one and rewrite all
-- references to a shared 'Name', we will accidentally fail to check
if the DFun or CoAxioms are compatible , as they will never be
-- checked--only exported entities are checked for compatibility,
and a non - exported TyThing is checked WHEN we are checking the
-- ClsInst or type family for compatibility in checkBootDeclM.
-- By virtue of the fact that everything's been pointed to the merged
-- declaration, you'll never notice there's a difference even if there
-- is one.
--
-- Fortunately, there are only a few places in the interface declarations
-- where this can occur, so we replace those calls with 'tcIfaceImplicit',
-- which will consult a local TypeEnv that records any never-exported
which we should wire up with .
--
-- Note that we actually knot-tie this local TypeEnv (the 'fixM'), because a
type family can refer to a coercion axiom , all of which are done in one go
when we typecheck ' mi_decls ' . An alternate strategy would be to
coercions first before type families , but that seemed more fragile .
--
{-
************************************************************************
* *
Type and class declarations
* *
************************************************************************
-}
tcHiBootIface :: HscSource -> Module -> TcRn SelfBootInfo
-- Load the hi-boot iface for the module being compiled,
-- if it indeed exists in the transitive closure of imports
Return the ModDetails ; Nothing if no hi - boot iface
tcHiBootIface hsc_src mod
| HsBootFile <- hsc_src -- Already compiling a hs-boot file
= return NoSelfBoot
| otherwise
= do { traceIf (text "loadHiBootInterface" <+> ppr mod)
; mode <- getGhcMode
; if not (isOneShot mode)
-- In --make and interactive mode, if this module has an hs-boot file
we 'll have compiled it already , and it 'll be in the HPT
--
-- We check whether the interface is a *boot* interface.
It can happen ( when using GHC from Visual Studio ) that we
-- compile a module in TypecheckOnly mode, with a stable,
fully - populated HPT . In that case the boot interface is n't there
-- (it's been replaced by the mother module) so we can't check it.
And that 's fine , because if M 's ModInfo is in the HPT , then
-- it's been compiled once, and we don't need to check the boot iface
then do { (_, hug) <- getEpsAndHug
; case lookupHugByModule mod hug of
Just info | mi_boot (hm_iface info) == IsBoot
-> mkSelfBootInfo (hm_iface info) (hm_details info)
_ -> return NoSelfBoot }
else do
OK , so we 're in one - shot mode .
-- Re #9245, we always check if there is an hi-boot interface
-- to check consistency against, rather than just when we notice
-- that an hi-boot is necessary due to a circular import.
{ hsc_env <- getTopEnv
; read_result <- liftIO $ findAndReadIface hsc_env
need (fst (getModuleInstantiation mod)) mod
IsBoot -- Hi-boot file
; case read_result of {
Succeeded (iface, _path) -> do { tc_iface <- initIfaceTcRn $ typecheckIface iface
; mkSelfBootInfo iface tc_iface } ;
Failed err ->
-- There was no hi-boot file. But if there is circularity in
-- the module graph, there really should have been one.
-- Since we've read all the direct imports by now,
-- eps_is_boot will record if any of our imports mention the
-- current module, which either means a module loop (not
-- a SOURCE import) or that our hi-boot file has mysteriously
-- disappeared.
do { eps <- getEps
; case lookupInstalledModuleEnv (eps_is_boot eps) (toUnitId <$> mod) of
-- The typical case
Nothing -> return NoSelfBoot
-- error cases
Just (GWIB { gwib_isBoot = is_boot }) -> case is_boot of
IsBoot -> failWithTc (mkTcRnUnknownMessage $ mkPlainError noHints (elaborate err))
-- The hi-boot file has mysteriously disappeared.
NotBoot -> failWithTc (mkTcRnUnknownMessage $ mkPlainError noHints moduleLoop)
-- Someone below us imported us!
-- This is a loop with no hi-boot in the way
}}}}
where
need = text "Need the hi-boot interface for" <+> ppr mod
<+> text "to compare against the Real Thing"
moduleLoop = text "Circular imports: module" <+> quotes (ppr mod)
<+> text "depends on itself"
elaborate err = hang (text "Could not find hi-boot interface for" <+>
quotes (ppr mod) <> colon) 4 err
mkSelfBootInfo :: ModIface -> ModDetails -> TcRn SelfBootInfo
mkSelfBootInfo iface mds
NB : This is computed DIRECTLY from the ModIface rather
than from the ModDetails , so that we can query ' sb_tcs '
-- WITHOUT forcing the contents of the interface.
let tcs = map ifName
. filter isIfaceTyCon
. map snd
$ mi_decls iface
return $ SelfBoot { sb_mds = mds
, sb_tcs = mkNameSet tcs }
where
Returns if , when you call ' tcIfaceDecl ' on
this ' IfaceDecl ' , an ATyCon would be returned .
NB : This code assumes that a can not be implicit .
isIfaceTyCon IfaceId{} = False
isIfaceTyCon IfaceData{} = True
isIfaceTyCon IfaceSynonym{} = True
isIfaceTyCon IfaceFamily{} = True
isIfaceTyCon IfaceClass{} = True
isIfaceTyCon IfaceAxiom{} = False
isIfaceTyCon IfacePatSyn{} = False
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* *
Type and class declarations
* *
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
When typechecking a data type decl , we * lazily * ( via forkM ) typecheck
the constructor argument types . This is in the hope that we may never
poke on those argument types , and hence may never need to load the
interface files for types mentioned in the arg types .
E.g.
data . S = MkS Baz . T
Maybe we can get away without even loading the interface for !
This is not just a performance thing . Suppose we have
data . S = MkS Baz . T
data . T = MkT . S
( in different interface files , of course ) .
Now , first we load and . S , and add it to the type envt .
If we do explore MkS 's argument , we 'll load and . T.
If we explore MkT 's argument we 'll find . S already in the envt .
If we typechecked constructor args eagerly , when loading . S we 'd try to
typecheck the type . T. So we 'd fault in . T ... and then need . S ...
which is n't done yet .
All very cunning . However , there is a rather subtle gotcha which bit
me when developing this stuff . When we typecheck the decl for S , we
extend the type envt with S , MkS , and all its implicit Ids . Suppose
( a bug , but it happened ) that the list of implicit Ids depended in
turn on the constructor arg types . Then the following sequence of
events takes place :
* we build a thunk < t > for the constructor arg tys
* we build a thunk for the extended type environment ( depends on < t > )
* we write the extended type envt into the global EPS mutvar
Now we look something up in the type envt
* that pulls on < t >
* which reads the global type envt out of the global EPS mutvar
* but that depends in turn on < t >
It 's subtle , because , it 'd work fine if we typechecked the constructor args
eagerly -- they do n't need the extended type envt . They just get the extended
type envt by accident , because they look at it later .
What this means is that the implicitTyThings MUST NOT DEPEND on any of
the forkM stuff .
************************************************************************
* *
Type and class declarations
* *
************************************************************************
When typechecking a data type decl, we *lazily* (via forkM) typecheck
the constructor argument types. This is in the hope that we may never
poke on those argument types, and hence may never need to load the
interface files for types mentioned in the arg types.
E.g.
data Foo.S = MkS Baz.T
Maybe we can get away without even loading the interface for Baz!
This is not just a performance thing. Suppose we have
data Foo.S = MkS Baz.T
data Baz.T = MkT Foo.S
(in different interface files, of course).
Now, first we load and typecheck Foo.S, and add it to the type envt.
If we do explore MkS's argument, we'll load and typecheck Baz.T.
If we explore MkT's argument we'll find Foo.S already in the envt.
If we typechecked constructor args eagerly, when loading Foo.S we'd try to
typecheck the type Baz.T. So we'd fault in Baz.T... and then need Foo.S...
which isn't done yet.
All very cunning. However, there is a rather subtle gotcha which bit
me when developing this stuff. When we typecheck the decl for S, we
extend the type envt with S, MkS, and all its implicit Ids. Suppose
(a bug, but it happened) that the list of implicit Ids depended in
turn on the constructor arg types. Then the following sequence of
events takes place:
* we build a thunk <t> for the constructor arg tys
* we build a thunk for the extended type environment (depends on <t>)
* we write the extended type envt into the global EPS mutvar
Now we look something up in the type envt
* that pulls on <t>
* which reads the global type envt out of the global EPS mutvar
* but that depends in turn on <t>
It's subtle, because, it'd work fine if we typechecked the constructor args
eagerly -- they don't need the extended type envt. They just get the extended
type envt by accident, because they look at it later.
What this means is that the implicitTyThings MUST NOT DEPEND on any of
the forkM stuff.
-}
^ True < = > discard IdInfo on IfaceId bindings
-> IfaceDecl
-> IfL TyThing
tcIfaceDecl = tc_iface_decl Nothing
tc_iface_decl :: Maybe Class -- ^ For associated type/data family declarations
^ True < = > discard IdInfo on IfaceId bindings
-> IfaceDecl
-> IfL TyThing
tc_iface_decl _ ignore_prags (IfaceId {ifName = name, ifType = iface_type,
ifIdDetails = details, ifIdInfo = info})
= do { ty <- tcIfaceType iface_type
; details <- tcIdDetails ty details
; info <- tcIdInfo ignore_prags TopLevel name ty info
; return (AnId (mkGlobalId details name ty info)) }
tc_iface_decl _ _ (IfaceData {ifName = tc_name,
ifCType = cType,
ifBinders = binders,
ifResKind = res_kind,
ifRoles = roles,
ifCtxt = ctxt, ifGadtSyntax = gadt_syn,
ifCons = rdr_cons,
ifParent = mb_parent })
= bindIfaceTyConBinders_AT binders $ \ binders' -> do
{ res_kind' <- tcIfaceType res_kind
; tycon <- fixM $ \ tycon -> do
{ stupid_theta <- tcIfaceCtxt ctxt
; parent' <- tc_parent tc_name mb_parent
; cons <- tcIfaceDataCons tc_name tycon binders' rdr_cons
; return (mkAlgTyCon tc_name binders' res_kind'
roles cType stupid_theta
cons parent' gadt_syn) }
; traceIf (text "tcIfaceDecl4" <+> ppr tycon)
; return (ATyCon tycon) }
where
tc_parent :: Name -> IfaceTyConParent -> IfL AlgTyConFlav
tc_parent tc_name IfNoParent
= do { tc_rep_name <- newTyConRepName tc_name
; return (VanillaAlgTyCon tc_rep_name) }
tc_parent _ (IfDataInstance ax_name _ arg_tys)
= do { ax <- tcIfaceCoAxiom ax_name
; let fam_tc = coAxiomTyCon ax
ax_unbr = toUnbranchedAxiom ax
; lhs_tys <- tcIfaceAppArgs arg_tys
; return (DataFamInstTyCon ax_unbr fam_tc lhs_tys) }
tc_iface_decl _ _ (IfaceSynonym {ifName = tc_name,
ifRoles = roles,
ifSynRhs = rhs_ty,
ifBinders = binders,
ifResKind = res_kind })
= bindIfaceTyConBinders_AT binders $ \ binders' -> do
{ res_kind' <- tcIfaceType res_kind -- Note [Synonym kind loop]
; rhs <- forkM (mk_doc tc_name) $
tcIfaceType rhs_ty
; let tycon = buildSynTyCon tc_name binders' res_kind' roles rhs
; return (ATyCon tycon) }
where
mk_doc n = text "Type synonym" <+> ppr n
tc_iface_decl parent _ (IfaceFamily {ifName = tc_name,
ifFamFlav = fam_flav,
ifBinders = binders,
ifResKind = res_kind,
ifResVar = res, ifFamInj = inj })
= bindIfaceTyConBinders_AT binders $ \ binders' -> do
{ res_kind' <- tcIfaceType res_kind -- Note [Synonym kind loop]
; rhs <- forkM (mk_doc tc_name) $
tc_fam_flav tc_name fam_flav
; res_name <- traverse (newIfaceName . mkTyVarOccFS) res
; let tycon = mkFamilyTyCon tc_name binders' res_kind' res_name rhs parent inj
; return (ATyCon tycon) }
where
mk_doc n = text "Type synonym" <+> ppr n
tc_fam_flav :: Name -> IfaceFamTyConFlav -> IfL FamTyConFlav
tc_fam_flav tc_name IfaceDataFamilyTyCon
= do { tc_rep_name <- newTyConRepName tc_name
; return (DataFamilyTyCon tc_rep_name) }
tc_fam_flav _ IfaceOpenSynFamilyTyCon= return OpenSynFamilyTyCon
tc_fam_flav _ (IfaceClosedSynFamilyTyCon mb_ax_name_branches)
= do { ax <- traverse (tcIfaceCoAxiom . fst) mb_ax_name_branches
; return (ClosedSynFamilyTyCon ax) }
tc_fam_flav _ IfaceAbstractClosedSynFamilyTyCon
= return AbstractClosedSynFamilyTyCon
tc_fam_flav _ IfaceBuiltInSynFamTyCon
= pprPanic "tc_iface_decl"
(text "IfaceBuiltInSynFamTyCon in interface file")
tc_iface_decl _parent _ignore_prags
(IfaceClass {ifName = tc_name,
ifRoles = roles,
ifBinders = binders,
ifFDs = rdr_fds,
ifBody = IfAbstractClass})
= bindIfaceTyConBinders binders $ \ binders' -> do
{ fds <- mapM tc_fd rdr_fds
; cls <- buildClass tc_name binders' roles fds Nothing
; return (ATyCon (classTyCon cls)) }
tc_iface_decl _parent ignore_prags
(IfaceClass {ifName = tc_name,
ifRoles = roles,
ifBinders = binders,
ifFDs = rdr_fds,
ifBody = IfConcreteClass {
ifClassCtxt = rdr_ctxt,
ifATs = rdr_ats, ifSigs = rdr_sigs,
ifMinDef = mindef_occ
}})
= bindIfaceTyConBinders binders $ \ binders' -> do
{ traceIf (text "tc-iface-class1" <+> ppr tc_name)
; ctxt <- mapM tc_sc rdr_ctxt
; traceIf (text "tc-iface-class2" <+> ppr tc_name)
; sigs <- mapM tc_sig rdr_sigs
; fds <- mapM tc_fd rdr_fds
; traceIf (text "tc-iface-class3" <+> ppr tc_name)
; mindef <- traverse (lookupIfaceTop . mkVarOccFS) mindef_occ
; cls <- fixM $ \ cls -> do
{ ats <- mapM (tc_at cls) rdr_ats
; traceIf (text "tc-iface-class4" <+> ppr tc_name)
; buildClass tc_name binders' roles fds (Just (ctxt, ats, sigs, mindef)) }
; return (ATyCon (classTyCon cls)) }
where
tc_sc pred = forkM (mk_sc_doc pred) (tcIfaceType pred)
The * length * of the superclasses is used by buildClass , and hence must
-- not be inside the thunk. But the *content* maybe recursive and hence
-- must be lazy (via forkM). Example:
-- class C (T a) => D a where
-- data T a
-- Here the associated type T is knot-tied with the class, and
so we must not pull on T too eagerly . See # 5970
tc_sig :: IfaceClassOp -> IfL TcMethInfo
tc_sig (IfaceClassOp op_name rdr_ty dm)
= do { let doc = mk_op_doc op_name rdr_ty
; op_ty <- forkM (doc <+> text "ty") $ tcIfaceType rdr_ty
-- Must be done lazily for just the same reason as the
-- type of a data con; to avoid sucking in types that
-- it mentions unless it's necessary to do so
; dm' <- tc_dm doc dm
; return (op_name, op_ty, dm') }
tc_dm :: SDoc
-> Maybe (DefMethSpec IfaceType)
-> IfL (Maybe (DefMethSpec (SrcSpan, Type)))
tc_dm _ Nothing = return Nothing
tc_dm _ (Just VanillaDM) = return (Just VanillaDM)
tc_dm doc (Just (GenericDM ty))
= do { -- Must be done lazily to avoid sucking in types
; ty' <- forkM (doc <+> text "dm") $ tcIfaceType ty
; return (Just (GenericDM (noSrcSpan, ty'))) }
tc_at cls (IfaceAT tc_decl if_def)
= do ATyCon tc <- tc_iface_decl (Just cls) ignore_prags tc_decl
mb_def <- case if_def of
Nothing -> return Nothing
Just def -> forkM (mk_at_doc tc) $
extendIfaceTyVarEnv (tyConTyVars tc) $
do { tc_def <- tcIfaceType def
; return (Just (tc_def, NoATVI)) }
-- Must be done lazily in case the RHS of the defaults mention
-- the type constructor being defined here
e.g. type AT a ; type AT b = AT [ b ] # 8002
return (ATI tc mb_def)
mk_sc_doc pred = text "Superclass" <+> ppr pred
mk_at_doc tc = text "Associated type" <+> ppr tc
mk_op_doc op_name op_ty = text "Class op" <+> sep [ppr op_name, ppr op_ty]
tc_iface_decl _ _ (IfaceAxiom { ifName = tc_name, ifTyCon = tc
, ifAxBranches = branches, ifRole = role })
= do { tc_tycon <- tcIfaceTyCon tc
-- Must be done lazily, because axioms are forced when checking
for family instance consistency , and the RHS may mention
-- a hs-boot declared type constructor that is going to be
-- defined by this module.
-- e.g. type instance F Int = ToBeDefined
See # 13803
; tc_branches <- forkM (text "Axiom branches" <+> ppr tc_name)
$ tc_ax_branches branches
; let axiom = CoAxiom { co_ax_unique = nameUnique tc_name
, co_ax_name = tc_name
, co_ax_tc = tc_tycon
, co_ax_role = role
, co_ax_branches = manyBranches tc_branches
, co_ax_implicit = False }
; return (ACoAxiom axiom) }
tc_iface_decl _ _ (IfacePatSyn{ ifName = name
, ifPatMatcher = if_matcher
, ifPatBuilder = if_builder
, ifPatIsInfix = is_infix
, ifPatUnivBndrs = univ_bndrs
, ifPatExBndrs = ex_bndrs
, ifPatProvCtxt = prov_ctxt
, ifPatReqCtxt = req_ctxt
, ifPatArgs = args
, ifPatTy = pat_ty
, ifFieldLabels = field_labels })
= do { traceIf (text "tc_iface_decl" <+> ppr name)
; matcher <- tc_pr if_matcher
; builder <- traverse tc_pr if_builder
; bindIfaceForAllBndrs univ_bndrs $ \univ_tvs -> do
{ bindIfaceForAllBndrs ex_bndrs $ \ex_tvs -> do
{ patsyn <- forkM (mk_doc name) $
do { prov_theta <- tcIfaceCtxt prov_ctxt
; req_theta <- tcIfaceCtxt req_ctxt
; pat_ty <- tcIfaceType pat_ty
; arg_tys <- mapM tcIfaceType args
; return $ buildPatSyn name is_infix matcher builder
(univ_tvs, req_theta)
(ex_tvs, prov_theta)
arg_tys pat_ty field_labels }
; return $ AConLike . PatSynCon $ patsyn }}}
where
mk_doc n = text "Pattern synonym" <+> ppr n
tc_pr :: (IfExtName, Bool) -> IfL (Name, Type, Bool)
tc_pr (nm, b) = do { id <- forkM (ppr nm) (tcIfaceExtId nm)
; return (nm, idType id, b) }
tcTopIfaceBindings :: IORef TypeEnv -> [IfaceBindingX IfaceMaybeRhs IfaceTopBndrInfo]
-> IfL [CoreBind]
tcTopIfaceBindings ty_var ver_decls
= do
int <- mapM tcTopBinders ver_decls
let all_ids :: [Id] = concatMap toList int
liftIO $ modifyIORef ty_var (flip extendTypeEnvList (map AnId all_ids))
extendIfaceIdEnv all_ids $ mapM (tc_iface_bindings) int
tcTopBinders :: IfaceBindingX a IfaceTopBndrInfo -> IfL (IfaceBindingX a Id)
tcTopBinders = traverse mk_top_id
tc_iface_bindings :: IfaceBindingX IfaceMaybeRhs Id -> IfL CoreBind
tc_iface_bindings (IfaceNonRec b rhs) = do
rhs' <- tc_iface_binding b rhs
return $ NonRec b rhs'
tc_iface_bindings (IfaceRec bs) = do
rs <- mapM (\(b, rhs) -> (b,) <$> tc_iface_binding b rhs) bs
return (Rec rs)
-- | See Note [Interface File with Core: Sharing RHSs]
tc_iface_binding :: Id -> IfaceMaybeRhs -> IfL CoreExpr
tc_iface_binding i IfUseUnfoldingRhs =
case maybeUnfoldingTemplate $ realIdUnfolding i of
Just e -> return e
Nothing -> pprPanic "tc_iface_binding" (vcat [text "Binding" <+> quotes (ppr i) <+> text "had an unfolding when the interface file was created"
, text "which has now gone missing, something has badly gone wrong."
, text "Unfolding:" <+> ppr (realIdUnfolding i)])
tc_iface_binding _ (IfRhs rhs) = tcIfaceExpr rhs
mk_top_id :: IfaceTopBndrInfo -> IfL Id
mk_top_id (IfGblTopBndr gbl_name)
-- See Note [Root-main Id]
-- This special binding is actually defined in the current module
-- (hence don't go looking for it externally) but the module name is rOOT_MAIN
-- rather than the current module so we need this special case.
-- See some similar logic in `GHC.Rename.Env`.
| Just rOOT_MAIN == nameModule_maybe gbl_name
= do
ATyCon ioTyCon <- tcIfaceGlobal ioTyConName
return $ mkExportedVanillaId gbl_name (mkTyConApp ioTyCon [unitTy])
| otherwise = tcIfaceExtId gbl_name
mk_top_id (IfLclTopBndr raw_name iface_type info details) = do
name <- newIfaceName (mkVarOccFS raw_name)
ty <- tcIfaceType iface_type
info' <- tcIdInfo False TopLevel name ty info
details' <- tcIdDetails ty details
let new_id = mkGlobalId details' name ty info'
return new_id
tcIfaceDecls :: Bool
-> [(Fingerprint, IfaceDecl)]
-> IfL [(Name,TyThing)]
tcIfaceDecls ignore_prags ver_decls
= concatMapM (tc_iface_decl_fingerprint ignore_prags) ver_decls
tc_iface_decl_fingerprint :: Bool -- Don't load pragmas into the decl pool
-> (Fingerprint, IfaceDecl)
-> IfL [(Name,TyThing)] -- The list can be poked eagerly, but the
are forkM'd thunks
tc_iface_decl_fingerprint ignore_prags (_version, decl)
= do { -- Populate the name cache with final versions of all
-- the names associated with the decl
let main_name = ifName decl
the thing , lazily
NB . Firstly , the laziness is there in case we never need the
declaration ( in one - shot mode ) , and secondly it is there so that
we do n't look up the occurrence of a name before calling
-- on the binder. This is important because we must get the right name
-- which includes its nameParent.
; thing <- forkM doc $ do { bumpDeclStats main_name
; tcIfaceDecl ignore_prags decl }
-- Populate the type environment with the implicitTyThings too.
--
-- Note [Tricky iface loop]
-- ~~~~~~~~~~~~~~~~~~~~~~~~
-- Summary: The delicate point here is that 'mini-env' must be
-- buildable from 'thing' without demanding any of the things
' forkM'd by .
--
-- In more detail: Consider the example
data T a = MkT { x : : T a }
-- The implicitTyThings of T are: [ <datacon MkT>, <selector x>]
-- (plus their workers, wrappers, coercions etc etc)
--
-- We want to return an environment
[ " MkT " - > < datacon MkT > , " x " - > < selector x > , ... ]
( where the " MkT " is the * Name * associated with MkT , etc . )
--
-- We do this by mapping the implicit_names to the associated
. By the invariant on ifaceDeclImplicitBndrs and
-- implicitTyThings, we can use getOccName on the implicit
to make this association : each Name 's OccName should
-- be the OccName of exactly one implicitTyThing. So the key is
-- to define a "mini-env"
--
[ ' MkT ' - > < datacon MkT > , ' x ' - > < selector x > , ... ]
where the ' MkT ' here is the * OccName * associated with MkT.
--
-- However, there is a subtlety: due to how type checking needs
-- to be staged, we can't poke on the forkM'd thunks inside the
-- implicitTyThings while building this mini-env.
If we poke these thunks too early , two problems could happen :
( 1 ) When processing mutually recursive modules across
-- hs-boot boundaries, poking too early will do the
-- type-checking before the recursive knot has been tied,
-- so things will be type-checked in the wrong
-- environment, and necessary variables won't be in
-- scope.
--
( 2 ) Looking up one OccName in the mini_env will cause
-- others to be looked up, which might cause that
-- original one to be looked up again, and hence loop.
--
-- The code below works because of the following invariant:
getOccName on a TyThing does not force the suspended type
-- checks in order to extract the name. For example, we don't
-- poke on the "T a" type of <selector x> on the way to
-- extracting <selector x>'s OccName. Of course, there is no
-- reason in principle why getting the OccName should force the
-- thunks, but this means we need to be careful in
-- implicitTyThings and its helper functions.
--
-- All a bit too finely-balanced for my liking.
-- This mini-env and lookup function mediates between the
' Name 's n and the map from ' OccName 's to the implicit
; let mini_env = mkOccEnv [(getOccName t, t) | t <- implicitTyThings thing]
lookup n = case lookupOccEnv mini_env (getOccName n) of
Just thing -> thing
Nothing ->
pprPanic "tc_iface_decl_fingerprint" (ppr main_name <+> ppr n $$ ppr (decl))
; implicit_names <- mapM lookupIfaceTop (ifaceDeclImplicitBndrs decl)
; traceIf ( text " Loading decl for " < > ppr main_name $ $ ppr implicit_names )
; return $ (main_name, thing) :
-- uses the invariant that implicit_names and
-- implicitTyThings are bijective
[(n, lookup n) | n <- implicit_names]
}
where
doc = text "Declaration for" <+> ppr (ifName decl)
Record that one more declaration has actually been used
bumpDeclStats name
= do { traceIf (text "Loading decl for" <+> ppr name)
; updateEps_ (\eps -> let stats = eps_stats eps
in eps { eps_stats = stats { n_decls_out = n_decls_out stats + 1 } })
}
tc_fd :: FunDep IfLclName -> IfL (FunDep TyVar)
tc_fd (tvs1, tvs2) = do { tvs1' <- mapM tcIfaceTyVar tvs1
; tvs2' <- mapM tcIfaceTyVar tvs2
; return (tvs1', tvs2') }
tc_ax_branches :: [IfaceAxBranch] -> IfL [CoAxBranch]
tc_ax_branches if_branches = foldlM tc_ax_branch [] if_branches
tc_ax_branch :: [CoAxBranch] -> IfaceAxBranch -> IfL [CoAxBranch]
tc_ax_branch prev_branches
(IfaceAxBranch { ifaxbTyVars = tv_bndrs
, ifaxbEtaTyVars = eta_tv_bndrs
, ifaxbCoVars = cv_bndrs
, ifaxbLHS = lhs, ifaxbRHS = rhs
, ifaxbRoles = roles, ifaxbIncomps = incomps })
= bindIfaceTyConBinders_AT
(map (\b -> Bndr (IfaceTvBndr b) (NamedTCB Inferred)) tv_bndrs) $ \ tvs ->
The _ AT variant is needed here ; see Note [ CoAxBranch type variables ] in GHC.Core . Coercion . Axiom
bindIfaceIds cv_bndrs $ \ cvs -> do
{ tc_lhs <- tcIfaceAppArgs lhs
; tc_rhs <- tcIfaceType rhs
; eta_tvs <- bindIfaceTyVars eta_tv_bndrs return
; this_mod <- getIfModule
; let loc = mkGeneralSrcSpan (fsLit "module " `appendFS`
moduleNameFS (moduleName this_mod))
br = CoAxBranch { cab_loc = loc
, cab_tvs = binderVars tvs
, cab_eta_tvs = eta_tvs
, cab_cvs = cvs
, cab_lhs = tc_lhs
, cab_roles = roles
, cab_rhs = tc_rhs
, cab_incomps = map (prev_branches `getNth`) incomps }
; return (prev_branches ++ [br]) }
tcIfaceDataCons :: Name -> TyCon -> [TyConBinder] -> IfaceConDecls -> IfL AlgTyConRhs
tcIfaceDataCons tycon_name tycon tc_tybinders if_cons
= case if_cons of
IfAbstractTyCon
-> return AbstractTyCon
IfDataTyCon type_data cons
-> do { data_cons <- mapM tc_con_decl cons
; return $
mkLevPolyDataTyConRhs
(isFixedRuntimeRepKind $ tyConResKind tycon)
type_data
data_cons }
IfNewTyCon con
-> do { data_con <- tc_con_decl con
; mkNewTyConRhs tycon_name tycon data_con }
where
univ_tvs :: [TyVar]
univ_tvs = binderVars tc_tybinders
tag_map :: NameEnv ConTag
tag_map = mkTyConTagMap tycon
tc_con_decl (IfCon { ifConInfix = is_infix,
ifConExTCvs = ex_bndrs,
ifConUserTvBinders = user_bndrs,
ifConName = dc_name,
ifConCtxt = ctxt, ifConEqSpec = spec,
ifConArgTys = args, ifConFields = lbl_names,
ifConStricts = if_stricts,
ifConSrcStricts = if_src_stricts})
Universally - quantified tyvars are shared with
parent , and are already in scope
bindIfaceBndrs ex_bndrs $ \ ex_tvs -> do
{ traceIf (text "Start interface-file tc_con_decl" <+> ppr dc_name)
-- By this point, we have bound every universal and existential
-- tyvar. Because of the dcUserTyVarBinders invariant
-- (see Note [DataCon user type variable binders]), *every* tyvar in
-- ifConUserTvBinders has a matching counterpart somewhere in the
-- bound universals/existentials. As a result, calling tcIfaceTyVar
-- below is always guaranteed to succeed.
; user_tv_bndrs <- mapM (\(Bndr bd vis) ->
case bd of
IfaceIdBndr (_, name, _) ->
Bndr <$> tcIfaceLclId name <*> pure vis
IfaceTvBndr (name, _) ->
Bndr <$> tcIfaceTyVar name <*> pure vis)
user_bndrs
Read the context and argument types , but lazily for two reasons
-- (a) to avoid looking tugging on a recursive use of
-- the type itself, which is knot-tied
-- (b) to avoid faulting in the component types unless
-- they are really needed
; ~(eq_spec, theta, arg_tys, stricts) <- forkM (mk_doc dc_name) $
do { eq_spec <- tcIfaceEqSpec spec
; theta <- tcIfaceCtxt ctxt
This fixes # 13710 . The enclosing lazy thunk gets
-- forced when typechecking record wildcard pattern
-- matching (it's not completely clear why this
tuple is needed ) , which causes trouble if one of
-- the argument types was recursively defined.
-- See also Note [Tying the knot]
; arg_tys <- forkM (mk_doc dc_name <+> text "arg_tys")
$ mapM (\(w, ty) -> mkScaled <$> tcIfaceType w <*> tcIfaceType ty) args
; stricts <- mapM tc_strict if_stricts
The IfBang field can mention
-- the type itself; hence inside forkM
; return (eq_spec, theta, arg_tys, stricts) }
Remember , is the representation tycon
; let orig_res_ty = mkFamilyTyConApp tycon
(substTyCoVars (mkTvSubstPrs (map eqSpecPair eq_spec))
(binderVars tc_tybinders))
; prom_rep_name <- newTyConRepName dc_name
; let bang_opts = FixedBangOpts stricts
-- Pass the HsImplBangs (i.e. final decisions) to buildDataCon;
-- it'll use these to guide the construction of a worker.
See Note [ Bangs on imported data constructors ] in GHC.Types . Id. Make
; con <- buildDataCon (pprPanic "tcIfaceDataCons: FamInstEnvs" (ppr dc_name))
bang_opts
dc_name is_infix prom_rep_name
(map src_strict if_src_stricts)
lbl_names
univ_tvs ex_tvs user_tv_bndrs
eq_spec theta
arg_tys orig_res_ty tycon tag_map
; traceIf (text "Done interface-file tc_con_decl" <+> ppr dc_name)
; return con }
mk_doc con_name = text "Constructor" <+> ppr con_name
tc_strict :: IfaceBang -> IfL HsImplBang
tc_strict IfNoBang = return (HsLazy)
tc_strict IfStrict = return (HsStrict True)
tc_strict IfUnpack = return (HsUnpack Nothing)
tc_strict (IfUnpackCo if_co) = do { co <- tcIfaceCo if_co
; return (HsUnpack (Just co)) }
src_strict :: IfaceSrcBang -> HsSrcBang
src_strict (IfSrcBang unpk bang) = HsSrcBang NoSourceText unpk bang
tcIfaceEqSpec :: IfaceEqSpec -> IfL [EqSpec]
tcIfaceEqSpec spec
= mapM do_item spec
where
do_item (occ, if_ty) = do { tv <- tcIfaceTyVar occ
; ty <- tcIfaceType if_ty
; return (mkEqSpec tv ty) }
Note [ Synonym kind loop ]
~~~~~~~~~~~~~~~~~~~~~~~~
Notice that we eagerly grab the * kind * from the interface file , but
build a forkM thunk for the * rhs * ( and family stuff ) . To see why ,
consider this ( # 2412 )
M.hs : module M where { import X ; data T = MkT S }
X.hs : module X where { import { - # SOURCE #
Note [Synonym kind loop]
~~~~~~~~~~~~~~~~~~~~~~~~
Notice that we eagerly grab the *kind* from the interface file, but
build a forkM thunk for the *rhs* (and family stuff). To see why,
consider this (#2412)
M.hs: module M where { import X; data T = MkT S }
X.hs: module X where { import {-# SOURCE #-} M; type S = T }
M.hs-boot: module M where { data T }
When kind-checking M.hs we need S's kind. But we do not want to
find S's kind from (typeKind S-rhs), because we don't want to look at
S-rhs yet! Since S is imported from X.hi, S gets just one chance to
be defined, and we must not do that until we've finished with M.T.
Solution: record S's kind in the interface file; now we can safely
look at it.
************************************************************************
* *
Instances
* *
************************************************************************
-}
tcRoughTyCon :: Maybe IfaceTyCon -> RoughMatchTc
tcRoughTyCon (Just tc) = RM_KnownTc (ifaceTyConName tc)
tcRoughTyCon Nothing = RM_WildCard
tcIfaceInst :: IfaceClsInst -> IfL ClsInst
tcIfaceInst (IfaceClsInst { ifDFun = dfun_name, ifOFlag = oflag
, ifInstCls = cls, ifInstTys = mb_tcs
, ifInstOrph = orph })
= do { dfun <- forkM (text "Dict fun" <+> ppr dfun_name) $
fmap tyThingId (tcIfaceImplicit dfun_name)
; let mb_tcs' = map tcRoughTyCon mb_tcs
; return (mkImportedClsInst cls mb_tcs' dfun_name dfun oflag orph) }
tcIfaceFamInst :: IfaceFamInst -> IfL FamInst
tcIfaceFamInst (IfaceFamInst { ifFamInstFam = fam, ifFamInstTys = mb_tcs
, ifFamInstAxiom = axiom_name
, ifFamInstOrph = orphan } )
= do { axiom' <- forkM (text "Axiom" <+> ppr axiom_name) $
tcIfaceCoAxiom axiom_name
-- will panic if branched, but that's OK
; let axiom'' = toUnbranchedAxiom axiom'
mb_tcs' = map tcRoughTyCon mb_tcs
; return (mkImportedFamInst fam mb_tcs' axiom'' orphan) }
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* *
Rules
* *
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
We move a IfaceRule from eps_rules to eps_rule_base when all its LHS free vars
are in the type environment . However , remember that typechecking a Rule may
( as a side effect ) augment the type envt , and so we may need to iterate the process .
************************************************************************
* *
Rules
* *
************************************************************************
We move a IfaceRule from eps_rules to eps_rule_base when all its LHS free vars
are in the type environment. However, remember that typechecking a Rule may
(as a side effect) augment the type envt, and so we may need to iterate the process.
-}
tcIfaceRules :: Bool -- True <=> ignore rules
-> [IfaceRule]
-> IfL [CoreRule]
tcIfaceRules ignore_prags if_rules
| ignore_prags = return []
| otherwise = mapM tcIfaceRule if_rules
tcIfaceRule :: IfaceRule -> IfL CoreRule
tcIfaceRule (IfaceRule {ifRuleName = name, ifActivation = act, ifRuleBndrs = bndrs,
ifRuleHead = fn, ifRuleArgs = args, ifRuleRhs = rhs,
ifRuleAuto = auto, ifRuleOrph = orph })
= do { ~(bndrs', args', rhs') <-
the payload lazily , in the hope it 'll never be looked at
forkM (text "Rule" <+> pprRuleName name) $
bindIfaceBndrs bndrs $ \ bndrs' ->
do { args' <- mapM tcIfaceExpr args
; rhs' <- tcIfaceExpr rhs
; whenGOptM Opt_DoCoreLinting $ do
{ dflags <- getDynFlags
; (_, lcl_env) <- getEnvs
; let in_scope :: [Var]
in_scope = ((nonDetEltsUFM $ if_tv_env lcl_env) ++
(nonDetEltsUFM $ if_id_env lcl_env) ++
bndrs' ++
exprsFreeIdsList args')
; case lintExpr (initLintConfig dflags in_scope) rhs' of
Nothing -> return ()
Just errs -> do
logger <- getLogger
liftIO $ displayLintResults logger False doc
(pprCoreExpr rhs')
(emptyBag, errs) }
; return (bndrs', args', rhs') }
; let mb_tcs = map ifTopFreeName args
; this_mod <- getIfModule
; return (Rule { ru_name = name, ru_fn = fn, ru_act = act,
ru_bndrs = bndrs', ru_args = args',
ru_rhs = occurAnalyseExpr rhs',
ru_rough = mb_tcs,
ru_origin = this_mod,
ru_orphan = orph,
ru_auto = auto,
ru_local = False }) } -- An imported RULE is never for a local Id
-- or, even if it is (module loop, perhaps)
-- we'll just leave it in the non-local set
where
-- This function *must* mirror exactly what Rules.roughTopNames does
-- We could have stored the ru_rough field in the iface file
-- but that would be redundant, I think.
-- The only wrinkle is that we must not be deceived by
-- type synonyms at the top of a type arg. Since
-- we can't tell at this point, we are careful not
to write them out in coreRuleToIfaceRule
ifTopFreeName :: IfaceExpr -> Maybe Name
ifTopFreeName (IfaceType (IfaceTyConApp tc _ )) = Just (ifaceTyConName tc)
ifTopFreeName (IfaceType (IfaceTupleTy s _ ts)) = Just (tupleTyConName s (length (appArgsIfaceTypes ts)))
ifTopFreeName (IfaceApp f _) = ifTopFreeName f
ifTopFreeName (IfaceExt n) = Just n
ifTopFreeName _ = Nothing
doc = text "Unfolding of" <+> ppr name
{-
************************************************************************
* *
Annotations
* *
************************************************************************
-}
tcIfaceAnnotations :: [IfaceAnnotation] -> IfL [Annotation]
tcIfaceAnnotations = mapM tcIfaceAnnotation
tcIfaceAnnotation :: IfaceAnnotation -> IfL Annotation
tcIfaceAnnotation (IfaceAnnotation target serialized) = do
target' <- tcIfaceAnnTarget target
return $ Annotation {
ann_target = target',
ann_value = serialized
}
tcIfaceAnnTarget :: IfaceAnnTarget -> IfL (AnnTarget Name)
tcIfaceAnnTarget (NamedTarget occ) =
NamedTarget <$> lookupIfaceTop occ
tcIfaceAnnTarget (ModuleTarget mod) =
return $ ModuleTarget mod
{-
************************************************************************
* *
Complete Match Pragmas
* *
************************************************************************
-}
tcIfaceCompleteMatches :: [IfaceCompleteMatch] -> IfL [CompleteMatch]
tcIfaceCompleteMatches = mapM tcIfaceCompleteMatch
tcIfaceCompleteMatch :: IfaceCompleteMatch -> IfL CompleteMatch
tcIfaceCompleteMatch (IfaceCompleteMatch ms mtc) = forkM doc $ do -- See Note [Positioning of forkM]
conlikes <- mkUniqDSet <$> mapM tcIfaceConLike ms
mtc' <- traverse tcIfaceTyCon mtc
return (CompleteMatch conlikes mtc')
where
doc = text "COMPLETE sig" <+> ppr ms
Note [ Positioning of forkM ]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
We need to be lazy when type checking the interface , since these functions are
called when the interface itself is being loaded , which means it is not in the
PIT yet . In particular , the ` tcIfaceTCon ` must be inside the forkM , otherwise
we 'll try to look it up the , find it 's not there , and so initiate the
process ( again ) of loading the ( very same ) interface file . Result : infinite
loop . See # 19744 .
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
We need to be lazy when type checking the interface, since these functions are
called when the interface itself is being loaded, which means it is not in the
PIT yet. In particular, the `tcIfaceTCon` must be inside the forkM, otherwise
we'll try to look it up the TyCon, find it's not there, and so initiate the
process (again) of loading the (very same) interface file. Result: infinite
loop. See #19744.
-}
{-
************************************************************************
* *
Types
* *
************************************************************************
-}
tcIfaceType :: IfaceType -> IfL Type
tcIfaceType = go
where
go (IfaceTyVar n) = TyVarTy <$> tcIfaceTyVar n
go (IfaceFreeTyVar n) = pprPanic "tcIfaceType:IfaceFreeTyVar" (ppr n)
go (IfaceLitTy l) = LitTy <$> tcIfaceTyLit l
go (IfaceFunTy flag w t1 t2) = FunTy flag <$> tcIfaceType w <*> go t1 <*> go t2
go (IfaceTupleTy s i tks) = tcIfaceTupleTy s i tks
go (IfaceAppTy t ts)
= do { t' <- go t
; ts' <- traverse go (appArgsIfaceTypes ts)
; pure (foldl' AppTy t' ts') }
go (IfaceTyConApp tc tks)
= do { tc' <- tcIfaceTyCon tc
; tks' <- mapM go (appArgsIfaceTypes tks)
; return (mkTyConApp tc' tks') }
go (IfaceForAllTy bndr t)
= bindIfaceForAllBndr bndr $ \ tv' vis ->
ForAllTy (Bndr tv' vis) <$> go t
go (IfaceCastTy ty co) = CastTy <$> go ty <*> tcIfaceCo co
go (IfaceCoercionTy co) = CoercionTy <$> tcIfaceCo co
tcIfaceTupleTy :: TupleSort -> PromotionFlag -> IfaceAppArgs -> IfL Type
tcIfaceTupleTy sort is_promoted args
= do { args' <- tcIfaceAppArgs args
; let arity = length args'
; base_tc <- tcTupleTyCon True sort arity
; case is_promoted of
NotPromoted
-> return (mkTyConApp base_tc args')
IsPromoted
-> do { let tc = promoteDataCon (tyConSingleDataCon base_tc)
kind_args = map typeKind args'
; return (mkTyConApp tc (kind_args ++ args')) } }
See Note [ tuple RuntimeRep vars ] in GHC.Core . TyCon
tcTupleTyCon :: Bool -- True <=> typechecking a *type* (vs. an expr)
-> TupleSort
-> Arity -- the number of args. *not* the tuple arity.
-> IfL TyCon
tcTupleTyCon in_type sort arity
= case sort of
ConstraintTuple -> return (cTupleTyCon arity)
BoxedTuple -> return (tupleTyCon Boxed arity)
UnboxedTuple -> return (tupleTyCon Unboxed arity')
where arity' | in_type = arity `div` 2
| otherwise = arity
-- in expressions, we only have term args
tcIfaceAppArgs :: IfaceAppArgs -> IfL [Type]
tcIfaceAppArgs = mapM tcIfaceType . appArgsIfaceTypes
-----------------------------------------
tcIfaceCtxt :: IfaceContext -> IfL ThetaType
tcIfaceCtxt sts = mapM tcIfaceType sts
-----------------------------------------
tcIfaceTyLit :: IfaceTyLit -> IfL TyLit
tcIfaceTyLit (IfaceNumTyLit n) = return (NumTyLit n)
tcIfaceTyLit (IfaceStrTyLit n) = return (StrTyLit n)
tcIfaceTyLit (IfaceCharTyLit n) = return (CharTyLit n)
% * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
% * *
* *
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
%************************************************************************
%* *
Coercions
* *
************************************************************************
-}
tcIfaceCo :: IfaceCoercion -> IfL Coercion
tcIfaceCo = go
where
go_mco IfaceMRefl = pure MRefl
go_mco (IfaceMCo co) = MCo <$> (go co)
go (IfaceReflCo t) = Refl <$> tcIfaceType t
go (IfaceGReflCo r t mco) = GRefl r <$> tcIfaceType t <*> go_mco mco
go (IfaceFunCo r w c1 c2) = mkFunCoNoFTF r <$> go w <*> go c1 <*> go c2
go (IfaceTyConAppCo r tc cs) = TyConAppCo r <$> tcIfaceTyCon tc <*> mapM go cs
go (IfaceAppCo c1 c2) = AppCo <$> go c1 <*> go c2
go (IfaceForAllCo tv k c) = do { k' <- go k
; bindIfaceBndr tv $ \ tv' ->
ForAllCo tv' k' <$> go c }
go (IfaceCoVarCo n) = CoVarCo <$> go_var n
go (IfaceAxiomInstCo n i cs) = AxiomInstCo <$> tcIfaceCoAxiom n <*> pure i <*> mapM go cs
go (IfaceUnivCo p r t1 t2) = UnivCo <$> tcIfaceUnivCoProv p <*> pure r
<*> tcIfaceType t1 <*> tcIfaceType t2
go (IfaceSymCo c) = SymCo <$> go c
go (IfaceTransCo c1 c2) = TransCo <$> go c1
<*> go c2
go (IfaceInstCo c1 t2) = InstCo <$> go c1
<*> go t2
go (IfaceSelCo d c) = do { c' <- go c
; return $ mkSelCo d c' }
go (IfaceLRCo lr c) = LRCo lr <$> go c
go (IfaceKindCo c) = KindCo <$> go c
go (IfaceSubCo c) = SubCo <$> go c
go (IfaceAxiomRuleCo ax cos) = AxiomRuleCo <$> tcIfaceCoAxiomRule ax
<*> mapM go cos
go (IfaceFreeCoVar c) = pprPanic "tcIfaceCo:IfaceFreeCoVar" (ppr c)
go (IfaceHoleCo c) = pprPanic "tcIfaceCo:IfaceHoleCo" (ppr c)
go_var :: FastString -> IfL CoVar
go_var = tcIfaceLclId
tcIfaceUnivCoProv :: IfaceUnivCoProv -> IfL UnivCoProvenance
tcIfaceUnivCoProv (IfacePhantomProv kco) = PhantomProv <$> tcIfaceCo kco
tcIfaceUnivCoProv (IfaceProofIrrelProv kco) = ProofIrrelProv <$> tcIfaceCo kco
tcIfaceUnivCoProv (IfacePluginProv str) = return $ PluginProv str
tcIfaceUnivCoProv (IfaceCorePrepProv b) = return $ CorePrepProv b
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* *
* *
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
************************************************************************
* *
Core
* *
************************************************************************
-}
tcIfaceExpr :: IfaceExpr -> IfL CoreExpr
tcIfaceExpr (IfaceType ty)
= Type <$> tcIfaceType ty
tcIfaceExpr (IfaceCo co)
= Coercion <$> tcIfaceCo co
tcIfaceExpr (IfaceCast expr co)
= Cast <$> tcIfaceExpr expr <*> tcIfaceCo co
tcIfaceExpr (IfaceLcl name)
= Var <$> tcIfaceLclId name
tcIfaceExpr (IfaceExt gbl)
= Var <$> tcIfaceExtId gbl
tcIfaceExpr (IfaceLitRubbish tc rep)
= do rep' <- tcIfaceType rep
return (Lit (LitRubbish tc rep'))
tcIfaceExpr (IfaceLit lit)
= do lit' <- tcIfaceLit lit
return (Lit lit')
tcIfaceExpr (IfaceFCall cc ty) = do
ty' <- tcIfaceType ty
u <- newUnique
return (Var (mkFCallId u cc ty'))
tcIfaceExpr (IfaceTuple sort args)
= do { args' <- mapM tcIfaceExpr args
; tc <- tcTupleTyCon False sort arity
; let con_tys = map exprType args'
some_con_args = map Type con_tys ++ args'
con_args = case sort of
UnboxedTuple -> map (Type . getRuntimeRep) con_tys ++ some_con_args
_ -> some_con_args
-- Put the missing type arguments back in
con_id = dataConWorkId (tyConSingleDataCon tc)
; return (mkApps (Var con_id) con_args) }
where
arity = length args
tcIfaceExpr (IfaceLam (bndr, os) body)
= bindIfaceBndr bndr $ \bndr' ->
Lam (tcIfaceOneShot os bndr') <$> tcIfaceExpr body
where
tcIfaceOneShot IfaceOneShot b = setOneShotLambda b
tcIfaceOneShot _ b = b
tcIfaceExpr (IfaceApp fun arg)
= App <$> tcIfaceExpr fun <*> tcIfaceExpr arg
tcIfaceExpr (IfaceECase scrut ty)
= do { scrut' <- tcIfaceExpr scrut
; ty' <- tcIfaceType ty
; return (castBottomExpr scrut' ty') }
tcIfaceExpr (IfaceCase scrut case_bndr alts) = do
scrut' <- tcIfaceExpr scrut
case_bndr_name <- newIfaceName (mkVarOccFS case_bndr)
let
scrut_ty = exprType scrut'
case_mult = ManyTy
case_bndr' = mkLocalIdOrCoVar case_bndr_name case_mult scrut_ty
" OrCoVar " since a coercion can be a scrutinee with -fdefer - type - errors
( e.g. see test T15695 ) . Ticket # 17291 covers fixing this problem .
tc_app = splitTyConApp scrut_ty
NB : Wo n't always succeed ( polymorphic case )
-- but won't be demanded in those cases
NB : not tcSplitTyConApp ; we are looking at Core here
-- look through non-rec newtypes to find the tycon that
corresponds to the datacon in this case alternative
extendIfaceIdEnv [case_bndr'] $ do
alts' <- mapM (tcIfaceAlt scrut' case_mult tc_app) alts
return (Case scrut' case_bndr' (coreAltsType alts') alts')
tcIfaceExpr (IfaceLet (IfaceNonRec (IfLetBndr fs ty info ji) rhs) body)
= do { name <- newIfaceName (mkVarOccFS fs)
; ty' <- tcIfaceType ty
Do n't ignore prags ; we are inside one !
NotTopLevel name ty' info
; let id = mkLocalIdWithInfo name ManyTy ty' id_info
`asJoinId_maybe` tcJoinInfo ji
; rhs' <- tcIfaceExpr rhs
; body' <- extendIfaceIdEnv [id] (tcIfaceExpr body)
; return (Let (NonRec id rhs') body') }
tcIfaceExpr (IfaceLet (IfaceRec pairs) body)
= do { ids <- mapM tc_rec_bndr (map fst pairs)
; extendIfaceIdEnv ids $ do
{ pairs' <- zipWithM tc_pair pairs ids
; body' <- tcIfaceExpr body
; return (Let (Rec pairs') body') } }
where
tc_rec_bndr (IfLetBndr fs ty _ ji)
= do { name <- newIfaceName (mkVarOccFS fs)
; ty' <- tcIfaceType ty
; return (mkLocalId name ManyTy ty' `asJoinId_maybe` tcJoinInfo ji) }
tc_pair (IfLetBndr _ _ info _, rhs) id
= do { rhs' <- tcIfaceExpr rhs
Do n't ignore prags ; we are inside one !
NotTopLevel (idName id) (idType id) info
; return (setIdInfo id id_info, rhs') }
tcIfaceExpr (IfaceTick tickish expr) = do
expr' <- tcIfaceExpr expr
-- If debug flag is not set: Ignore source notes
need_notes <- needSourceNotes <$> getDynFlags
case tickish of
IfaceSource{} | not (need_notes)
-> return expr'
_otherwise -> do
tickish' <- tcIfaceTickish tickish
return (Tick tickish' expr')
-------------------------
tcIfaceTickish :: IfaceTickish -> IfM lcl CoreTickish
tcIfaceTickish (IfaceHpcTick modl ix) = return (HpcTick modl ix)
tcIfaceTickish (IfaceSCC cc tick push) = return (ProfNote cc tick push)
tcIfaceTickish (IfaceSource src name) = return (SourceNote src name)
-------------------------
tcIfaceLit :: Literal -> IfL Literal
tcIfaceLit lit = return lit
-------------------------
tcIfaceAlt :: CoreExpr -> Mult -> (TyCon, [Type])
-> IfaceAlt
-> IfL CoreAlt
tcIfaceAlt _ _ _ (IfaceAlt IfaceDefault names rhs)
= assert (null names) $ do
rhs' <- tcIfaceExpr rhs
return (Alt DEFAULT [] rhs')
tcIfaceAlt _ _ _ (IfaceAlt (IfaceLitAlt lit) names rhs)
= assert (null names) $ do
lit' <- tcIfaceLit lit
rhs' <- tcIfaceExpr rhs
return (Alt (LitAlt lit') [] rhs')
-- A case alternative is made quite a bit more complicated
-- by the fact that we omit type annotations because we can
-- work them out. True enough, but its not that easy!
tcIfaceAlt scrut mult (tycon, inst_tys) (IfaceAlt (IfaceDataAlt data_occ) arg_strs rhs)
= do { con <- tcIfaceDataCon data_occ
; when (debugIsOn && not (con `elem` tyConDataCons tycon))
(failIfM (ppr scrut $$ ppr con $$ ppr tycon $$ ppr (tyConDataCons tycon)))
; tcIfaceDataAlt mult con inst_tys arg_strs rhs }
tcIfaceDataAlt :: Mult -> DataCon -> [Type] -> [FastString] -> IfaceExpr
-> IfL CoreAlt
tcIfaceDataAlt mult con inst_tys arg_strs rhs
= do { uniqs <- getUniquesM
; let (ex_tvs, arg_ids)
= dataConRepFSInstPat arg_strs uniqs mult con inst_tys
; rhs' <- extendIfaceEnvs ex_tvs $
extendIfaceIdEnv arg_ids $
tcIfaceExpr rhs
; return (Alt (DataAlt con) (ex_tvs ++ arg_ids) rhs') }
{-
************************************************************************
* *
IdInfo
* *
************************************************************************
-}
tcIdDetails :: Type -> IfaceIdDetails -> IfL IdDetails
tcIdDetails _ IfVanillaId = return VanillaId
tcIdDetails _ (IfWorkerLikeId dmds) = return $ WorkerLikeId dmds
tcIdDetails ty IfDFunId
= return (DFunId (isNewTyCon (classTyCon cls)))
where
(_, _, cls, _) = tcSplitDFunTy ty
tcIdDetails _ (IfRecSelId tc naughty)
= do { tc' <- either (fmap RecSelData . tcIfaceTyCon)
(fmap (RecSelPatSyn . tyThingPatSyn) . tcIfaceDecl False)
tc
; return (RecSelId { sel_tycon = tc', sel_naughty = naughty }) }
where
tyThingPatSyn (AConLike (PatSynCon ps)) = ps
tyThingPatSyn _ = panic "tcIdDetails: expecting patsyn"
tcIdInfo :: Bool -> TopLevelFlag -> Name -> Type -> IfaceIdInfo -> IfL IdInfo
tcIdInfo ignore_prags toplvl name ty info = do
lcl_env <- getLclEnv
-- Set the CgInfo to something sensible but uninformative before
we start ; default assumption is that it has CAFs
let init_info = if if_boot lcl_env == IsBoot
then vanillaIdInfo `setUnfoldingInfo` BootUnfolding
else vanillaIdInfo
foldlM tcPrag init_info (needed_prags info)
where
needed_prags :: [IfaceInfoItem] -> [IfaceInfoItem]
needed_prags items
| not ignore_prags = items
| otherwise = filter need_prag items
need_prag :: IfaceInfoItem -> Bool
-- Always read in compulsory unfoldings
See Note [ Always expose compulsory unfoldings ] in GHC.Iface . Tidy
need_prag (HsUnfold _ (IfCoreUnfold src _ _ _)) = isCompulsorySource src
need_prag _ = False
tcPrag :: IdInfo -> IfaceInfoItem -> IfL IdInfo
tcPrag info HsNoCafRefs = return (info `setCafInfo` NoCafRefs)
tcPrag info (HsArity arity) = return (info `setArityInfo` arity)
tcPrag info (HsDmdSig str) = return (info `setDmdSigInfo` str)
tcPrag info (HsCprSig cpr) = return (info `setCprSigInfo` cpr)
tcPrag info (HsInline prag) = return (info `setInlinePragInfo` prag)
tcPrag info (HsLFInfo lf_info) = do
lf_info <- tcLFInfo lf_info
return (info `setLFInfo` lf_info)
tcPrag info (HsTagSig sig) = do
return (info `setTagSig` sig)
The next two are lazy , so they do n't transitively suck stuff in
tcPrag info (HsUnfold lb if_unf)
= do { unf <- tcUnfolding toplvl name ty info if_unf
; let info1 | lb = info `setOccInfo` strongLoopBreaker
| otherwise = info
; return (info1 `setUnfoldingInfo` unf) }
tcJoinInfo :: IfaceJoinInfo -> Maybe JoinArity
tcJoinInfo (IfaceJoinPoint ar) = Just ar
tcJoinInfo IfaceNotJoinPoint = Nothing
tcLFInfo :: IfaceLFInfo -> IfL LambdaFormInfo
tcLFInfo lfi = case lfi of
IfLFReEntrant rep_arity ->
-- LFReEntrant closures in interface files are guaranteed to
--
-- - Be top-level, as only top-level closures are exported.
-- - Have no free variables, as only non-top-level closures have free
-- variables
- Do n't have ArgDescrs , as ArgDescr is used when generating code for
-- the closure
--
-- These invariants are checked when generating LFInfos in toIfaceLFInfo.
return (LFReEntrant TopLevel rep_arity True ArgUnknown)
IfLFThunk updatable mb_fun ->
LFThunk closure in interface files are guaranteed to
--
-- - Be top-level
-- - No have free variables
--
-- These invariants are checked when generating LFInfos in toIfaceLFInfo.
return (LFThunk TopLevel True updatable NonStandardThunk mb_fun)
IfLFUnlifted ->
return LFUnlifted
IfLFCon con_name ->
LFCon <$!> tcIfaceDataCon con_name
IfLFUnknown fun_flag ->
return (LFUnknown fun_flag)
tcUnfolding :: TopLevelFlag -> Name -> Type -> IdInfo -> IfaceUnfolding -> IfL Unfolding
See Note [ Lazily checking Unfoldings ]
tcUnfolding toplvl name _ info (IfCoreUnfold src cache if_guidance if_expr)
= do { uf_opts <- unfoldingOpts <$> getDynFlags
; expr <- tcUnfoldingRhs (isCompulsorySource src) toplvl name if_expr
; let guidance = case if_guidance of
IfWhen arity unsat_ok boring_ok -> UnfWhen arity unsat_ok boring_ok
IfNoGuidance -> calcUnfoldingGuidance uf_opts is_top_bottoming expr
See Note [ Tying the ' CoreUnfolding ' knot ]
; return $ mkCoreUnfolding src True expr (Just cache) guidance }
where
Strictness should occur before unfolding !
is_top_bottoming = isTopLevel toplvl && isDeadEndSig (dmdSigInfo info)
tcUnfolding _toplvl name dfun_ty _ (IfDFunUnfold bs ops)
= bindIfaceBndrs bs $ \ bs' ->
do { ops1 <- forkM doc $ mapM tcIfaceExpr ops
; return $ mkDFunUnfolding bs' (classDataCon cls) ops1 }
where
doc = text "Class ops for dfun" <+> ppr name
(_, _, cls, _) = tcSplitDFunTy dfun_ty
Note [ Tying the ' CoreUnfolding ' knot ]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
The unfolding of recursive definitions can contain references to the
I d being defined . Consider the following example :
foo : : ( )
foo = foo
The unfolding template of ' foo ' is , of course , ' foo ' ; so the interface
file for this module contains :
foo : : ( ) ; Unfolding = foo
When rehydrating the interface file we are going to make an I d for
' foo ' ( in GHC.IfaceToCore ) , with an ' Unfolding ' . We used to make this
' Unfolding ' by calling ' ' , but that needs to populate ,
among other fields , the ' uf_is_value ' field , by computing
' exprIsValue ' of the template ( in this case , ' foo ' ) .
' exprIsValue e ' looks at the unfoldings of variables in ' e ' to see if
they are evaluated ; so it consults the ` uf_is_value ` field of
variables in ` e ` . Now we can see the problem : to set the ` uf_is_value `
field of ` foo ` 's unfolding , we look at its unfolding ( in this case
just ` foo ` itself ! ) . Loop . This is the root cause of ticket # 22272 .
The simple solution we chose is to serialise the various auxiliary
fields of ` CoreUnfolding ` so that we do n't need to recreate them when
rehydrating . Specifically , the following fields are moved to the
' UnfoldingCache ' , which is persisted in the interface file :
* ' uf_is_conlike '
* ' uf_is_value '
* ' uf_is_work_free '
* ' uf_expandable '
These four bits make the interface files only one byte larger per
unfolding ; on the other hand , this does save calls to ' exprIsValue ' ,
' exprIsExpandable ' etc for every imported Id.
We could choose to do this only for loop breakers . But that 's a bit
more complicated and it seems good all round .
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
The unfolding of recursive definitions can contain references to the
Id being defined. Consider the following example:
foo :: ()
foo = foo
The unfolding template of 'foo' is, of course, 'foo'; so the interface
file for this module contains:
foo :: (); Unfolding = foo
When rehydrating the interface file we are going to make an Id for
'foo' (in GHC.IfaceToCore), with an 'Unfolding'. We used to make this
'Unfolding' by calling 'mkFinalUnfolding', but that needs to populate,
among other fields, the 'uf_is_value' field, by computing
'exprIsValue' of the template (in this case, 'foo').
'exprIsValue e' looks at the unfoldings of variables in 'e' to see if
they are evaluated; so it consults the `uf_is_value` field of
variables in `e`. Now we can see the problem: to set the `uf_is_value`
field of `foo`'s unfolding, we look at its unfolding (in this case
just `foo` itself!). Loop. This is the root cause of ticket #22272.
The simple solution we chose is to serialise the various auxiliary
fields of `CoreUnfolding` so that we don't need to recreate them when
rehydrating. Specifically, the following fields are moved to the
'UnfoldingCache', which is persisted in the interface file:
* 'uf_is_conlike'
* 'uf_is_value'
* 'uf_is_work_free'
* 'uf_expandable'
These four bits make the interface files only one byte larger per
unfolding; on the other hand, this does save calls to 'exprIsValue',
'exprIsExpandable' etc for every imported Id.
We could choose to do this only for loop breakers. But that's a bit
more complicated and it seems good all round.
-}
Note [ Lazily checking Unfoldings ]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
For unfoldings , we try to do the job lazily , so that we never typecheck
an unfolding that is n't going to be looked at .
The main idea is that if M.hi has a declaration
f : : Int - > Int
f = \x . ... A.g ... -- The unfolding for f
then we do n't even want to /read/ A.hi unless f 's unfolding is actually used ; say ,
if f is inlined . But we need to be careful . Even if we do n't inline f , we might ask
hasNoBinding of it ( does this in GHC.Core . Lint.checkCanEtaExpand ) ,
and hasNoBinding looks to see if f has a compulsory unfolding .
So the root Unfolding constructor must be visible : we want to be able to read the ' uf_src '
field which says whether it is a compulsory unfolding , without forcing the unfolding RHS
which is stored in ' uf_tmpl ' . This matters for efficiency , but not only : if 's unfolding
mentions f , we must not look at the unfolding RHS for f , as this is precisely what we are
in the middle of checking ( so looking at it would cause a loop ) .
Conclusion : ` tcUnfolding ` must return an ` Unfolding ` whose ` uf_src ` field is readable without
forcing the ` uf_tmpl ` field . In particular , all the functions used at the end of
` tcUnfolding ` ( such as ` mkFinalUnfolding ` , ` mkCoreUnfolding ` ) must be
lazy in ` expr ` .
Ticket # 21139
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
For unfoldings, we try to do the job lazily, so that we never typecheck
an unfolding that isn't going to be looked at.
The main idea is that if M.hi has a declaration
f :: Int -> Int
f = \x. ...A.g... -- The unfolding for f
then we don't even want to /read/ A.hi unless f's unfolding is actually used; say,
if f is inlined. But we need to be careful. Even if we don't inline f, we might ask
hasNoBinding of it (Core Lint does this in GHC.Core.Lint.checkCanEtaExpand),
and hasNoBinding looks to see if f has a compulsory unfolding.
So the root Unfolding constructor must be visible: we want to be able to read the 'uf_src'
field which says whether it is a compulsory unfolding, without forcing the unfolding RHS
which is stored in 'uf_tmpl'. This matters for efficiency, but not only: if g's unfolding
mentions f, we must not look at the unfolding RHS for f, as this is precisely what we are
in the middle of checking (so looking at it would cause a loop).
Conclusion: `tcUnfolding` must return an `Unfolding` whose `uf_src` field is readable without
forcing the `uf_tmpl` field. In particular, all the functions used at the end of
`tcUnfolding` (such as `mkFinalUnfolding`, `mkCoreUnfolding`) must be
lazy in `expr`.
Ticket #21139
-}
tcUnfoldingRhs :: Bool -- ^ Is this unfolding compulsory?
See Note [ Checking for representation polymorphism ] in GHC.Core .
-> TopLevelFlag -> Name -> IfaceExpr -> IfL CoreExpr
tcUnfoldingRhs is_compulsory toplvl name expr
= forkM doc $ do
core_expr' <- tcIfaceExpr expr
-- Check for type consistency in the unfolding
See Note [ Linting Unfoldings from Interfaces ] in GHC.Core .
when (isTopLevel toplvl) $
whenGOptM Opt_DoCoreLinting $ do
in_scope <- nonDetEltsUniqSet <$> get_in_scope
dflags <- getDynFlags
logger <- getLogger
case lintUnfolding is_compulsory (initLintConfig dflags in_scope) noSrcLoc core_expr' of
Nothing -> return ()
Just errs -> liftIO $
displayLintResults logger False doc
(pprCoreExpr core_expr') (emptyBag, errs)
return core_expr'
where
doc = ppWhen is_compulsory (text "Compulsory") <+>
text "Unfolding of" <+> ppr name
get_in_scope :: IfL VarSet -- Totally disgusting; but just for linting
get_in_scope
= do { (gbl_env, lcl_env) <- getEnvs
; let type_envs = knotVarElems (if_rec_types gbl_env)
; top_level_vars <- concat <$> mapM (fmap typeEnvIds . setLclEnv ()) type_envs
; return (bindingsVars (if_tv_env lcl_env) `unionVarSet`
bindingsVars (if_id_env lcl_env) `unionVarSet`
mkVarSet top_level_vars) }
bindingsVars :: FastStringEnv Var -> VarSet
bindingsVars ufm = mkVarSet $ nonDetEltsUFM ufm
-- It's OK to use nonDetEltsUFM here because we immediately forget
-- the ordering by creating a set
tcIfaceOneShot :: IfaceOneShot -> OneShotInfo
tcIfaceOneShot IfaceNoOneShot = NoOneShotInfo
tcIfaceOneShot IfaceOneShot = OneShotLam
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* *
Getting from Names to
* *
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
************************************************************************
* *
Getting from Names to TyThings
* *
************************************************************************
-}
tcIfaceGlobal :: Name -> IfL TyThing
tcIfaceGlobal name
| Just thing <- wiredInNameTyThing_maybe name
Wired - in things include TyCons , DataCons , and Ids
-- Even though we are in an interface file, we want to make
sure the instances and RULES of this thing ( particularly ) are loaded
-- Imagine: f :: Double -> Double
= do { ifCheckWiredInThing thing; return thing }
| otherwise
= do { env <- getGblEnv
; cur_mod <- if_mod <$> getLclEnv
; case lookupKnotVars (if_rec_types env) (fromMaybe cur_mod (nameModule_maybe name)) of -- Note [Tying the knot]
Just get_type_env
-> do -- It's defined in a module in the hs-boot loop
{ type_env <- setLclEnv () get_type_env -- yuk
; case lookupNameEnv type_env name of
Just thing -> return thing
-- See Note [Knot-tying fallback on boot]
Nothing -> via_external
}
_ -> via_external }
where
via_external = do
{ hsc_env <- getTopEnv
; mb_thing <- liftIO (lookupType hsc_env name)
; case mb_thing of {
Just thing -> return thing ;
Nothing -> do
{ mb_thing <- importDecl name -- It's imported; go get it
; case mb_thing of
Failed err -> failIfM (ppr name <+> err)
Succeeded thing -> return thing
}}}
-- Note [Tying the knot]
-- ~~~~~~~~~~~~~~~~~~~~~
The if_rec_types field is used when we are compiling M.hs , which indirectly
imports Foo.hi , which mentions Then we look up M.T in M 's type
environment , which is splatted into if_rec_types after we 've built M 's type
envt .
--
This is a dark and complicated part of GHC type checking , with a lot
of moving parts . Interested readers should also look at :
--
-- * Note [Knot-tying typecheckIface]
-- * Note [DFun knot-tying]
-- * Note [hsc_type_env_var hack]
-- * Note [Knot-tying fallback on boot]
-- * Note [Hydrating Modules]
--
-- There is also a wiki page on the subject, see:
--
-- -the-knot
-- Note [Knot-tying fallback on boot]
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Suppose that you are typechecking A.hs , which transitively imports ,
via B.hs , A.hs - boot . When we poke on and discover that it
has a reference to a type T from A , what TyThing should we wire
-- it up with? Clearly, if we have already typechecked T and
-- added it into the type environment, we should go ahead and use that
-- type. But what if we haven't typechecked it yet?
--
For the longest time , GHC adopted the policy that this was
* an error condition * ; that you MUST NEVER poke on B.hs 's reference
to a T defined in A.hs until A.hs has gotten around to kind - checking
-- T and adding it to the env. However, actually ensuring this is the
-- case has proven to be a bug farm, because it's really difficult to
-- actually ensure this never happens. The problem was especially poignant
-- with type family consistency checks, which eagerly happen before any
-- typechecking takes place.
--
Today , we take a different strategy : if we ever try to access
-- an entity from A which doesn't exist, we just fall back on the
-- definition of A from the hs-boot file. This is complicated in
its own way : it means that you may end up with a mix of A.hs and
A.hs - boot during the course of typechecking . We do n't
-- think (and have not observed) any cases where this would cause
-- problems, but the hypothetical situation one might worry about
is something along these lines in Core :
--
-- case x of
-- A -> e1
-- B -> e2
--
-- If, when typechecking this, we find x :: T, and the T we are hooked
-- up with is the abstract one from the hs-boot file, rather than the
-- one defined in this module with constructors A and B. But it's hard
-- to see how this could happen, especially because the reference to
the constructor ( A and B ) means that GHC will always
-- this expression *after* typechecking T.
tcIfaceTyCon :: IfaceTyCon -> IfL TyCon
tcIfaceTyCon (IfaceTyCon name _info)
= do { thing <- tcIfaceGlobal name
; case thing of
ATyCon tc -> return tc
AConLike (RealDataCon dc) -> return (promoteDataCon dc)
_ -> pprPanic "tcIfaceTyCon" (ppr thing) }
tcIfaceCoAxiom :: Name -> IfL (CoAxiom Branched)
tcIfaceCoAxiom name = do { thing <- tcIfaceImplicit name
; return (tyThingCoAxiom thing) }
tcIfaceCoAxiomRule :: IfLclName -> IfL CoAxiomRule
Unlike CoAxioms , which arise from user ' type instance ' declarations ,
there are a fixed set of CoAxiomRules :
- axioms for type - level literals ( and Symbol ) ,
-- enumerated in typeNatCoAxiomRules
tcIfaceCoAxiomRule n
| Just ax <- lookupUFM typeNatCoAxiomRules n
= return ax
| otherwise
= pprPanic "tcIfaceCoAxiomRule" (ppr n)
tcIfaceDataCon :: Name -> IfL DataCon
tcIfaceDataCon name = do { thing <- tcIfaceGlobal name
; case thing of
AConLike (RealDataCon dc) -> return dc
_ -> pprPanic "tcIfaceDataCon" (ppr name$$ ppr thing) }
tcIfaceConLike :: Name -> IfL ConLike
tcIfaceConLike name = do { thing <- tcIfaceGlobal name
; case thing of
AConLike cl -> return cl
_ -> pprPanic "tcIfaceConLike" (ppr name$$ ppr thing) }
tcIfaceExtId :: Name -> IfL Id
tcIfaceExtId name = do { thing <- tcIfaceGlobal name
; case thing of
AnId id -> return id
_ -> pprPanic "tcIfaceExtId" (ppr name$$ ppr thing) }
-- See Note [Resolving never-exported Names] in GHC.IfaceToCore
tcIfaceImplicit :: Name -> IfL TyThing
tcIfaceImplicit n = do
lcl_env <- getLclEnv
case if_implicits_env lcl_env of
Nothing -> tcIfaceGlobal n
Just tenv ->
case lookupTypeEnv tenv n of
Nothing -> pprPanic "tcIfaceInst" (ppr n $$ ppr tenv)
Just tything -> return tything
{-
************************************************************************
* *
Bindings
* *
************************************************************************
-}
bindIfaceId :: IfaceIdBndr -> (Id -> IfL a) -> IfL a
bindIfaceId (w, fs, ty) thing_inside
= do { name <- newIfaceName (mkVarOccFS fs)
; ty' <- tcIfaceType ty
; w' <- tcIfaceType w
; let id = mkLocalIdOrCoVar name w' ty'
We should not have " OrCoVar " here , this is a bug ( # 17545 )
; extendIfaceIdEnv [id] (thing_inside id) }
bindIfaceIds :: [IfaceIdBndr] -> ([Id] -> IfL a) -> IfL a
bindIfaceIds [] thing_inside = thing_inside []
bindIfaceIds (b:bs) thing_inside
= bindIfaceId b $ \b' ->
bindIfaceIds bs $ \bs' ->
thing_inside (b':bs')
bindIfaceBndr :: IfaceBndr -> (CoreBndr -> IfL a) -> IfL a
bindIfaceBndr (IfaceIdBndr bndr) thing_inside
= bindIfaceId bndr thing_inside
bindIfaceBndr (IfaceTvBndr bndr) thing_inside
= bindIfaceTyVar bndr thing_inside
bindIfaceBndrs :: [IfaceBndr] -> ([CoreBndr] -> IfL a) -> IfL a
bindIfaceBndrs [] thing_inside = thing_inside []
bindIfaceBndrs (b:bs) thing_inside
= bindIfaceBndr b $ \ b' ->
bindIfaceBndrs bs $ \ bs' ->
thing_inside (b':bs')
-----------------------
bindIfaceForAllBndrs :: [VarBndr IfaceBndr vis] -> ([VarBndr TyCoVar vis] -> IfL a) -> IfL a
bindIfaceForAllBndrs [] thing_inside = thing_inside []
bindIfaceForAllBndrs (bndr:bndrs) thing_inside
= bindIfaceForAllBndr bndr $ \tv vis ->
bindIfaceForAllBndrs bndrs $ \bndrs' ->
thing_inside (Bndr tv vis : bndrs')
bindIfaceForAllBndr :: (VarBndr IfaceBndr vis) -> (TyCoVar -> vis -> IfL a) -> IfL a
bindIfaceForAllBndr (Bndr (IfaceTvBndr tv) vis) thing_inside
= bindIfaceTyVar tv $ \tv' -> thing_inside tv' vis
bindIfaceForAllBndr (Bndr (IfaceIdBndr tv) vis) thing_inside
= bindIfaceId tv $ \tv' -> thing_inside tv' vis
bindIfaceTyVar :: IfaceTvBndr -> (TyVar -> IfL a) -> IfL a
bindIfaceTyVar (occ,kind) thing_inside
= do { name <- newIfaceName (mkTyVarOccFS occ)
; tyvar <- mk_iface_tyvar name kind
; extendIfaceTyVarEnv [tyvar] (thing_inside tyvar) }
bindIfaceTyVars :: [IfaceTvBndr] -> ([TyVar] -> IfL a) -> IfL a
bindIfaceTyVars [] thing_inside = thing_inside []
bindIfaceTyVars (bndr:bndrs) thing_inside
= bindIfaceTyVar bndr $ \tv ->
bindIfaceTyVars bndrs $ \tvs ->
thing_inside (tv : tvs)
mk_iface_tyvar :: Name -> IfaceKind -> IfL TyVar
mk_iface_tyvar name ifKind
= do { kind <- tcIfaceType ifKind
; return (Var.mkTyVar name kind) }
bindIfaceTyConBinders :: [IfaceTyConBinder]
-> ([TyConBinder] -> IfL a) -> IfL a
bindIfaceTyConBinders [] thing_inside = thing_inside []
bindIfaceTyConBinders (b:bs) thing_inside
= bindIfaceTyConBinderX bindIfaceBndr b $ \ b' ->
bindIfaceTyConBinders bs $ \ bs' ->
thing_inside (b':bs')
bindIfaceTyConBinders_AT :: [IfaceTyConBinder]
-> ([TyConBinder] -> IfL a) -> IfL a
-- Used for type variable in nested associated data/type declarations
-- where some of the type variables are already in scope
-- class C a where { data T a b }
-- Here 'a' is in scope when we look at the 'data T'
bindIfaceTyConBinders_AT [] thing_inside
= thing_inside []
bindIfaceTyConBinders_AT (b : bs) thing_inside
= bindIfaceTyConBinderX bind_tv b $ \b' ->
bindIfaceTyConBinders_AT bs $ \bs' ->
thing_inside (b':bs')
where
bind_tv tv thing
= do { mb_tv <- lookupIfaceVar tv
; case mb_tv of
Just b' -> thing b'
Nothing -> bindIfaceBndr tv thing }
bindIfaceTyConBinderX :: (IfaceBndr -> (TyCoVar -> IfL a) -> IfL a)
-> IfaceTyConBinder
-> (TyConBinder -> IfL a) -> IfL a
bindIfaceTyConBinderX bind_tv (Bndr tv vis) thing_inside
= bind_tv tv $ \tv' ->
thing_inside (Bndr tv' vis)
-- CgBreakInfo
hydrateCgBreakInfo :: CgBreakInfo -> IfL ([Maybe (Id, Word16)], Type)
hydrateCgBreakInfo CgBreakInfo{..} = do
bindIfaceTyVars cgb_tyvars $ \_ -> do
result_ty <- tcIfaceType cgb_resty
mbVars <- mapM (traverse (\(if_gbl, offset) -> (,offset) <$> bindIfaceId if_gbl return)) cgb_vars
return (mbVars, result_ty)
| null | https://raw.githubusercontent.com/ghc/ghc/3c0f0c6d99486502c72e6514a40e7264baaa6afc/compiler/GHC/IfaceToCore.hs | haskell | Desired by HERMIT (#7683)
needs to build types & coercions in a knot
For ( b ) consider : f = \$( ... h .... )
where h is imported , and calls f via an hi - boot file .
This is bad ! But it is not seen as a staging error , because h
is indeed imported . We do n't want the type - checker to black - hole
when simplifying and compiling the splice !
Simple solution : discard any unfolding that mentions a variable
bound in this module ( and hence not yet processed ) .
The discarding happens when forkM finds a type error .
For (b) consider: f = \$(...h....)
where h is imported, and calls f via an hi-boot file.
This is bad! But it is not seen as a staging error, because h
is indeed imported. We don't want the type-checker to black-hole
when simplifying and compiling the splice!
Simple solution: discard any unfolding that mentions a variable
bound in this module (and hence not yet processed).
The discarding happens when forkM finds a type error.
Clients of this function be careful, see Note [Knot-tying typecheckIface]
Get the decls from here
Get the right set of decls and rules. If we are compiling without -O
we discard pragmas before typechecking, so that we don't "see"
information that we shouldn't. From a versioning point of view
It's not actually *wrong* to do so, but in fact GHCi is unable
to handle unboxed tuples, so it must not see unfoldings.
within this single module works out right. It's the callers
job to make sure the knot is tied.
Now do those rules, instances and annotations
Exports
Finished
we'll infinite loop with hs-boot. See #10083 for
an example where this would cause non-termination.
| Returns true if an 'IfaceDecl' is for @data T@ (an abstract data type)
later.)
It doesn't matter; we'll check for consistency later when
we merge, see 'mergeSignatures'
Note [Role merging]
~~~~~~~~~~~~~~~~~~~
merge? It may rescue a merge that might otherwise fail:
signature A where
type role T nominal representational
data T a b
signature A where
type role T representational nominal
data T a b
A module that defines T as representational in both arguments
would successfully fill both signatures, so it would be better
if we merged the roles of these types in some nontrivial
way.
However, we have to be very careful about how we go about
doing this, because role subtyping is *conditional* on
the supertype being NOT representationally injective, e.g.,
if we have instead:
signature A where
type role T nominal representational
data T a b = T a b
signature A where
type role T representational nominal
data T a b = T a b
Absolutely not: neither resulting type is a subtype of the original
types (see Note [Role subtyping]), because data is not representationally
injective.
Thus, merging only occurs when BOTH TyCons in question are
representationally injective. If they're not, no merge.
| This is a very interesting function. Like typecheckIface, we want
merge them together. So in particular, we have to take a different
to get the "base" truth for what we believe the types will be
(this is "type computation.") Then we read everything in relative
to this truth and check for compatibility.
During the merge process, we may need to nondeterministically
pick a particular declaration to use, if multiple signatures define
the declaration ('mergeIfaceDecl'). If, for all choices, there
are no type synonym cycles in the resulting merged graph, then
we can show that our choice cannot matter. Consider the
set of entities which the declarations depend on: by assumption
of acyclicity, we can assume that these have already been shown to be equal
to each other (otherwise merging will fail). Then it must
be the case that all candidate declarations here are type-equal
(the choice doesn't matter) or there is an inequality (in which
case merging will fail.)
Unfortunately, the choice can matter if there is a cycle. Consider the
following merge:
signature H where { type A = C; type B = A; data C }
signature H where { type A = (); data B; type C = B }
If we pick @type A = C@ as our representative, there will be
a cycle and merging will fail. But if we pick @type A = ()@ as
our representative, no cycle occurs, and we instead conclude
that all of the types are unit. So it seems that we either
(a) need a stronger acyclicity check which considers *all*
possible choices from a merge, or (b) we must find a selection
of declarations which is acyclic, and show that this is always
is the case but does not have a proof). For now this is
not implemented.
It's worth noting that at the moment, a data constructor and a
type synonym are never compatible. Consider:
signature H where { type Int=C; type B = Int; data C = Int}
signature H where { export Prelude.Int; data B; type C = B; }
signature (a proper data type) is never considered equal to a
type synonym. Perhaps this should be relaxed, where a type synonym
in a signature is considered implemented by a data type declaration
which matches the reference of the type synonym.
cannot be boot (False)
Build the initial environment
TODO: change tcIfaceDecls to accept w/o Fingerprint
See Note [Resolving never-exported Names] in GHC.IfaceToCore
But note that we use this type_env to typecheck references to DFun
in 'IfaceInst'
instantiated it under some implementation (recorded in 'mi_semantic_module')
and want to check if the implementation fills the signature.
This needs to operate slightly differently than 'typecheckIface'
implementing module, which we will use to give our top-level
declarations the correct 'Name's even when the implementor
DFun silliness (see Note [rnIfaceNeverExported])
See Note [Resolving never-exported Names] in GHC.IfaceToCore
See Note [rnIfaceNeverExported]
Note [Resolving never-exported Names]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
For the high-level overview, see
As described in 'typecheckIfacesForMerging', the splendid innovation
of signature merging is to rewrite all Names in each of the signatures
we are merging together to a pre-merged structure; this is the key
ingredient that lets us solve some problems when merging type
synonyms.
However, when a 'Name' refers to a NON-exported entity, as is the
references to a shared 'Name', we will accidentally fail to check
checked--only exported entities are checked for compatibility,
ClsInst or type family for compatibility in checkBootDeclM.
By virtue of the fact that everything's been pointed to the merged
declaration, you'll never notice there's a difference even if there
is one.
Fortunately, there are only a few places in the interface declarations
where this can occur, so we replace those calls with 'tcIfaceImplicit',
which will consult a local TypeEnv that records any never-exported
Note that we actually knot-tie this local TypeEnv (the 'fixM'), because a
************************************************************************
* *
Type and class declarations
* *
************************************************************************
Load the hi-boot iface for the module being compiled,
if it indeed exists in the transitive closure of imports
Already compiling a hs-boot file
In --make and interactive mode, if this module has an hs-boot file
We check whether the interface is a *boot* interface.
compile a module in TypecheckOnly mode, with a stable,
(it's been replaced by the mother module) so we can't check it.
it's been compiled once, and we don't need to check the boot iface
Re #9245, we always check if there is an hi-boot interface
to check consistency against, rather than just when we notice
that an hi-boot is necessary due to a circular import.
Hi-boot file
There was no hi-boot file. But if there is circularity in
the module graph, there really should have been one.
Since we've read all the direct imports by now,
eps_is_boot will record if any of our imports mention the
current module, which either means a module loop (not
a SOURCE import) or that our hi-boot file has mysteriously
disappeared.
The typical case
error cases
The hi-boot file has mysteriously disappeared.
Someone below us imported us!
This is a loop with no hi-boot in the way
WITHOUT forcing the contents of the interface.
they do n't need the extended type envt . They just get the extended
they don't need the extended type envt. They just get the extended
^ For associated type/data family declarations
Note [Synonym kind loop]
Note [Synonym kind loop]
not be inside the thunk. But the *content* maybe recursive and hence
must be lazy (via forkM). Example:
class C (T a) => D a where
data T a
Here the associated type T is knot-tied with the class, and
Must be done lazily for just the same reason as the
type of a data con; to avoid sucking in types that
it mentions unless it's necessary to do so
Must be done lazily to avoid sucking in types
Must be done lazily in case the RHS of the defaults mention
the type constructor being defined here
Must be done lazily, because axioms are forced when checking
a hs-boot declared type constructor that is going to be
defined by this module.
e.g. type instance F Int = ToBeDefined
| See Note [Interface File with Core: Sharing RHSs]
See Note [Root-main Id]
This special binding is actually defined in the current module
(hence don't go looking for it externally) but the module name is rOOT_MAIN
rather than the current module so we need this special case.
See some similar logic in `GHC.Rename.Env`.
Don't load pragmas into the decl pool
The list can be poked eagerly, but the
Populate the name cache with final versions of all
the names associated with the decl
on the binder. This is important because we must get the right name
which includes its nameParent.
Populate the type environment with the implicitTyThings too.
Note [Tricky iface loop]
~~~~~~~~~~~~~~~~~~~~~~~~
Summary: The delicate point here is that 'mini-env' must be
buildable from 'thing' without demanding any of the things
In more detail: Consider the example
The implicitTyThings of T are: [ <datacon MkT>, <selector x>]
(plus their workers, wrappers, coercions etc etc)
We want to return an environment
We do this by mapping the implicit_names to the associated
implicitTyThings, we can use getOccName on the implicit
be the OccName of exactly one implicitTyThing. So the key is
to define a "mini-env"
However, there is a subtlety: due to how type checking needs
to be staged, we can't poke on the forkM'd thunks inside the
implicitTyThings while building this mini-env.
hs-boot boundaries, poking too early will do the
type-checking before the recursive knot has been tied,
so things will be type-checked in the wrong
environment, and necessary variables won't be in
scope.
others to be looked up, which might cause that
original one to be looked up again, and hence loop.
The code below works because of the following invariant:
checks in order to extract the name. For example, we don't
poke on the "T a" type of <selector x> on the way to
extracting <selector x>'s OccName. Of course, there is no
reason in principle why getting the OccName should force the
thunks, but this means we need to be careful in
implicitTyThings and its helper functions.
All a bit too finely-balanced for my liking.
This mini-env and lookup function mediates between the
uses the invariant that implicit_names and
implicitTyThings are bijective
By this point, we have bound every universal and existential
tyvar. Because of the dcUserTyVarBinders invariant
(see Note [DataCon user type variable binders]), *every* tyvar in
ifConUserTvBinders has a matching counterpart somewhere in the
bound universals/existentials. As a result, calling tcIfaceTyVar
below is always guaranteed to succeed.
(a) to avoid looking tugging on a recursive use of
the type itself, which is knot-tied
(b) to avoid faulting in the component types unless
they are really needed
forced when typechecking record wildcard pattern
matching (it's not completely clear why this
the argument types was recursively defined.
See also Note [Tying the knot]
the type itself; hence inside forkM
Pass the HsImplBangs (i.e. final decisions) to buildDataCon;
it'll use these to guide the construction of a worker.
# SOURCE #
will panic if branched, but that's OK
True <=> ignore rules
An imported RULE is never for a local Id
or, even if it is (module loop, perhaps)
we'll just leave it in the non-local set
This function *must* mirror exactly what Rules.roughTopNames does
We could have stored the ru_rough field in the iface file
but that would be redundant, I think.
The only wrinkle is that we must not be deceived by
type synonyms at the top of a type arg. Since
we can't tell at this point, we are careful not
************************************************************************
* *
Annotations
* *
************************************************************************
************************************************************************
* *
Complete Match Pragmas
* *
************************************************************************
See Note [Positioning of forkM]
************************************************************************
* *
Types
* *
************************************************************************
True <=> typechecking a *type* (vs. an expr)
the number of args. *not* the tuple arity.
in expressions, we only have term args
---------------------------------------
---------------------------------------
Put the missing type arguments back in
but won't be demanded in those cases
look through non-rec newtypes to find the tycon that
If debug flag is not set: Ignore source notes
-----------------------
-----------------------
-----------------------
A case alternative is made quite a bit more complicated
by the fact that we omit type annotations because we can
work them out. True enough, but its not that easy!
************************************************************************
* *
IdInfo
* *
************************************************************************
Set the CgInfo to something sensible but uninformative before
Always read in compulsory unfoldings
LFReEntrant closures in interface files are guaranteed to
- Be top-level, as only top-level closures are exported.
- Have no free variables, as only non-top-level closures have free
variables
the closure
These invariants are checked when generating LFInfos in toIfaceLFInfo.
- Be top-level
- No have free variables
These invariants are checked when generating LFInfos in toIfaceLFInfo.
The unfolding for f
The unfolding for f
^ Is this unfolding compulsory?
Check for type consistency in the unfolding
Totally disgusting; but just for linting
It's OK to use nonDetEltsUFM here because we immediately forget
the ordering by creating a set
Even though we are in an interface file, we want to make
Imagine: f :: Double -> Double
Note [Tying the knot]
It's defined in a module in the hs-boot loop
yuk
See Note [Knot-tying fallback on boot]
It's imported; go get it
Note [Tying the knot]
~~~~~~~~~~~~~~~~~~~~~
* Note [Knot-tying typecheckIface]
* Note [DFun knot-tying]
* Note [hsc_type_env_var hack]
* Note [Knot-tying fallback on boot]
* Note [Hydrating Modules]
There is also a wiki page on the subject, see:
-the-knot
Note [Knot-tying fallback on boot]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
it up with? Clearly, if we have already typechecked T and
added it into the type environment, we should go ahead and use that
type. But what if we haven't typechecked it yet?
T and adding it to the env. However, actually ensuring this is the
case has proven to be a bug farm, because it's really difficult to
actually ensure this never happens. The problem was especially poignant
with type family consistency checks, which eagerly happen before any
typechecking takes place.
an entity from A which doesn't exist, we just fall back on the
definition of A from the hs-boot file. This is complicated in
think (and have not observed) any cases where this would cause
problems, but the hypothetical situation one might worry about
case x of
A -> e1
B -> e2
If, when typechecking this, we find x :: T, and the T we are hooked
up with is the abstract one from the hs-boot file, rather than the
one defined in this module with constructors A and B. But it's hard
to see how this could happen, especially because the reference to
this expression *after* typechecking T.
enumerated in typeNatCoAxiomRules
See Note [Resolving never-exported Names] in GHC.IfaceToCore
************************************************************************
* *
Bindings
* *
************************************************************************
---------------------
Used for type variable in nested associated data/type declarations
where some of the type variables are already in scope
class C a where { data T a b }
Here 'a' is in scope when we look at the 'data T'
CgBreakInfo |
( c ) The University of Glasgow 2006
( c ) The GRASP / AQUA Project , Glasgow University , 1992 - 1998
Type checking of type signatures in interface files
(c) The University of Glasgow 2006
(c) The GRASP/AQUA Project, Glasgow University, 1992-1998
Type checking of type signatures in interface files
-}
# LANGUAGE NondecreasingIndentation #
# LANGUAGE FlexibleContexts #
# OPTIONS_GHC -Wno - incomplete - record - updates #
# LANGUAGE TupleSections #
# LANGUAGE RecordWildCards #
module GHC.IfaceToCore (
tcLookupImported_maybe,
importDecl, checkWiredInTyCon, tcHiBootIface, typecheckIface,
typecheckWholeCoreBindings,
typecheckIfacesForMerging,
typecheckIfaceForInstantiate,
tcIfaceDecl, tcIfaceDecls,
tcIfaceInst, tcIfaceFamInst, tcIfaceRules,
tcIfaceAnnotations, tcIfaceCompleteMatches,
tcIfaceGlobal,
tcIfaceOneShot, tcTopIfaceBindings,
hydrateCgBreakInfo
) where
import GHC.Prelude
import GHC.ByteCode.Types
import Data.Word
import GHC.Driver.Env
import GHC.Driver.Session
import GHC.Driver.Config.Core.Lint ( initLintConfig )
import GHC.Builtin.Types.Literals(typeNatCoAxiomRules)
import GHC.Builtin.Types
import GHC.Iface.Syntax
import GHC.Iface.Load
import GHC.Iface.Env
import GHC.StgToCmm.Types
import GHC.Runtime.Heap.Layout
import GHC.Tc.Errors.Types
import GHC.Tc.TyCl.Build
import GHC.Tc.Utils.Monad
import GHC.Tc.Utils.TcType
import GHC.Core.Type
import GHC.Core.Coercion
import GHC.Core.Coercion.Axiom
import GHC.Core.FVs
import GHC.Core.TyCo.Subst ( substTyCoVars )
import GHC.Core.InstEnv
import GHC.Core.FamInstEnv
import GHC.Core
import GHC.Core.RoughMap( RoughMatchTc(..) )
import GHC.Core.Utils
import GHC.Core.Unfold( calcUnfoldingGuidance )
import GHC.Core.Unfold.Make
import GHC.Core.Lint
import GHC.Core.Make
import GHC.Core.Class
import GHC.Core.TyCon
import GHC.Core.ConLike
import GHC.Core.DataCon
import GHC.Core.Opt.OccurAnal ( occurAnalyseExpr )
import GHC.Core.Ppr
import GHC.Unit.Env
import GHC.Unit.External
import GHC.Unit.Module
import GHC.Unit.Module.ModDetails
import GHC.Unit.Module.ModIface
import GHC.Unit.Home.ModInfo
import GHC.Utils.Outputable
import GHC.Utils.Misc
import GHC.Utils.Panic
import GHC.Utils.Panic.Plain
import GHC.Utils.Constants (debugIsOn)
import GHC.Utils.Logger
import GHC.Data.Bag
import GHC.Data.Maybe
import GHC.Data.FastString
import GHC.Data.List.SetOps
import GHC.Types.Annotations
import GHC.Types.SourceFile
import GHC.Types.SourceText
import GHC.Types.Basic hiding ( SuccessFlag(..) )
import GHC.Types.CompleteMatch
import GHC.Types.SrcLoc
import GHC.Types.TypeEnv
import GHC.Types.Unique.FM
import GHC.Types.Unique.DSet ( mkUniqDSet )
import GHC.Types.Unique.Set ( nonDetEltsUniqSet )
import GHC.Types.Unique.Supply
import GHC.Types.Demand( isDeadEndSig )
import GHC.Types.Literal
import GHC.Types.Var as Var
import GHC.Types.Var.Set
import GHC.Types.Name
import GHC.Types.Name.Env
import GHC.Types.Name.Set
import GHC.Types.Id
import GHC.Types.Id.Make
import GHC.Types.Id.Info
import GHC.Types.Tickish
import GHC.Types.TyThing
import GHC.Types.Error
import GHC.Fingerprint
import qualified GHC.Data.BooleanFormula as BF
import Control.Monad
import GHC.Parser.Annotation
import GHC.Driver.Env.KnotVars
import GHC.Unit.Module.WholeCoreBindings
import Data.IORef
import Data.Foldable
import GHC.Builtin.Names (ioTyConName, rOOT_MAIN)
This module takes
IfaceDecl - > TyThing
IfaceType - > Type
etc
An IfaceDecl is populated with RdrNames , and these are not renamed to
Names before typechecking , because there should be no scope errors etc .
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* *
Type - checking a complete interface
* *
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
Suppose we discover we do n't need to recompile . Then we must type
check the old interface file . This is a bit different to the
incremental type checking we do as we suck in interface files . Instead
we do things similarly as when we are typechecking source decls : we
bring into scope the type envt for the interface all at once , using a
and even if they were , the type decls might be mutually recursive .
Note [ Knot - tying typecheckIface ]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Suppose we are typechecking an interface A.hi , and we come across
a Name for another entity defined in A.hi . How do we get the
' ' , in this case ? There are three cases :
1 ) tcHiBootIface in GHC.IfaceToCore : We 're typechecking an
hi - boot file in preparation of checking if the hs file we 're
building is compatible . In this case , we want all of the
internal TyCons to MATCH the ones that we just constructed
during typechecking : the knot is thus tied through if_rec_types .
2 ) rehydrate in GHC.Driver . Make : We are rehydrating a
mutually recursive cluster of hi files , in order to ensure
that all of the references refer to each other correctly .
In this case , the knot is tied through the HPT passed in ,
which contains all of the interfaces we are in the process
of typechecking .
3 ) genModDetails in GHC.Driver . Main : We are typechecking an
old interface to generate the ModDetails . In this case ,
we do the same thing as ( 2 ) and pass in an HPT with
the HomeModInfo being generated to tie knots .
The upshot is that the CLIENT of this function is responsible
for making sure that the knot is tied correctly . If you do n't ,
then you 'll get a message saying that we could n't load the
declaration you wanted .
BTW , in one - shot mode we never call typecheckIface ; instead ,
loadInterface handles type - checking interface . In that case ,
knots are tied through the EPS . No problem !
This module takes
IfaceDecl -> TyThing
IfaceType -> Type
etc
An IfaceDecl is populated with RdrNames, and these are not renamed to
Names before typechecking, because there should be no scope errors etc.
************************************************************************
* *
Type-checking a complete interface
* *
************************************************************************
Suppose we discover we don't need to recompile. Then we must type
check the old interface file. This is a bit different to the
incremental type checking we do as we suck in interface files. Instead
we do things similarly as when we are typechecking source decls: we
bring into scope the type envt for the interface all at once, using a
and even if they were, the type decls might be mutually recursive.
Note [Knot-tying typecheckIface]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Suppose we are typechecking an interface A.hi, and we come across
a Name for another entity defined in A.hi. How do we get the
'TyCon', in this case? There are three cases:
1) tcHiBootIface in GHC.IfaceToCore: We're typechecking an
hi-boot file in preparation of checking if the hs file we're
building is compatible. In this case, we want all of the
internal TyCons to MATCH the ones that we just constructed
during typechecking: the knot is thus tied through if_rec_types.
2) rehydrate in GHC.Driver.Make: We are rehydrating a
mutually recursive cluster of hi files, in order to ensure
that all of the references refer to each other correctly.
In this case, the knot is tied through the HPT passed in,
which contains all of the interfaces we are in the process
of typechecking.
3) genModDetails in GHC.Driver.Main: We are typechecking an
old interface to generate the ModDetails. In this case,
we do the same thing as (2) and pass in an HPT with
the HomeModInfo being generated to tie knots.
The upshot is that the CLIENT of this function is responsible
for making sure that the knot is tied correctly. If you don't,
then you'll get a message saying that we couldn't load the
declaration you wanted.
BTW, in one-shot mode we never call typecheckIface; instead,
loadInterface handles type-checking interface. In that case,
knots are tied through the EPS. No problem!
-}
-> IfG ModDetails
typecheckIface iface
= initIfaceLcl (mi_semantic_module iface) (text "typecheckIface") (mi_boot iface) $ do
ignore_prags <- goptM Opt_IgnoreInterfacePragmas
the decls . This is done lazily , so that the knot - tying
; names_w_things <- tcIfaceDecls ignore_prags (mi_decls iface)
; let type_env = mkNameEnv names_w_things
; insts <- mapM tcIfaceInst (mi_insts iface)
; fam_insts <- mapM tcIfaceFamInst (mi_fam_insts iface)
; rules <- tcIfaceRules ignore_prags (mi_rules iface)
; anns <- tcIfaceAnnotations (mi_anns iface)
; exports <- ifaceExportNames (mi_exports iface)
; complete_matches <- tcIfaceCompleteMatches (mi_complete_matches iface)
; traceIf (vcat [text "Finished typechecking interface for" <+> ppr (mi_module iface),
Careful ! If we tug on the TyThing thunks too early
text "Type envt:" <+> ppr (map fst names_w_things)])
; return $ ModDetails { md_types = type_env
, md_insts = mkInstEnv insts
, md_fam_insts = fam_insts
, md_rules = rules
, md_anns = anns
, md_exports = exports
, md_complete_matches = complete_matches
}
}
typecheckWholeCoreBindings :: IORef TypeEnv -> WholeCoreBindings -> IfG [CoreBind]
typecheckWholeCoreBindings type_var (WholeCoreBindings tidy_bindings this_mod _) =
initIfaceLcl this_mod (text "typecheckWholeCoreBindings") NotBoot $ do
tcTopIfaceBindings type_var tidy_bindings
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* *
for merging
* *
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
************************************************************************
* *
Typechecking for merging
* *
************************************************************************
-}
isAbstractIfaceDecl :: IfaceDecl -> Bool
isAbstractIfaceDecl IfaceData{ ifCons = IfAbstractTyCon {} } = True
isAbstractIfaceDecl IfaceClass{ ifBody = IfAbstractClass } = True
isAbstractIfaceDecl IfaceFamily{ ifFamFlav = IfaceAbstractClosedSynFamilyTyCon } = True
isAbstractIfaceDecl _ = False
ifMaybeRoles :: IfaceDecl -> Maybe [Role]
ifMaybeRoles IfaceData { ifRoles = rs } = Just rs
ifMaybeRoles IfaceSynonym { ifRoles = rs } = Just rs
ifMaybeRoles IfaceClass { ifRoles = rs } = Just rs
ifMaybeRoles _ = Nothing
| Merge two ' IfaceDecl 's together , preferring a non - abstract one . If
both are non - abstract we pick one arbitrarily ( and check for consistency
mergeIfaceDecl :: IfaceDecl -> IfaceDecl -> IfaceDecl
mergeIfaceDecl d1 d2
| isAbstractIfaceDecl d1 = d2 `withRolesFrom` d1
| isAbstractIfaceDecl d2 = d1 `withRolesFrom` d2
| IfaceClass{ ifBody = IfConcreteClass { ifSigs = ops1, ifMinDef = bf1 } } <- d1
, IfaceClass{ ifBody = IfConcreteClass { ifSigs = ops2, ifMinDef = bf2 } } <- d2
= let ops = nonDetNameEnvElts $
plusNameEnv_C mergeIfaceClassOp
(mkNameEnv [ (n, op) | op@(IfaceClassOp n _ _) <- ops1 ])
(mkNameEnv [ (n, op) | op@(IfaceClassOp n _ _) <- ops2 ])
in d1 { ifBody = (ifBody d1) {
ifSigs = ops,
ifMinDef = BF.mkOr [noLocA bf1, noLocA bf2]
}
} `withRolesFrom` d2
| otherwise = d1 `withRolesFrom` d2
First , why might it be necessary to do a non - trivial role
Should we merge the definitions of T so that the roles are R / R ( or N / N ) ?
withRolesFrom :: IfaceDecl -> IfaceDecl -> IfaceDecl
d1 `withRolesFrom` d2
| Just roles1 <- ifMaybeRoles d1
, Just roles2 <- ifMaybeRoles d2
, not (isRepInjectiveIfaceDecl d1 || isRepInjectiveIfaceDecl d2)
= d1 { ifRoles = mergeRoles roles1 roles2 }
| otherwise = d1
where
mergeRoles roles1 roles2 = zipWithEqual "mergeRoles" max roles1 roles2
isRepInjectiveIfaceDecl :: IfaceDecl -> Bool
isRepInjectiveIfaceDecl IfaceData{ ifCons = IfDataTyCon{} } = True
isRepInjectiveIfaceDecl IfaceFamily{ ifFamFlav = IfaceDataFamilyTyCon } = True
isRepInjectiveIfaceDecl _ = False
mergeIfaceClassOp :: IfaceClassOp -> IfaceClassOp -> IfaceClassOp
mergeIfaceClassOp op1@(IfaceClassOp _ _ (Just _)) _ = op1
mergeIfaceClassOp _ op2 = op2
| Merge two ' OccEnv 's of ' IfaceDecl 's by ' OccName ' .
mergeIfaceDecls :: OccEnv IfaceDecl -> OccEnv IfaceDecl -> OccEnv IfaceDecl
mergeIfaceDecls = plusOccEnv_C mergeIfaceDecl
to type check an interface file into a ModDetails . However , the use - case
for these ModDetails is different : we want to compare all of the
ModDetails to ensure they define compatible declarations , and then
strategy for knot - tying : we first speculatively merge the declarations
the " best " choice we could have made ( ezyang conjectures this
This will be rejected , because the reexported Int in the second
typecheckIfacesForMerging :: Module -> [ModIface] -> (KnotVars (IORef TypeEnv)) -> IfM lcl (TypeEnv, [ModDetails])
typecheckIfacesForMerging mod ifaces tc_env_vars =
initIfaceLcl mod (text "typecheckIfacesForMerging") NotBoot $ do
ignore_prags <- goptM Opt_IgnoreInterfacePragmas
NB : Do n't include dfuns here , because we do n't want to
serialize them out . See Note [ rnIfaceNeverExported ] in GHC.Iface . Rename
NB : But coercions are OK , because they will have the right OccName .
let mk_decl_env decls
= mkOccEnv [ (getOccName decl, decl)
| decl <- decls
, case decl of
exclude DFuns
_ -> True ]
decl_envs = map (mk_decl_env . map snd . mi_decls) ifaces
:: [OccEnv IfaceDecl]
decl_env = foldl' mergeIfaceDecls emptyOccEnv decl_envs
:: OccEnv IfaceDecl
names_w_things <- tcIfaceDecls ignore_prags (map (\x -> (fingerprint0, x))
(nonDetOccEnvElts decl_env))
let global_type_env = mkNameEnv names_w_things
case lookupKnotVars tc_env_vars mod of
Just tc_env_var -> writeMutVar tc_env_var global_type_env
Nothing -> return ()
OK , now each ModIface using this environment
details <- forM ifaces $ \iface -> do
type_env <- fixM $ \type_env ->
setImplicitEnvM type_env $ do
decls <- tcIfaceDecls ignore_prags (mi_decls iface)
return (mkNameEnv decls)
setImplicitEnvM type_env $ do
insts <- mapM tcIfaceInst (mi_insts iface)
fam_insts <- mapM tcIfaceFamInst (mi_fam_insts iface)
rules <- tcIfaceRules ignore_prags (mi_rules iface)
anns <- tcIfaceAnnotations (mi_anns iface)
exports <- ifaceExportNames (mi_exports iface)
complete_matches <- tcIfaceCompleteMatches (mi_complete_matches iface)
return $ ModDetails { md_types = type_env
, md_insts = mkInstEnv insts
, md_fam_insts = fam_insts
, md_rules = rules
, md_anns = anns
, md_exports = exports
, md_complete_matches = complete_matches
}
return (global_type_env, details)
| a signature ' ModIface ' under the assumption that we have
because ( 1 ) we have a ' NameShape ' , from the exports of the
provided them with a reexport , and ( 2 ) we have to deal with
typecheckIfaceForInstantiate :: NameShape -> ModIface -> IfM lcl ModDetails
typecheckIfaceForInstantiate nsubst iface =
initIfaceLclWithSubst (mi_semantic_module iface)
(text "typecheckIfaceForInstantiate")
(mi_boot iface) nsubst $ do
ignore_prags <- goptM Opt_IgnoreInterfacePragmas
type_env <- fixM $ \type_env ->
setImplicitEnvM type_env $ do
decls <- tcIfaceDecls ignore_prags (mi_decls iface)
return (mkNameEnv decls)
setImplicitEnvM type_env $ do
insts <- mapM tcIfaceInst (mi_insts iface)
fam_insts <- mapM tcIfaceFamInst (mi_fam_insts iface)
rules <- tcIfaceRules ignore_prags (mi_rules iface)
anns <- tcIfaceAnnotations (mi_anns iface)
exports <- ifaceExportNames (mi_exports iface)
complete_matches <- tcIfaceCompleteMatches (mi_complete_matches iface)
return $ ModDetails { md_types = type_env
, md_insts = mkInstEnv insts
, md_fam_insts = fam_insts
, md_rules = rules
, md_anns = anns
, md_exports = exports
, md_complete_matches = complete_matches
}
Note [ Handling never - exported under Backpack ]
case with the DFun of a ClsInst , or a of a type family ,
this strategy causes problems : if we pick one and rewrite all
if the DFun or CoAxioms are compatible , as they will never be
and a non - exported TyThing is checked WHEN we are checking the
which we should wire up with .
type family can refer to a coercion axiom , all of which are done in one go
when we typecheck ' mi_decls ' . An alternate strategy would be to
coercions first before type families , but that seemed more fragile .
tcHiBootIface :: HscSource -> Module -> TcRn SelfBootInfo
Return the ModDetails ; Nothing if no hi - boot iface
tcHiBootIface hsc_src mod
= return NoSelfBoot
| otherwise
= do { traceIf (text "loadHiBootInterface" <+> ppr mod)
; mode <- getGhcMode
; if not (isOneShot mode)
we 'll have compiled it already , and it 'll be in the HPT
It can happen ( when using GHC from Visual Studio ) that we
fully - populated HPT . In that case the boot interface is n't there
And that 's fine , because if M 's ModInfo is in the HPT , then
then do { (_, hug) <- getEpsAndHug
; case lookupHugByModule mod hug of
Just info | mi_boot (hm_iface info) == IsBoot
-> mkSelfBootInfo (hm_iface info) (hm_details info)
_ -> return NoSelfBoot }
else do
OK , so we 're in one - shot mode .
{ hsc_env <- getTopEnv
; read_result <- liftIO $ findAndReadIface hsc_env
need (fst (getModuleInstantiation mod)) mod
; case read_result of {
Succeeded (iface, _path) -> do { tc_iface <- initIfaceTcRn $ typecheckIface iface
; mkSelfBootInfo iface tc_iface } ;
Failed err ->
do { eps <- getEps
; case lookupInstalledModuleEnv (eps_is_boot eps) (toUnitId <$> mod) of
Nothing -> return NoSelfBoot
Just (GWIB { gwib_isBoot = is_boot }) -> case is_boot of
IsBoot -> failWithTc (mkTcRnUnknownMessage $ mkPlainError noHints (elaborate err))
NotBoot -> failWithTc (mkTcRnUnknownMessage $ mkPlainError noHints moduleLoop)
}}}}
where
need = text "Need the hi-boot interface for" <+> ppr mod
<+> text "to compare against the Real Thing"
moduleLoop = text "Circular imports: module" <+> quotes (ppr mod)
<+> text "depends on itself"
elaborate err = hang (text "Could not find hi-boot interface for" <+>
quotes (ppr mod) <> colon) 4 err
mkSelfBootInfo :: ModIface -> ModDetails -> TcRn SelfBootInfo
mkSelfBootInfo iface mds
NB : This is computed DIRECTLY from the ModIface rather
than from the ModDetails , so that we can query ' sb_tcs '
let tcs = map ifName
. filter isIfaceTyCon
. map snd
$ mi_decls iface
return $ SelfBoot { sb_mds = mds
, sb_tcs = mkNameSet tcs }
where
Returns if , when you call ' tcIfaceDecl ' on
this ' IfaceDecl ' , an ATyCon would be returned .
NB : This code assumes that a can not be implicit .
isIfaceTyCon IfaceId{} = False
isIfaceTyCon IfaceData{} = True
isIfaceTyCon IfaceSynonym{} = True
isIfaceTyCon IfaceFamily{} = True
isIfaceTyCon IfaceClass{} = True
isIfaceTyCon IfaceAxiom{} = False
isIfaceTyCon IfacePatSyn{} = False
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* *
Type and class declarations
* *
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
When typechecking a data type decl , we * lazily * ( via forkM ) typecheck
the constructor argument types . This is in the hope that we may never
poke on those argument types , and hence may never need to load the
interface files for types mentioned in the arg types .
E.g.
data . S = MkS Baz . T
Maybe we can get away without even loading the interface for !
This is not just a performance thing . Suppose we have
data . S = MkS Baz . T
data . T = MkT . S
( in different interface files , of course ) .
Now , first we load and . S , and add it to the type envt .
If we do explore MkS 's argument , we 'll load and . T.
If we explore MkT 's argument we 'll find . S already in the envt .
If we typechecked constructor args eagerly , when loading . S we 'd try to
typecheck the type . T. So we 'd fault in . T ... and then need . S ...
which is n't done yet .
All very cunning . However , there is a rather subtle gotcha which bit
me when developing this stuff . When we typecheck the decl for S , we
extend the type envt with S , MkS , and all its implicit Ids . Suppose
( a bug , but it happened ) that the list of implicit Ids depended in
turn on the constructor arg types . Then the following sequence of
events takes place :
* we build a thunk < t > for the constructor arg tys
* we build a thunk for the extended type environment ( depends on < t > )
* we write the extended type envt into the global EPS mutvar
Now we look something up in the type envt
* that pulls on < t >
* which reads the global type envt out of the global EPS mutvar
* but that depends in turn on < t >
It 's subtle , because , it 'd work fine if we typechecked the constructor args
type envt by accident , because they look at it later .
What this means is that the implicitTyThings MUST NOT DEPEND on any of
the forkM stuff .
************************************************************************
* *
Type and class declarations
* *
************************************************************************
When typechecking a data type decl, we *lazily* (via forkM) typecheck
the constructor argument types. This is in the hope that we may never
poke on those argument types, and hence may never need to load the
interface files for types mentioned in the arg types.
E.g.
data Foo.S = MkS Baz.T
Maybe we can get away without even loading the interface for Baz!
This is not just a performance thing. Suppose we have
data Foo.S = MkS Baz.T
data Baz.T = MkT Foo.S
(in different interface files, of course).
Now, first we load and typecheck Foo.S, and add it to the type envt.
If we do explore MkS's argument, we'll load and typecheck Baz.T.
If we explore MkT's argument we'll find Foo.S already in the envt.
If we typechecked constructor args eagerly, when loading Foo.S we'd try to
typecheck the type Baz.T. So we'd fault in Baz.T... and then need Foo.S...
which isn't done yet.
All very cunning. However, there is a rather subtle gotcha which bit
me when developing this stuff. When we typecheck the decl for S, we
extend the type envt with S, MkS, and all its implicit Ids. Suppose
(a bug, but it happened) that the list of implicit Ids depended in
turn on the constructor arg types. Then the following sequence of
events takes place:
* we build a thunk <t> for the constructor arg tys
* we build a thunk for the extended type environment (depends on <t>)
* we write the extended type envt into the global EPS mutvar
Now we look something up in the type envt
* that pulls on <t>
* which reads the global type envt out of the global EPS mutvar
* but that depends in turn on <t>
It's subtle, because, it'd work fine if we typechecked the constructor args
type envt by accident, because they look at it later.
What this means is that the implicitTyThings MUST NOT DEPEND on any of
the forkM stuff.
-}
^ True < = > discard IdInfo on IfaceId bindings
-> IfaceDecl
-> IfL TyThing
tcIfaceDecl = tc_iface_decl Nothing
^ True < = > discard IdInfo on IfaceId bindings
-> IfaceDecl
-> IfL TyThing
tc_iface_decl _ ignore_prags (IfaceId {ifName = name, ifType = iface_type,
ifIdDetails = details, ifIdInfo = info})
= do { ty <- tcIfaceType iface_type
; details <- tcIdDetails ty details
; info <- tcIdInfo ignore_prags TopLevel name ty info
; return (AnId (mkGlobalId details name ty info)) }
tc_iface_decl _ _ (IfaceData {ifName = tc_name,
ifCType = cType,
ifBinders = binders,
ifResKind = res_kind,
ifRoles = roles,
ifCtxt = ctxt, ifGadtSyntax = gadt_syn,
ifCons = rdr_cons,
ifParent = mb_parent })
= bindIfaceTyConBinders_AT binders $ \ binders' -> do
{ res_kind' <- tcIfaceType res_kind
; tycon <- fixM $ \ tycon -> do
{ stupid_theta <- tcIfaceCtxt ctxt
; parent' <- tc_parent tc_name mb_parent
; cons <- tcIfaceDataCons tc_name tycon binders' rdr_cons
; return (mkAlgTyCon tc_name binders' res_kind'
roles cType stupid_theta
cons parent' gadt_syn) }
; traceIf (text "tcIfaceDecl4" <+> ppr tycon)
; return (ATyCon tycon) }
where
tc_parent :: Name -> IfaceTyConParent -> IfL AlgTyConFlav
tc_parent tc_name IfNoParent
= do { tc_rep_name <- newTyConRepName tc_name
; return (VanillaAlgTyCon tc_rep_name) }
tc_parent _ (IfDataInstance ax_name _ arg_tys)
= do { ax <- tcIfaceCoAxiom ax_name
; let fam_tc = coAxiomTyCon ax
ax_unbr = toUnbranchedAxiom ax
; lhs_tys <- tcIfaceAppArgs arg_tys
; return (DataFamInstTyCon ax_unbr fam_tc lhs_tys) }
tc_iface_decl _ _ (IfaceSynonym {ifName = tc_name,
ifRoles = roles,
ifSynRhs = rhs_ty,
ifBinders = binders,
ifResKind = res_kind })
= bindIfaceTyConBinders_AT binders $ \ binders' -> do
; rhs <- forkM (mk_doc tc_name) $
tcIfaceType rhs_ty
; let tycon = buildSynTyCon tc_name binders' res_kind' roles rhs
; return (ATyCon tycon) }
where
mk_doc n = text "Type synonym" <+> ppr n
tc_iface_decl parent _ (IfaceFamily {ifName = tc_name,
ifFamFlav = fam_flav,
ifBinders = binders,
ifResKind = res_kind,
ifResVar = res, ifFamInj = inj })
= bindIfaceTyConBinders_AT binders $ \ binders' -> do
; rhs <- forkM (mk_doc tc_name) $
tc_fam_flav tc_name fam_flav
; res_name <- traverse (newIfaceName . mkTyVarOccFS) res
; let tycon = mkFamilyTyCon tc_name binders' res_kind' res_name rhs parent inj
; return (ATyCon tycon) }
where
mk_doc n = text "Type synonym" <+> ppr n
tc_fam_flav :: Name -> IfaceFamTyConFlav -> IfL FamTyConFlav
tc_fam_flav tc_name IfaceDataFamilyTyCon
= do { tc_rep_name <- newTyConRepName tc_name
; return (DataFamilyTyCon tc_rep_name) }
tc_fam_flav _ IfaceOpenSynFamilyTyCon= return OpenSynFamilyTyCon
tc_fam_flav _ (IfaceClosedSynFamilyTyCon mb_ax_name_branches)
= do { ax <- traverse (tcIfaceCoAxiom . fst) mb_ax_name_branches
; return (ClosedSynFamilyTyCon ax) }
tc_fam_flav _ IfaceAbstractClosedSynFamilyTyCon
= return AbstractClosedSynFamilyTyCon
tc_fam_flav _ IfaceBuiltInSynFamTyCon
= pprPanic "tc_iface_decl"
(text "IfaceBuiltInSynFamTyCon in interface file")
tc_iface_decl _parent _ignore_prags
(IfaceClass {ifName = tc_name,
ifRoles = roles,
ifBinders = binders,
ifFDs = rdr_fds,
ifBody = IfAbstractClass})
= bindIfaceTyConBinders binders $ \ binders' -> do
{ fds <- mapM tc_fd rdr_fds
; cls <- buildClass tc_name binders' roles fds Nothing
; return (ATyCon (classTyCon cls)) }
tc_iface_decl _parent ignore_prags
(IfaceClass {ifName = tc_name,
ifRoles = roles,
ifBinders = binders,
ifFDs = rdr_fds,
ifBody = IfConcreteClass {
ifClassCtxt = rdr_ctxt,
ifATs = rdr_ats, ifSigs = rdr_sigs,
ifMinDef = mindef_occ
}})
= bindIfaceTyConBinders binders $ \ binders' -> do
{ traceIf (text "tc-iface-class1" <+> ppr tc_name)
; ctxt <- mapM tc_sc rdr_ctxt
; traceIf (text "tc-iface-class2" <+> ppr tc_name)
; sigs <- mapM tc_sig rdr_sigs
; fds <- mapM tc_fd rdr_fds
; traceIf (text "tc-iface-class3" <+> ppr tc_name)
; mindef <- traverse (lookupIfaceTop . mkVarOccFS) mindef_occ
; cls <- fixM $ \ cls -> do
{ ats <- mapM (tc_at cls) rdr_ats
; traceIf (text "tc-iface-class4" <+> ppr tc_name)
; buildClass tc_name binders' roles fds (Just (ctxt, ats, sigs, mindef)) }
; return (ATyCon (classTyCon cls)) }
where
tc_sc pred = forkM (mk_sc_doc pred) (tcIfaceType pred)
The * length * of the superclasses is used by buildClass , and hence must
so we must not pull on T too eagerly . See # 5970
tc_sig :: IfaceClassOp -> IfL TcMethInfo
tc_sig (IfaceClassOp op_name rdr_ty dm)
= do { let doc = mk_op_doc op_name rdr_ty
; op_ty <- forkM (doc <+> text "ty") $ tcIfaceType rdr_ty
; dm' <- tc_dm doc dm
; return (op_name, op_ty, dm') }
tc_dm :: SDoc
-> Maybe (DefMethSpec IfaceType)
-> IfL (Maybe (DefMethSpec (SrcSpan, Type)))
tc_dm _ Nothing = return Nothing
tc_dm _ (Just VanillaDM) = return (Just VanillaDM)
tc_dm doc (Just (GenericDM ty))
; ty' <- forkM (doc <+> text "dm") $ tcIfaceType ty
; return (Just (GenericDM (noSrcSpan, ty'))) }
tc_at cls (IfaceAT tc_decl if_def)
= do ATyCon tc <- tc_iface_decl (Just cls) ignore_prags tc_decl
mb_def <- case if_def of
Nothing -> return Nothing
Just def -> forkM (mk_at_doc tc) $
extendIfaceTyVarEnv (tyConTyVars tc) $
do { tc_def <- tcIfaceType def
; return (Just (tc_def, NoATVI)) }
e.g. type AT a ; type AT b = AT [ b ] # 8002
return (ATI tc mb_def)
mk_sc_doc pred = text "Superclass" <+> ppr pred
mk_at_doc tc = text "Associated type" <+> ppr tc
mk_op_doc op_name op_ty = text "Class op" <+> sep [ppr op_name, ppr op_ty]
tc_iface_decl _ _ (IfaceAxiom { ifName = tc_name, ifTyCon = tc
, ifAxBranches = branches, ifRole = role })
= do { tc_tycon <- tcIfaceTyCon tc
for family instance consistency , and the RHS may mention
See # 13803
; tc_branches <- forkM (text "Axiom branches" <+> ppr tc_name)
$ tc_ax_branches branches
; let axiom = CoAxiom { co_ax_unique = nameUnique tc_name
, co_ax_name = tc_name
, co_ax_tc = tc_tycon
, co_ax_role = role
, co_ax_branches = manyBranches tc_branches
, co_ax_implicit = False }
; return (ACoAxiom axiom) }
tc_iface_decl _ _ (IfacePatSyn{ ifName = name
, ifPatMatcher = if_matcher
, ifPatBuilder = if_builder
, ifPatIsInfix = is_infix
, ifPatUnivBndrs = univ_bndrs
, ifPatExBndrs = ex_bndrs
, ifPatProvCtxt = prov_ctxt
, ifPatReqCtxt = req_ctxt
, ifPatArgs = args
, ifPatTy = pat_ty
, ifFieldLabels = field_labels })
= do { traceIf (text "tc_iface_decl" <+> ppr name)
; matcher <- tc_pr if_matcher
; builder <- traverse tc_pr if_builder
; bindIfaceForAllBndrs univ_bndrs $ \univ_tvs -> do
{ bindIfaceForAllBndrs ex_bndrs $ \ex_tvs -> do
{ patsyn <- forkM (mk_doc name) $
do { prov_theta <- tcIfaceCtxt prov_ctxt
; req_theta <- tcIfaceCtxt req_ctxt
; pat_ty <- tcIfaceType pat_ty
; arg_tys <- mapM tcIfaceType args
; return $ buildPatSyn name is_infix matcher builder
(univ_tvs, req_theta)
(ex_tvs, prov_theta)
arg_tys pat_ty field_labels }
; return $ AConLike . PatSynCon $ patsyn }}}
where
mk_doc n = text "Pattern synonym" <+> ppr n
tc_pr :: (IfExtName, Bool) -> IfL (Name, Type, Bool)
tc_pr (nm, b) = do { id <- forkM (ppr nm) (tcIfaceExtId nm)
; return (nm, idType id, b) }
tcTopIfaceBindings :: IORef TypeEnv -> [IfaceBindingX IfaceMaybeRhs IfaceTopBndrInfo]
-> IfL [CoreBind]
tcTopIfaceBindings ty_var ver_decls
= do
int <- mapM tcTopBinders ver_decls
let all_ids :: [Id] = concatMap toList int
liftIO $ modifyIORef ty_var (flip extendTypeEnvList (map AnId all_ids))
extendIfaceIdEnv all_ids $ mapM (tc_iface_bindings) int
tcTopBinders :: IfaceBindingX a IfaceTopBndrInfo -> IfL (IfaceBindingX a Id)
tcTopBinders = traverse mk_top_id
tc_iface_bindings :: IfaceBindingX IfaceMaybeRhs Id -> IfL CoreBind
tc_iface_bindings (IfaceNonRec b rhs) = do
rhs' <- tc_iface_binding b rhs
return $ NonRec b rhs'
tc_iface_bindings (IfaceRec bs) = do
rs <- mapM (\(b, rhs) -> (b,) <$> tc_iface_binding b rhs) bs
return (Rec rs)
tc_iface_binding :: Id -> IfaceMaybeRhs -> IfL CoreExpr
tc_iface_binding i IfUseUnfoldingRhs =
case maybeUnfoldingTemplate $ realIdUnfolding i of
Just e -> return e
Nothing -> pprPanic "tc_iface_binding" (vcat [text "Binding" <+> quotes (ppr i) <+> text "had an unfolding when the interface file was created"
, text "which has now gone missing, something has badly gone wrong."
, text "Unfolding:" <+> ppr (realIdUnfolding i)])
tc_iface_binding _ (IfRhs rhs) = tcIfaceExpr rhs
mk_top_id :: IfaceTopBndrInfo -> IfL Id
mk_top_id (IfGblTopBndr gbl_name)
| Just rOOT_MAIN == nameModule_maybe gbl_name
= do
ATyCon ioTyCon <- tcIfaceGlobal ioTyConName
return $ mkExportedVanillaId gbl_name (mkTyConApp ioTyCon [unitTy])
| otherwise = tcIfaceExtId gbl_name
mk_top_id (IfLclTopBndr raw_name iface_type info details) = do
name <- newIfaceName (mkVarOccFS raw_name)
ty <- tcIfaceType iface_type
info' <- tcIdInfo False TopLevel name ty info
details' <- tcIdDetails ty details
let new_id = mkGlobalId details' name ty info'
return new_id
tcIfaceDecls :: Bool
-> [(Fingerprint, IfaceDecl)]
-> IfL [(Name,TyThing)]
tcIfaceDecls ignore_prags ver_decls
= concatMapM (tc_iface_decl_fingerprint ignore_prags) ver_decls
-> (Fingerprint, IfaceDecl)
are forkM'd thunks
tc_iface_decl_fingerprint ignore_prags (_version, decl)
let main_name = ifName decl
the thing , lazily
NB . Firstly , the laziness is there in case we never need the
declaration ( in one - shot mode ) , and secondly it is there so that
we do n't look up the occurrence of a name before calling
; thing <- forkM doc $ do { bumpDeclStats main_name
; tcIfaceDecl ignore_prags decl }
' forkM'd by .
data T a = MkT { x : : T a }
[ " MkT " - > < datacon MkT > , " x " - > < selector x > , ... ]
( where the " MkT " is the * Name * associated with MkT , etc . )
. By the invariant on ifaceDeclImplicitBndrs and
to make this association : each Name 's OccName should
[ ' MkT ' - > < datacon MkT > , ' x ' - > < selector x > , ... ]
where the ' MkT ' here is the * OccName * associated with MkT.
If we poke these thunks too early , two problems could happen :
( 1 ) When processing mutually recursive modules across
( 2 ) Looking up one OccName in the mini_env will cause
getOccName on a TyThing does not force the suspended type
' Name 's n and the map from ' OccName 's to the implicit
; let mini_env = mkOccEnv [(getOccName t, t) | t <- implicitTyThings thing]
lookup n = case lookupOccEnv mini_env (getOccName n) of
Just thing -> thing
Nothing ->
pprPanic "tc_iface_decl_fingerprint" (ppr main_name <+> ppr n $$ ppr (decl))
; implicit_names <- mapM lookupIfaceTop (ifaceDeclImplicitBndrs decl)
; traceIf ( text " Loading decl for " < > ppr main_name $ $ ppr implicit_names )
; return $ (main_name, thing) :
[(n, lookup n) | n <- implicit_names]
}
where
doc = text "Declaration for" <+> ppr (ifName decl)
Record that one more declaration has actually been used
bumpDeclStats name
= do { traceIf (text "Loading decl for" <+> ppr name)
; updateEps_ (\eps -> let stats = eps_stats eps
in eps { eps_stats = stats { n_decls_out = n_decls_out stats + 1 } })
}
tc_fd :: FunDep IfLclName -> IfL (FunDep TyVar)
tc_fd (tvs1, tvs2) = do { tvs1' <- mapM tcIfaceTyVar tvs1
; tvs2' <- mapM tcIfaceTyVar tvs2
; return (tvs1', tvs2') }
tc_ax_branches :: [IfaceAxBranch] -> IfL [CoAxBranch]
tc_ax_branches if_branches = foldlM tc_ax_branch [] if_branches
tc_ax_branch :: [CoAxBranch] -> IfaceAxBranch -> IfL [CoAxBranch]
tc_ax_branch prev_branches
(IfaceAxBranch { ifaxbTyVars = tv_bndrs
, ifaxbEtaTyVars = eta_tv_bndrs
, ifaxbCoVars = cv_bndrs
, ifaxbLHS = lhs, ifaxbRHS = rhs
, ifaxbRoles = roles, ifaxbIncomps = incomps })
= bindIfaceTyConBinders_AT
(map (\b -> Bndr (IfaceTvBndr b) (NamedTCB Inferred)) tv_bndrs) $ \ tvs ->
The _ AT variant is needed here ; see Note [ CoAxBranch type variables ] in GHC.Core . Coercion . Axiom
bindIfaceIds cv_bndrs $ \ cvs -> do
{ tc_lhs <- tcIfaceAppArgs lhs
; tc_rhs <- tcIfaceType rhs
; eta_tvs <- bindIfaceTyVars eta_tv_bndrs return
; this_mod <- getIfModule
; let loc = mkGeneralSrcSpan (fsLit "module " `appendFS`
moduleNameFS (moduleName this_mod))
br = CoAxBranch { cab_loc = loc
, cab_tvs = binderVars tvs
, cab_eta_tvs = eta_tvs
, cab_cvs = cvs
, cab_lhs = tc_lhs
, cab_roles = roles
, cab_rhs = tc_rhs
, cab_incomps = map (prev_branches `getNth`) incomps }
; return (prev_branches ++ [br]) }
tcIfaceDataCons :: Name -> TyCon -> [TyConBinder] -> IfaceConDecls -> IfL AlgTyConRhs
tcIfaceDataCons tycon_name tycon tc_tybinders if_cons
= case if_cons of
IfAbstractTyCon
-> return AbstractTyCon
IfDataTyCon type_data cons
-> do { data_cons <- mapM tc_con_decl cons
; return $
mkLevPolyDataTyConRhs
(isFixedRuntimeRepKind $ tyConResKind tycon)
type_data
data_cons }
IfNewTyCon con
-> do { data_con <- tc_con_decl con
; mkNewTyConRhs tycon_name tycon data_con }
where
univ_tvs :: [TyVar]
univ_tvs = binderVars tc_tybinders
tag_map :: NameEnv ConTag
tag_map = mkTyConTagMap tycon
tc_con_decl (IfCon { ifConInfix = is_infix,
ifConExTCvs = ex_bndrs,
ifConUserTvBinders = user_bndrs,
ifConName = dc_name,
ifConCtxt = ctxt, ifConEqSpec = spec,
ifConArgTys = args, ifConFields = lbl_names,
ifConStricts = if_stricts,
ifConSrcStricts = if_src_stricts})
Universally - quantified tyvars are shared with
parent , and are already in scope
bindIfaceBndrs ex_bndrs $ \ ex_tvs -> do
{ traceIf (text "Start interface-file tc_con_decl" <+> ppr dc_name)
; user_tv_bndrs <- mapM (\(Bndr bd vis) ->
case bd of
IfaceIdBndr (_, name, _) ->
Bndr <$> tcIfaceLclId name <*> pure vis
IfaceTvBndr (name, _) ->
Bndr <$> tcIfaceTyVar name <*> pure vis)
user_bndrs
Read the context and argument types , but lazily for two reasons
; ~(eq_spec, theta, arg_tys, stricts) <- forkM (mk_doc dc_name) $
do { eq_spec <- tcIfaceEqSpec spec
; theta <- tcIfaceCtxt ctxt
This fixes # 13710 . The enclosing lazy thunk gets
tuple is needed ) , which causes trouble if one of
; arg_tys <- forkM (mk_doc dc_name <+> text "arg_tys")
$ mapM (\(w, ty) -> mkScaled <$> tcIfaceType w <*> tcIfaceType ty) args
; stricts <- mapM tc_strict if_stricts
The IfBang field can mention
; return (eq_spec, theta, arg_tys, stricts) }
Remember , is the representation tycon
; let orig_res_ty = mkFamilyTyConApp tycon
(substTyCoVars (mkTvSubstPrs (map eqSpecPair eq_spec))
(binderVars tc_tybinders))
; prom_rep_name <- newTyConRepName dc_name
; let bang_opts = FixedBangOpts stricts
See Note [ Bangs on imported data constructors ] in GHC.Types . Id. Make
; con <- buildDataCon (pprPanic "tcIfaceDataCons: FamInstEnvs" (ppr dc_name))
bang_opts
dc_name is_infix prom_rep_name
(map src_strict if_src_stricts)
lbl_names
univ_tvs ex_tvs user_tv_bndrs
eq_spec theta
arg_tys orig_res_ty tycon tag_map
; traceIf (text "Done interface-file tc_con_decl" <+> ppr dc_name)
; return con }
mk_doc con_name = text "Constructor" <+> ppr con_name
tc_strict :: IfaceBang -> IfL HsImplBang
tc_strict IfNoBang = return (HsLazy)
tc_strict IfStrict = return (HsStrict True)
tc_strict IfUnpack = return (HsUnpack Nothing)
tc_strict (IfUnpackCo if_co) = do { co <- tcIfaceCo if_co
; return (HsUnpack (Just co)) }
src_strict :: IfaceSrcBang -> HsSrcBang
src_strict (IfSrcBang unpk bang) = HsSrcBang NoSourceText unpk bang
tcIfaceEqSpec :: IfaceEqSpec -> IfL [EqSpec]
tcIfaceEqSpec spec
= mapM do_item spec
where
do_item (occ, if_ty) = do { tv <- tcIfaceTyVar occ
; ty <- tcIfaceType if_ty
; return (mkEqSpec tv ty) }
Note [ Synonym kind loop ]
~~~~~~~~~~~~~~~~~~~~~~~~
Notice that we eagerly grab the * kind * from the interface file , but
build a forkM thunk for the * rhs * ( and family stuff ) . To see why ,
consider this ( # 2412 )
M.hs : module M where { import X ; data T = MkT S }
X.hs : module X where { import { - # SOURCE #
Note [Synonym kind loop]
~~~~~~~~~~~~~~~~~~~~~~~~
Notice that we eagerly grab the *kind* from the interface file, but
build a forkM thunk for the *rhs* (and family stuff). To see why,
consider this (#2412)
M.hs: module M where { import X; data T = MkT S }
M.hs-boot: module M where { data T }
When kind-checking M.hs we need S's kind. But we do not want to
find S's kind from (typeKind S-rhs), because we don't want to look at
S-rhs yet! Since S is imported from X.hi, S gets just one chance to
be defined, and we must not do that until we've finished with M.T.
Solution: record S's kind in the interface file; now we can safely
look at it.
************************************************************************
* *
Instances
* *
************************************************************************
-}
tcRoughTyCon :: Maybe IfaceTyCon -> RoughMatchTc
tcRoughTyCon (Just tc) = RM_KnownTc (ifaceTyConName tc)
tcRoughTyCon Nothing = RM_WildCard
tcIfaceInst :: IfaceClsInst -> IfL ClsInst
tcIfaceInst (IfaceClsInst { ifDFun = dfun_name, ifOFlag = oflag
, ifInstCls = cls, ifInstTys = mb_tcs
, ifInstOrph = orph })
= do { dfun <- forkM (text "Dict fun" <+> ppr dfun_name) $
fmap tyThingId (tcIfaceImplicit dfun_name)
; let mb_tcs' = map tcRoughTyCon mb_tcs
; return (mkImportedClsInst cls mb_tcs' dfun_name dfun oflag orph) }
tcIfaceFamInst :: IfaceFamInst -> IfL FamInst
tcIfaceFamInst (IfaceFamInst { ifFamInstFam = fam, ifFamInstTys = mb_tcs
, ifFamInstAxiom = axiom_name
, ifFamInstOrph = orphan } )
= do { axiom' <- forkM (text "Axiom" <+> ppr axiom_name) $
tcIfaceCoAxiom axiom_name
; let axiom'' = toUnbranchedAxiom axiom'
mb_tcs' = map tcRoughTyCon mb_tcs
; return (mkImportedFamInst fam mb_tcs' axiom'' orphan) }
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* *
Rules
* *
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
We move a IfaceRule from eps_rules to eps_rule_base when all its LHS free vars
are in the type environment . However , remember that typechecking a Rule may
( as a side effect ) augment the type envt , and so we may need to iterate the process .
************************************************************************
* *
Rules
* *
************************************************************************
We move a IfaceRule from eps_rules to eps_rule_base when all its LHS free vars
are in the type environment. However, remember that typechecking a Rule may
(as a side effect) augment the type envt, and so we may need to iterate the process.
-}
-> [IfaceRule]
-> IfL [CoreRule]
tcIfaceRules ignore_prags if_rules
| ignore_prags = return []
| otherwise = mapM tcIfaceRule if_rules
tcIfaceRule :: IfaceRule -> IfL CoreRule
tcIfaceRule (IfaceRule {ifRuleName = name, ifActivation = act, ifRuleBndrs = bndrs,
ifRuleHead = fn, ifRuleArgs = args, ifRuleRhs = rhs,
ifRuleAuto = auto, ifRuleOrph = orph })
= do { ~(bndrs', args', rhs') <-
the payload lazily , in the hope it 'll never be looked at
forkM (text "Rule" <+> pprRuleName name) $
bindIfaceBndrs bndrs $ \ bndrs' ->
do { args' <- mapM tcIfaceExpr args
; rhs' <- tcIfaceExpr rhs
; whenGOptM Opt_DoCoreLinting $ do
{ dflags <- getDynFlags
; (_, lcl_env) <- getEnvs
; let in_scope :: [Var]
in_scope = ((nonDetEltsUFM $ if_tv_env lcl_env) ++
(nonDetEltsUFM $ if_id_env lcl_env) ++
bndrs' ++
exprsFreeIdsList args')
; case lintExpr (initLintConfig dflags in_scope) rhs' of
Nothing -> return ()
Just errs -> do
logger <- getLogger
liftIO $ displayLintResults logger False doc
(pprCoreExpr rhs')
(emptyBag, errs) }
; return (bndrs', args', rhs') }
; let mb_tcs = map ifTopFreeName args
; this_mod <- getIfModule
; return (Rule { ru_name = name, ru_fn = fn, ru_act = act,
ru_bndrs = bndrs', ru_args = args',
ru_rhs = occurAnalyseExpr rhs',
ru_rough = mb_tcs,
ru_origin = this_mod,
ru_orphan = orph,
ru_auto = auto,
where
to write them out in coreRuleToIfaceRule
ifTopFreeName :: IfaceExpr -> Maybe Name
ifTopFreeName (IfaceType (IfaceTyConApp tc _ )) = Just (ifaceTyConName tc)
ifTopFreeName (IfaceType (IfaceTupleTy s _ ts)) = Just (tupleTyConName s (length (appArgsIfaceTypes ts)))
ifTopFreeName (IfaceApp f _) = ifTopFreeName f
ifTopFreeName (IfaceExt n) = Just n
ifTopFreeName _ = Nothing
doc = text "Unfolding of" <+> ppr name
tcIfaceAnnotations :: [IfaceAnnotation] -> IfL [Annotation]
tcIfaceAnnotations = mapM tcIfaceAnnotation
tcIfaceAnnotation :: IfaceAnnotation -> IfL Annotation
tcIfaceAnnotation (IfaceAnnotation target serialized) = do
target' <- tcIfaceAnnTarget target
return $ Annotation {
ann_target = target',
ann_value = serialized
}
tcIfaceAnnTarget :: IfaceAnnTarget -> IfL (AnnTarget Name)
tcIfaceAnnTarget (NamedTarget occ) =
NamedTarget <$> lookupIfaceTop occ
tcIfaceAnnTarget (ModuleTarget mod) =
return $ ModuleTarget mod
tcIfaceCompleteMatches :: [IfaceCompleteMatch] -> IfL [CompleteMatch]
tcIfaceCompleteMatches = mapM tcIfaceCompleteMatch
tcIfaceCompleteMatch :: IfaceCompleteMatch -> IfL CompleteMatch
conlikes <- mkUniqDSet <$> mapM tcIfaceConLike ms
mtc' <- traverse tcIfaceTyCon mtc
return (CompleteMatch conlikes mtc')
where
doc = text "COMPLETE sig" <+> ppr ms
Note [ Positioning of forkM ]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
We need to be lazy when type checking the interface , since these functions are
called when the interface itself is being loaded , which means it is not in the
PIT yet . In particular , the ` tcIfaceTCon ` must be inside the forkM , otherwise
we 'll try to look it up the , find it 's not there , and so initiate the
process ( again ) of loading the ( very same ) interface file . Result : infinite
loop . See # 19744 .
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
We need to be lazy when type checking the interface, since these functions are
called when the interface itself is being loaded, which means it is not in the
PIT yet. In particular, the `tcIfaceTCon` must be inside the forkM, otherwise
we'll try to look it up the TyCon, find it's not there, and so initiate the
process (again) of loading the (very same) interface file. Result: infinite
loop. See #19744.
-}
tcIfaceType :: IfaceType -> IfL Type
tcIfaceType = go
where
go (IfaceTyVar n) = TyVarTy <$> tcIfaceTyVar n
go (IfaceFreeTyVar n) = pprPanic "tcIfaceType:IfaceFreeTyVar" (ppr n)
go (IfaceLitTy l) = LitTy <$> tcIfaceTyLit l
go (IfaceFunTy flag w t1 t2) = FunTy flag <$> tcIfaceType w <*> go t1 <*> go t2
go (IfaceTupleTy s i tks) = tcIfaceTupleTy s i tks
go (IfaceAppTy t ts)
= do { t' <- go t
; ts' <- traverse go (appArgsIfaceTypes ts)
; pure (foldl' AppTy t' ts') }
go (IfaceTyConApp tc tks)
= do { tc' <- tcIfaceTyCon tc
; tks' <- mapM go (appArgsIfaceTypes tks)
; return (mkTyConApp tc' tks') }
go (IfaceForAllTy bndr t)
= bindIfaceForAllBndr bndr $ \ tv' vis ->
ForAllTy (Bndr tv' vis) <$> go t
go (IfaceCastTy ty co) = CastTy <$> go ty <*> tcIfaceCo co
go (IfaceCoercionTy co) = CoercionTy <$> tcIfaceCo co
tcIfaceTupleTy :: TupleSort -> PromotionFlag -> IfaceAppArgs -> IfL Type
tcIfaceTupleTy sort is_promoted args
= do { args' <- tcIfaceAppArgs args
; let arity = length args'
; base_tc <- tcTupleTyCon True sort arity
; case is_promoted of
NotPromoted
-> return (mkTyConApp base_tc args')
IsPromoted
-> do { let tc = promoteDataCon (tyConSingleDataCon base_tc)
kind_args = map typeKind args'
; return (mkTyConApp tc (kind_args ++ args')) } }
See Note [ tuple RuntimeRep vars ] in GHC.Core . TyCon
-> TupleSort
-> IfL TyCon
tcTupleTyCon in_type sort arity
= case sort of
ConstraintTuple -> return (cTupleTyCon arity)
BoxedTuple -> return (tupleTyCon Boxed arity)
UnboxedTuple -> return (tupleTyCon Unboxed arity')
where arity' | in_type = arity `div` 2
| otherwise = arity
tcIfaceAppArgs :: IfaceAppArgs -> IfL [Type]
tcIfaceAppArgs = mapM tcIfaceType . appArgsIfaceTypes
tcIfaceCtxt :: IfaceContext -> IfL ThetaType
tcIfaceCtxt sts = mapM tcIfaceType sts
tcIfaceTyLit :: IfaceTyLit -> IfL TyLit
tcIfaceTyLit (IfaceNumTyLit n) = return (NumTyLit n)
tcIfaceTyLit (IfaceStrTyLit n) = return (StrTyLit n)
tcIfaceTyLit (IfaceCharTyLit n) = return (CharTyLit n)
% * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
% * *
* *
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
%************************************************************************
%* *
Coercions
* *
************************************************************************
-}
tcIfaceCo :: IfaceCoercion -> IfL Coercion
tcIfaceCo = go
where
go_mco IfaceMRefl = pure MRefl
go_mco (IfaceMCo co) = MCo <$> (go co)
go (IfaceReflCo t) = Refl <$> tcIfaceType t
go (IfaceGReflCo r t mco) = GRefl r <$> tcIfaceType t <*> go_mco mco
go (IfaceFunCo r w c1 c2) = mkFunCoNoFTF r <$> go w <*> go c1 <*> go c2
go (IfaceTyConAppCo r tc cs) = TyConAppCo r <$> tcIfaceTyCon tc <*> mapM go cs
go (IfaceAppCo c1 c2) = AppCo <$> go c1 <*> go c2
go (IfaceForAllCo tv k c) = do { k' <- go k
; bindIfaceBndr tv $ \ tv' ->
ForAllCo tv' k' <$> go c }
go (IfaceCoVarCo n) = CoVarCo <$> go_var n
go (IfaceAxiomInstCo n i cs) = AxiomInstCo <$> tcIfaceCoAxiom n <*> pure i <*> mapM go cs
go (IfaceUnivCo p r t1 t2) = UnivCo <$> tcIfaceUnivCoProv p <*> pure r
<*> tcIfaceType t1 <*> tcIfaceType t2
go (IfaceSymCo c) = SymCo <$> go c
go (IfaceTransCo c1 c2) = TransCo <$> go c1
<*> go c2
go (IfaceInstCo c1 t2) = InstCo <$> go c1
<*> go t2
go (IfaceSelCo d c) = do { c' <- go c
; return $ mkSelCo d c' }
go (IfaceLRCo lr c) = LRCo lr <$> go c
go (IfaceKindCo c) = KindCo <$> go c
go (IfaceSubCo c) = SubCo <$> go c
go (IfaceAxiomRuleCo ax cos) = AxiomRuleCo <$> tcIfaceCoAxiomRule ax
<*> mapM go cos
go (IfaceFreeCoVar c) = pprPanic "tcIfaceCo:IfaceFreeCoVar" (ppr c)
go (IfaceHoleCo c) = pprPanic "tcIfaceCo:IfaceHoleCo" (ppr c)
go_var :: FastString -> IfL CoVar
go_var = tcIfaceLclId
tcIfaceUnivCoProv :: IfaceUnivCoProv -> IfL UnivCoProvenance
tcIfaceUnivCoProv (IfacePhantomProv kco) = PhantomProv <$> tcIfaceCo kco
tcIfaceUnivCoProv (IfaceProofIrrelProv kco) = ProofIrrelProv <$> tcIfaceCo kco
tcIfaceUnivCoProv (IfacePluginProv str) = return $ PluginProv str
tcIfaceUnivCoProv (IfaceCorePrepProv b) = return $ CorePrepProv b
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* *
* *
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
************************************************************************
* *
Core
* *
************************************************************************
-}
tcIfaceExpr :: IfaceExpr -> IfL CoreExpr
tcIfaceExpr (IfaceType ty)
= Type <$> tcIfaceType ty
tcIfaceExpr (IfaceCo co)
= Coercion <$> tcIfaceCo co
tcIfaceExpr (IfaceCast expr co)
= Cast <$> tcIfaceExpr expr <*> tcIfaceCo co
tcIfaceExpr (IfaceLcl name)
= Var <$> tcIfaceLclId name
tcIfaceExpr (IfaceExt gbl)
= Var <$> tcIfaceExtId gbl
tcIfaceExpr (IfaceLitRubbish tc rep)
= do rep' <- tcIfaceType rep
return (Lit (LitRubbish tc rep'))
tcIfaceExpr (IfaceLit lit)
= do lit' <- tcIfaceLit lit
return (Lit lit')
tcIfaceExpr (IfaceFCall cc ty) = do
ty' <- tcIfaceType ty
u <- newUnique
return (Var (mkFCallId u cc ty'))
tcIfaceExpr (IfaceTuple sort args)
= do { args' <- mapM tcIfaceExpr args
; tc <- tcTupleTyCon False sort arity
; let con_tys = map exprType args'
some_con_args = map Type con_tys ++ args'
con_args = case sort of
UnboxedTuple -> map (Type . getRuntimeRep) con_tys ++ some_con_args
_ -> some_con_args
con_id = dataConWorkId (tyConSingleDataCon tc)
; return (mkApps (Var con_id) con_args) }
where
arity = length args
tcIfaceExpr (IfaceLam (bndr, os) body)
= bindIfaceBndr bndr $ \bndr' ->
Lam (tcIfaceOneShot os bndr') <$> tcIfaceExpr body
where
tcIfaceOneShot IfaceOneShot b = setOneShotLambda b
tcIfaceOneShot _ b = b
tcIfaceExpr (IfaceApp fun arg)
= App <$> tcIfaceExpr fun <*> tcIfaceExpr arg
tcIfaceExpr (IfaceECase scrut ty)
= do { scrut' <- tcIfaceExpr scrut
; ty' <- tcIfaceType ty
; return (castBottomExpr scrut' ty') }
tcIfaceExpr (IfaceCase scrut case_bndr alts) = do
scrut' <- tcIfaceExpr scrut
case_bndr_name <- newIfaceName (mkVarOccFS case_bndr)
let
scrut_ty = exprType scrut'
case_mult = ManyTy
case_bndr' = mkLocalIdOrCoVar case_bndr_name case_mult scrut_ty
" OrCoVar " since a coercion can be a scrutinee with -fdefer - type - errors
( e.g. see test T15695 ) . Ticket # 17291 covers fixing this problem .
tc_app = splitTyConApp scrut_ty
NB : Wo n't always succeed ( polymorphic case )
NB : not tcSplitTyConApp ; we are looking at Core here
corresponds to the datacon in this case alternative
extendIfaceIdEnv [case_bndr'] $ do
alts' <- mapM (tcIfaceAlt scrut' case_mult tc_app) alts
return (Case scrut' case_bndr' (coreAltsType alts') alts')
tcIfaceExpr (IfaceLet (IfaceNonRec (IfLetBndr fs ty info ji) rhs) body)
= do { name <- newIfaceName (mkVarOccFS fs)
; ty' <- tcIfaceType ty
Do n't ignore prags ; we are inside one !
NotTopLevel name ty' info
; let id = mkLocalIdWithInfo name ManyTy ty' id_info
`asJoinId_maybe` tcJoinInfo ji
; rhs' <- tcIfaceExpr rhs
; body' <- extendIfaceIdEnv [id] (tcIfaceExpr body)
; return (Let (NonRec id rhs') body') }
tcIfaceExpr (IfaceLet (IfaceRec pairs) body)
= do { ids <- mapM tc_rec_bndr (map fst pairs)
; extendIfaceIdEnv ids $ do
{ pairs' <- zipWithM tc_pair pairs ids
; body' <- tcIfaceExpr body
; return (Let (Rec pairs') body') } }
where
tc_rec_bndr (IfLetBndr fs ty _ ji)
= do { name <- newIfaceName (mkVarOccFS fs)
; ty' <- tcIfaceType ty
; return (mkLocalId name ManyTy ty' `asJoinId_maybe` tcJoinInfo ji) }
tc_pair (IfLetBndr _ _ info _, rhs) id
= do { rhs' <- tcIfaceExpr rhs
Do n't ignore prags ; we are inside one !
NotTopLevel (idName id) (idType id) info
; return (setIdInfo id id_info, rhs') }
tcIfaceExpr (IfaceTick tickish expr) = do
expr' <- tcIfaceExpr expr
need_notes <- needSourceNotes <$> getDynFlags
case tickish of
IfaceSource{} | not (need_notes)
-> return expr'
_otherwise -> do
tickish' <- tcIfaceTickish tickish
return (Tick tickish' expr')
tcIfaceTickish :: IfaceTickish -> IfM lcl CoreTickish
tcIfaceTickish (IfaceHpcTick modl ix) = return (HpcTick modl ix)
tcIfaceTickish (IfaceSCC cc tick push) = return (ProfNote cc tick push)
tcIfaceTickish (IfaceSource src name) = return (SourceNote src name)
tcIfaceLit :: Literal -> IfL Literal
tcIfaceLit lit = return lit
tcIfaceAlt :: CoreExpr -> Mult -> (TyCon, [Type])
-> IfaceAlt
-> IfL CoreAlt
tcIfaceAlt _ _ _ (IfaceAlt IfaceDefault names rhs)
= assert (null names) $ do
rhs' <- tcIfaceExpr rhs
return (Alt DEFAULT [] rhs')
tcIfaceAlt _ _ _ (IfaceAlt (IfaceLitAlt lit) names rhs)
= assert (null names) $ do
lit' <- tcIfaceLit lit
rhs' <- tcIfaceExpr rhs
return (Alt (LitAlt lit') [] rhs')
tcIfaceAlt scrut mult (tycon, inst_tys) (IfaceAlt (IfaceDataAlt data_occ) arg_strs rhs)
= do { con <- tcIfaceDataCon data_occ
; when (debugIsOn && not (con `elem` tyConDataCons tycon))
(failIfM (ppr scrut $$ ppr con $$ ppr tycon $$ ppr (tyConDataCons tycon)))
; tcIfaceDataAlt mult con inst_tys arg_strs rhs }
tcIfaceDataAlt :: Mult -> DataCon -> [Type] -> [FastString] -> IfaceExpr
-> IfL CoreAlt
tcIfaceDataAlt mult con inst_tys arg_strs rhs
= do { uniqs <- getUniquesM
; let (ex_tvs, arg_ids)
= dataConRepFSInstPat arg_strs uniqs mult con inst_tys
; rhs' <- extendIfaceEnvs ex_tvs $
extendIfaceIdEnv arg_ids $
tcIfaceExpr rhs
; return (Alt (DataAlt con) (ex_tvs ++ arg_ids) rhs') }
tcIdDetails :: Type -> IfaceIdDetails -> IfL IdDetails
tcIdDetails _ IfVanillaId = return VanillaId
tcIdDetails _ (IfWorkerLikeId dmds) = return $ WorkerLikeId dmds
tcIdDetails ty IfDFunId
= return (DFunId (isNewTyCon (classTyCon cls)))
where
(_, _, cls, _) = tcSplitDFunTy ty
tcIdDetails _ (IfRecSelId tc naughty)
= do { tc' <- either (fmap RecSelData . tcIfaceTyCon)
(fmap (RecSelPatSyn . tyThingPatSyn) . tcIfaceDecl False)
tc
; return (RecSelId { sel_tycon = tc', sel_naughty = naughty }) }
where
tyThingPatSyn (AConLike (PatSynCon ps)) = ps
tyThingPatSyn _ = panic "tcIdDetails: expecting patsyn"
tcIdInfo :: Bool -> TopLevelFlag -> Name -> Type -> IfaceIdInfo -> IfL IdInfo
tcIdInfo ignore_prags toplvl name ty info = do
lcl_env <- getLclEnv
we start ; default assumption is that it has CAFs
let init_info = if if_boot lcl_env == IsBoot
then vanillaIdInfo `setUnfoldingInfo` BootUnfolding
else vanillaIdInfo
foldlM tcPrag init_info (needed_prags info)
where
needed_prags :: [IfaceInfoItem] -> [IfaceInfoItem]
needed_prags items
| not ignore_prags = items
| otherwise = filter need_prag items
need_prag :: IfaceInfoItem -> Bool
See Note [ Always expose compulsory unfoldings ] in GHC.Iface . Tidy
need_prag (HsUnfold _ (IfCoreUnfold src _ _ _)) = isCompulsorySource src
need_prag _ = False
tcPrag :: IdInfo -> IfaceInfoItem -> IfL IdInfo
tcPrag info HsNoCafRefs = return (info `setCafInfo` NoCafRefs)
tcPrag info (HsArity arity) = return (info `setArityInfo` arity)
tcPrag info (HsDmdSig str) = return (info `setDmdSigInfo` str)
tcPrag info (HsCprSig cpr) = return (info `setCprSigInfo` cpr)
tcPrag info (HsInline prag) = return (info `setInlinePragInfo` prag)
tcPrag info (HsLFInfo lf_info) = do
lf_info <- tcLFInfo lf_info
return (info `setLFInfo` lf_info)
tcPrag info (HsTagSig sig) = do
return (info `setTagSig` sig)
The next two are lazy , so they do n't transitively suck stuff in
tcPrag info (HsUnfold lb if_unf)
= do { unf <- tcUnfolding toplvl name ty info if_unf
; let info1 | lb = info `setOccInfo` strongLoopBreaker
| otherwise = info
; return (info1 `setUnfoldingInfo` unf) }
tcJoinInfo :: IfaceJoinInfo -> Maybe JoinArity
tcJoinInfo (IfaceJoinPoint ar) = Just ar
tcJoinInfo IfaceNotJoinPoint = Nothing
tcLFInfo :: IfaceLFInfo -> IfL LambdaFormInfo
tcLFInfo lfi = case lfi of
IfLFReEntrant rep_arity ->
- Do n't have ArgDescrs , as ArgDescr is used when generating code for
return (LFReEntrant TopLevel rep_arity True ArgUnknown)
IfLFThunk updatable mb_fun ->
LFThunk closure in interface files are guaranteed to
return (LFThunk TopLevel True updatable NonStandardThunk mb_fun)
IfLFUnlifted ->
return LFUnlifted
IfLFCon con_name ->
LFCon <$!> tcIfaceDataCon con_name
IfLFUnknown fun_flag ->
return (LFUnknown fun_flag)
tcUnfolding :: TopLevelFlag -> Name -> Type -> IdInfo -> IfaceUnfolding -> IfL Unfolding
See Note [ Lazily checking Unfoldings ]
tcUnfolding toplvl name _ info (IfCoreUnfold src cache if_guidance if_expr)
= do { uf_opts <- unfoldingOpts <$> getDynFlags
; expr <- tcUnfoldingRhs (isCompulsorySource src) toplvl name if_expr
; let guidance = case if_guidance of
IfWhen arity unsat_ok boring_ok -> UnfWhen arity unsat_ok boring_ok
IfNoGuidance -> calcUnfoldingGuidance uf_opts is_top_bottoming expr
See Note [ Tying the ' CoreUnfolding ' knot ]
; return $ mkCoreUnfolding src True expr (Just cache) guidance }
where
Strictness should occur before unfolding !
is_top_bottoming = isTopLevel toplvl && isDeadEndSig (dmdSigInfo info)
tcUnfolding _toplvl name dfun_ty _ (IfDFunUnfold bs ops)
= bindIfaceBndrs bs $ \ bs' ->
do { ops1 <- forkM doc $ mapM tcIfaceExpr ops
; return $ mkDFunUnfolding bs' (classDataCon cls) ops1 }
where
doc = text "Class ops for dfun" <+> ppr name
(_, _, cls, _) = tcSplitDFunTy dfun_ty
Note [ Tying the ' CoreUnfolding ' knot ]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
The unfolding of recursive definitions can contain references to the
I d being defined . Consider the following example :
foo : : ( )
foo = foo
The unfolding template of ' foo ' is , of course , ' foo ' ; so the interface
file for this module contains :
foo : : ( ) ; Unfolding = foo
When rehydrating the interface file we are going to make an I d for
' foo ' ( in GHC.IfaceToCore ) , with an ' Unfolding ' . We used to make this
' Unfolding ' by calling ' ' , but that needs to populate ,
among other fields , the ' uf_is_value ' field , by computing
' exprIsValue ' of the template ( in this case , ' foo ' ) .
' exprIsValue e ' looks at the unfoldings of variables in ' e ' to see if
they are evaluated ; so it consults the ` uf_is_value ` field of
variables in ` e ` . Now we can see the problem : to set the ` uf_is_value `
field of ` foo ` 's unfolding , we look at its unfolding ( in this case
just ` foo ` itself ! ) . Loop . This is the root cause of ticket # 22272 .
The simple solution we chose is to serialise the various auxiliary
fields of ` CoreUnfolding ` so that we do n't need to recreate them when
rehydrating . Specifically , the following fields are moved to the
' UnfoldingCache ' , which is persisted in the interface file :
* ' uf_is_conlike '
* ' uf_is_value '
* ' uf_is_work_free '
* ' uf_expandable '
These four bits make the interface files only one byte larger per
unfolding ; on the other hand , this does save calls to ' exprIsValue ' ,
' exprIsExpandable ' etc for every imported Id.
We could choose to do this only for loop breakers . But that 's a bit
more complicated and it seems good all round .
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
The unfolding of recursive definitions can contain references to the
Id being defined. Consider the following example:
foo :: ()
foo = foo
The unfolding template of 'foo' is, of course, 'foo'; so the interface
file for this module contains:
foo :: (); Unfolding = foo
When rehydrating the interface file we are going to make an Id for
'foo' (in GHC.IfaceToCore), with an 'Unfolding'. We used to make this
'Unfolding' by calling 'mkFinalUnfolding', but that needs to populate,
among other fields, the 'uf_is_value' field, by computing
'exprIsValue' of the template (in this case, 'foo').
'exprIsValue e' looks at the unfoldings of variables in 'e' to see if
they are evaluated; so it consults the `uf_is_value` field of
variables in `e`. Now we can see the problem: to set the `uf_is_value`
field of `foo`'s unfolding, we look at its unfolding (in this case
just `foo` itself!). Loop. This is the root cause of ticket #22272.
The simple solution we chose is to serialise the various auxiliary
fields of `CoreUnfolding` so that we don't need to recreate them when
rehydrating. Specifically, the following fields are moved to the
'UnfoldingCache', which is persisted in the interface file:
* 'uf_is_conlike'
* 'uf_is_value'
* 'uf_is_work_free'
* 'uf_expandable'
These four bits make the interface files only one byte larger per
unfolding; on the other hand, this does save calls to 'exprIsValue',
'exprIsExpandable' etc for every imported Id.
We could choose to do this only for loop breakers. But that's a bit
more complicated and it seems good all round.
-}
Note [ Lazily checking Unfoldings ]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
For unfoldings , we try to do the job lazily , so that we never typecheck
an unfolding that is n't going to be looked at .
The main idea is that if M.hi has a declaration
f : : Int - > Int
then we do n't even want to /read/ A.hi unless f 's unfolding is actually used ; say ,
if f is inlined . But we need to be careful . Even if we do n't inline f , we might ask
hasNoBinding of it ( does this in GHC.Core . Lint.checkCanEtaExpand ) ,
and hasNoBinding looks to see if f has a compulsory unfolding .
So the root Unfolding constructor must be visible : we want to be able to read the ' uf_src '
field which says whether it is a compulsory unfolding , without forcing the unfolding RHS
which is stored in ' uf_tmpl ' . This matters for efficiency , but not only : if 's unfolding
mentions f , we must not look at the unfolding RHS for f , as this is precisely what we are
in the middle of checking ( so looking at it would cause a loop ) .
Conclusion : ` tcUnfolding ` must return an ` Unfolding ` whose ` uf_src ` field is readable without
forcing the ` uf_tmpl ` field . In particular , all the functions used at the end of
` tcUnfolding ` ( such as ` mkFinalUnfolding ` , ` mkCoreUnfolding ` ) must be
lazy in ` expr ` .
Ticket # 21139
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
For unfoldings, we try to do the job lazily, so that we never typecheck
an unfolding that isn't going to be looked at.
The main idea is that if M.hi has a declaration
f :: Int -> Int
then we don't even want to /read/ A.hi unless f's unfolding is actually used; say,
if f is inlined. But we need to be careful. Even if we don't inline f, we might ask
hasNoBinding of it (Core Lint does this in GHC.Core.Lint.checkCanEtaExpand),
and hasNoBinding looks to see if f has a compulsory unfolding.
So the root Unfolding constructor must be visible: we want to be able to read the 'uf_src'
field which says whether it is a compulsory unfolding, without forcing the unfolding RHS
which is stored in 'uf_tmpl'. This matters for efficiency, but not only: if g's unfolding
mentions f, we must not look at the unfolding RHS for f, as this is precisely what we are
in the middle of checking (so looking at it would cause a loop).
Conclusion: `tcUnfolding` must return an `Unfolding` whose `uf_src` field is readable without
forcing the `uf_tmpl` field. In particular, all the functions used at the end of
`tcUnfolding` (such as `mkFinalUnfolding`, `mkCoreUnfolding`) must be
lazy in `expr`.
Ticket #21139
-}
See Note [ Checking for representation polymorphism ] in GHC.Core .
-> TopLevelFlag -> Name -> IfaceExpr -> IfL CoreExpr
tcUnfoldingRhs is_compulsory toplvl name expr
= forkM doc $ do
core_expr' <- tcIfaceExpr expr
See Note [ Linting Unfoldings from Interfaces ] in GHC.Core .
when (isTopLevel toplvl) $
whenGOptM Opt_DoCoreLinting $ do
in_scope <- nonDetEltsUniqSet <$> get_in_scope
dflags <- getDynFlags
logger <- getLogger
case lintUnfolding is_compulsory (initLintConfig dflags in_scope) noSrcLoc core_expr' of
Nothing -> return ()
Just errs -> liftIO $
displayLintResults logger False doc
(pprCoreExpr core_expr') (emptyBag, errs)
return core_expr'
where
doc = ppWhen is_compulsory (text "Compulsory") <+>
text "Unfolding of" <+> ppr name
get_in_scope
= do { (gbl_env, lcl_env) <- getEnvs
; let type_envs = knotVarElems (if_rec_types gbl_env)
; top_level_vars <- concat <$> mapM (fmap typeEnvIds . setLclEnv ()) type_envs
; return (bindingsVars (if_tv_env lcl_env) `unionVarSet`
bindingsVars (if_id_env lcl_env) `unionVarSet`
mkVarSet top_level_vars) }
bindingsVars :: FastStringEnv Var -> VarSet
bindingsVars ufm = mkVarSet $ nonDetEltsUFM ufm
tcIfaceOneShot :: IfaceOneShot -> OneShotInfo
tcIfaceOneShot IfaceNoOneShot = NoOneShotInfo
tcIfaceOneShot IfaceOneShot = OneShotLam
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* *
Getting from Names to
* *
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
************************************************************************
* *
Getting from Names to TyThings
* *
************************************************************************
-}
tcIfaceGlobal :: Name -> IfL TyThing
tcIfaceGlobal name
| Just thing <- wiredInNameTyThing_maybe name
Wired - in things include TyCons , DataCons , and Ids
sure the instances and RULES of this thing ( particularly ) are loaded
= do { ifCheckWiredInThing thing; return thing }
| otherwise
= do { env <- getGblEnv
; cur_mod <- if_mod <$> getLclEnv
Just get_type_env
; case lookupNameEnv type_env name of
Just thing -> return thing
Nothing -> via_external
}
_ -> via_external }
where
via_external = do
{ hsc_env <- getTopEnv
; mb_thing <- liftIO (lookupType hsc_env name)
; case mb_thing of {
Just thing -> return thing ;
Nothing -> do
; case mb_thing of
Failed err -> failIfM (ppr name <+> err)
Succeeded thing -> return thing
}}}
The if_rec_types field is used when we are compiling M.hs , which indirectly
imports Foo.hi , which mentions Then we look up M.T in M 's type
environment , which is splatted into if_rec_types after we 've built M 's type
envt .
This is a dark and complicated part of GHC type checking , with a lot
of moving parts . Interested readers should also look at :
Suppose that you are typechecking A.hs , which transitively imports ,
via B.hs , A.hs - boot . When we poke on and discover that it
has a reference to a type T from A , what TyThing should we wire
For the longest time , GHC adopted the policy that this was
* an error condition * ; that you MUST NEVER poke on B.hs 's reference
to a T defined in A.hs until A.hs has gotten around to kind - checking
Today , we take a different strategy : if we ever try to access
its own way : it means that you may end up with a mix of A.hs and
A.hs - boot during the course of typechecking . We do n't
is something along these lines in Core :
the constructor ( A and B ) means that GHC will always
tcIfaceTyCon :: IfaceTyCon -> IfL TyCon
tcIfaceTyCon (IfaceTyCon name _info)
= do { thing <- tcIfaceGlobal name
; case thing of
ATyCon tc -> return tc
AConLike (RealDataCon dc) -> return (promoteDataCon dc)
_ -> pprPanic "tcIfaceTyCon" (ppr thing) }
tcIfaceCoAxiom :: Name -> IfL (CoAxiom Branched)
tcIfaceCoAxiom name = do { thing <- tcIfaceImplicit name
; return (tyThingCoAxiom thing) }
tcIfaceCoAxiomRule :: IfLclName -> IfL CoAxiomRule
Unlike CoAxioms , which arise from user ' type instance ' declarations ,
there are a fixed set of CoAxiomRules :
- axioms for type - level literals ( and Symbol ) ,
tcIfaceCoAxiomRule n
| Just ax <- lookupUFM typeNatCoAxiomRules n
= return ax
| otherwise
= pprPanic "tcIfaceCoAxiomRule" (ppr n)
tcIfaceDataCon :: Name -> IfL DataCon
tcIfaceDataCon name = do { thing <- tcIfaceGlobal name
; case thing of
AConLike (RealDataCon dc) -> return dc
_ -> pprPanic "tcIfaceDataCon" (ppr name$$ ppr thing) }
tcIfaceConLike :: Name -> IfL ConLike
tcIfaceConLike name = do { thing <- tcIfaceGlobal name
; case thing of
AConLike cl -> return cl
_ -> pprPanic "tcIfaceConLike" (ppr name$$ ppr thing) }
tcIfaceExtId :: Name -> IfL Id
tcIfaceExtId name = do { thing <- tcIfaceGlobal name
; case thing of
AnId id -> return id
_ -> pprPanic "tcIfaceExtId" (ppr name$$ ppr thing) }
tcIfaceImplicit :: Name -> IfL TyThing
tcIfaceImplicit n = do
lcl_env <- getLclEnv
case if_implicits_env lcl_env of
Nothing -> tcIfaceGlobal n
Just tenv ->
case lookupTypeEnv tenv n of
Nothing -> pprPanic "tcIfaceInst" (ppr n $$ ppr tenv)
Just tything -> return tything
bindIfaceId :: IfaceIdBndr -> (Id -> IfL a) -> IfL a
bindIfaceId (w, fs, ty) thing_inside
= do { name <- newIfaceName (mkVarOccFS fs)
; ty' <- tcIfaceType ty
; w' <- tcIfaceType w
; let id = mkLocalIdOrCoVar name w' ty'
We should not have " OrCoVar " here , this is a bug ( # 17545 )
; extendIfaceIdEnv [id] (thing_inside id) }
bindIfaceIds :: [IfaceIdBndr] -> ([Id] -> IfL a) -> IfL a
bindIfaceIds [] thing_inside = thing_inside []
bindIfaceIds (b:bs) thing_inside
= bindIfaceId b $ \b' ->
bindIfaceIds bs $ \bs' ->
thing_inside (b':bs')
bindIfaceBndr :: IfaceBndr -> (CoreBndr -> IfL a) -> IfL a
bindIfaceBndr (IfaceIdBndr bndr) thing_inside
= bindIfaceId bndr thing_inside
bindIfaceBndr (IfaceTvBndr bndr) thing_inside
= bindIfaceTyVar bndr thing_inside
bindIfaceBndrs :: [IfaceBndr] -> ([CoreBndr] -> IfL a) -> IfL a
bindIfaceBndrs [] thing_inside = thing_inside []
bindIfaceBndrs (b:bs) thing_inside
= bindIfaceBndr b $ \ b' ->
bindIfaceBndrs bs $ \ bs' ->
thing_inside (b':bs')
bindIfaceForAllBndrs :: [VarBndr IfaceBndr vis] -> ([VarBndr TyCoVar vis] -> IfL a) -> IfL a
bindIfaceForAllBndrs [] thing_inside = thing_inside []
bindIfaceForAllBndrs (bndr:bndrs) thing_inside
= bindIfaceForAllBndr bndr $ \tv vis ->
bindIfaceForAllBndrs bndrs $ \bndrs' ->
thing_inside (Bndr tv vis : bndrs')
bindIfaceForAllBndr :: (VarBndr IfaceBndr vis) -> (TyCoVar -> vis -> IfL a) -> IfL a
bindIfaceForAllBndr (Bndr (IfaceTvBndr tv) vis) thing_inside
= bindIfaceTyVar tv $ \tv' -> thing_inside tv' vis
bindIfaceForAllBndr (Bndr (IfaceIdBndr tv) vis) thing_inside
= bindIfaceId tv $ \tv' -> thing_inside tv' vis
bindIfaceTyVar :: IfaceTvBndr -> (TyVar -> IfL a) -> IfL a
bindIfaceTyVar (occ,kind) thing_inside
= do { name <- newIfaceName (mkTyVarOccFS occ)
; tyvar <- mk_iface_tyvar name kind
; extendIfaceTyVarEnv [tyvar] (thing_inside tyvar) }
bindIfaceTyVars :: [IfaceTvBndr] -> ([TyVar] -> IfL a) -> IfL a
bindIfaceTyVars [] thing_inside = thing_inside []
bindIfaceTyVars (bndr:bndrs) thing_inside
= bindIfaceTyVar bndr $ \tv ->
bindIfaceTyVars bndrs $ \tvs ->
thing_inside (tv : tvs)
mk_iface_tyvar :: Name -> IfaceKind -> IfL TyVar
mk_iface_tyvar name ifKind
= do { kind <- tcIfaceType ifKind
; return (Var.mkTyVar name kind) }
bindIfaceTyConBinders :: [IfaceTyConBinder]
-> ([TyConBinder] -> IfL a) -> IfL a
bindIfaceTyConBinders [] thing_inside = thing_inside []
bindIfaceTyConBinders (b:bs) thing_inside
= bindIfaceTyConBinderX bindIfaceBndr b $ \ b' ->
bindIfaceTyConBinders bs $ \ bs' ->
thing_inside (b':bs')
bindIfaceTyConBinders_AT :: [IfaceTyConBinder]
-> ([TyConBinder] -> IfL a) -> IfL a
bindIfaceTyConBinders_AT [] thing_inside
= thing_inside []
bindIfaceTyConBinders_AT (b : bs) thing_inside
= bindIfaceTyConBinderX bind_tv b $ \b' ->
bindIfaceTyConBinders_AT bs $ \bs' ->
thing_inside (b':bs')
where
bind_tv tv thing
= do { mb_tv <- lookupIfaceVar tv
; case mb_tv of
Just b' -> thing b'
Nothing -> bindIfaceBndr tv thing }
bindIfaceTyConBinderX :: (IfaceBndr -> (TyCoVar -> IfL a) -> IfL a)
-> IfaceTyConBinder
-> (TyConBinder -> IfL a) -> IfL a
bindIfaceTyConBinderX bind_tv (Bndr tv vis) thing_inside
= bind_tv tv $ \tv' ->
thing_inside (Bndr tv' vis)
hydrateCgBreakInfo :: CgBreakInfo -> IfL ([Maybe (Id, Word16)], Type)
hydrateCgBreakInfo CgBreakInfo{..} = do
bindIfaceTyVars cgb_tyvars $ \_ -> do
result_ty <- tcIfaceType cgb_resty
mbVars <- mapM (traverse (\(if_gbl, offset) -> (,offset) <$> bindIfaceId if_gbl return)) cgb_vars
return (mbVars, result_ty)
|
a9d8a727f24f9914fdb621a33a61ba1ae2b57723732fb942026ac03d99bc9547 | bozsahin/cogs542 | tr.ccg.lisp | (DEFPARAMETER *CCG-GRAMMAR*
'(((KEY 1) (PHON COCUK) (MORPH N) (SYN ((BCAT NP) (FEATS NIL))) (SEM "CHILD")
(PARAM 1.0))
((KEY 2) (PHON COCUK) (MORPH N)
(SYN
(((BCAT S) (FEATS NIL)) (DIR FS) (MODAL ALL)
(((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE NOM)))))))
(SEM (LAM P (P "CHILD"))) (PARAM 1.0))
((KEY 3) (PHON COCUK) (MORPH N)
(SYN
(((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
(((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE NOM)))))))
(SEM (LAM P (P ("BG" "CHILD")))) (PARAM 1.0))
((KEY 4) (PHON KITABI) (MORPH N) (SYN ((BCAT NP) (FEATS NIL))) (SEM "BOOK")
(PARAM 1.0))
((KEY 5) (PHON KITABI) (MORPH N)
(SYN
((((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE NOM)))))
(DIR FS) (MODAL ALL)
((((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE NOM)))))
(DIR BS) (MODAL ALL) ((BCAT NP) (FEATS ((CASE ACC)))))))
(SEM (LAM P (P "BOOK"))) (PARAM 1.0))
((KEY 6) (PHON KITABI) (MORPH N)
(SYN
(((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
(((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE ACC)))))))
(SEM (LAM P (P ("BG" "BOOK")))) (PARAM 1.0))
((KEY 7) (PHON KITABI) (MORPH N)
(SYN
(((BCAT S) (FEATS NIL)) (DIR FS) (MODAL ALL)
(((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE ACC)))))))
(SEM (LAM P (P ("FG" "BOOK")))) (PARAM 1.0))
((KEY 8) (PHON OKUDU) (MORPH V)
(SYN
((((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE NOM)))))
(DIR BS) (MODAL ALL) ((BCAT NP) (FEATS ((CASE ACC))))))
(SEM (LAM X (LAM Y (("READ" X) Y)))) (PARAM 1.0))
((KEY 9) (PHON OKUDU) (MORPH V)
(SYN
((((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE ACC)))))
(DIR BS) (MODAL ALL) ((BCAT NP) (FEATS ((CASE NOM))))))
(SEM (LAM X (LAM Y (("READ" Y) X)))) (PARAM 1.0))
((KEY 10) (PHON OKUDU) (MORPH V)
(SYN
((((BCAT S) (FEATS NIL)) (DIR FS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE NOM)))))
(DIR BS) (MODAL ALL) ((BCAT NP) (FEATS ((CASE ACC))))))
(SEM (LAM X (LAM Y (("READ" X) Y)))) (PARAM 1.0))
((KEY 11) (PHON OKUDU) (MORPH V)
(SYN
((((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE NOM)))))
(DIR FS) (MODAL ALL) ((BCAT NP) (FEATS ((CASE ACC))))))
(SEM (LAM X (LAM Y (("READ" X) Y)))) (PARAM 1.0))
((KEY 12) (PHON OKUDU) (MORPH V)
(SYN
((((BCAT S) (FEATS NIL)) (DIR FS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE ACC)))))
(DIR FS) (MODAL ALL) ((BCAT NP) (FEATS ((CASE NOM))))))
(SEM (LAM X (LAM Y (("READ" Y) X)))) (PARAM 1.0))
((KEY 13) (PHON OKUDU) (MORPH V)
(SYN
((((BCAT S) (FEATS NIL)) (DIR FS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE NOM)))))
(DIR FS) (MODAL ALL) ((BCAT NP) (FEATS ((CASE ACC))))))
(SEM (LAM X (LAM Y (("READ" X) Y)))) (PARAM 1.0)))) | null | https://raw.githubusercontent.com/bozsahin/cogs542/3093fe6dc720405096af2e18d7ed9edd5f2ef47d/ccglab-examples/wo-turkish/tr.ccg.lisp | lisp | (DEFPARAMETER *CCG-GRAMMAR*
'(((KEY 1) (PHON COCUK) (MORPH N) (SYN ((BCAT NP) (FEATS NIL))) (SEM "CHILD")
(PARAM 1.0))
((KEY 2) (PHON COCUK) (MORPH N)
(SYN
(((BCAT S) (FEATS NIL)) (DIR FS) (MODAL ALL)
(((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE NOM)))))))
(SEM (LAM P (P "CHILD"))) (PARAM 1.0))
((KEY 3) (PHON COCUK) (MORPH N)
(SYN
(((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
(((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE NOM)))))))
(SEM (LAM P (P ("BG" "CHILD")))) (PARAM 1.0))
((KEY 4) (PHON KITABI) (MORPH N) (SYN ((BCAT NP) (FEATS NIL))) (SEM "BOOK")
(PARAM 1.0))
((KEY 5) (PHON KITABI) (MORPH N)
(SYN
((((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE NOM)))))
(DIR FS) (MODAL ALL)
((((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE NOM)))))
(DIR BS) (MODAL ALL) ((BCAT NP) (FEATS ((CASE ACC)))))))
(SEM (LAM P (P "BOOK"))) (PARAM 1.0))
((KEY 6) (PHON KITABI) (MORPH N)
(SYN
(((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
(((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE ACC)))))))
(SEM (LAM P (P ("BG" "BOOK")))) (PARAM 1.0))
((KEY 7) (PHON KITABI) (MORPH N)
(SYN
(((BCAT S) (FEATS NIL)) (DIR FS) (MODAL ALL)
(((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE ACC)))))))
(SEM (LAM P (P ("FG" "BOOK")))) (PARAM 1.0))
((KEY 8) (PHON OKUDU) (MORPH V)
(SYN
((((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE NOM)))))
(DIR BS) (MODAL ALL) ((BCAT NP) (FEATS ((CASE ACC))))))
(SEM (LAM X (LAM Y (("READ" X) Y)))) (PARAM 1.0))
((KEY 9) (PHON OKUDU) (MORPH V)
(SYN
((((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE ACC)))))
(DIR BS) (MODAL ALL) ((BCAT NP) (FEATS ((CASE NOM))))))
(SEM (LAM X (LAM Y (("READ" Y) X)))) (PARAM 1.0))
((KEY 10) (PHON OKUDU) (MORPH V)
(SYN
((((BCAT S) (FEATS NIL)) (DIR FS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE NOM)))))
(DIR BS) (MODAL ALL) ((BCAT NP) (FEATS ((CASE ACC))))))
(SEM (LAM X (LAM Y (("READ" X) Y)))) (PARAM 1.0))
((KEY 11) (PHON OKUDU) (MORPH V)
(SYN
((((BCAT S) (FEATS NIL)) (DIR BS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE NOM)))))
(DIR FS) (MODAL ALL) ((BCAT NP) (FEATS ((CASE ACC))))))
(SEM (LAM X (LAM Y (("READ" X) Y)))) (PARAM 1.0))
((KEY 12) (PHON OKUDU) (MORPH V)
(SYN
((((BCAT S) (FEATS NIL)) (DIR FS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE ACC)))))
(DIR FS) (MODAL ALL) ((BCAT NP) (FEATS ((CASE NOM))))))
(SEM (LAM X (LAM Y (("READ" Y) X)))) (PARAM 1.0))
((KEY 13) (PHON OKUDU) (MORPH V)
(SYN
((((BCAT S) (FEATS NIL)) (DIR FS) (MODAL ALL)
((BCAT NP) (FEATS ((CASE NOM)))))
(DIR FS) (MODAL ALL) ((BCAT NP) (FEATS ((CASE ACC))))))
(SEM (LAM X (LAM Y (("READ" X) Y)))) (PARAM 1.0)))) |
|
fbd1403aae07018ada6851424824c838a672fbfa03092c53fc6c553dd626c2da | haskell-distributed/distributed-process-platform | TestRegistry.hs | # LANGUAGE ScopedTypeVariables #
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE BangPatterns #-}
# LANGUAGE TemplateHaskell #
module Main where
import Control.Concurrent.MVar (newEmptyMVar, takeMVar)
import Control.Concurrent.Utils (Lock, Exclusive(..), Synchronised(..))
import Control.Distributed.Process
import Control.Distributed.Process.Node
import Control.Distributed.Process.Platform
( awaitExit
, spawnSignalled
, Killable(..)
)
import Control.Distributed.Process.Platform.Service.Registry
( Registry(..)
, KeyUpdateEvent(..)
, RegistryKeyMonitorNotification(..)
, addName
, addProperty
, giveAwayName
, registerName
, registerValue
, unregisterName
, lookupName
, lookupProperty
, registeredNames
, foldNames
, queryNames
, findByProperty
, findByPropertyValue
, awaitTimeout
, await
, SearchHandle
, AwaitResult(..)
, RegisterKeyReply(..)
, UnregisterKeyReply(..)
)
import qualified Control.Distributed.Process.Platform.Service.Registry as Registry
import Control.Distributed.Process.Platform.Test
import Control.Distributed.Process.Platform.Time
import Control.Distributed.Process.Platform.Timer (sleep)
import Control.Monad (void, forM_, forM)
import Control.Rematch
( equalTo
)
import qualified Data.Foldable as Foldable
import qualified Data.List as List
#if ! MIN_VERSION_base(4,6,0)
import Prelude hiding (catch)
#endif
import Test.HUnit (Assertion, assertFailure)
import Test.Framework (Test, testGroup)
import Test.Framework.Providers.HUnit (testCase)
import TestUtils
import qualified Network.Transport as NT
myRegistry :: Process (Registry String ())
myRegistry = Registry.start
counterReg :: Process (Registry String Int)
counterReg = Registry.start
withRegistry :: LocalNode
-> (Registry String () -> Process ())
-> Assertion
withRegistry node proc = do
runProcess node $ do
reg' <- myRegistry
(proc reg') `finally` (killProc reg' "goodbye")
testAddLocalName :: TestResult RegisterKeyReply -> Process ()
testAddLocalName result = do
reg <- myRegistry
stash result =<< addName reg "foobar"
testAddLocalProperty :: TestResult (Maybe Int) -> Process ()
testAddLocalProperty result = do
reg <- counterReg
addProperty reg "chickens" (42 :: Int)
stash result =<< lookupProperty reg "chickens"
testAddRemoteProperty :: TestResult Int -> Process ()
testAddRemoteProperty result = do
reg <- counterReg
p <- spawnLocal $ do
pid <- expect
Just i <- lookupProperty reg "ducks" :: Process (Maybe Int)
send pid i
RegisteredOk <- registerValue reg p "ducks" (39 :: Int)
getSelfPid >>= send p
expect >>= stash result
testFindByPropertySet :: TestResult Bool -> Process ()
testFindByPropertySet result = do
reg <- counterReg
p1 <- spawnLocal $ addProperty reg "animals" (1 :: Int) >> expect >>= return
p2 <- spawnLocal $ addProperty reg "animals" (1 :: Int) >> expect >>= return
sleep $ seconds 1
found <- findByProperty reg "animals"
found `shouldContain` p1
found `shouldContain` p2
notFound <- findByProperty reg "foobar"
stash result $ length notFound == 0
testFindByPropertyValueSet :: TestResult Bool -> Process ()
testFindByPropertyValueSet result = do
us <- getSelfPid
reg <- counterReg
p1 <- spawnLocal $ link us >> addProperty reg "animals" (1 :: Int) >> expect >>= return
_ <- spawnLocal $ link us >> addProperty reg "animals" (2 :: Int) >> expect >>= return
p3 <- spawnLocal $ link us >> addProperty reg "animals" (1 :: Int) >> expect >>= return
_ <- spawnLocal $ link us >> addProperty reg "ducks" (1 :: Int) >> expect >>= return
sleep $ seconds 1
found <- findByPropertyValue reg "animals" (1 :: Int)
found `shouldContain` p1
found `shouldContain` p3
stash result $ length found == 2
testCheckLocalName :: Registry String () -> Process ()
testCheckLocalName reg = do
void $ addName reg "fwibble"
fwibble <- lookupName reg "fwibble"
selfPid <- getSelfPid
fwibble `shouldBe` equalTo (Just selfPid)
testGiveAwayName :: Registry String () -> Process ()
testGiveAwayName reg = do
testPid <- getSelfPid
void $ addName reg "cat"
pid <- spawnLocal $ link testPid >> (expect :: Process ())
giveAwayName reg "cat" pid
cat <- lookupName reg "cat"
cat `shouldBe` equalTo (Just pid)
testMultipleRegistrations :: Registry String () -> Process ()
testMultipleRegistrations reg = do
self <- getSelfPid
forM_ names (addName reg)
forM_ names $ \name -> do
found <- lookupName reg name
found `shouldBe` equalTo (Just self)
where
names = ["foo", "bar", "baz"]
testDuplicateRegistrations :: Registry String () -> Process ()
testDuplicateRegistrations reg = do
void $ addName reg "foobar"
RegisteredOk <- addName reg "foobar"
pid <- spawnLocal $ (expect :: Process ()) >>= return
result <- registerName reg "foobar" pid
result `shouldBe` equalTo AlreadyRegistered
testUnregisterName :: Registry String () -> Process ()
testUnregisterName reg = do
self <- getSelfPid
void $ addName reg "fwibble"
void $ addName reg "fwobble"
Just self' <- lookupName reg "fwibble"
self' `shouldBe` equalTo self
unreg <- unregisterName reg "fwibble"
unregFwibble <- lookupName reg "fwibble"
unreg `shouldBe` equalTo UnregisterOk
-- fwibble is gone...
unregFwibble `shouldBe` equalTo Nothing
-- but fwobble is still registered
fwobble <- lookupName reg "fwobble"
fwobble `shouldBe` equalTo (Just self)
testUnregisterUnknownName :: Registry String () -> Process ()
testUnregisterUnknownName reg = do
result <- unregisterName reg "no.such.name"
result `shouldBe` equalTo UnregisterKeyNotFound
testUnregisterAnothersName :: Registry String () -> Process ()
testUnregisterAnothersName reg = do
(sp, rp) <- newChan
pid <- spawnLocal $ do
void $ addName reg "proc.name"
sendChan sp ()
(expect :: Process ()) >>= return
() <- receiveChan rp
found <- lookupName reg "proc.name"
found `shouldBe` equalTo (Just pid)
unreg <- unregisterName reg "proc.name"
unreg `shouldBe` equalTo UnregisterInvalidKey
testProcessDeathHandling :: Registry String () -> Process ()
testProcessDeathHandling reg = do
(sp, rp) <- newChan
pid <- spawnLocal $ do
void $ addName reg "proc.name.1"
void $ addName reg "proc.name.2"
sendChan sp ()
(expect :: Process ()) >>= return
() <- receiveChan rp
void $ monitor pid
regNames <- registeredNames reg pid
regNames `shouldContain` "proc.name.1"
regNames `shouldContain` "proc.name.2"
send pid ()
receiveWait [
match (\(ProcessMonitorNotification _ _ _) -> return ())
]
forM_ [1..2 :: Int] $ \n -> do
let name = "proc.name." ++ (show n)
found <- lookupName reg name
found `shouldBe` equalTo Nothing
regNames' <- registeredNames reg pid
regNames' `shouldBe` equalTo ([] :: [String])
testLocalRegNamesFold :: Registry String () -> Process ()
testLocalRegNamesFold reg = do
parent <- getSelfPid
forM_ [1..1000] $ \(i :: Int) -> spawnLocal $ do
send parent i
addName reg (show i) >> expect :: Process ()
waitForTestRegistrations
ns <- foldNames reg [] $ \acc (n, _) -> return ((read n :: Int):acc)
(List.sort ns) `shouldBe` equalTo [1..1000]
where
waitForTestRegistrations = do
void $ receiveWait [ matchIf (\(i :: Int) -> i == 1000) (\_ -> return ()) ]
sleep $ milliSeconds 150
testLocalQueryNamesFold :: Registry String () -> Process ()
testLocalQueryNamesFold reg = do
pids <- forM [1..1000] $ \(i :: Int) -> spawnLocal $ do
addName reg (show i) >> expect :: Process ()
waitRegs reg 1000
ns <- queryNames reg $ \(sh :: SearchHandle String ProcessId) -> do
return $ Foldable.foldl (\acc pid -> (pid:acc)) [] sh
(List.sort ns) `shouldBe` equalTo pids
where
waitRegs :: Registry String () -> Int -> Process ()
waitRegs _ 0 = return ()
waitRegs reg' n = await reg' (show n) >> waitRegs reg' (n - 1)
testMonitorName :: Registry String () -> Process ()
testMonitorName reg = do
(sp, rp) <- newChan
pid <- spawnLocal $ do
void $ addName reg "proc.name.1"
void $ addName reg "proc.name.2"
sendChan sp ()
(expect :: Process ()) >>= return
() <- receiveChan rp
mRef <- Registry.monitorName reg "proc.name.2"
send pid ()
res <- receiveTimeout (after 2 Seconds) [
matchIf (\(RegistryKeyMonitorNotification k ref _ _) ->
k == "proc.name.2" && ref == mRef)
(\(RegistryKeyMonitorNotification _ _ ev _) -> return ev)
]
res `shouldBe` equalTo (Just (KeyOwnerDied DiedNormal))
testMonitorNameChange :: Registry String () -> Process ()
testMonitorNameChange reg = do
let k = "proc.name.foo"
lock <- liftIO $ new :: Process Lock
acquire lock
testPid <- getSelfPid
pid <- spawnSignalled (addName reg k) $ const $ do
link testPid
synchronised lock $ giveAwayName reg k testPid
expect >>= return
-- at this point, we know the child has grabbed the name k for itself
mRef <- Registry.monitorName reg k
release lock
ev <- receiveWait [ matchIf (\(RegistryKeyMonitorNotification k' ref _ _) ->
k' == k && ref == mRef)
(\(RegistryKeyMonitorNotification _ _ ev' _) ->
return ev') ]
ev `shouldBe` equalTo (KeyOwnerChanged pid testPid)
testUnmonitor :: TestResult Bool -> Process ()
testUnmonitor result = do
let k = "chickens"
let name = "poultry"
reg <- counterReg
(sp, rp) <- newChan
pid <- spawnLocal $ do
void $ addProperty reg k (42 :: Int)
addName reg name
sendChan sp ()
expect >>= return
() <- receiveChan rp
mRef <- Registry.monitorProp reg k pid
void $ receiveWait [
matchIf (\(RegistryKeyMonitorNotification k' ref ev _) ->
k' == k && ref == mRef && ev == (KeyRegistered pid))
return
]
Registry.unmonitor reg mRef
kill pid "goodbye!"
awaitExit pid
Nothing <- lookupName reg name
t <- receiveTimeout (after 1 Seconds) [
matchIf (\(RegistryKeyMonitorNotification k' ref ev _) ->
k' == k && ref == mRef && ev == (KeyRegistered pid))
return
]
t `shouldBe` (equalTo Nothing)
stash result True
testMonitorPropertyChanged :: TestResult Bool -> Process ()
testMonitorPropertyChanged result = do
let k = "chickens"
let name = "poultry"
lock <- liftIO $ new :: Process Lock
reg <- counterReg
-- yes, using the lock here without exception handling is risky...
acquire lock
pid <- spawnSignalled (addProperty reg k (42 :: Int)) $ const $ do
addName reg name
synchronised lock $ addProperty reg k (45 :: Int)
expect >>= return
at this point , the worker has already registered 42 ( since we used
-- spawnSignalled to start it) and is waiting for us to unlock...
mRef <- Registry.monitorProp reg k pid
we /must/ receive a monitor notification first , for the pre - existing
-- key and only then will we let the worker move on and update the value
void $ receiveWait [
matchIf (\(RegistryKeyMonitorNotification k' ref ev _) ->
k' == k && ref == mRef && ev == (KeyRegistered pid))
return
]
release lock
kr <- receiveTimeout 1000000 [
matchIf (\(RegistryKeyMonitorNotification k' ref ev _) ->
k' == k && ref == mRef && ev == (KeyRegistered pid))
return
]
stash result (kr /= Nothing)
testMonitorPropertyOwnerDied :: Registry String () -> Process ()
testMonitorPropertyOwnerDied reg = do
let k = "foo.bar"
pid <- spawnSignalled (addProperty reg k ()) $ const $ do
expect >>= return
mRef <- Registry.monitorProp reg k pid
kill pid "goodbye!"
we /must/ receive a monitor notification first , for the pre - existing
-- key and only then will we let the worker move on and update the value
r <- receiveTimeout 1000000 [
matchIf (\(RegistryKeyMonitorNotification k' ref ev _) ->
k' == k && ref == mRef && ev /= (KeyRegistered pid))
(\(RegistryKeyMonitorNotification _ _ ev _) ->
return ev)
]
case r of
Just (KeyOwnerDied (DiedException _)) -> return ()
_ -> (liftIO $ putStrLn (show r)) >> return ()
-- testMonitorLeaseExpired :: ProcessId -> Process ()
-- testMonitorPropertyLeaseExpired :: ProcessId -> Process ()
testMonitorUnregistration :: Registry String () -> Process ()
testMonitorUnregistration reg = do
(sp, rp) <- newChan
pid <- spawnLocal $ do
void $ addName reg "proc.1"
sendChan sp ()
expect :: Process ()
void $ unregisterName reg "proc.1"
sendChan sp ()
(expect :: Process ()) >>= return
() <- receiveChan rp
mRef <- Registry.monitorName reg "proc.1"
send pid ()
() <- receiveChan rp
res <- receiveTimeout (after 2 Seconds) [
matchIf (\(RegistryKeyMonitorNotification k ref _ _) ->
k == "proc.1" && ref == mRef)
(\(RegistryKeyMonitorNotification _ _ ev _) -> return ev)
]
res `shouldBe` equalTo (Just KeyUnregistered)
testMonitorRegistration :: Registry String () -> Process ()
testMonitorRegistration reg = do
kRef <- Registry.monitorName reg "my.proc"
pid <- spawnSignalled (addName reg "my.proc") $ const expect
res <- receiveTimeout (after 5 Seconds) [
matchIf (\(RegistryKeyMonitorNotification k ref _ _) ->
k == "my.proc" && ref == kRef)
(\(RegistryKeyMonitorNotification _ _ ev _) -> return ev)
]
res `shouldBe` equalTo (Just (KeyRegistered pid))
testAwaitRegistration :: Registry String () -> Process ()
testAwaitRegistration reg = do
pid <- spawnLocal $ do
void $ addName reg "foo.bar"
expect :: Process ()
res <- awaitTimeout reg (Delay $ within 5 Seconds) "foo.bar"
res `shouldBe` equalTo (RegisteredName pid "foo.bar")
testAwaitRegistrationNoTimeout :: Registry String () -> Process ()
testAwaitRegistrationNoTimeout reg = do
parent <- getSelfPid
barrier <- liftIO $ newEmptyMVar
void $ spawnLocal $ do
res <- await reg "baz.bog"
case res of
RegisteredName _ "baz.bog" -> stash barrier ()
_ -> kill parent "BANG!"
void $ addName reg "baz.bog"
liftIO $ takeMVar barrier >>= return
testAwaitServerDied :: Registry String () -> Process ()
testAwaitServerDied reg = do
result <- liftIO $ newEmptyMVar
_ <- spawnLocal $ await reg "bobobob" >>= stash result
sleep $ milliSeconds 250
killProc reg "bye!"
res <- liftIO $ takeMVar result
case res of
ServerUnreachable (DiedException _) -> return ()
_ -> liftIO $ assertFailure (show res)
tests :: NT.Transport -> IO [Test]
tests transport = do
localNode <- newLocalNode transport initRemoteTable
let testProc = withRegistry localNode
return [
testGroup "Name Registration/Unregistration"
[
testCase "Simple Registration"
(delayedAssertion
"expected the server to return the incremented state as 7"
localNode RegisteredOk testAddLocalName)
, testCase "Give Away Name"
(testProc testGiveAwayName)
, testCase "Verified Registration"
(testProc testCheckLocalName)
, testCase "Single Process, Multiple Registered Names"
(testProc testMultipleRegistrations)
, testCase "Duplicate Registration Fails"
(testProc testDuplicateRegistrations)
, testCase "Unregister Own Name"
(testProc testUnregisterName)
, testCase "Unregister Unknown Name"
(testProc testUnregisterUnknownName)
, testCase "Unregister Someone Else's Name"
(testProc testUnregisterAnothersName)
]
, testGroup "Properties"
[
testCase "Simple Property Registration"
(delayedAssertion
"expected the server to return the property value 42"
localNode (Just 42) testAddLocalProperty)
, testCase "Remote Property Registration"
(delayedAssertion
"expected the server to return the property value 39"
localNode 39 testAddRemoteProperty)
]
, testGroup "Queries"
[
testCase "Folding Over Registered Names (Locally)"
(testProc testLocalRegNamesFold)
, testCase "Querying Registered Names (Locally)"
(testProc testLocalQueryNamesFold)
, testCase "Querying Process Where Property Exists (Locally)"
(delayedAssertion
"expected the server to return only the relevant processes"
localNode True testFindByPropertySet)
, testCase "Querying Process Where Property Is Set To Specific Value (Locally)"
(delayedAssertion
"expected the server to return only the relevant processes"
localNode True testFindByPropertyValueSet)
]
, testGroup "Named Process Monitoring/Tracking"
[
testCase "Process Death Results In Unregistration"
(testProc testProcessDeathHandling)
, testCase "Monitoring Name Changes"
(testProc testMonitorName)
, testCase "Monitoring Name Changes (KeyOwnerChanged)"
(testProc testMonitorNameChange)
, testCase "Unmonitoring (Ignoring) Changes"
(delayedAssertion
"expected no further notifications after 'unmonitor' was called"
localNode True testUnmonitor)
, testCase "Monitoring Property Changes/Updates"
(delayedAssertion
"expected the server to send additional notifications for each change"
localNode True testMonitorPropertyChanged)
, testCase "Monitoring Property Owner Death"
(testProc testMonitorPropertyOwnerDied)
, testCase "Monitoring Registration"
(testProc testMonitorRegistration)
, testCase "Awaiting Registration"
(testProc testAwaitRegistration)
, testCase "Await without timeout"
(testProc testAwaitRegistrationNoTimeout)
, testCase "Server Died During Await"
(testProc testAwaitServerDied)
, testCase "Monitoring Unregistration"
(testProc testMonitorUnregistration)
]
]
main :: IO ()
main = testMain $ tests
| null | https://raw.githubusercontent.com/haskell-distributed/distributed-process-platform/46d63f81910e7dd527fb1d41e654a5cfb0dbfdba/tests/TestRegistry.hs | haskell | # LANGUAGE DeriveDataTypeable #
# LANGUAGE BangPatterns #
fwibble is gone...
but fwobble is still registered
at this point, we know the child has grabbed the name k for itself
yes, using the lock here without exception handling is risky...
spawnSignalled to start it) and is waiting for us to unlock...
key and only then will we let the worker move on and update the value
key and only then will we let the worker move on and update the value
testMonitorLeaseExpired :: ProcessId -> Process ()
testMonitorPropertyLeaseExpired :: ProcessId -> Process () | # LANGUAGE ScopedTypeVariables #
# LANGUAGE TemplateHaskell #
module Main where
import Control.Concurrent.MVar (newEmptyMVar, takeMVar)
import Control.Concurrent.Utils (Lock, Exclusive(..), Synchronised(..))
import Control.Distributed.Process
import Control.Distributed.Process.Node
import Control.Distributed.Process.Platform
( awaitExit
, spawnSignalled
, Killable(..)
)
import Control.Distributed.Process.Platform.Service.Registry
( Registry(..)
, KeyUpdateEvent(..)
, RegistryKeyMonitorNotification(..)
, addName
, addProperty
, giveAwayName
, registerName
, registerValue
, unregisterName
, lookupName
, lookupProperty
, registeredNames
, foldNames
, queryNames
, findByProperty
, findByPropertyValue
, awaitTimeout
, await
, SearchHandle
, AwaitResult(..)
, RegisterKeyReply(..)
, UnregisterKeyReply(..)
)
import qualified Control.Distributed.Process.Platform.Service.Registry as Registry
import Control.Distributed.Process.Platform.Test
import Control.Distributed.Process.Platform.Time
import Control.Distributed.Process.Platform.Timer (sleep)
import Control.Monad (void, forM_, forM)
import Control.Rematch
( equalTo
)
import qualified Data.Foldable as Foldable
import qualified Data.List as List
#if ! MIN_VERSION_base(4,6,0)
import Prelude hiding (catch)
#endif
import Test.HUnit (Assertion, assertFailure)
import Test.Framework (Test, testGroup)
import Test.Framework.Providers.HUnit (testCase)
import TestUtils
import qualified Network.Transport as NT
myRegistry :: Process (Registry String ())
myRegistry = Registry.start
counterReg :: Process (Registry String Int)
counterReg = Registry.start
withRegistry :: LocalNode
-> (Registry String () -> Process ())
-> Assertion
withRegistry node proc = do
runProcess node $ do
reg' <- myRegistry
(proc reg') `finally` (killProc reg' "goodbye")
testAddLocalName :: TestResult RegisterKeyReply -> Process ()
testAddLocalName result = do
reg <- myRegistry
stash result =<< addName reg "foobar"
testAddLocalProperty :: TestResult (Maybe Int) -> Process ()
testAddLocalProperty result = do
reg <- counterReg
addProperty reg "chickens" (42 :: Int)
stash result =<< lookupProperty reg "chickens"
testAddRemoteProperty :: TestResult Int -> Process ()
testAddRemoteProperty result = do
reg <- counterReg
p <- spawnLocal $ do
pid <- expect
Just i <- lookupProperty reg "ducks" :: Process (Maybe Int)
send pid i
RegisteredOk <- registerValue reg p "ducks" (39 :: Int)
getSelfPid >>= send p
expect >>= stash result
testFindByPropertySet :: TestResult Bool -> Process ()
testFindByPropertySet result = do
reg <- counterReg
p1 <- spawnLocal $ addProperty reg "animals" (1 :: Int) >> expect >>= return
p2 <- spawnLocal $ addProperty reg "animals" (1 :: Int) >> expect >>= return
sleep $ seconds 1
found <- findByProperty reg "animals"
found `shouldContain` p1
found `shouldContain` p2
notFound <- findByProperty reg "foobar"
stash result $ length notFound == 0
testFindByPropertyValueSet :: TestResult Bool -> Process ()
testFindByPropertyValueSet result = do
us <- getSelfPid
reg <- counterReg
p1 <- spawnLocal $ link us >> addProperty reg "animals" (1 :: Int) >> expect >>= return
_ <- spawnLocal $ link us >> addProperty reg "animals" (2 :: Int) >> expect >>= return
p3 <- spawnLocal $ link us >> addProperty reg "animals" (1 :: Int) >> expect >>= return
_ <- spawnLocal $ link us >> addProperty reg "ducks" (1 :: Int) >> expect >>= return
sleep $ seconds 1
found <- findByPropertyValue reg "animals" (1 :: Int)
found `shouldContain` p1
found `shouldContain` p3
stash result $ length found == 2
testCheckLocalName :: Registry String () -> Process ()
testCheckLocalName reg = do
void $ addName reg "fwibble"
fwibble <- lookupName reg "fwibble"
selfPid <- getSelfPid
fwibble `shouldBe` equalTo (Just selfPid)
testGiveAwayName :: Registry String () -> Process ()
testGiveAwayName reg = do
testPid <- getSelfPid
void $ addName reg "cat"
pid <- spawnLocal $ link testPid >> (expect :: Process ())
giveAwayName reg "cat" pid
cat <- lookupName reg "cat"
cat `shouldBe` equalTo (Just pid)
testMultipleRegistrations :: Registry String () -> Process ()
testMultipleRegistrations reg = do
self <- getSelfPid
forM_ names (addName reg)
forM_ names $ \name -> do
found <- lookupName reg name
found `shouldBe` equalTo (Just self)
where
names = ["foo", "bar", "baz"]
testDuplicateRegistrations :: Registry String () -> Process ()
testDuplicateRegistrations reg = do
void $ addName reg "foobar"
RegisteredOk <- addName reg "foobar"
pid <- spawnLocal $ (expect :: Process ()) >>= return
result <- registerName reg "foobar" pid
result `shouldBe` equalTo AlreadyRegistered
testUnregisterName :: Registry String () -> Process ()
testUnregisterName reg = do
self <- getSelfPid
void $ addName reg "fwibble"
void $ addName reg "fwobble"
Just self' <- lookupName reg "fwibble"
self' `shouldBe` equalTo self
unreg <- unregisterName reg "fwibble"
unregFwibble <- lookupName reg "fwibble"
unreg `shouldBe` equalTo UnregisterOk
unregFwibble `shouldBe` equalTo Nothing
fwobble <- lookupName reg "fwobble"
fwobble `shouldBe` equalTo (Just self)
testUnregisterUnknownName :: Registry String () -> Process ()
testUnregisterUnknownName reg = do
result <- unregisterName reg "no.such.name"
result `shouldBe` equalTo UnregisterKeyNotFound
testUnregisterAnothersName :: Registry String () -> Process ()
testUnregisterAnothersName reg = do
(sp, rp) <- newChan
pid <- spawnLocal $ do
void $ addName reg "proc.name"
sendChan sp ()
(expect :: Process ()) >>= return
() <- receiveChan rp
found <- lookupName reg "proc.name"
found `shouldBe` equalTo (Just pid)
unreg <- unregisterName reg "proc.name"
unreg `shouldBe` equalTo UnregisterInvalidKey
testProcessDeathHandling :: Registry String () -> Process ()
testProcessDeathHandling reg = do
(sp, rp) <- newChan
pid <- spawnLocal $ do
void $ addName reg "proc.name.1"
void $ addName reg "proc.name.2"
sendChan sp ()
(expect :: Process ()) >>= return
() <- receiveChan rp
void $ monitor pid
regNames <- registeredNames reg pid
regNames `shouldContain` "proc.name.1"
regNames `shouldContain` "proc.name.2"
send pid ()
receiveWait [
match (\(ProcessMonitorNotification _ _ _) -> return ())
]
forM_ [1..2 :: Int] $ \n -> do
let name = "proc.name." ++ (show n)
found <- lookupName reg name
found `shouldBe` equalTo Nothing
regNames' <- registeredNames reg pid
regNames' `shouldBe` equalTo ([] :: [String])
testLocalRegNamesFold :: Registry String () -> Process ()
testLocalRegNamesFold reg = do
parent <- getSelfPid
forM_ [1..1000] $ \(i :: Int) -> spawnLocal $ do
send parent i
addName reg (show i) >> expect :: Process ()
waitForTestRegistrations
ns <- foldNames reg [] $ \acc (n, _) -> return ((read n :: Int):acc)
(List.sort ns) `shouldBe` equalTo [1..1000]
where
waitForTestRegistrations = do
void $ receiveWait [ matchIf (\(i :: Int) -> i == 1000) (\_ -> return ()) ]
sleep $ milliSeconds 150
testLocalQueryNamesFold :: Registry String () -> Process ()
testLocalQueryNamesFold reg = do
pids <- forM [1..1000] $ \(i :: Int) -> spawnLocal $ do
addName reg (show i) >> expect :: Process ()
waitRegs reg 1000
ns <- queryNames reg $ \(sh :: SearchHandle String ProcessId) -> do
return $ Foldable.foldl (\acc pid -> (pid:acc)) [] sh
(List.sort ns) `shouldBe` equalTo pids
where
waitRegs :: Registry String () -> Int -> Process ()
waitRegs _ 0 = return ()
waitRegs reg' n = await reg' (show n) >> waitRegs reg' (n - 1)
testMonitorName :: Registry String () -> Process ()
testMonitorName reg = do
(sp, rp) <- newChan
pid <- spawnLocal $ do
void $ addName reg "proc.name.1"
void $ addName reg "proc.name.2"
sendChan sp ()
(expect :: Process ()) >>= return
() <- receiveChan rp
mRef <- Registry.monitorName reg "proc.name.2"
send pid ()
res <- receiveTimeout (after 2 Seconds) [
matchIf (\(RegistryKeyMonitorNotification k ref _ _) ->
k == "proc.name.2" && ref == mRef)
(\(RegistryKeyMonitorNotification _ _ ev _) -> return ev)
]
res `shouldBe` equalTo (Just (KeyOwnerDied DiedNormal))
testMonitorNameChange :: Registry String () -> Process ()
testMonitorNameChange reg = do
let k = "proc.name.foo"
lock <- liftIO $ new :: Process Lock
acquire lock
testPid <- getSelfPid
pid <- spawnSignalled (addName reg k) $ const $ do
link testPid
synchronised lock $ giveAwayName reg k testPid
expect >>= return
mRef <- Registry.monitorName reg k
release lock
ev <- receiveWait [ matchIf (\(RegistryKeyMonitorNotification k' ref _ _) ->
k' == k && ref == mRef)
(\(RegistryKeyMonitorNotification _ _ ev' _) ->
return ev') ]
ev `shouldBe` equalTo (KeyOwnerChanged pid testPid)
testUnmonitor :: TestResult Bool -> Process ()
testUnmonitor result = do
let k = "chickens"
let name = "poultry"
reg <- counterReg
(sp, rp) <- newChan
pid <- spawnLocal $ do
void $ addProperty reg k (42 :: Int)
addName reg name
sendChan sp ()
expect >>= return
() <- receiveChan rp
mRef <- Registry.monitorProp reg k pid
void $ receiveWait [
matchIf (\(RegistryKeyMonitorNotification k' ref ev _) ->
k' == k && ref == mRef && ev == (KeyRegistered pid))
return
]
Registry.unmonitor reg mRef
kill pid "goodbye!"
awaitExit pid
Nothing <- lookupName reg name
t <- receiveTimeout (after 1 Seconds) [
matchIf (\(RegistryKeyMonitorNotification k' ref ev _) ->
k' == k && ref == mRef && ev == (KeyRegistered pid))
return
]
t `shouldBe` (equalTo Nothing)
stash result True
testMonitorPropertyChanged :: TestResult Bool -> Process ()
testMonitorPropertyChanged result = do
let k = "chickens"
let name = "poultry"
lock <- liftIO $ new :: Process Lock
reg <- counterReg
acquire lock
pid <- spawnSignalled (addProperty reg k (42 :: Int)) $ const $ do
addName reg name
synchronised lock $ addProperty reg k (45 :: Int)
expect >>= return
at this point , the worker has already registered 42 ( since we used
mRef <- Registry.monitorProp reg k pid
we /must/ receive a monitor notification first , for the pre - existing
void $ receiveWait [
matchIf (\(RegistryKeyMonitorNotification k' ref ev _) ->
k' == k && ref == mRef && ev == (KeyRegistered pid))
return
]
release lock
kr <- receiveTimeout 1000000 [
matchIf (\(RegistryKeyMonitorNotification k' ref ev _) ->
k' == k && ref == mRef && ev == (KeyRegistered pid))
return
]
stash result (kr /= Nothing)
testMonitorPropertyOwnerDied :: Registry String () -> Process ()
testMonitorPropertyOwnerDied reg = do
let k = "foo.bar"
pid <- spawnSignalled (addProperty reg k ()) $ const $ do
expect >>= return
mRef <- Registry.monitorProp reg k pid
kill pid "goodbye!"
we /must/ receive a monitor notification first , for the pre - existing
r <- receiveTimeout 1000000 [
matchIf (\(RegistryKeyMonitorNotification k' ref ev _) ->
k' == k && ref == mRef && ev /= (KeyRegistered pid))
(\(RegistryKeyMonitorNotification _ _ ev _) ->
return ev)
]
case r of
Just (KeyOwnerDied (DiedException _)) -> return ()
_ -> (liftIO $ putStrLn (show r)) >> return ()
testMonitorUnregistration :: Registry String () -> Process ()
testMonitorUnregistration reg = do
(sp, rp) <- newChan
pid <- spawnLocal $ do
void $ addName reg "proc.1"
sendChan sp ()
expect :: Process ()
void $ unregisterName reg "proc.1"
sendChan sp ()
(expect :: Process ()) >>= return
() <- receiveChan rp
mRef <- Registry.monitorName reg "proc.1"
send pid ()
() <- receiveChan rp
res <- receiveTimeout (after 2 Seconds) [
matchIf (\(RegistryKeyMonitorNotification k ref _ _) ->
k == "proc.1" && ref == mRef)
(\(RegistryKeyMonitorNotification _ _ ev _) -> return ev)
]
res `shouldBe` equalTo (Just KeyUnregistered)
testMonitorRegistration :: Registry String () -> Process ()
testMonitorRegistration reg = do
kRef <- Registry.monitorName reg "my.proc"
pid <- spawnSignalled (addName reg "my.proc") $ const expect
res <- receiveTimeout (after 5 Seconds) [
matchIf (\(RegistryKeyMonitorNotification k ref _ _) ->
k == "my.proc" && ref == kRef)
(\(RegistryKeyMonitorNotification _ _ ev _) -> return ev)
]
res `shouldBe` equalTo (Just (KeyRegistered pid))
testAwaitRegistration :: Registry String () -> Process ()
testAwaitRegistration reg = do
pid <- spawnLocal $ do
void $ addName reg "foo.bar"
expect :: Process ()
res <- awaitTimeout reg (Delay $ within 5 Seconds) "foo.bar"
res `shouldBe` equalTo (RegisteredName pid "foo.bar")
testAwaitRegistrationNoTimeout :: Registry String () -> Process ()
testAwaitRegistrationNoTimeout reg = do
parent <- getSelfPid
barrier <- liftIO $ newEmptyMVar
void $ spawnLocal $ do
res <- await reg "baz.bog"
case res of
RegisteredName _ "baz.bog" -> stash barrier ()
_ -> kill parent "BANG!"
void $ addName reg "baz.bog"
liftIO $ takeMVar barrier >>= return
testAwaitServerDied :: Registry String () -> Process ()
testAwaitServerDied reg = do
result <- liftIO $ newEmptyMVar
_ <- spawnLocal $ await reg "bobobob" >>= stash result
sleep $ milliSeconds 250
killProc reg "bye!"
res <- liftIO $ takeMVar result
case res of
ServerUnreachable (DiedException _) -> return ()
_ -> liftIO $ assertFailure (show res)
tests :: NT.Transport -> IO [Test]
tests transport = do
localNode <- newLocalNode transport initRemoteTable
let testProc = withRegistry localNode
return [
testGroup "Name Registration/Unregistration"
[
testCase "Simple Registration"
(delayedAssertion
"expected the server to return the incremented state as 7"
localNode RegisteredOk testAddLocalName)
, testCase "Give Away Name"
(testProc testGiveAwayName)
, testCase "Verified Registration"
(testProc testCheckLocalName)
, testCase "Single Process, Multiple Registered Names"
(testProc testMultipleRegistrations)
, testCase "Duplicate Registration Fails"
(testProc testDuplicateRegistrations)
, testCase "Unregister Own Name"
(testProc testUnregisterName)
, testCase "Unregister Unknown Name"
(testProc testUnregisterUnknownName)
, testCase "Unregister Someone Else's Name"
(testProc testUnregisterAnothersName)
]
, testGroup "Properties"
[
testCase "Simple Property Registration"
(delayedAssertion
"expected the server to return the property value 42"
localNode (Just 42) testAddLocalProperty)
, testCase "Remote Property Registration"
(delayedAssertion
"expected the server to return the property value 39"
localNode 39 testAddRemoteProperty)
]
, testGroup "Queries"
[
testCase "Folding Over Registered Names (Locally)"
(testProc testLocalRegNamesFold)
, testCase "Querying Registered Names (Locally)"
(testProc testLocalQueryNamesFold)
, testCase "Querying Process Where Property Exists (Locally)"
(delayedAssertion
"expected the server to return only the relevant processes"
localNode True testFindByPropertySet)
, testCase "Querying Process Where Property Is Set To Specific Value (Locally)"
(delayedAssertion
"expected the server to return only the relevant processes"
localNode True testFindByPropertyValueSet)
]
, testGroup "Named Process Monitoring/Tracking"
[
testCase "Process Death Results In Unregistration"
(testProc testProcessDeathHandling)
, testCase "Monitoring Name Changes"
(testProc testMonitorName)
, testCase "Monitoring Name Changes (KeyOwnerChanged)"
(testProc testMonitorNameChange)
, testCase "Unmonitoring (Ignoring) Changes"
(delayedAssertion
"expected no further notifications after 'unmonitor' was called"
localNode True testUnmonitor)
, testCase "Monitoring Property Changes/Updates"
(delayedAssertion
"expected the server to send additional notifications for each change"
localNode True testMonitorPropertyChanged)
, testCase "Monitoring Property Owner Death"
(testProc testMonitorPropertyOwnerDied)
, testCase "Monitoring Registration"
(testProc testMonitorRegistration)
, testCase "Awaiting Registration"
(testProc testAwaitRegistration)
, testCase "Await without timeout"
(testProc testAwaitRegistrationNoTimeout)
, testCase "Server Died During Await"
(testProc testAwaitServerDied)
, testCase "Monitoring Unregistration"
(testProc testMonitorUnregistration)
]
]
main :: IO ()
main = testMain $ tests
|
589d5410e20f5a8cdf56951dc78aad3ef7749b7b1bea07784d89ff6bb66535a2 | ardumont/haskell-lab | CountingChange.hs | module CountingChange where
import Data.List
countchange :: Int -> [Int] -> Int
countchange m c = countChange m $ (reverse . sort) c
countChange :: Int -> [Int] -> Int
countChange _ [] = 0
countChange 0 _ = 1
countChange m c@(x:xs) = if m < 0
then 0
else countChange m xs + countChange (m - x) c
* CountingChange > countchange 300 [ 5,10,20,50,100,200,500 ] -- 1022
1022
* CountingChange > countchange 301 [ 5,10,20,50,100,200,500 ] -- 1022
0
* CountingChange > countchange 4 [ 5,10,20,50,100,200,500 ] -- 1022
0
* CountingChange > countchange 4 [ 1,2 ] -- 1022
3
* CountingChange > countchange 4 [ ] -- 1022
0
* CountingChange > countchange 0 [ 1,2 ] -- 1022
1
* CountingChange > countchange 100 [ 50,25,10,5,1 ]
292
| null | https://raw.githubusercontent.com/ardumont/haskell-lab/6d1f130300f33dc982c9a6b5d0b6a63af2c2666d/src/CountingChange.hs | haskell | 1022
1022
1022
1022
1022
1022 | module CountingChange where
import Data.List
countchange :: Int -> [Int] -> Int
countchange m c = countChange m $ (reverse . sort) c
countChange :: Int -> [Int] -> Int
countChange _ [] = 0
countChange 0 _ = 1
countChange m c@(x:xs) = if m < 0
then 0
else countChange m xs + countChange (m - x) c
1022
0
0
3
0
1
* CountingChange > countchange 100 [ 50,25,10,5,1 ]
292
|
9ffd35b54b49c7e76db7eab53da6e5be10131b81fcd62cc2be38da8ef4310d7c | flyspeck/flyspeck | itab.ml | (* ========================================================================= *)
(* Intuitionistic theorem prover (complete for propositional fragment). *)
(* *)
, University of Cambridge Computer Laboratory
(* *)
( c ) Copyright , University of Cambridge 1998
( c ) Copyright , 1998 - 2007
(* ========================================================================= *)
open Parser
include Tactics
(* ------------------------------------------------------------------------- *)
(* Accept a theorem modulo unification. *)
(* ------------------------------------------------------------------------- *)
let UNIFY_ACCEPT_TAC mvs th (asl,w) =
let insts = term_unify mvs (concl th) w in
([],insts),[],
let th' = INSTANTIATE insts th in
fun i [] -> INSTANTIATE i th';;
(* ------------------------------------------------------------------------- *)
(* The actual prover, as a tactic. *)
(* ------------------------------------------------------------------------- *)
let ITAUT_TAC =
let CONJUNCTS_THEN' ttac cth =
ttac(CONJUNCT1 cth) THEN ttac(CONJUNCT2 cth) in
let IMPLICATE t =
let th1 = AP_THM NOT_DEF (dest_neg t) in
CONV_RULE (RAND_CONV BETA_CONV) th1 in
let RIGHT_REVERSIBLE_TAC = FIRST
[CONJ_TAC; (* and *)
GEN_TAC; (* forall *)
DISCH_TAC; (* implies *)
(fun gl -> CONV_TAC(K(IMPLICATE(snd gl))) gl); (* not *)
EQ_TAC] (* iff *)
and LEFT_REVERSIBLE_TAC th gl = tryfind (fun ttac -> ttac th gl)
[CONJUNCTS_THEN' ASSUME_TAC; (* and *)
DISJ_CASES_TAC; (* or *)
CHOOSE_TAC; (* exists *)
(fun th -> ASSUME_TAC (EQ_MP (IMPLICATE (concl th)) th)); (* not *)
(CONJUNCTS_THEN' MP_TAC o uncurry CONJ o EQ_IMP_RULE)] (* iff *)
in
let rec ITAUT_TAC mvs n gl =
if n <= 0 then failwith "ITAUT_TAC: Too deep" else
((FIRST_ASSUM (UNIFY_ACCEPT_TAC mvs)) ORELSE
(ACCEPT_TAC TRUTH) ORELSE
(FIRST_ASSUM CONTR_TAC) ORELSE
(RIGHT_REVERSIBLE_TAC THEN TRY (ITAUT_TAC mvs n)) ORELSE
(FIRST_X_ASSUM LEFT_REVERSIBLE_TAC THEN TRY(ITAUT_TAC mvs n)) ORELSE
(FIRST_X_ASSUM(fun th -> ASSUME_TAC th THEN
(let gv = genvar(type_of(fst(dest_forall(concl th)))) in
META_SPEC_TAC gv th THEN
ITAUT_TAC (gv::mvs) (n - 2) THEN NO_TAC))) ORELSE
(DISJ1_TAC THEN ITAUT_TAC mvs n THEN NO_TAC) ORELSE
(DISJ2_TAC THEN ITAUT_TAC mvs n THEN NO_TAC) ORELSE
(fun gl -> let gv = genvar(type_of(fst(dest_exists(snd gl)))) in
(X_META_EXISTS_TAC gv THEN
ITAUT_TAC (gv::mvs) (n - 2) THEN NO_TAC) gl) ORELSE
(FIRST_ASSUM(fun th -> SUBGOAL_THEN (fst(dest_imp(concl th)))
(fun ath -> ASSUME_TAC (MP th ath)) THEN
ITAUT_TAC mvs (n - 1) THEN NO_TAC))) gl in
let rec ITAUT_ITERDEEP_TAC n gl =
remark ("Searching with limit "^(string_of_int n));
((ITAUT_TAC [] n THEN NO_TAC) ORELSE ITAUT_ITERDEEP_TAC (n + 1)) gl in
ITAUT_ITERDEEP_TAC 0;;
(* ------------------------------------------------------------------------- *)
(* Alternative interface. *)
(* ------------------------------------------------------------------------- *)
let ITAUT tm = prove(tm,ITAUT_TAC);;
print_endline "itab.ml loaded"
| null | https://raw.githubusercontent.com/flyspeck/flyspeck/05bd66666b4b641f49e5131a37830f4881f39db9/azure/hol-light-nat/itab.ml | ocaml | =========================================================================
Intuitionistic theorem prover (complete for propositional fragment).
=========================================================================
-------------------------------------------------------------------------
Accept a theorem modulo unification.
-------------------------------------------------------------------------
-------------------------------------------------------------------------
The actual prover, as a tactic.
-------------------------------------------------------------------------
and
forall
implies
not
iff
and
or
exists
not
iff
-------------------------------------------------------------------------
Alternative interface.
------------------------------------------------------------------------- | , University of Cambridge Computer Laboratory
( c ) Copyright , University of Cambridge 1998
( c ) Copyright , 1998 - 2007
open Parser
include Tactics
let UNIFY_ACCEPT_TAC mvs th (asl,w) =
let insts = term_unify mvs (concl th) w in
([],insts),[],
let th' = INSTANTIATE insts th in
fun i [] -> INSTANTIATE i th';;
let ITAUT_TAC =
let CONJUNCTS_THEN' ttac cth =
ttac(CONJUNCT1 cth) THEN ttac(CONJUNCT2 cth) in
let IMPLICATE t =
let th1 = AP_THM NOT_DEF (dest_neg t) in
CONV_RULE (RAND_CONV BETA_CONV) th1 in
let RIGHT_REVERSIBLE_TAC = FIRST
and LEFT_REVERSIBLE_TAC th gl = tryfind (fun ttac -> ttac th gl)
in
let rec ITAUT_TAC mvs n gl =
if n <= 0 then failwith "ITAUT_TAC: Too deep" else
((FIRST_ASSUM (UNIFY_ACCEPT_TAC mvs)) ORELSE
(ACCEPT_TAC TRUTH) ORELSE
(FIRST_ASSUM CONTR_TAC) ORELSE
(RIGHT_REVERSIBLE_TAC THEN TRY (ITAUT_TAC mvs n)) ORELSE
(FIRST_X_ASSUM LEFT_REVERSIBLE_TAC THEN TRY(ITAUT_TAC mvs n)) ORELSE
(FIRST_X_ASSUM(fun th -> ASSUME_TAC th THEN
(let gv = genvar(type_of(fst(dest_forall(concl th)))) in
META_SPEC_TAC gv th THEN
ITAUT_TAC (gv::mvs) (n - 2) THEN NO_TAC))) ORELSE
(DISJ1_TAC THEN ITAUT_TAC mvs n THEN NO_TAC) ORELSE
(DISJ2_TAC THEN ITAUT_TAC mvs n THEN NO_TAC) ORELSE
(fun gl -> let gv = genvar(type_of(fst(dest_exists(snd gl)))) in
(X_META_EXISTS_TAC gv THEN
ITAUT_TAC (gv::mvs) (n - 2) THEN NO_TAC) gl) ORELSE
(FIRST_ASSUM(fun th -> SUBGOAL_THEN (fst(dest_imp(concl th)))
(fun ath -> ASSUME_TAC (MP th ath)) THEN
ITAUT_TAC mvs (n - 1) THEN NO_TAC))) gl in
let rec ITAUT_ITERDEEP_TAC n gl =
remark ("Searching with limit "^(string_of_int n));
((ITAUT_TAC [] n THEN NO_TAC) ORELSE ITAUT_ITERDEEP_TAC (n + 1)) gl in
ITAUT_ITERDEEP_TAC 0;;
let ITAUT tm = prove(tm,ITAUT_TAC);;
print_endline "itab.ml loaded"
|
def4bec8450e68017f640aabb43c7a4e7b367d6a4e67c93835d449be5aa83a63 | runtimeverification/haskell-backend | AssociativeCommutative.hs | # LANGUAGE UndecidableInstances #
|
Module : Kore . Builtin . AssociativeCommutative
Description : Handles built - in operations which are associative , commutative ,
with neutral elements , key - based , with unique keys , and which
return bottom when applied to unique keys .
Copyright : ( c ) Runtime Verification , 2019 - 2021
License : BSD-3 - Clause
Maintainer :
This module is intended to be imported qualified , to avoid collision with other
builtin modules .
@
import qualified Kore . Builtin . AssociativeCommutative as Ac
@
Module : Kore.Builtin.AssociativeCommutative
Description : Handles built-in operations which are associative, commutative,
with neutral elements, key-based, with unique keys, and which
return bottom when applied to unique keys.
Copyright : (c) Runtime Verification, 2019-2021
License : BSD-3-Clause
Maintainer :
This module is intended to be imported qualified, to avoid collision with other
builtin modules.
@
import qualified Kore.Builtin.AssociativeCommutative as Ac
@
-}
module Kore.Builtin.AssociativeCommutative (
asInternalConcrete,
asPattern,
ConcatSymbol (..),
ConcreteElements (..),
evalConcatNormalizedOrBottom,
NormalizedOrBottom (..),
Opaque (..),
returnAc,
returnConcreteAc,
TermWrapper (..),
renormalize,
TermNormalizedAc,
unifyEqualsNormalized,
matchUnifyEqualsNormalizedAc,
UnitSymbol (..),
VariableElements (..),
UnifyEqualsNormAc (..),
) where
import Control.Error (
MaybeT,
)
import Control.Monad qualified as Monad
import Data.HashMap.Strict (
HashMap,
)
import Data.HashMap.Strict qualified as HashMap
import Data.HashSet (
HashSet,
)
import Data.HashSet qualified as HashSet
import Data.Kind (
Type,
)
import Data.List qualified
import Data.List qualified as List
import Data.Text (Text)
import GHC.Generics qualified as GHC
import Generics.SOP qualified as SOP
import Kore.Attribute.Pattern.Simplified qualified as Attribute (
Simplified,
)
import Kore.Attribute.Symbol qualified as Attribute (
Symbol,
)
import Kore.Builtin.Builtin qualified as Builtin
import Kore.Builtin.Map.Map qualified as Map
import Kore.Builtin.Set.Set qualified as Set
import Kore.Debug
import Kore.IndexedModule.MetadataTools (
SmtMetadataTools,
)
import Kore.Internal.Condition (
Condition,
)
import Kore.Internal.Condition qualified as Condition
import Kore.Internal.Conditional (
Conditional,
andCondition,
withCondition,
)
import Kore.Internal.Conditional qualified as Conditional
import Kore.Internal.InternalMap
import Kore.Internal.InternalSet
import Kore.Internal.Pattern (
Pattern,
)
import Kore.Internal.Pattern qualified as Pattern
import Kore.Internal.SideCondition qualified as SideCondition (
topTODO,
)
import Kore.Internal.Symbol (
Symbol,
)
import Kore.Internal.TermLike (
Key,
TermLike,
mkElemVar,
termLikeSort,
pattern App_,
pattern ElemVar_,
pattern InternalMap_,
pattern InternalSet_,
)
import Kore.Internal.TermLike qualified as TermLike
import Kore.Log.DebugUnifyBottom (
debugUnifyBottomAndReturnBottom,
)
import Kore.Rewrite.RewritingVariable (
RewritingVariableName,
)
import Kore.Simplify.Simplify as Simplifier
import Kore.Sort (
Sort,
sameSort,
)
import Kore.Syntax.Variable
import Kore.Unification.Unify (
MonadUnify,
)
import Kore.Unparser (
unparse,
unparseToString,
)
import Kore.Unparser qualified as Unparser
import Logic
import Prelude.Kore
import Pretty qualified
-- | Any @TermWrapper@ may be inside of an 'InternalAc'.
class
AcWrapper (normalized :: Type -> Type -> Type) =>
TermWrapper normalized
where
| Render a normalized value ( e.g. ' NormalizedSet ' ) as an ' InternalAc ' .
--
The result sort must be hooked to the builtin normalized sort ( e.g. ) .
asInternalBuiltin ::
SmtMetadataTools Attribute.Symbol ->
Sort ->
normalized Key child ->
InternalAc Key normalized child
TODO ( thomas.tuegel ): Use From .
| Render a normalized value ( e.g. ' NormalizedSet ' ) as a ' TermLike ' .
--
The result sort must be hooked to the builtin normalized sort ( e.g. ) .
asInternal ::
InternalVariable variable =>
SmtMetadataTools Attribute.Symbol ->
Sort ->
normalized Key (TermLike variable) ->
TermLike variable
|Transforms a @TermLike@ representation into a @NormalizedOrBottom@.
--
-- The term may become bottom if we had conflicts between elements that were
-- not detected before, e.g.
--
-- @
-- concat({1}, concat(X:Set, {1}))
-- concat(elem(Y:Int), concat({1}, elem(Y:Int)))
-- concat(X:Set, concat({1}, X:Set))
-- @
toNormalized ::
HasCallStack =>
Ord variable =>
Hashable variable =>
TermLike variable ->
NormalizedOrBottom normalized variable
| Pattern match on a ' TermLike ' to return a ' normalized ' .
--
-- @matchBuiltin@ returns 'Nothing' if the 'TermLike' does not wrap a
-- 'normalized' value.
matchBuiltin ::
TermLike variable ->
Maybe (normalized Key (TermLike variable))
simplifiedAttributeValue ::
Value normalized (TermLike variable) -> Attribute.Simplified
instance TermWrapper NormalizedMap where
asInternalBuiltin tools builtinAcSort builtinAcChild =
InternalAc
{ builtinAcSort
, builtinAcUnit = Builtin.lookupSymbolUnit tools builtinAcSort
, builtinAcElement = Builtin.lookupSymbolElement tools builtinAcSort
, builtinAcConcat = Builtin.lookupSymbolConcat tools builtinAcSort
, builtinAcChild
}
asInternal tools sort child =
TermLike.mkInternalMap (asInternalBuiltin tools sort child)
matchBuiltin (InternalMap_ internalMap) =
Just (builtinAcChild internalMap)
matchBuiltin _ = Nothing
toNormalized (InternalMap_ InternalAc{builtinAcChild}) =
maybe Bottom Normalized (renormalize builtinAcChild)
toNormalized (App_ symbol args)
| Map.isSymbolUnit symbol =
case args of
[] -> (Normalized . wrapAc) emptyNormalizedAc
_ -> Builtin.wrongArity "MAP.unit"
| Map.isSymbolElement symbol =
case args of
[key, value]
| Just key' <- TermLike.retractKey key ->
(Normalized . wrapAc)
NormalizedAc
{ elementsWithVariables = []
, concreteElements =
HashMap.singleton key' (MapValue value)
, opaque = []
}
| otherwise ->
(Normalized . wrapAc)
NormalizedAc
{ elementsWithVariables = [MapElement (key, value)]
, concreteElements = HashMap.empty
, opaque = []
}
_ -> Builtin.wrongArity "MAP.element"
| Map.isSymbolConcat symbol =
case args of
[map1, map2] -> toNormalized map1 <> toNormalized map2
_ -> Builtin.wrongArity "MAP.concat"
toNormalized patt =
(Normalized . wrapAc)
NormalizedAc
{ elementsWithVariables = []
, concreteElements = HashMap.empty
, opaque = [patt]
}
simplifiedAttributeValue = TermLike.simplifiedAttribute . getMapValue
instance TermWrapper NormalizedSet where
asInternalBuiltin tools builtinAcSort builtinAcChild =
InternalAc
{ builtinAcSort
, builtinAcUnit = Builtin.lookupSymbolUnit tools builtinAcSort
, builtinAcElement = Builtin.lookupSymbolElement tools builtinAcSort
, builtinAcConcat = Builtin.lookupSymbolConcat tools builtinAcSort
, builtinAcChild
}
asInternal tools sort child =
TermLike.mkInternalSet (asInternalBuiltin tools sort child)
matchBuiltin (InternalSet_ internalSet) =
Just (builtinAcChild internalSet)
matchBuiltin _ = Nothing
toNormalized (InternalSet_ InternalAc{builtinAcChild}) =
maybe Bottom Normalized (renormalize builtinAcChild)
toNormalized (App_ symbol args)
| Set.isSymbolUnit symbol =
case args of
[] -> (Normalized . wrapAc) emptyNormalizedAc
_ -> Builtin.wrongArity "SET.unit"
| Set.isSymbolElement symbol =
case args of
[elem1]
| Just elem1' <- TermLike.retractKey elem1 ->
(Normalized . wrapAc)
NormalizedAc
{ elementsWithVariables = []
, concreteElements = HashMap.singleton elem1' SetValue
, opaque = []
}
| otherwise ->
(Normalized . wrapAc)
NormalizedAc
{ elementsWithVariables = [SetElement elem1]
, concreteElements = HashMap.empty
, opaque = []
}
_ -> Builtin.wrongArity "SET.element"
| Set.isSymbolConcat symbol =
case args of
[set1, set2] -> toNormalized set1 <> toNormalized set2
_ -> Builtin.wrongArity "SET.concat"
toNormalized patt =
(Normalized . wrapAc)
emptyNormalizedAc{opaque = [patt]}
simplifiedAttributeValue SetValue = mempty
| Wrapper for terms that keeps the " concrete " vs " with variable " distinction
after converting @TermLike Concrete@ to @TermLike variable@.
after converting @TermLike Concrete@ to @TermLike variable@.
-}
data ConcreteOrWithVariable normalized variable
= ConcretePat (TermLike variable, Value normalized (TermLike variable))
| WithVariablePat (TermLike variable, Value normalized (TermLike variable))
instance
From
(ConcreteOrWithVariable normalized variable)
(TermLike variable, Value normalized (TermLike variable))
where
from =
\case
ConcretePat result -> result
WithVariablePat result -> result
fromConcreteOrWithVariable ::
ConcreteOrWithVariable normalized variable ->
(TermLike variable, Value normalized (TermLike variable))
fromConcreteOrWithVariable = from
-- | Particularizes @NormalizedAc@ to the most common types.
type TermNormalizedAc normalized variable =
normalized Key (TermLike variable)
{- | A normalized representation of an associative-commutative structure that
also allows bottom values.
-}
data NormalizedOrBottom collection variable
= Normalized (TermNormalizedAc collection variable)
| Bottom
deriving stock (GHC.Generic)
deriving stock instance
Eq (TermNormalizedAc collection variable) =>
Eq (NormalizedOrBottom collection variable)
deriving stock instance
Ord (TermNormalizedAc collection variable) =>
Ord (NormalizedOrBottom collection variable)
deriving stock instance
Show (TermNormalizedAc collection variable) =>
Show (NormalizedOrBottom collection variable)
instance SOP.Generic (NormalizedOrBottom collection variable)
instance SOP.HasDatatypeInfo (NormalizedOrBottom collection variable)
instance
Debug (collection Key (TermLike variable)) =>
Debug (NormalizedOrBottom collection variable)
instance
( Debug (collection Key (TermLike variable))
, Diff (collection Key (TermLike variable))
) =>
Diff (NormalizedOrBottom collection variable)
-- | The semigroup defined by the `concat` operation.
instance
(Ord variable, TermWrapper normalized, Hashable variable) =>
Semigroup (NormalizedOrBottom normalized variable)
where
Bottom <> _ = Bottom
_ <> Bottom = Bottom
Normalized normalized1 <> Normalized normalized2 =
maybe Bottom Normalized $ concatNormalized normalized1 normalized2
concatNormalized ::
forall normalized variable.
(TermWrapper normalized, Ord variable, Hashable variable) =>
normalized Key (TermLike variable) ->
normalized Key (TermLike variable) ->
Maybe (normalized Key (TermLike variable))
concatNormalized normalized1 normalized2 = do
Monad.guard disjointConcreteElements
abstract' <-
updateAbstractElements $ onBoth (++) elementsWithVariables
let concrete' = onBoth HashMap.union concreteElements
opaque' = Data.List.sort $ onBoth (++) opaque
renormalize $
wrapAc
NormalizedAc
{ elementsWithVariables = abstract'
, concreteElements = concrete'
, opaque = opaque'
}
where
onBoth ::
(a -> a -> r) ->
( NormalizedAc
normalized
Key
(TermLike variable) ->
a
) ->
r
onBoth f g = on f (g . unwrapAc) normalized1 normalized2
disjointConcreteElements =
null $ onBoth HashMap.intersection concreteElements
| Take a ( possibly de - normalized ) internal representation to its normal form .
@renormalize@ returns ' Nothing ' if the normal form is @\\bottom@.
First , abstract elements are converted to concrete elements wherever
possible . Second , any opaque terms which are actually builtins are combined with
the top - level term , so that the normal form never has children which are
internal representations themselves ; this " flattening " step also recurses to
@renormalize@ the previously - opaque children .
@renormalize@ returns 'Nothing' if the normal form is @\\bottom@.
First, abstract elements are converted to concrete elements wherever
possible. Second, any opaque terms which are actually builtins are combined with
the top-level term, so that the normal form never has children which are
internal representations themselves; this "flattening" step also recurses to
@renormalize@ the previously-opaque children.
-}
renormalize ::
(TermWrapper normalized, Ord variable, Hashable variable) =>
normalized Key (TermLike variable) ->
Maybe (normalized Key (TermLike variable))
renormalize = normalizeAbstractElements >=> flattenOpaque
-- | Insert the @key@-@value@ pair if it is missing from the 'Map'.
insertMissing ::
Ord key =>
Hashable key =>
key ->
value ->
HashMap key value ->
Maybe (HashMap key value)
insertMissing k v m
| HashMap.member k m = Nothing
| otherwise = Just (HashMap.insert k v m)
{- | Insert the new concrete elements into the 'Map'.
Return 'Nothing' if there are any duplicate keys.
-}
updateConcreteElements ::
HashMap Key value ->
[(Key, value)] ->
Maybe (HashMap Key value)
updateConcreteElements elems newElems =
foldrM (uncurry insertMissing) elems newElems
{- | Sort the abstract elements.
Return 'Nothing' if there are any duplicate keys.
-}
updateAbstractElements ::
(AcWrapper collection, Ord child, Hashable child) =>
[Element collection child] ->
Maybe [Element collection child]
updateAbstractElements elements =
fmap (map wrapElement . HashMap.toList) $
foldrM (uncurry insertMissing) HashMap.empty $
map unwrapElement elements
{- | Make any abstract elements into concrete elements if possible.
Return 'Nothing' if there are any duplicate (concrete or abstract) keys.
-}
normalizeAbstractElements ::
(TermWrapper normalized, Ord variable) =>
normalized Key (TermLike variable) ->
Maybe (normalized Key (TermLike variable))
normalizeAbstractElements (unwrapAc -> normalized) = do
concrete' <- updateConcreteElements concrete newConcrete
abstract' <- updateAbstractElements newAbstract
return $
wrapAc
NormalizedAc
{ elementsWithVariables = abstract'
, concreteElements = concrete'
, opaque = opaque normalized
}
where
abstract = elementsWithVariables normalized
concrete = concreteElements normalized
(newConcrete, newAbstract) =
partitionEithers (extractConcreteElement <$> abstract)
{- | 'Left' if the element's key can be concretized, or 'Right' if it
remains abstract.
-}
extractConcreteElement ::
AcWrapper collection =>
Element collection (TermLike variable) ->
Either
(Key, Value collection (TermLike variable))
(Element collection (TermLike variable))
extractConcreteElement element =
maybe (Right element) (Left . flip (,) value) (TermLike.retractKey key)
where
(key, value) = unwrapElement element
{- | Move any @normalized@ children to the top-level by concatenation.
@flattenOpaque@ recursively flattens the children of children, and so on.
-}
flattenOpaque ::
(TermWrapper normalized, Ord variable, Hashable variable) =>
normalized Key (TermLike variable) ->
Maybe (normalized Key (TermLike variable))
flattenOpaque (unwrapAc -> normalized) = do
let NormalizedAc{opaque} = normalized
(builtin, opaque') = partitionEithers (extractBuiltin <$> opaque)
transparent = wrapAc normalized{opaque = opaque'}
foldrM concatNormalized transparent builtin
where
extractBuiltin termLike =
maybe (Right termLike) Left (matchBuiltin termLike)
-- | The monoid defined by the `concat` and `unit` operations.
instance
(Ord variable, TermWrapper normalized, Hashable variable) =>
Monoid (NormalizedOrBottom normalized variable)
where
mempty = Normalized $ wrapAc emptyNormalizedAc
| Computes the union of two maps if they are disjoint . Returns @Nothing@
otherwise .
otherwise.
-}
addToMapDisjoint ::
(Ord a, Foldable t, Hashable a) =>
HashMap a b ->
t (a, b) ->
Maybe (HashMap a b)
addToMapDisjoint = Monad.foldM addElementDisjoint
addElementDisjoint ::
Ord a =>
Hashable a =>
HashMap a b ->
(a, b) ->
Maybe (HashMap a b)
addElementDisjoint existing (key, value) =
if key `HashMap.member` existing
then Nothing
else return (HashMap.insert key value existing)
-- | Given a @NormalizedAc@, returns it as a function result.
returnAc ::
( InternalVariable variable
, TermWrapper normalized
) =>
Sort ->
TermNormalizedAc normalized variable ->
Simplifier (Pattern variable)
returnAc resultSort ac = do
tools <- Simplifier.askMetadataTools
asInternal tools resultSort ac
& Pattern.fromTermLike
& return
{- | Converts an Ac of concrete elements to a @NormalizedAc@ and returns it
as a function result.
-}
returnConcreteAc ::
( InternalVariable variable
, TermWrapper normalized
) =>
Sort ->
HashMap Key (Value normalized (TermLike variable)) ->
Simplifier (Pattern variable)
returnConcreteAc resultSort concrete =
(returnAc resultSort . wrapAc)
NormalizedAc
{ elementsWithVariables = []
, concreteElements = concrete
, opaque = []
}
| The same as ' asInternal ' , but for ac structures made only of concrete
elements .
elements.
-}
asInternalConcrete ::
(InternalVariable variable, TermWrapper normalized) =>
SmtMetadataTools Attribute.Symbol ->
Sort ->
HashMap Key (Value normalized (TermLike variable)) ->
TermLike variable
asInternalConcrete tools sort1 concreteAc =
asInternal tools sort1 $
wrapAc
NormalizedAc
{ elementsWithVariables = []
, concreteElements = concreteAc
, opaque = []
}
elementListAsInternal ::
forall normalized variable.
(InternalVariable variable, TermWrapper normalized) =>
SmtMetadataTools Attribute.Symbol ->
Sort ->
[(TermLike variable, Value normalized (TermLike variable))] ->
Maybe (TermLike variable)
elementListAsInternal tools sort1 terms =
asInternal tools sort1 . wrapAc
<$> elementListAsNormalized terms
elementListAsNormalized ::
forall normalized variable.
(InternalVariable variable, TermWrapper normalized) =>
[(TermLike variable, Value normalized (TermLike variable))] ->
Maybe (NormalizedAc normalized Key (TermLike variable))
elementListAsNormalized terms = do
let (withVariables, concrete) = splitVariableConcrete terms
_checkDisjoinVariables <- disjointMap withVariables
concreteAc <- disjointMap concrete
return
NormalizedAc
{ elementsWithVariables = wrapElement <$> withVariables
, concreteElements = concreteAc
, opaque = []
}
| Render a ' NormalizedAc ' as an extended domain value pattern .
asPattern ::
( InternalVariable variable
, TermWrapper normalized
) =>
SmtMetadataTools Attribute.Symbol ->
Sort ->
TermNormalizedAc normalized variable ->
Pattern variable
asPattern tools resultSort =
Pattern.fromTermLike . asInternal tools resultSort
| Evaluates a concatenation of two AC structures represented as
NormalizedOrBottom , providind the result in the form of a function result .
NormalizedOrBottom, providind the result in the form of a function result.
-}
evalConcatNormalizedOrBottom ::
forall normalized variable.
( InternalVariable variable
, TermWrapper normalized
) =>
Sort ->
NormalizedOrBottom normalized variable ->
NormalizedOrBottom normalized variable ->
MaybeT Simplifier (Pattern variable)
evalConcatNormalizedOrBottom resultSort Bottom _ =
return (Pattern.bottomOf resultSort)
evalConcatNormalizedOrBottom resultSort _ Bottom =
return (Pattern.bottomOf resultSort)
evalConcatNormalizedOrBottom
resultSort
(Normalized normalized1)
(Normalized normalized2) =
maybe (return $ Pattern.bottomOf resultSort) (lift . returnAc resultSort) $
concatNormalized normalized1 normalized2
disjointMap :: Ord a => Hashable a => [(a, b)] -> Maybe (HashMap a b)
disjointMap = addToMapDisjoint HashMap.empty
splitVariableConcrete ::
forall variable a.
[(TermLike variable, a)] ->
([(TermLike variable, a)], [(Key, a)])
splitVariableConcrete terms =
partitionEithers (map toConcreteEither terms)
where
toConcreteEither ::
(TermLike variable, a) ->
Either (TermLike variable, a) (Key, a)
toConcreteEither (term, a) =
case TermLike.retractKey term of
Nothing -> Left (term, a)
Just result -> Right (result, a)
| Simplify the conjunction or equality of two Ac domain values in their
normalized form .
When it is used for simplifying equality , one should separately solve the
case ⊥ = ⊥. One should also throw away the term in the returned pattern .
The domain values are assumed to have the same sort , but this is not checked . If
multiple sorts are hooked to the same builtin domain , the verifier should
reject the definition .
normalized form.
When it is used for simplifying equality, one should separately solve the
case ⊥ = ⊥. One should also throw away the term in the returned pattern.
The domain values are assumed to have the same sort, but this is not checked. If
multiple sorts are hooked to the same builtin domain, the verifier should
reject the definition.
-}
unifyEqualsNormalized ::
forall normalized unifier.
( Traversable (Value normalized)
, TermWrapper normalized
, MonadUnify unifier
) =>
HasCallStack =>
SmtMetadataTools Attribute.Symbol ->
TermLike RewritingVariableName ->
TermLike RewritingVariableName ->
( TermLike RewritingVariableName ->
TermLike RewritingVariableName ->
unifier (Pattern RewritingVariableName)
) ->
InternalAc Key normalized (TermLike RewritingVariableName) ->
InternalAc Key normalized (TermLike RewritingVariableName) ->
UnifyEqualsNormAc normalized RewritingVariableName ->
unifier (Pattern RewritingVariableName)
unifyEqualsNormalized
tools
first
second
unifyEqualsChildren
normalized1
normalized2
unifyData =
do
let InternalAc{builtinAcChild = firstNormalized} =
normalized1
InternalAc{builtinAcChild = secondNormalized} =
normalized2
unifierNormalized <-
unifyEqualsNormalizedAc
tools
first
second
unifyEqualsChildren
firstNormalized
secondNormalized
unifyData
let unifierNormalizedTerm ::
TermNormalizedAc normalized RewritingVariableName
unifierCondition :: Condition RewritingVariableName
(unifierNormalizedTerm, unifierCondition) =
Conditional.splitTerm unifierNormalized
normalizedTerm :: TermLike RewritingVariableName
normalizedTerm = asInternal tools sort1 unifierNormalizedTerm
-- TODO(virgil): Check whether this normalization is still needed
-- (the normalizedTerm may already be re-normalized) and remove it if not.
renormalized <- normalize1 normalizedTerm
let unifierTerm :: TermLike RewritingVariableName
unifierTerm = markSimplified $ asInternal tools sort1 renormalized
markSimplified =
TermLike.setSimplified
( foldMap TermLike.simplifiedAttribute opaque
<> foldMap TermLike.simplifiedAttribute abstractKeys
<> foldMap simplifiedAttributeValue abstractValues
<> foldMap simplifiedAttributeValue concreteValues
)
where
unwrapped = unwrapAc renormalized
NormalizedAc{opaque} = unwrapped
(abstractKeys, abstractValues) =
(unzip . map unwrapElement)
(elementsWithVariables unwrapped)
(_, concreteValues) =
(unzip . HashMap.toList)
(concreteElements unwrapped)
return (unifierTerm `Pattern.withCondition` unifierCondition)
where
sort1 = termLikeSort first
normalize1 ::
HasCallStack =>
InternalVariable variable =>
TermLike variable ->
unifier (TermNormalizedAc normalized variable)
normalize1 patt =
case toNormalized patt of
Bottom ->
debugUnifyBottomAndReturnBottom
"Duplicated elements in normalization."
first
second
Normalized n -> return n
data UnifyEqualsElementListsData normalized = UnifyEqualsElementListsData
Given normalized data norm1 , norm2 , norm1 - norm2 and norm2 - norm1
allElements1, allElements2 :: ![ConcreteOrWithVariable normalized RewritingVariableName]
Is Just v if v is the sole opaque in norm1 - norm2 , else Nothing
maybeVar :: !(Maybe (ElementVariable RewritingVariableName))
}
data UnifyEqualsNormAc normalized variable
= UnifyEqualsElementLists !(UnifyEqualsElementListsData normalized)
| UnifyOpaqueVar !(UnifyOpVarResult variable)
matchUnifyEqualsNormalizedAc ::
forall normalized.
TermWrapper normalized =>
SmtMetadataTools Attribute.Symbol ->
InternalAc Key normalized (TermLike RewritingVariableName) ->
InternalAc Key normalized (TermLike RewritingVariableName) ->
Maybe (UnifyEqualsNormAc normalized RewritingVariableName)
matchUnifyEqualsNormalizedAc
tools
normalized1
normalized2 =
case (opaqueDifference1, opaqueDifference2) of
([], []) ->
Just $
UnifyEqualsElementLists $
UnifyEqualsElementListsData
allElements1
allElements2
Nothing
([ElemVar_ v1], _)
| null opaqueDifference2 ->
Just $
UnifyEqualsElementLists $
UnifyEqualsElementListsData
allElements1
allElements2
(Just v1)
| null allElements1 ->
fmap UnifyOpaqueVar $
matchUnifyOpaqueVariable'
v1
allElements2
opaqueDifference2
_ -> Nothing
where
matchUnifyOpaqueVariable' =
matchUnifyOpaqueVariable tools
listToMap :: Hashable a => [a] -> HashMap a Int
listToMap keys = HashMap.fromListWith (+) [(k, 1) | k <- keys]
mapToList :: HashMap a Int -> [a]
mapToList =
HashMap.foldrWithKey
(\key count result -> replicate count key ++ result)
[]
NormalizedAc
{ elementsWithVariables = preElementsWithVariables1
, concreteElements = concreteElements1
, opaque = opaque1
} =
unwrapAc firstNormalized
NormalizedAc
{ elementsWithVariables = preElementsWithVariables2
, concreteElements = concreteElements2
, opaque = opaque2
} =
unwrapAc secondNormalized
InternalAc{builtinAcChild = firstNormalized} =
normalized1
InternalAc{builtinAcChild = secondNormalized} =
normalized2
opaque1Map = listToMap opaque1
opaque2Map = listToMap opaque2
elementsWithVariables1 = unwrapElement <$> preElementsWithVariables1
elementsWithVariables2 = unwrapElement <$> preElementsWithVariables2
elementsWithVariables1Map = HashMap.fromList elementsWithVariables1
elementsWithVariables2Map = HashMap.fromList elementsWithVariables2
commonElements =
HashMap.intersectionWith
(,)
concreteElements1
concreteElements2
commonVariables =
HashMap.intersectionWith
(,)
elementsWithVariables1Map
elementsWithVariables2Map
-- Duplicates must be kept in case any of the opaque terms turns out to be
non - empty , in which case one of the terms is bottom , which
-- means that the unification result is bottom.
commonOpaqueMap = HashMap.intersectionWith max opaque1Map opaque2Map
commonOpaqueKeys = HashMap.keysSet commonOpaqueMap
elementDifference1 =
HashMap.toList (HashMap.difference concreteElements1 commonElements)
elementDifference2 =
HashMap.toList (HashMap.difference concreteElements2 commonElements)
elementVariableDifference1 =
HashMap.toList (HashMap.difference elementsWithVariables1Map commonVariables)
elementVariableDifference2 =
HashMap.toList (HashMap.difference elementsWithVariables2Map commonVariables)
opaqueDifference1 =
mapToList (withoutKeys opaque1Map commonOpaqueKeys)
opaqueDifference2 =
mapToList (withoutKeys opaque2Map commonOpaqueKeys)
withoutKeys ::
Hashable k =>
HashMap k v ->
HashSet k ->
HashMap k v
withoutKeys hmap hset = hmap `HashMap.difference` (HashSet.toMap hset)
allElements1 =
map WithVariablePat elementVariableDifference1
++ map toConcretePat elementDifference1
allElements2 =
map WithVariablePat elementVariableDifference2
++ map toConcretePat elementDifference2
toConcretePat ::
(Key, Value normalized (TermLike RewritingVariableName)) ->
ConcreteOrWithVariable
normalized
RewritingVariableName
toConcretePat (a, b) =
ConcretePat (from @Key @(TermLike RewritingVariableName) a, b)
| two AC structs represented as @NormalizedAc@.
Currently allows at most one opaque term in the two arguments taken together .
Currently allows at most one opaque term in the two arguments taken together.
-}
unifyEqualsNormalizedAc ::
forall normalized unifier.
( Traversable (Value normalized)
, TermWrapper normalized
, MonadUnify unifier
) =>
SmtMetadataTools Attribute.Symbol ->
TermLike RewritingVariableName ->
TermLike RewritingVariableName ->
( TermLike RewritingVariableName ->
TermLike RewritingVariableName ->
unifier (Pattern RewritingVariableName)
) ->
TermNormalizedAc normalized RewritingVariableName ->
TermNormalizedAc normalized RewritingVariableName ->
UnifyEqualsNormAc normalized RewritingVariableName ->
unifier
( Conditional
RewritingVariableName
(TermNormalizedAc normalized RewritingVariableName)
)
unifyEqualsNormalizedAc
tools
first
second
unifyEqualsChildren
normalized1
normalized2
unifyData =
do
(simpleUnifier, opaques) <- case unifyData of
UnifyEqualsElementLists unifyData' ->
unifyEqualsElementLists'
allElements1
allElements2
maybeVar
where
UnifyEqualsElementListsData{allElements1, allElements2, maybeVar} = unifyData'
UnifyOpaqueVar unifyData' ->
unifyOpaqueVariable
bottomWithExplanation
unifyEqualsChildren
unifyData'
let (unifiedElements, unifierCondition) =
Conditional.splitTerm simpleUnifier
do
-- unifier monad
-- unify the parts not sent to unifyEqualsNormalizedElements.
(commonElementsTerms, commonElementsCondition) <-
unifyElementList (HashMap.toList commonElements)
(commonVariablesTerms, commonVariablesCondition) <-
unifyElementList (HashMap.toList commonVariables)
-- simplify results so that things like inj applications that
-- may have been broken into smaller pieces are being put
-- back together.
unifiedSimplified <- mapM simplifyPair unifiedElements
opaquesSimplified <- mapM simplify opaques
buildResultFromUnifiers
bottomWithExplanation
commonElementsTerms
commonVariablesTerms
commonOpaque
unifiedSimplified
opaquesSimplified
[ unifierCondition
, commonElementsCondition
, commonVariablesCondition
]
where
listToMap :: Hashable a => [a] -> HashMap a Int
listToMap keys = HashMap.fromListWith (+) [(k, 1) | k <- keys]
mapToList :: HashMap a Int -> [a]
mapToList =
HashMap.foldrWithKey
(\key count result -> replicate count key ++ result)
[]
bottomWithExplanation :: Text -> unifier a
bottomWithExplanation explanation =
debugUnifyBottomAndReturnBottom explanation first second
unifyEqualsElementLists' =
unifyEqualsElementLists
tools
first
second
unifyEqualsChildren
NormalizedAc
{ elementsWithVariables = preElementsWithVariables1
, concreteElements = concreteElements1
, opaque = opaque1
} =
unwrapAc normalized1
NormalizedAc
{ elementsWithVariables = preElementsWithVariables2
, concreteElements = concreteElements2
, opaque = opaque2
} =
unwrapAc normalized2
opaque1Map = listToMap opaque1
opaque2Map = listToMap opaque2
elementsWithVariables1 = unwrapElement <$> preElementsWithVariables1
elementsWithVariables2 = unwrapElement <$> preElementsWithVariables2
elementsWithVariables1Map = HashMap.fromList elementsWithVariables1
elementsWithVariables2Map = HashMap.fromList elementsWithVariables2
commonElements =
HashMap.intersectionWith
(,)
concreteElements1
concreteElements2
commonVariables =
HashMap.intersectionWith
(,)
elementsWithVariables1Map
elementsWithVariables2Map
-- Duplicates must be kept in case any of the opaque terms turns out to be
non - empty , in which case one of the terms is bottom , which
-- means that the unification result is bottom.
commonOpaqueMap = HashMap.intersectionWith max opaque1Map opaque2Map
commonOpaque = mapToList commonOpaqueMap
unifyElementList ::
forall key.
[ ( key
, ( Value normalized (TermLike RewritingVariableName)
, Value normalized (TermLike RewritingVariableName)
)
)
] ->
unifier
( [(key, Value normalized (TermLike RewritingVariableName))]
, Condition RewritingVariableName
)
unifyElementList elements = do
result <- mapM (unifyCommonElements unifyEqualsChildren) elements
let terms :: [(key, Value normalized (TermLike RewritingVariableName))]
predicates :: [Condition RewritingVariableName]
(terms, predicates) = unzip (map Conditional.splitTerm result)
predicate :: Condition RewritingVariableName
predicate =
List.foldl'
andCondition
Condition.top
predicates
return (terms, predicate)
simplify ::
TermLike RewritingVariableName ->
unifier (Pattern RewritingVariableName)
simplify term =
mapLogicT liftSimplifier (simplifyPatternScatter SideCondition.topTODO (Pattern.fromTermLike term))
& lowerLogicT
simplifyPair ::
( TermLike RewritingVariableName
, Value normalized (TermLike RewritingVariableName)
) ->
unifier
( Conditional
RewritingVariableName
( TermLike RewritingVariableName
, Value normalized (TermLike RewritingVariableName)
)
)
simplifyPair (key, value) = do
simplifiedKey <- simplifyTermLike' key
let (keyTerm, keyCondition) = Conditional.splitTerm simplifiedKey
simplifiedValue <- traverse simplifyTermLike' value
let splitSimplifiedValue ::
Value
normalized
( TermLike RewritingVariableName
, Condition RewritingVariableName
)
splitSimplifiedValue =
fmap Conditional.splitTerm simplifiedValue
simplifiedValueTerm ::
Value normalized (TermLike RewritingVariableName)
simplifiedValueTerm = fmap fst splitSimplifiedValue
simplifiedValueConditions ::
Value normalized (Condition RewritingVariableName)
simplifiedValueConditions = fmap snd splitSimplifiedValue
simplifiedValueCondition :: Condition RewritingVariableName
simplifiedValueCondition =
foldr
andCondition
Condition.top
simplifiedValueConditions
return
( (keyTerm, simplifiedValueTerm)
`withCondition` keyCondition
`andCondition` simplifiedValueCondition
)
where
-- TODO: can this be rewritten?
simplifyTermLike' ::
TermLike RewritingVariableName ->
unifier (Pattern RewritingVariableName)
simplifyTermLike' term =
mapLogicT liftSimplifier (simplifyPatternScatter SideCondition.topTODO (Pattern.fromTermLike term))
& lowerLogicT
buildResultFromUnifiers ::
forall normalized unifier variable.
( Monad unifier
, InternalVariable variable
, TermWrapper normalized
) =>
(forall result. Text -> unifier result) ->
[(Key, Value normalized (TermLike variable))] ->
[(TermLike variable, Value normalized (TermLike variable))] ->
[TermLike variable] ->
[ Conditional
variable
(TermLike variable, Value normalized (TermLike variable))
] ->
[Pattern variable] ->
[Condition variable] ->
unifier (Conditional variable (TermNormalizedAc normalized variable))
buildResultFromUnifiers
bottomWithExplanation
commonElementsTerms
commonVariablesTerms
commonOpaque
unifiedElementsSimplified
opaquesSimplified
predicates =
do
-- unifier monad
let almostResultTerms ::
[ ( TermLike variable
, Value normalized (TermLike variable)
)
]
almostResultConditions :: [Condition variable]
(almostResultTerms, almostResultConditions) =
unzip (map Conditional.splitTerm unifiedElementsSimplified)
(withVariableTerms, concreteTerms) =
splitVariableConcrete almostResultTerms
(opaquesTerms, opaquesConditions) =
unzip (map Conditional.splitTerm opaquesSimplified)
opaquesNormalized :: NormalizedOrBottom normalized variable
opaquesNormalized = foldMap toNormalized opaquesTerms
NormalizedAc
{ elementsWithVariables = preOpaquesElementsWithVariables
, concreteElements = opaquesConcreteTerms
, opaque = opaquesOpaque
} <- case opaquesNormalized of
Bottom ->
bottomWithExplanation "Duplicated elements after unification."
Normalized result -> return (unwrapAc result)
let opaquesElementsWithVariables =
unwrapElement <$> preOpaquesElementsWithVariables
-- Add back all the common objects that were removed before
-- unification.
withVariableMap <-
addAllDisjoint
bottomWithExplanation
HashMap.empty
( commonVariablesTerms
++ withVariableTerms
++ opaquesElementsWithVariables
)
concreteMap <-
addAllDisjoint
bottomWithExplanation
HashMap.empty
( commonElementsTerms
++ concreteTerms
++ HashMap.toList opaquesConcreteTerms
)
let allOpaque = Data.List.sort (commonOpaque ++ opaquesOpaque)
-- Merge all unification predicates.
predicate =
List.foldl'
andCondition
Condition.top
(almostResultConditions ++ opaquesConditions ++ predicates)
result ::
Conditional
variable
(normalized Key (TermLike variable))
result =
wrapAc
NormalizedAc
{ elementsWithVariables =
wrapElement <$> HashMap.toList withVariableMap
, concreteElements = concreteMap
, opaque = allOpaque
}
`Conditional.withCondition` predicate
return result
addAllDisjoint ::
(Monad unifier, Ord a, Hashable a) =>
(forall result. Text -> unifier result) ->
HashMap a b ->
[(a, b)] ->
unifier (HashMap a b)
addAllDisjoint bottomWithExplanation existing elements =
case addToMapDisjoint existing elements of
Nothing ->
bottomWithExplanation "Duplicated elements after AC unification."
Just result -> return result
unifyCommonElements ::
forall key normalized unifier variable.
( AcWrapper normalized
, MonadUnify unifier
, InternalVariable variable
, Traversable (Value normalized)
) =>
(TermLike variable -> TermLike variable -> unifier (Pattern variable)) ->
( key
, ( Value normalized (TermLike variable)
, Value normalized (TermLike variable)
)
) ->
unifier
( Conditional
variable
(key, Value normalized (TermLike variable))
)
unifyCommonElements
unifier
(key, (firstValue, secondValue)) =
do
valuesUnifier <- unifyWrappedValues unifier firstValue secondValue
let (valuesTerm, valueCondition) = Conditional.splitTerm valuesUnifier
return ((key, valuesTerm) `withCondition` valueCondition)
unifyWrappedValues ::
forall normalized unifier variable.
( AcWrapper normalized
, MonadUnify unifier
, InternalVariable variable
, Traversable (Value normalized)
) =>
(TermLike variable -> TermLike variable -> unifier (Pattern variable)) ->
Value normalized (TermLike variable) ->
Value normalized (TermLike variable) ->
unifier
(Conditional variable (Value normalized (TermLike variable)))
unifyWrappedValues unifier firstValue secondValue = do
let aligned = alignValues firstValue secondValue
unifiedValues <- traverse (uncurry unifier) aligned
let splitValues ::
Value normalized (TermLike variable, Condition variable)
splitValues = fmap Pattern.splitTerm unifiedValues
valueUnifierTerm :: Value normalized (TermLike variable)
valueUnifierTerm = fmap fst splitValues
valueConditions :: Value normalized (Condition variable)
valueConditions = fmap snd splitValues
valueUnifierCondition :: Condition variable
valueUnifierCondition =
foldr Conditional.andCondition Condition.top valueConditions
return (valueUnifierTerm `withCondition` valueUnifierCondition)
| two ac structures given their representation as a list of
@ConcreteOrWithVariable@ , with the first structure being allowed an additional
opaque chunk ( e.g. a variable ) that will be sent to the unifier function
together with some part of the second structure .
The keys of the two structures are assumend to be disjoint .
@ConcreteOrWithVariable@, with the first structure being allowed an additional
opaque chunk (e.g. a variable) that will be sent to the unifier function
together with some part of the second structure.
The keys of the two structures are assumend to be disjoint.
-}
unifyEqualsElementLists ::
forall normalized variable unifier.
( InternalVariable variable
, MonadUnify unifier
, TermWrapper normalized
, Traversable (Value normalized)
) =>
SmtMetadataTools Attribute.Symbol ->
TermLike variable ->
TermLike variable ->
-- | unifier function
(TermLike variable -> TermLike variable -> unifier (Pattern variable)) ->
| First structure elements
[ConcreteOrWithVariable normalized variable] ->
| Second structure elements
[ConcreteOrWithVariable normalized variable] ->
| Opaque element variable of the first structure
Maybe (ElementVariable variable) ->
unifier
( Conditional
variable
[(TermLike variable, Value normalized (TermLike variable))]
, [TermLike variable]
)
unifyEqualsElementLists
_tools
first
second
unifyEqualsChildren
firstElements
secondElements
Nothing
| length firstElements /= length secondElements =
Neither the first , not the second ac structure include an opaque term , so
the listed elements form the two structures .
--
Since the two lists have different counts , their structures can
-- never unify.
debugUnifyBottomAndReturnBottom
"Cannot unify ac structures with different sizes."
first
second
| otherwise = do
(result, remainder1, remainder2) <-
unifyWithPermutations firstElements secondElements
The second structure does not include an opaque term so there is nothing
to match whatever is left in remainder1 . This should have been caught by
-- the "length" check above so, most likely, this can be an assertion.
unless
(null remainder1)
(remainderError firstElements secondElements remainder1)
The first structure does not include an opaque term so there is nothing
to match whatever is left in remainder2 . This should have been caught by
-- the "length" check above so, most likely, this can be an assertion.
unless
(null remainder2)
(remainderError firstElements secondElements remainder2)
return (result, [])
where
unifyWithPermutations ::
First structure elements
[ConcreteOrWithVariable normalized variable] ->
Second structure elements
[ConcreteOrWithVariable normalized variable] ->
unifier
( Conditional
variable
[ ( TermLike variable
, Value normalized (TermLike variable)
)
]
, [ConcreteOrWithVariable normalized variable]
, [ConcreteOrWithVariable normalized variable]
)
unifyWithPermutations =
unifyEqualsElementPermutations
(unifyEqualsConcreteOrWithVariable unifyEqualsChildren)
remainderError = nonEmptyRemainderError first second
unifyEqualsElementLists
tools
first
second
unifyEqualsChildren
firstElements
secondElements
(Just opaqueElemVar)
| length firstElements > length secondElements =
The second structure does not include an opaque term , so all the
elements in the first structure must be matched by elements in the second
-- one. Since we don't have enough, we return bottom.
debugUnifyBottomAndReturnBottom
"Cannot unify ac structures with different sizes."
first
second
| otherwise = do
(unifier, remainder1, remainder2) <-
unifyWithPermutations firstElements secondElements
The second structure does not include an opaque term so there is nothing
to match whatever is left in remainder1 . This should have been caught by
-- the "length" check above so, most likely, this can be an assertion.
unless
(null remainder1)
(remainderError firstElements secondElements remainder1)
let remainder2Terms = map fromConcreteOrWithVariable remainder2
case elementListAsInternal
tools
(sameSort (termLikeSort first) (termLikeSort second))
remainder2Terms of
Nothing ->
debugUnifyBottomAndReturnBottom
"Duplicated element in unification results"
first
second
Just remainderTerm
| TermLike.isFunctionPattern remainderTerm -> do
opaqueUnifier <-
unifyEqualsChildren
(mkElemVar opaqueElemVar)
remainderTerm
let (opaqueTerm, opaqueCondition) =
Pattern.splitTerm opaqueUnifier
result = unifier `andCondition` opaqueCondition
return (result, [opaqueTerm])
_ ->
error . show . Pretty.vsep $
[ "Unification case that should be handled somewhere else: \
\attempting normalized unification with \
\non-function maps could lead to infinite loops."
, Pretty.indent 2 "first="
, Pretty.indent 4 (unparse first)
, Pretty.indent 2 "second="
, Pretty.indent 4 (unparse second)
]
where
unifyWithPermutations =
unifyEqualsElementPermutations
(unifyEqualsConcreteOrWithVariable unifyEqualsChildren)
remainderError = nonEmptyRemainderError first second
data NoCheckUnifyOpaqueChildrenData variable = NoCheckUnifyOpaqueChildrenData
Given normalized data norm1 , , the sole opaque variable in norm1 - norm2
v1 :: !(TermLike.ElementVariable variable)
, -- The term to unify against v1
second :: !(TermLike variable)
}
data UnifyOpVarResult variable
= NoCheckUnifyOpaqueChildren !(NoCheckUnifyOpaqueChildrenData variable)
| BottomWithExplanation
matchUnifyOpaqueVariable ::
( TermWrapper normalized
, InternalVariable variable
) =>
SmtMetadataTools Attribute.Symbol ->
TermLike.ElementVariable variable ->
[ConcreteOrWithVariable normalized variable] ->
[TermLike variable] ->
Maybe (UnifyOpVarResult variable)
matchUnifyOpaqueVariable _ v1 [] [second@(ElemVar_ _)] =
Just $ NoCheckUnifyOpaqueChildren NoCheckUnifyOpaqueChildrenData{v1, second}
matchUnifyOpaqueVariable
tools
v1
concreteOrVariableTerms
opaqueTerms =
case elementListAsNormalized pairs of
Nothing -> Just BottomWithExplanation
Just elementTerm ->
let secondTerm =
asInternal
tools
sort
( wrapAc
elementTerm{opaque = opaqueTerms}
)
in if TermLike.isFunctionPattern secondTerm
then
Just $
NoCheckUnifyOpaqueChildren $
NoCheckUnifyOpaqueChildrenData v1 secondTerm
else Nothing
where
sort = variableSort v1
pairs = map fromConcreteOrWithVariable concreteOrVariableTerms
unifyOpaqueVariable ::
( MonadUnify unifier
, InternalVariable variable
) =>
(forall a. Text -> unifier a) ->
-- | unifier function
(TermLike variable -> TermLike variable -> unifier (Pattern variable)) ->
UnifyOpVarResult variable ->
unifier
( Conditional
variable
[(TermLike variable, Value normalized (TermLike variable))]
, [TermLike variable]
)
unifyOpaqueVariable
bottomWithExplanation
unifyChildren
unifyData =
case unifyData of
NoCheckUnifyOpaqueChildren unifyData' ->
noCheckUnifyOpaqueChildren unifyChildren v1 second
where
NoCheckUnifyOpaqueChildrenData{v1, second} = unifyData'
_ ->
bottomWithExplanation
"Duplicated element in unification results"
noCheckUnifyOpaqueChildren ::
( MonadUnify unifier
, InternalVariable variable
) =>
(TermLike variable -> TermLike variable -> unifier (Pattern variable)) ->
TermLike.ElementVariable variable ->
TermLike variable ->
unifier
( Conditional
variable
[(TermLike variable, Value normalized (TermLike variable))]
, [TermLike variable]
)
noCheckUnifyOpaqueChildren unifyChildren v1 second = do
unifier <- unifyChildren (mkElemVar v1) second
let (opaque, predicate) = Conditional.splitTerm unifier
return ([] `Conditional.withCondition` predicate, [opaque])
|Unifies two patterns represented as @ConcreteOrWithVariable@ , making sure
that a concrete pattern ( if any ) is sent on the first position of the unify
function .
We prefer having a concrete pattern on the first position because the
unifier prefers returning it when it does not know what to use , e.g.
@
unify 10 ( f A ) = = > 10 and ( 10 = = f A )
unify ( f A ) 10 = = > ( f A ) and ( 10 = = f A )
@
and it would probably be more useful to have a concrete term as the
unification term . Also , tests are easier to write .
that a concrete pattern (if any) is sent on the first position of the unify
function.
We prefer having a concrete pattern on the first position because the
unifier prefers returning it when it does not know what to use, e.g.
@
unify 10 (f A) ==> 10 and (10 == f A)
unify (f A) 10 ==> (f A) and (10 == f A)
@
and it would probably be more useful to have a concrete term as the
unification term. Also, tests are easier to write.
-}
unifyEqualsConcreteOrWithVariable ::
( AcWrapper normalized
, MonadUnify unifier
, Traversable (Value normalized)
, InternalVariable variable
) =>
(TermLike variable -> TermLike variable -> unifier (Pattern variable)) ->
ConcreteOrWithVariable normalized variable ->
ConcreteOrWithVariable normalized variable ->
unifier
( Conditional
variable
(TermLike variable, Value normalized (TermLike variable))
)
unifyEqualsConcreteOrWithVariable
unifier
(ConcretePat concrete1)
(ConcretePat concrete2) =
unifyEqualsPair unifier concrete1 concrete2
unifyEqualsConcreteOrWithVariable
unifier
(ConcretePat concrete1)
(WithVariablePat withVariable2) =
unifyEqualsPair unifier concrete1 withVariable2
unifyEqualsConcreteOrWithVariable
unifier
(WithVariablePat withVariable)
(ConcretePat concrete2) =
unifyEqualsPair unifier concrete2 withVariable
unifyEqualsConcreteOrWithVariable
unifier
(WithVariablePat withVariable)
(WithVariablePat withVariable2) =
unifyEqualsPair unifier withVariable withVariable2
unifyEqualsPair ::
forall normalized unifier variable.
( AcWrapper normalized
, MonadUnify unifier
, InternalVariable variable
, Traversable (Value normalized)
) =>
(TermLike variable -> TermLike variable -> unifier (Pattern variable)) ->
(TermLike variable, Value normalized (TermLike variable)) ->
(TermLike variable, Value normalized (TermLike variable)) ->
unifier
( Conditional
variable
(TermLike variable, Value normalized (TermLike variable))
)
unifyEqualsPair
unifier
(firstKey, firstValue)
(secondKey, secondValue) =
do
keyUnifier <- unifier firstKey secondKey
valueUnifier <- unifyWrappedValues unifier firstValue secondValue
let valueUnifierTerm :: Value normalized (TermLike variable)
valueUnifierCondition :: Condition variable
(valueUnifierTerm, valueUnifierCondition) =
Conditional.splitTerm valueUnifier
let (keyUnifierTerm, keyUnifierCondition) = Pattern.splitTerm keyUnifier
return
( (keyUnifierTerm, valueUnifierTerm)
`withCondition` keyUnifierCondition
`andCondition` valueUnifierCondition
)
| Given a unify function and two lists of unifiable things , returns
all possible ways to unify disjoint pairs of the two that use all items
from at least one of the lists .
Also returns the non - unified part os the lists ( one of the two will be empty ) .
all possible ways to unify disjoint pairs of the two that use all items
from at least one of the lists.
Also returns the non-unified part os the lists (one of the two will be empty).
-}
unifyEqualsElementPermutations ::
( Alternative unifier
, Monad unifier
, InternalVariable variable
) =>
(a -> b -> unifier (Conditional variable c)) ->
[a] ->
[b] ->
unifier
( Conditional variable [c]
, [a]
, [b]
)
unifyEqualsElementPermutations unifier firsts seconds = do
(unifiers, remainderFirst, remainderSecond) <-
if length firsts < length seconds
then do
(u, r) <-
kPermutationsBacktracking (flip unifier) seconds firsts
return (u, [], r)
else do
(u, r) <-
kPermutationsBacktracking unifier firsts seconds
return (u, r, [])
let (terms, predicates) = unzip (map Conditional.splitTerm unifiers)
predicate = foldr andCondition Condition.top predicates
return (terms `withCondition` predicate, remainderFirst, remainderSecond)
|Given two lists generates k - permutation pairings and merges them using the
provided merge function .
k is the length of the second list , which means that , if the @[b]@ list is
longer than the @[a]@ list , this will not generate any k - permutations .
However , it will probably take a long time to generate nothing .
If the pairing function fails ( i.e. returns empty ) , the entire function will
stop exploring future branches that would include the given pair .
Note that this does not mean that we wo n't try a failing pair again with a
different set of previous choices , so this function could be optimized to
at least cache pairing results .
provided merge function.
k is the length of the second list, which means that, if the @[b]@ list is
longer than the @[a]@ list, this will not generate any k-permutations.
However, it will probably take a long time to generate nothing.
If the pairing function fails (i.e. returns empty), the entire function will
stop exploring future branches that would include the given pair.
Note that this does not mean that we won't try a failing pair again with a
different set of previous choices, so this function could be optimized to
at least cache pairing results.
-}
kPermutationsBacktracking ::
forall a b c m.
Alternative m =>
(a -> b -> m c) ->
[a] ->
[b] ->
m ([c], [a])
kPermutationsBacktracking _ first [] = pure ([], first)
kPermutationsBacktracking transform firstList secondList =
generateKPermutationsWorker firstList [] secondList
where
generateKPermutationsWorker :: [a] -> [a] -> [b] -> m ([c], [a])
generateKPermutationsWorker _ (_ : _) [] =
error "Unexpected non-empty skipped list with empty pair opportunities"
generateKPermutationsWorker [] [] [] = pure ([], [])
generateKPermutationsWorker [] _ _ = empty
generateKPermutationsWorker first [] [] = pure ([], first)
generateKPermutationsWorker (first : firsts) skipped (second : seconds) =
pickElement <|> skipElement
where
pickElement =
addToFirst
<$> transform first second
<*> generateKPermutationsWorker (skipped ++ firsts) [] seconds
addToFirst :: x -> ([x], y) -> ([x], y)
addToFirst x (xs, y) = (x : xs, y)
skipElement =
generateKPermutationsWorker
firsts
(first : skipped)
(second : seconds)
nonEmptyRemainderError ::
forall a normalized variable.
( HasCallStack
, InternalVariable variable
, AcWrapper normalized
) =>
TermLike variable ->
TermLike variable ->
[ConcreteOrWithVariable normalized variable] ->
[ConcreteOrWithVariable normalized variable] ->
[ConcreteOrWithVariable normalized variable] ->
a
nonEmptyRemainderError first second input1 input2 remainder =
(error . unlines)
[ "Unexpected unused elements, should have been caught"
, "by checks above:"
, "first=" ++ unparseToString first
, "second=" ++ unparseToString second
, "input1=" ++ unlines (map unparseWrapped input1)
, "input2=" ++ unlines (map unparseWrapped input2)
, "remainder=" ++ unlines (map unparseWrapped remainder)
]
where
unparseWrapped =
Unparser.renderDefault . unparsePair . fromConcreteOrWithVariable
unparsePair = unparseElement unparse . wrapElement
-- | Wrapper for giving names to arguments.
newtype UnitSymbol = UnitSymbol {getUnitSymbol :: Symbol}
-- | Wrapper for giving names to arguments.
newtype ConcatSymbol = ConcatSymbol {getConcatSymbol :: Symbol}
-- | Wrapper for giving names to arguments.
newtype ConcreteElements variable = ConcreteElements {getConcreteElements :: [TermLike variable]}
-- | Wrapper for giving names to arguments.
newtype VariableElements variable = VariableElements {getVariableElements :: [TermLike variable]}
-- | Wrapper for giving names to arguments.
newtype Opaque variable = Opaque {getOpaque :: [TermLike variable]}
| null | https://raw.githubusercontent.com/runtimeverification/haskell-backend/fae73ac06cc9bcf8e24b0bdd2f07069610277d58/kore/src/Kore/Builtin/AssociativeCommutative.hs | haskell | | Any @TermWrapper@ may be inside of an 'InternalAc'.
The term may become bottom if we had conflicts between elements that were
not detected before, e.g.
@
concat({1}, concat(X:Set, {1}))
concat(elem(Y:Int), concat({1}, elem(Y:Int)))
concat(X:Set, concat({1}, X:Set))
@
@matchBuiltin@ returns 'Nothing' if the 'TermLike' does not wrap a
'normalized' value.
| Particularizes @NormalizedAc@ to the most common types.
| A normalized representation of an associative-commutative structure that
also allows bottom values.
| The semigroup defined by the `concat` operation.
| Insert the @key@-@value@ pair if it is missing from the 'Map'.
| Insert the new concrete elements into the 'Map'.
Return 'Nothing' if there are any duplicate keys.
| Sort the abstract elements.
Return 'Nothing' if there are any duplicate keys.
| Make any abstract elements into concrete elements if possible.
Return 'Nothing' if there are any duplicate (concrete or abstract) keys.
| 'Left' if the element's key can be concretized, or 'Right' if it
remains abstract.
| Move any @normalized@ children to the top-level by concatenation.
@flattenOpaque@ recursively flattens the children of children, and so on.
| The monoid defined by the `concat` and `unit` operations.
| Given a @NormalizedAc@, returns it as a function result.
| Converts an Ac of concrete elements to a @NormalizedAc@ and returns it
as a function result.
TODO(virgil): Check whether this normalization is still needed
(the normalizedTerm may already be re-normalized) and remove it if not.
Duplicates must be kept in case any of the opaque terms turns out to be
means that the unification result is bottom.
unifier monad
unify the parts not sent to unifyEqualsNormalizedElements.
simplify results so that things like inj applications that
may have been broken into smaller pieces are being put
back together.
Duplicates must be kept in case any of the opaque terms turns out to be
means that the unification result is bottom.
TODO: can this be rewritten?
unifier monad
Add back all the common objects that were removed before
unification.
Merge all unification predicates.
| unifier function
never unify.
the "length" check above so, most likely, this can be an assertion.
the "length" check above so, most likely, this can be an assertion.
one. Since we don't have enough, we return bottom.
the "length" check above so, most likely, this can be an assertion.
The term to unify against v1
| unifier function
| Wrapper for giving names to arguments.
| Wrapper for giving names to arguments.
| Wrapper for giving names to arguments.
| Wrapper for giving names to arguments.
| Wrapper for giving names to arguments. | # LANGUAGE UndecidableInstances #
|
Module : Kore . Builtin . AssociativeCommutative
Description : Handles built - in operations which are associative , commutative ,
with neutral elements , key - based , with unique keys , and which
return bottom when applied to unique keys .
Copyright : ( c ) Runtime Verification , 2019 - 2021
License : BSD-3 - Clause
Maintainer :
This module is intended to be imported qualified , to avoid collision with other
builtin modules .
@
import qualified Kore . Builtin . AssociativeCommutative as Ac
@
Module : Kore.Builtin.AssociativeCommutative
Description : Handles built-in operations which are associative, commutative,
with neutral elements, key-based, with unique keys, and which
return bottom when applied to unique keys.
Copyright : (c) Runtime Verification, 2019-2021
License : BSD-3-Clause
Maintainer :
This module is intended to be imported qualified, to avoid collision with other
builtin modules.
@
import qualified Kore.Builtin.AssociativeCommutative as Ac
@
-}
module Kore.Builtin.AssociativeCommutative (
asInternalConcrete,
asPattern,
ConcatSymbol (..),
ConcreteElements (..),
evalConcatNormalizedOrBottom,
NormalizedOrBottom (..),
Opaque (..),
returnAc,
returnConcreteAc,
TermWrapper (..),
renormalize,
TermNormalizedAc,
unifyEqualsNormalized,
matchUnifyEqualsNormalizedAc,
UnitSymbol (..),
VariableElements (..),
UnifyEqualsNormAc (..),
) where
import Control.Error (
MaybeT,
)
import Control.Monad qualified as Monad
import Data.HashMap.Strict (
HashMap,
)
import Data.HashMap.Strict qualified as HashMap
import Data.HashSet (
HashSet,
)
import Data.HashSet qualified as HashSet
import Data.Kind (
Type,
)
import Data.List qualified
import Data.List qualified as List
import Data.Text (Text)
import GHC.Generics qualified as GHC
import Generics.SOP qualified as SOP
import Kore.Attribute.Pattern.Simplified qualified as Attribute (
Simplified,
)
import Kore.Attribute.Symbol qualified as Attribute (
Symbol,
)
import Kore.Builtin.Builtin qualified as Builtin
import Kore.Builtin.Map.Map qualified as Map
import Kore.Builtin.Set.Set qualified as Set
import Kore.Debug
import Kore.IndexedModule.MetadataTools (
SmtMetadataTools,
)
import Kore.Internal.Condition (
Condition,
)
import Kore.Internal.Condition qualified as Condition
import Kore.Internal.Conditional (
Conditional,
andCondition,
withCondition,
)
import Kore.Internal.Conditional qualified as Conditional
import Kore.Internal.InternalMap
import Kore.Internal.InternalSet
import Kore.Internal.Pattern (
Pattern,
)
import Kore.Internal.Pattern qualified as Pattern
import Kore.Internal.SideCondition qualified as SideCondition (
topTODO,
)
import Kore.Internal.Symbol (
Symbol,
)
import Kore.Internal.TermLike (
Key,
TermLike,
mkElemVar,
termLikeSort,
pattern App_,
pattern ElemVar_,
pattern InternalMap_,
pattern InternalSet_,
)
import Kore.Internal.TermLike qualified as TermLike
import Kore.Log.DebugUnifyBottom (
debugUnifyBottomAndReturnBottom,
)
import Kore.Rewrite.RewritingVariable (
RewritingVariableName,
)
import Kore.Simplify.Simplify as Simplifier
import Kore.Sort (
Sort,
sameSort,
)
import Kore.Syntax.Variable
import Kore.Unification.Unify (
MonadUnify,
)
import Kore.Unparser (
unparse,
unparseToString,
)
import Kore.Unparser qualified as Unparser
import Logic
import Prelude.Kore
import Pretty qualified
class
AcWrapper (normalized :: Type -> Type -> Type) =>
TermWrapper normalized
where
| Render a normalized value ( e.g. ' NormalizedSet ' ) as an ' InternalAc ' .
The result sort must be hooked to the builtin normalized sort ( e.g. ) .
asInternalBuiltin ::
SmtMetadataTools Attribute.Symbol ->
Sort ->
normalized Key child ->
InternalAc Key normalized child
TODO ( thomas.tuegel ): Use From .
| Render a normalized value ( e.g. ' NormalizedSet ' ) as a ' TermLike ' .
The result sort must be hooked to the builtin normalized sort ( e.g. ) .
asInternal ::
InternalVariable variable =>
SmtMetadataTools Attribute.Symbol ->
Sort ->
normalized Key (TermLike variable) ->
TermLike variable
|Transforms a @TermLike@ representation into a @NormalizedOrBottom@.
toNormalized ::
HasCallStack =>
Ord variable =>
Hashable variable =>
TermLike variable ->
NormalizedOrBottom normalized variable
| Pattern match on a ' TermLike ' to return a ' normalized ' .
matchBuiltin ::
TermLike variable ->
Maybe (normalized Key (TermLike variable))
simplifiedAttributeValue ::
Value normalized (TermLike variable) -> Attribute.Simplified
instance TermWrapper NormalizedMap where
asInternalBuiltin tools builtinAcSort builtinAcChild =
InternalAc
{ builtinAcSort
, builtinAcUnit = Builtin.lookupSymbolUnit tools builtinAcSort
, builtinAcElement = Builtin.lookupSymbolElement tools builtinAcSort
, builtinAcConcat = Builtin.lookupSymbolConcat tools builtinAcSort
, builtinAcChild
}
asInternal tools sort child =
TermLike.mkInternalMap (asInternalBuiltin tools sort child)
matchBuiltin (InternalMap_ internalMap) =
Just (builtinAcChild internalMap)
matchBuiltin _ = Nothing
toNormalized (InternalMap_ InternalAc{builtinAcChild}) =
maybe Bottom Normalized (renormalize builtinAcChild)
toNormalized (App_ symbol args)
| Map.isSymbolUnit symbol =
case args of
[] -> (Normalized . wrapAc) emptyNormalizedAc
_ -> Builtin.wrongArity "MAP.unit"
| Map.isSymbolElement symbol =
case args of
[key, value]
| Just key' <- TermLike.retractKey key ->
(Normalized . wrapAc)
NormalizedAc
{ elementsWithVariables = []
, concreteElements =
HashMap.singleton key' (MapValue value)
, opaque = []
}
| otherwise ->
(Normalized . wrapAc)
NormalizedAc
{ elementsWithVariables = [MapElement (key, value)]
, concreteElements = HashMap.empty
, opaque = []
}
_ -> Builtin.wrongArity "MAP.element"
| Map.isSymbolConcat symbol =
case args of
[map1, map2] -> toNormalized map1 <> toNormalized map2
_ -> Builtin.wrongArity "MAP.concat"
toNormalized patt =
(Normalized . wrapAc)
NormalizedAc
{ elementsWithVariables = []
, concreteElements = HashMap.empty
, opaque = [patt]
}
simplifiedAttributeValue = TermLike.simplifiedAttribute . getMapValue
instance TermWrapper NormalizedSet where
asInternalBuiltin tools builtinAcSort builtinAcChild =
InternalAc
{ builtinAcSort
, builtinAcUnit = Builtin.lookupSymbolUnit tools builtinAcSort
, builtinAcElement = Builtin.lookupSymbolElement tools builtinAcSort
, builtinAcConcat = Builtin.lookupSymbolConcat tools builtinAcSort
, builtinAcChild
}
asInternal tools sort child =
TermLike.mkInternalSet (asInternalBuiltin tools sort child)
matchBuiltin (InternalSet_ internalSet) =
Just (builtinAcChild internalSet)
matchBuiltin _ = Nothing
toNormalized (InternalSet_ InternalAc{builtinAcChild}) =
maybe Bottom Normalized (renormalize builtinAcChild)
toNormalized (App_ symbol args)
| Set.isSymbolUnit symbol =
case args of
[] -> (Normalized . wrapAc) emptyNormalizedAc
_ -> Builtin.wrongArity "SET.unit"
| Set.isSymbolElement symbol =
case args of
[elem1]
| Just elem1' <- TermLike.retractKey elem1 ->
(Normalized . wrapAc)
NormalizedAc
{ elementsWithVariables = []
, concreteElements = HashMap.singleton elem1' SetValue
, opaque = []
}
| otherwise ->
(Normalized . wrapAc)
NormalizedAc
{ elementsWithVariables = [SetElement elem1]
, concreteElements = HashMap.empty
, opaque = []
}
_ -> Builtin.wrongArity "SET.element"
| Set.isSymbolConcat symbol =
case args of
[set1, set2] -> toNormalized set1 <> toNormalized set2
_ -> Builtin.wrongArity "SET.concat"
toNormalized patt =
(Normalized . wrapAc)
emptyNormalizedAc{opaque = [patt]}
simplifiedAttributeValue SetValue = mempty
| Wrapper for terms that keeps the " concrete " vs " with variable " distinction
after converting @TermLike Concrete@ to @TermLike variable@.
after converting @TermLike Concrete@ to @TermLike variable@.
-}
data ConcreteOrWithVariable normalized variable
= ConcretePat (TermLike variable, Value normalized (TermLike variable))
| WithVariablePat (TermLike variable, Value normalized (TermLike variable))
instance
From
(ConcreteOrWithVariable normalized variable)
(TermLike variable, Value normalized (TermLike variable))
where
from =
\case
ConcretePat result -> result
WithVariablePat result -> result
fromConcreteOrWithVariable ::
ConcreteOrWithVariable normalized variable ->
(TermLike variable, Value normalized (TermLike variable))
fromConcreteOrWithVariable = from
type TermNormalizedAc normalized variable =
normalized Key (TermLike variable)
data NormalizedOrBottom collection variable
= Normalized (TermNormalizedAc collection variable)
| Bottom
deriving stock (GHC.Generic)
deriving stock instance
Eq (TermNormalizedAc collection variable) =>
Eq (NormalizedOrBottom collection variable)
deriving stock instance
Ord (TermNormalizedAc collection variable) =>
Ord (NormalizedOrBottom collection variable)
deriving stock instance
Show (TermNormalizedAc collection variable) =>
Show (NormalizedOrBottom collection variable)
instance SOP.Generic (NormalizedOrBottom collection variable)
instance SOP.HasDatatypeInfo (NormalizedOrBottom collection variable)
instance
Debug (collection Key (TermLike variable)) =>
Debug (NormalizedOrBottom collection variable)
instance
( Debug (collection Key (TermLike variable))
, Diff (collection Key (TermLike variable))
) =>
Diff (NormalizedOrBottom collection variable)
instance
(Ord variable, TermWrapper normalized, Hashable variable) =>
Semigroup (NormalizedOrBottom normalized variable)
where
Bottom <> _ = Bottom
_ <> Bottom = Bottom
Normalized normalized1 <> Normalized normalized2 =
maybe Bottom Normalized $ concatNormalized normalized1 normalized2
concatNormalized ::
forall normalized variable.
(TermWrapper normalized, Ord variable, Hashable variable) =>
normalized Key (TermLike variable) ->
normalized Key (TermLike variable) ->
Maybe (normalized Key (TermLike variable))
concatNormalized normalized1 normalized2 = do
Monad.guard disjointConcreteElements
abstract' <-
updateAbstractElements $ onBoth (++) elementsWithVariables
let concrete' = onBoth HashMap.union concreteElements
opaque' = Data.List.sort $ onBoth (++) opaque
renormalize $
wrapAc
NormalizedAc
{ elementsWithVariables = abstract'
, concreteElements = concrete'
, opaque = opaque'
}
where
onBoth ::
(a -> a -> r) ->
( NormalizedAc
normalized
Key
(TermLike variable) ->
a
) ->
r
onBoth f g = on f (g . unwrapAc) normalized1 normalized2
disjointConcreteElements =
null $ onBoth HashMap.intersection concreteElements
| Take a ( possibly de - normalized ) internal representation to its normal form .
@renormalize@ returns ' Nothing ' if the normal form is @\\bottom@.
First , abstract elements are converted to concrete elements wherever
possible . Second , any opaque terms which are actually builtins are combined with
the top - level term , so that the normal form never has children which are
internal representations themselves ; this " flattening " step also recurses to
@renormalize@ the previously - opaque children .
@renormalize@ returns 'Nothing' if the normal form is @\\bottom@.
First, abstract elements are converted to concrete elements wherever
possible. Second, any opaque terms which are actually builtins are combined with
the top-level term, so that the normal form never has children which are
internal representations themselves; this "flattening" step also recurses to
@renormalize@ the previously-opaque children.
-}
renormalize ::
(TermWrapper normalized, Ord variable, Hashable variable) =>
normalized Key (TermLike variable) ->
Maybe (normalized Key (TermLike variable))
renormalize = normalizeAbstractElements >=> flattenOpaque
insertMissing ::
Ord key =>
Hashable key =>
key ->
value ->
HashMap key value ->
Maybe (HashMap key value)
insertMissing k v m
| HashMap.member k m = Nothing
| otherwise = Just (HashMap.insert k v m)
updateConcreteElements ::
HashMap Key value ->
[(Key, value)] ->
Maybe (HashMap Key value)
updateConcreteElements elems newElems =
foldrM (uncurry insertMissing) elems newElems
updateAbstractElements ::
(AcWrapper collection, Ord child, Hashable child) =>
[Element collection child] ->
Maybe [Element collection child]
updateAbstractElements elements =
fmap (map wrapElement . HashMap.toList) $
foldrM (uncurry insertMissing) HashMap.empty $
map unwrapElement elements
normalizeAbstractElements ::
(TermWrapper normalized, Ord variable) =>
normalized Key (TermLike variable) ->
Maybe (normalized Key (TermLike variable))
normalizeAbstractElements (unwrapAc -> normalized) = do
concrete' <- updateConcreteElements concrete newConcrete
abstract' <- updateAbstractElements newAbstract
return $
wrapAc
NormalizedAc
{ elementsWithVariables = abstract'
, concreteElements = concrete'
, opaque = opaque normalized
}
where
abstract = elementsWithVariables normalized
concrete = concreteElements normalized
(newConcrete, newAbstract) =
partitionEithers (extractConcreteElement <$> abstract)
extractConcreteElement ::
AcWrapper collection =>
Element collection (TermLike variable) ->
Either
(Key, Value collection (TermLike variable))
(Element collection (TermLike variable))
extractConcreteElement element =
maybe (Right element) (Left . flip (,) value) (TermLike.retractKey key)
where
(key, value) = unwrapElement element
flattenOpaque ::
(TermWrapper normalized, Ord variable, Hashable variable) =>
normalized Key (TermLike variable) ->
Maybe (normalized Key (TermLike variable))
flattenOpaque (unwrapAc -> normalized) = do
let NormalizedAc{opaque} = normalized
(builtin, opaque') = partitionEithers (extractBuiltin <$> opaque)
transparent = wrapAc normalized{opaque = opaque'}
foldrM concatNormalized transparent builtin
where
extractBuiltin termLike =
maybe (Right termLike) Left (matchBuiltin termLike)
instance
(Ord variable, TermWrapper normalized, Hashable variable) =>
Monoid (NormalizedOrBottom normalized variable)
where
mempty = Normalized $ wrapAc emptyNormalizedAc
| Computes the union of two maps if they are disjoint . Returns @Nothing@
otherwise .
otherwise.
-}
addToMapDisjoint ::
(Ord a, Foldable t, Hashable a) =>
HashMap a b ->
t (a, b) ->
Maybe (HashMap a b)
addToMapDisjoint = Monad.foldM addElementDisjoint
addElementDisjoint ::
Ord a =>
Hashable a =>
HashMap a b ->
(a, b) ->
Maybe (HashMap a b)
addElementDisjoint existing (key, value) =
if key `HashMap.member` existing
then Nothing
else return (HashMap.insert key value existing)
returnAc ::
( InternalVariable variable
, TermWrapper normalized
) =>
Sort ->
TermNormalizedAc normalized variable ->
Simplifier (Pattern variable)
returnAc resultSort ac = do
tools <- Simplifier.askMetadataTools
asInternal tools resultSort ac
& Pattern.fromTermLike
& return
returnConcreteAc ::
( InternalVariable variable
, TermWrapper normalized
) =>
Sort ->
HashMap Key (Value normalized (TermLike variable)) ->
Simplifier (Pattern variable)
returnConcreteAc resultSort concrete =
(returnAc resultSort . wrapAc)
NormalizedAc
{ elementsWithVariables = []
, concreteElements = concrete
, opaque = []
}
| The same as ' asInternal ' , but for ac structures made only of concrete
elements .
elements.
-}
asInternalConcrete ::
(InternalVariable variable, TermWrapper normalized) =>
SmtMetadataTools Attribute.Symbol ->
Sort ->
HashMap Key (Value normalized (TermLike variable)) ->
TermLike variable
asInternalConcrete tools sort1 concreteAc =
asInternal tools sort1 $
wrapAc
NormalizedAc
{ elementsWithVariables = []
, concreteElements = concreteAc
, opaque = []
}
elementListAsInternal ::
forall normalized variable.
(InternalVariable variable, TermWrapper normalized) =>
SmtMetadataTools Attribute.Symbol ->
Sort ->
[(TermLike variable, Value normalized (TermLike variable))] ->
Maybe (TermLike variable)
elementListAsInternal tools sort1 terms =
asInternal tools sort1 . wrapAc
<$> elementListAsNormalized terms
elementListAsNormalized ::
forall normalized variable.
(InternalVariable variable, TermWrapper normalized) =>
[(TermLike variable, Value normalized (TermLike variable))] ->
Maybe (NormalizedAc normalized Key (TermLike variable))
elementListAsNormalized terms = do
let (withVariables, concrete) = splitVariableConcrete terms
_checkDisjoinVariables <- disjointMap withVariables
concreteAc <- disjointMap concrete
return
NormalizedAc
{ elementsWithVariables = wrapElement <$> withVariables
, concreteElements = concreteAc
, opaque = []
}
| Render a ' NormalizedAc ' as an extended domain value pattern .
asPattern ::
( InternalVariable variable
, TermWrapper normalized
) =>
SmtMetadataTools Attribute.Symbol ->
Sort ->
TermNormalizedAc normalized variable ->
Pattern variable
asPattern tools resultSort =
Pattern.fromTermLike . asInternal tools resultSort
| Evaluates a concatenation of two AC structures represented as
NormalizedOrBottom , providind the result in the form of a function result .
NormalizedOrBottom, providind the result in the form of a function result.
-}
evalConcatNormalizedOrBottom ::
forall normalized variable.
( InternalVariable variable
, TermWrapper normalized
) =>
Sort ->
NormalizedOrBottom normalized variable ->
NormalizedOrBottom normalized variable ->
MaybeT Simplifier (Pattern variable)
evalConcatNormalizedOrBottom resultSort Bottom _ =
return (Pattern.bottomOf resultSort)
evalConcatNormalizedOrBottom resultSort _ Bottom =
return (Pattern.bottomOf resultSort)
evalConcatNormalizedOrBottom
resultSort
(Normalized normalized1)
(Normalized normalized2) =
maybe (return $ Pattern.bottomOf resultSort) (lift . returnAc resultSort) $
concatNormalized normalized1 normalized2
disjointMap :: Ord a => Hashable a => [(a, b)] -> Maybe (HashMap a b)
disjointMap = addToMapDisjoint HashMap.empty
splitVariableConcrete ::
forall variable a.
[(TermLike variable, a)] ->
([(TermLike variable, a)], [(Key, a)])
splitVariableConcrete terms =
partitionEithers (map toConcreteEither terms)
where
toConcreteEither ::
(TermLike variable, a) ->
Either (TermLike variable, a) (Key, a)
toConcreteEither (term, a) =
case TermLike.retractKey term of
Nothing -> Left (term, a)
Just result -> Right (result, a)
| Simplify the conjunction or equality of two Ac domain values in their
normalized form .
When it is used for simplifying equality , one should separately solve the
case ⊥ = ⊥. One should also throw away the term in the returned pattern .
The domain values are assumed to have the same sort , but this is not checked . If
multiple sorts are hooked to the same builtin domain , the verifier should
reject the definition .
normalized form.
When it is used for simplifying equality, one should separately solve the
case ⊥ = ⊥. One should also throw away the term in the returned pattern.
The domain values are assumed to have the same sort, but this is not checked. If
multiple sorts are hooked to the same builtin domain, the verifier should
reject the definition.
-}
unifyEqualsNormalized ::
forall normalized unifier.
( Traversable (Value normalized)
, TermWrapper normalized
, MonadUnify unifier
) =>
HasCallStack =>
SmtMetadataTools Attribute.Symbol ->
TermLike RewritingVariableName ->
TermLike RewritingVariableName ->
( TermLike RewritingVariableName ->
TermLike RewritingVariableName ->
unifier (Pattern RewritingVariableName)
) ->
InternalAc Key normalized (TermLike RewritingVariableName) ->
InternalAc Key normalized (TermLike RewritingVariableName) ->
UnifyEqualsNormAc normalized RewritingVariableName ->
unifier (Pattern RewritingVariableName)
unifyEqualsNormalized
tools
first
second
unifyEqualsChildren
normalized1
normalized2
unifyData =
do
let InternalAc{builtinAcChild = firstNormalized} =
normalized1
InternalAc{builtinAcChild = secondNormalized} =
normalized2
unifierNormalized <-
unifyEqualsNormalizedAc
tools
first
second
unifyEqualsChildren
firstNormalized
secondNormalized
unifyData
let unifierNormalizedTerm ::
TermNormalizedAc normalized RewritingVariableName
unifierCondition :: Condition RewritingVariableName
(unifierNormalizedTerm, unifierCondition) =
Conditional.splitTerm unifierNormalized
normalizedTerm :: TermLike RewritingVariableName
normalizedTerm = asInternal tools sort1 unifierNormalizedTerm
renormalized <- normalize1 normalizedTerm
let unifierTerm :: TermLike RewritingVariableName
unifierTerm = markSimplified $ asInternal tools sort1 renormalized
markSimplified =
TermLike.setSimplified
( foldMap TermLike.simplifiedAttribute opaque
<> foldMap TermLike.simplifiedAttribute abstractKeys
<> foldMap simplifiedAttributeValue abstractValues
<> foldMap simplifiedAttributeValue concreteValues
)
where
unwrapped = unwrapAc renormalized
NormalizedAc{opaque} = unwrapped
(abstractKeys, abstractValues) =
(unzip . map unwrapElement)
(elementsWithVariables unwrapped)
(_, concreteValues) =
(unzip . HashMap.toList)
(concreteElements unwrapped)
return (unifierTerm `Pattern.withCondition` unifierCondition)
where
sort1 = termLikeSort first
normalize1 ::
HasCallStack =>
InternalVariable variable =>
TermLike variable ->
unifier (TermNormalizedAc normalized variable)
normalize1 patt =
case toNormalized patt of
Bottom ->
debugUnifyBottomAndReturnBottom
"Duplicated elements in normalization."
first
second
Normalized n -> return n
data UnifyEqualsElementListsData normalized = UnifyEqualsElementListsData
Given normalized data norm1 , norm2 , norm1 - norm2 and norm2 - norm1
allElements1, allElements2 :: ![ConcreteOrWithVariable normalized RewritingVariableName]
Is Just v if v is the sole opaque in norm1 - norm2 , else Nothing
maybeVar :: !(Maybe (ElementVariable RewritingVariableName))
}
data UnifyEqualsNormAc normalized variable
= UnifyEqualsElementLists !(UnifyEqualsElementListsData normalized)
| UnifyOpaqueVar !(UnifyOpVarResult variable)
matchUnifyEqualsNormalizedAc ::
forall normalized.
TermWrapper normalized =>
SmtMetadataTools Attribute.Symbol ->
InternalAc Key normalized (TermLike RewritingVariableName) ->
InternalAc Key normalized (TermLike RewritingVariableName) ->
Maybe (UnifyEqualsNormAc normalized RewritingVariableName)
matchUnifyEqualsNormalizedAc
tools
normalized1
normalized2 =
case (opaqueDifference1, opaqueDifference2) of
([], []) ->
Just $
UnifyEqualsElementLists $
UnifyEqualsElementListsData
allElements1
allElements2
Nothing
([ElemVar_ v1], _)
| null opaqueDifference2 ->
Just $
UnifyEqualsElementLists $
UnifyEqualsElementListsData
allElements1
allElements2
(Just v1)
| null allElements1 ->
fmap UnifyOpaqueVar $
matchUnifyOpaqueVariable'
v1
allElements2
opaqueDifference2
_ -> Nothing
where
matchUnifyOpaqueVariable' =
matchUnifyOpaqueVariable tools
listToMap :: Hashable a => [a] -> HashMap a Int
listToMap keys = HashMap.fromListWith (+) [(k, 1) | k <- keys]
mapToList :: HashMap a Int -> [a]
mapToList =
HashMap.foldrWithKey
(\key count result -> replicate count key ++ result)
[]
NormalizedAc
{ elementsWithVariables = preElementsWithVariables1
, concreteElements = concreteElements1
, opaque = opaque1
} =
unwrapAc firstNormalized
NormalizedAc
{ elementsWithVariables = preElementsWithVariables2
, concreteElements = concreteElements2
, opaque = opaque2
} =
unwrapAc secondNormalized
InternalAc{builtinAcChild = firstNormalized} =
normalized1
InternalAc{builtinAcChild = secondNormalized} =
normalized2
opaque1Map = listToMap opaque1
opaque2Map = listToMap opaque2
elementsWithVariables1 = unwrapElement <$> preElementsWithVariables1
elementsWithVariables2 = unwrapElement <$> preElementsWithVariables2
elementsWithVariables1Map = HashMap.fromList elementsWithVariables1
elementsWithVariables2Map = HashMap.fromList elementsWithVariables2
commonElements =
HashMap.intersectionWith
(,)
concreteElements1
concreteElements2
commonVariables =
HashMap.intersectionWith
(,)
elementsWithVariables1Map
elementsWithVariables2Map
non - empty , in which case one of the terms is bottom , which
commonOpaqueMap = HashMap.intersectionWith max opaque1Map opaque2Map
commonOpaqueKeys = HashMap.keysSet commonOpaqueMap
elementDifference1 =
HashMap.toList (HashMap.difference concreteElements1 commonElements)
elementDifference2 =
HashMap.toList (HashMap.difference concreteElements2 commonElements)
elementVariableDifference1 =
HashMap.toList (HashMap.difference elementsWithVariables1Map commonVariables)
elementVariableDifference2 =
HashMap.toList (HashMap.difference elementsWithVariables2Map commonVariables)
opaqueDifference1 =
mapToList (withoutKeys opaque1Map commonOpaqueKeys)
opaqueDifference2 =
mapToList (withoutKeys opaque2Map commonOpaqueKeys)
withoutKeys ::
Hashable k =>
HashMap k v ->
HashSet k ->
HashMap k v
withoutKeys hmap hset = hmap `HashMap.difference` (HashSet.toMap hset)
allElements1 =
map WithVariablePat elementVariableDifference1
++ map toConcretePat elementDifference1
allElements2 =
map WithVariablePat elementVariableDifference2
++ map toConcretePat elementDifference2
toConcretePat ::
(Key, Value normalized (TermLike RewritingVariableName)) ->
ConcreteOrWithVariable
normalized
RewritingVariableName
toConcretePat (a, b) =
ConcretePat (from @Key @(TermLike RewritingVariableName) a, b)
| two AC structs represented as @NormalizedAc@.
Currently allows at most one opaque term in the two arguments taken together .
Currently allows at most one opaque term in the two arguments taken together.
-}
unifyEqualsNormalizedAc ::
forall normalized unifier.
( Traversable (Value normalized)
, TermWrapper normalized
, MonadUnify unifier
) =>
SmtMetadataTools Attribute.Symbol ->
TermLike RewritingVariableName ->
TermLike RewritingVariableName ->
( TermLike RewritingVariableName ->
TermLike RewritingVariableName ->
unifier (Pattern RewritingVariableName)
) ->
TermNormalizedAc normalized RewritingVariableName ->
TermNormalizedAc normalized RewritingVariableName ->
UnifyEqualsNormAc normalized RewritingVariableName ->
unifier
( Conditional
RewritingVariableName
(TermNormalizedAc normalized RewritingVariableName)
)
unifyEqualsNormalizedAc
tools
first
second
unifyEqualsChildren
normalized1
normalized2
unifyData =
do
(simpleUnifier, opaques) <- case unifyData of
UnifyEqualsElementLists unifyData' ->
unifyEqualsElementLists'
allElements1
allElements2
maybeVar
where
UnifyEqualsElementListsData{allElements1, allElements2, maybeVar} = unifyData'
UnifyOpaqueVar unifyData' ->
unifyOpaqueVariable
bottomWithExplanation
unifyEqualsChildren
unifyData'
let (unifiedElements, unifierCondition) =
Conditional.splitTerm simpleUnifier
do
(commonElementsTerms, commonElementsCondition) <-
unifyElementList (HashMap.toList commonElements)
(commonVariablesTerms, commonVariablesCondition) <-
unifyElementList (HashMap.toList commonVariables)
unifiedSimplified <- mapM simplifyPair unifiedElements
opaquesSimplified <- mapM simplify opaques
buildResultFromUnifiers
bottomWithExplanation
commonElementsTerms
commonVariablesTerms
commonOpaque
unifiedSimplified
opaquesSimplified
[ unifierCondition
, commonElementsCondition
, commonVariablesCondition
]
where
listToMap :: Hashable a => [a] -> HashMap a Int
listToMap keys = HashMap.fromListWith (+) [(k, 1) | k <- keys]
mapToList :: HashMap a Int -> [a]
mapToList =
HashMap.foldrWithKey
(\key count result -> replicate count key ++ result)
[]
bottomWithExplanation :: Text -> unifier a
bottomWithExplanation explanation =
debugUnifyBottomAndReturnBottom explanation first second
unifyEqualsElementLists' =
unifyEqualsElementLists
tools
first
second
unifyEqualsChildren
NormalizedAc
{ elementsWithVariables = preElementsWithVariables1
, concreteElements = concreteElements1
, opaque = opaque1
} =
unwrapAc normalized1
NormalizedAc
{ elementsWithVariables = preElementsWithVariables2
, concreteElements = concreteElements2
, opaque = opaque2
} =
unwrapAc normalized2
opaque1Map = listToMap opaque1
opaque2Map = listToMap opaque2
elementsWithVariables1 = unwrapElement <$> preElementsWithVariables1
elementsWithVariables2 = unwrapElement <$> preElementsWithVariables2
elementsWithVariables1Map = HashMap.fromList elementsWithVariables1
elementsWithVariables2Map = HashMap.fromList elementsWithVariables2
commonElements =
HashMap.intersectionWith
(,)
concreteElements1
concreteElements2
commonVariables =
HashMap.intersectionWith
(,)
elementsWithVariables1Map
elementsWithVariables2Map
non - empty , in which case one of the terms is bottom , which
commonOpaqueMap = HashMap.intersectionWith max opaque1Map opaque2Map
commonOpaque = mapToList commonOpaqueMap
unifyElementList ::
forall key.
[ ( key
, ( Value normalized (TermLike RewritingVariableName)
, Value normalized (TermLike RewritingVariableName)
)
)
] ->
unifier
( [(key, Value normalized (TermLike RewritingVariableName))]
, Condition RewritingVariableName
)
unifyElementList elements = do
result <- mapM (unifyCommonElements unifyEqualsChildren) elements
let terms :: [(key, Value normalized (TermLike RewritingVariableName))]
predicates :: [Condition RewritingVariableName]
(terms, predicates) = unzip (map Conditional.splitTerm result)
predicate :: Condition RewritingVariableName
predicate =
List.foldl'
andCondition
Condition.top
predicates
return (terms, predicate)
simplify ::
TermLike RewritingVariableName ->
unifier (Pattern RewritingVariableName)
simplify term =
mapLogicT liftSimplifier (simplifyPatternScatter SideCondition.topTODO (Pattern.fromTermLike term))
& lowerLogicT
simplifyPair ::
( TermLike RewritingVariableName
, Value normalized (TermLike RewritingVariableName)
) ->
unifier
( Conditional
RewritingVariableName
( TermLike RewritingVariableName
, Value normalized (TermLike RewritingVariableName)
)
)
simplifyPair (key, value) = do
simplifiedKey <- simplifyTermLike' key
let (keyTerm, keyCondition) = Conditional.splitTerm simplifiedKey
simplifiedValue <- traverse simplifyTermLike' value
let splitSimplifiedValue ::
Value
normalized
( TermLike RewritingVariableName
, Condition RewritingVariableName
)
splitSimplifiedValue =
fmap Conditional.splitTerm simplifiedValue
simplifiedValueTerm ::
Value normalized (TermLike RewritingVariableName)
simplifiedValueTerm = fmap fst splitSimplifiedValue
simplifiedValueConditions ::
Value normalized (Condition RewritingVariableName)
simplifiedValueConditions = fmap snd splitSimplifiedValue
simplifiedValueCondition :: Condition RewritingVariableName
simplifiedValueCondition =
foldr
andCondition
Condition.top
simplifiedValueConditions
return
( (keyTerm, simplifiedValueTerm)
`withCondition` keyCondition
`andCondition` simplifiedValueCondition
)
where
simplifyTermLike' ::
TermLike RewritingVariableName ->
unifier (Pattern RewritingVariableName)
simplifyTermLike' term =
mapLogicT liftSimplifier (simplifyPatternScatter SideCondition.topTODO (Pattern.fromTermLike term))
& lowerLogicT
buildResultFromUnifiers ::
forall normalized unifier variable.
( Monad unifier
, InternalVariable variable
, TermWrapper normalized
) =>
(forall result. Text -> unifier result) ->
[(Key, Value normalized (TermLike variable))] ->
[(TermLike variable, Value normalized (TermLike variable))] ->
[TermLike variable] ->
[ Conditional
variable
(TermLike variable, Value normalized (TermLike variable))
] ->
[Pattern variable] ->
[Condition variable] ->
unifier (Conditional variable (TermNormalizedAc normalized variable))
buildResultFromUnifiers
bottomWithExplanation
commonElementsTerms
commonVariablesTerms
commonOpaque
unifiedElementsSimplified
opaquesSimplified
predicates =
do
let almostResultTerms ::
[ ( TermLike variable
, Value normalized (TermLike variable)
)
]
almostResultConditions :: [Condition variable]
(almostResultTerms, almostResultConditions) =
unzip (map Conditional.splitTerm unifiedElementsSimplified)
(withVariableTerms, concreteTerms) =
splitVariableConcrete almostResultTerms
(opaquesTerms, opaquesConditions) =
unzip (map Conditional.splitTerm opaquesSimplified)
opaquesNormalized :: NormalizedOrBottom normalized variable
opaquesNormalized = foldMap toNormalized opaquesTerms
NormalizedAc
{ elementsWithVariables = preOpaquesElementsWithVariables
, concreteElements = opaquesConcreteTerms
, opaque = opaquesOpaque
} <- case opaquesNormalized of
Bottom ->
bottomWithExplanation "Duplicated elements after unification."
Normalized result -> return (unwrapAc result)
let opaquesElementsWithVariables =
unwrapElement <$> preOpaquesElementsWithVariables
withVariableMap <-
addAllDisjoint
bottomWithExplanation
HashMap.empty
( commonVariablesTerms
++ withVariableTerms
++ opaquesElementsWithVariables
)
concreteMap <-
addAllDisjoint
bottomWithExplanation
HashMap.empty
( commonElementsTerms
++ concreteTerms
++ HashMap.toList opaquesConcreteTerms
)
let allOpaque = Data.List.sort (commonOpaque ++ opaquesOpaque)
predicate =
List.foldl'
andCondition
Condition.top
(almostResultConditions ++ opaquesConditions ++ predicates)
result ::
Conditional
variable
(normalized Key (TermLike variable))
result =
wrapAc
NormalizedAc
{ elementsWithVariables =
wrapElement <$> HashMap.toList withVariableMap
, concreteElements = concreteMap
, opaque = allOpaque
}
`Conditional.withCondition` predicate
return result
addAllDisjoint ::
(Monad unifier, Ord a, Hashable a) =>
(forall result. Text -> unifier result) ->
HashMap a b ->
[(a, b)] ->
unifier (HashMap a b)
addAllDisjoint bottomWithExplanation existing elements =
case addToMapDisjoint existing elements of
Nothing ->
bottomWithExplanation "Duplicated elements after AC unification."
Just result -> return result
unifyCommonElements ::
forall key normalized unifier variable.
( AcWrapper normalized
, MonadUnify unifier
, InternalVariable variable
, Traversable (Value normalized)
) =>
(TermLike variable -> TermLike variable -> unifier (Pattern variable)) ->
( key
, ( Value normalized (TermLike variable)
, Value normalized (TermLike variable)
)
) ->
unifier
( Conditional
variable
(key, Value normalized (TermLike variable))
)
unifyCommonElements
unifier
(key, (firstValue, secondValue)) =
do
valuesUnifier <- unifyWrappedValues unifier firstValue secondValue
let (valuesTerm, valueCondition) = Conditional.splitTerm valuesUnifier
return ((key, valuesTerm) `withCondition` valueCondition)
unifyWrappedValues ::
forall normalized unifier variable.
( AcWrapper normalized
, MonadUnify unifier
, InternalVariable variable
, Traversable (Value normalized)
) =>
(TermLike variable -> TermLike variable -> unifier (Pattern variable)) ->
Value normalized (TermLike variable) ->
Value normalized (TermLike variable) ->
unifier
(Conditional variable (Value normalized (TermLike variable)))
unifyWrappedValues unifier firstValue secondValue = do
let aligned = alignValues firstValue secondValue
unifiedValues <- traverse (uncurry unifier) aligned
let splitValues ::
Value normalized (TermLike variable, Condition variable)
splitValues = fmap Pattern.splitTerm unifiedValues
valueUnifierTerm :: Value normalized (TermLike variable)
valueUnifierTerm = fmap fst splitValues
valueConditions :: Value normalized (Condition variable)
valueConditions = fmap snd splitValues
valueUnifierCondition :: Condition variable
valueUnifierCondition =
foldr Conditional.andCondition Condition.top valueConditions
return (valueUnifierTerm `withCondition` valueUnifierCondition)
| two ac structures given their representation as a list of
@ConcreteOrWithVariable@ , with the first structure being allowed an additional
opaque chunk ( e.g. a variable ) that will be sent to the unifier function
together with some part of the second structure .
The keys of the two structures are assumend to be disjoint .
@ConcreteOrWithVariable@, with the first structure being allowed an additional
opaque chunk (e.g. a variable) that will be sent to the unifier function
together with some part of the second structure.
The keys of the two structures are assumend to be disjoint.
-}
unifyEqualsElementLists ::
forall normalized variable unifier.
( InternalVariable variable
, MonadUnify unifier
, TermWrapper normalized
, Traversable (Value normalized)
) =>
SmtMetadataTools Attribute.Symbol ->
TermLike variable ->
TermLike variable ->
(TermLike variable -> TermLike variable -> unifier (Pattern variable)) ->
| First structure elements
[ConcreteOrWithVariable normalized variable] ->
| Second structure elements
[ConcreteOrWithVariable normalized variable] ->
| Opaque element variable of the first structure
Maybe (ElementVariable variable) ->
unifier
( Conditional
variable
[(TermLike variable, Value normalized (TermLike variable))]
, [TermLike variable]
)
unifyEqualsElementLists
_tools
first
second
unifyEqualsChildren
firstElements
secondElements
Nothing
| length firstElements /= length secondElements =
Neither the first , not the second ac structure include an opaque term , so
the listed elements form the two structures .
Since the two lists have different counts , their structures can
debugUnifyBottomAndReturnBottom
"Cannot unify ac structures with different sizes."
first
second
| otherwise = do
(result, remainder1, remainder2) <-
unifyWithPermutations firstElements secondElements
The second structure does not include an opaque term so there is nothing
to match whatever is left in remainder1 . This should have been caught by
unless
(null remainder1)
(remainderError firstElements secondElements remainder1)
The first structure does not include an opaque term so there is nothing
to match whatever is left in remainder2 . This should have been caught by
unless
(null remainder2)
(remainderError firstElements secondElements remainder2)
return (result, [])
where
unifyWithPermutations ::
First structure elements
[ConcreteOrWithVariable normalized variable] ->
Second structure elements
[ConcreteOrWithVariable normalized variable] ->
unifier
( Conditional
variable
[ ( TermLike variable
, Value normalized (TermLike variable)
)
]
, [ConcreteOrWithVariable normalized variable]
, [ConcreteOrWithVariable normalized variable]
)
unifyWithPermutations =
unifyEqualsElementPermutations
(unifyEqualsConcreteOrWithVariable unifyEqualsChildren)
remainderError = nonEmptyRemainderError first second
unifyEqualsElementLists
tools
first
second
unifyEqualsChildren
firstElements
secondElements
(Just opaqueElemVar)
| length firstElements > length secondElements =
The second structure does not include an opaque term , so all the
elements in the first structure must be matched by elements in the second
debugUnifyBottomAndReturnBottom
"Cannot unify ac structures with different sizes."
first
second
| otherwise = do
(unifier, remainder1, remainder2) <-
unifyWithPermutations firstElements secondElements
The second structure does not include an opaque term so there is nothing
to match whatever is left in remainder1 . This should have been caught by
unless
(null remainder1)
(remainderError firstElements secondElements remainder1)
let remainder2Terms = map fromConcreteOrWithVariable remainder2
case elementListAsInternal
tools
(sameSort (termLikeSort first) (termLikeSort second))
remainder2Terms of
Nothing ->
debugUnifyBottomAndReturnBottom
"Duplicated element in unification results"
first
second
Just remainderTerm
| TermLike.isFunctionPattern remainderTerm -> do
opaqueUnifier <-
unifyEqualsChildren
(mkElemVar opaqueElemVar)
remainderTerm
let (opaqueTerm, opaqueCondition) =
Pattern.splitTerm opaqueUnifier
result = unifier `andCondition` opaqueCondition
return (result, [opaqueTerm])
_ ->
error . show . Pretty.vsep $
[ "Unification case that should be handled somewhere else: \
\attempting normalized unification with \
\non-function maps could lead to infinite loops."
, Pretty.indent 2 "first="
, Pretty.indent 4 (unparse first)
, Pretty.indent 2 "second="
, Pretty.indent 4 (unparse second)
]
where
unifyWithPermutations =
unifyEqualsElementPermutations
(unifyEqualsConcreteOrWithVariable unifyEqualsChildren)
remainderError = nonEmptyRemainderError first second
data NoCheckUnifyOpaqueChildrenData variable = NoCheckUnifyOpaqueChildrenData
Given normalized data norm1 , , the sole opaque variable in norm1 - norm2
v1 :: !(TermLike.ElementVariable variable)
second :: !(TermLike variable)
}
data UnifyOpVarResult variable
= NoCheckUnifyOpaqueChildren !(NoCheckUnifyOpaqueChildrenData variable)
| BottomWithExplanation
matchUnifyOpaqueVariable ::
( TermWrapper normalized
, InternalVariable variable
) =>
SmtMetadataTools Attribute.Symbol ->
TermLike.ElementVariable variable ->
[ConcreteOrWithVariable normalized variable] ->
[TermLike variable] ->
Maybe (UnifyOpVarResult variable)
matchUnifyOpaqueVariable _ v1 [] [second@(ElemVar_ _)] =
Just $ NoCheckUnifyOpaqueChildren NoCheckUnifyOpaqueChildrenData{v1, second}
matchUnifyOpaqueVariable
tools
v1
concreteOrVariableTerms
opaqueTerms =
case elementListAsNormalized pairs of
Nothing -> Just BottomWithExplanation
Just elementTerm ->
let secondTerm =
asInternal
tools
sort
( wrapAc
elementTerm{opaque = opaqueTerms}
)
in if TermLike.isFunctionPattern secondTerm
then
Just $
NoCheckUnifyOpaqueChildren $
NoCheckUnifyOpaqueChildrenData v1 secondTerm
else Nothing
where
sort = variableSort v1
pairs = map fromConcreteOrWithVariable concreteOrVariableTerms
unifyOpaqueVariable ::
( MonadUnify unifier
, InternalVariable variable
) =>
(forall a. Text -> unifier a) ->
(TermLike variable -> TermLike variable -> unifier (Pattern variable)) ->
UnifyOpVarResult variable ->
unifier
( Conditional
variable
[(TermLike variable, Value normalized (TermLike variable))]
, [TermLike variable]
)
unifyOpaqueVariable
bottomWithExplanation
unifyChildren
unifyData =
case unifyData of
NoCheckUnifyOpaqueChildren unifyData' ->
noCheckUnifyOpaqueChildren unifyChildren v1 second
where
NoCheckUnifyOpaqueChildrenData{v1, second} = unifyData'
_ ->
bottomWithExplanation
"Duplicated element in unification results"
noCheckUnifyOpaqueChildren ::
( MonadUnify unifier
, InternalVariable variable
) =>
(TermLike variable -> TermLike variable -> unifier (Pattern variable)) ->
TermLike.ElementVariable variable ->
TermLike variable ->
unifier
( Conditional
variable
[(TermLike variable, Value normalized (TermLike variable))]
, [TermLike variable]
)
noCheckUnifyOpaqueChildren unifyChildren v1 second = do
unifier <- unifyChildren (mkElemVar v1) second
let (opaque, predicate) = Conditional.splitTerm unifier
return ([] `Conditional.withCondition` predicate, [opaque])
|Unifies two patterns represented as @ConcreteOrWithVariable@ , making sure
that a concrete pattern ( if any ) is sent on the first position of the unify
function .
We prefer having a concrete pattern on the first position because the
unifier prefers returning it when it does not know what to use , e.g.
@
unify 10 ( f A ) = = > 10 and ( 10 = = f A )
unify ( f A ) 10 = = > ( f A ) and ( 10 = = f A )
@
and it would probably be more useful to have a concrete term as the
unification term . Also , tests are easier to write .
that a concrete pattern (if any) is sent on the first position of the unify
function.
We prefer having a concrete pattern on the first position because the
unifier prefers returning it when it does not know what to use, e.g.
@
unify 10 (f A) ==> 10 and (10 == f A)
unify (f A) 10 ==> (f A) and (10 == f A)
@
and it would probably be more useful to have a concrete term as the
unification term. Also, tests are easier to write.
-}
unifyEqualsConcreteOrWithVariable ::
( AcWrapper normalized
, MonadUnify unifier
, Traversable (Value normalized)
, InternalVariable variable
) =>
(TermLike variable -> TermLike variable -> unifier (Pattern variable)) ->
ConcreteOrWithVariable normalized variable ->
ConcreteOrWithVariable normalized variable ->
unifier
( Conditional
variable
(TermLike variable, Value normalized (TermLike variable))
)
unifyEqualsConcreteOrWithVariable
unifier
(ConcretePat concrete1)
(ConcretePat concrete2) =
unifyEqualsPair unifier concrete1 concrete2
unifyEqualsConcreteOrWithVariable
unifier
(ConcretePat concrete1)
(WithVariablePat withVariable2) =
unifyEqualsPair unifier concrete1 withVariable2
unifyEqualsConcreteOrWithVariable
unifier
(WithVariablePat withVariable)
(ConcretePat concrete2) =
unifyEqualsPair unifier concrete2 withVariable
unifyEqualsConcreteOrWithVariable
unifier
(WithVariablePat withVariable)
(WithVariablePat withVariable2) =
unifyEqualsPair unifier withVariable withVariable2
unifyEqualsPair ::
forall normalized unifier variable.
( AcWrapper normalized
, MonadUnify unifier
, InternalVariable variable
, Traversable (Value normalized)
) =>
(TermLike variable -> TermLike variable -> unifier (Pattern variable)) ->
(TermLike variable, Value normalized (TermLike variable)) ->
(TermLike variable, Value normalized (TermLike variable)) ->
unifier
( Conditional
variable
(TermLike variable, Value normalized (TermLike variable))
)
unifyEqualsPair
unifier
(firstKey, firstValue)
(secondKey, secondValue) =
do
keyUnifier <- unifier firstKey secondKey
valueUnifier <- unifyWrappedValues unifier firstValue secondValue
let valueUnifierTerm :: Value normalized (TermLike variable)
valueUnifierCondition :: Condition variable
(valueUnifierTerm, valueUnifierCondition) =
Conditional.splitTerm valueUnifier
let (keyUnifierTerm, keyUnifierCondition) = Pattern.splitTerm keyUnifier
return
( (keyUnifierTerm, valueUnifierTerm)
`withCondition` keyUnifierCondition
`andCondition` valueUnifierCondition
)
| Given a unify function and two lists of unifiable things , returns
all possible ways to unify disjoint pairs of the two that use all items
from at least one of the lists .
Also returns the non - unified part os the lists ( one of the two will be empty ) .
all possible ways to unify disjoint pairs of the two that use all items
from at least one of the lists.
Also returns the non-unified part os the lists (one of the two will be empty).
-}
unifyEqualsElementPermutations ::
( Alternative unifier
, Monad unifier
, InternalVariable variable
) =>
(a -> b -> unifier (Conditional variable c)) ->
[a] ->
[b] ->
unifier
( Conditional variable [c]
, [a]
, [b]
)
unifyEqualsElementPermutations unifier firsts seconds = do
(unifiers, remainderFirst, remainderSecond) <-
if length firsts < length seconds
then do
(u, r) <-
kPermutationsBacktracking (flip unifier) seconds firsts
return (u, [], r)
else do
(u, r) <-
kPermutationsBacktracking unifier firsts seconds
return (u, r, [])
let (terms, predicates) = unzip (map Conditional.splitTerm unifiers)
predicate = foldr andCondition Condition.top predicates
return (terms `withCondition` predicate, remainderFirst, remainderSecond)
|Given two lists generates k - permutation pairings and merges them using the
provided merge function .
k is the length of the second list , which means that , if the @[b]@ list is
longer than the @[a]@ list , this will not generate any k - permutations .
However , it will probably take a long time to generate nothing .
If the pairing function fails ( i.e. returns empty ) , the entire function will
stop exploring future branches that would include the given pair .
Note that this does not mean that we wo n't try a failing pair again with a
different set of previous choices , so this function could be optimized to
at least cache pairing results .
provided merge function.
k is the length of the second list, which means that, if the @[b]@ list is
longer than the @[a]@ list, this will not generate any k-permutations.
However, it will probably take a long time to generate nothing.
If the pairing function fails (i.e. returns empty), the entire function will
stop exploring future branches that would include the given pair.
Note that this does not mean that we won't try a failing pair again with a
different set of previous choices, so this function could be optimized to
at least cache pairing results.
-}
kPermutationsBacktracking ::
forall a b c m.
Alternative m =>
(a -> b -> m c) ->
[a] ->
[b] ->
m ([c], [a])
kPermutationsBacktracking _ first [] = pure ([], first)
kPermutationsBacktracking transform firstList secondList =
generateKPermutationsWorker firstList [] secondList
where
generateKPermutationsWorker :: [a] -> [a] -> [b] -> m ([c], [a])
generateKPermutationsWorker _ (_ : _) [] =
error "Unexpected non-empty skipped list with empty pair opportunities"
generateKPermutationsWorker [] [] [] = pure ([], [])
generateKPermutationsWorker [] _ _ = empty
generateKPermutationsWorker first [] [] = pure ([], first)
generateKPermutationsWorker (first : firsts) skipped (second : seconds) =
pickElement <|> skipElement
where
pickElement =
addToFirst
<$> transform first second
<*> generateKPermutationsWorker (skipped ++ firsts) [] seconds
addToFirst :: x -> ([x], y) -> ([x], y)
addToFirst x (xs, y) = (x : xs, y)
skipElement =
generateKPermutationsWorker
firsts
(first : skipped)
(second : seconds)
nonEmptyRemainderError ::
forall a normalized variable.
( HasCallStack
, InternalVariable variable
, AcWrapper normalized
) =>
TermLike variable ->
TermLike variable ->
[ConcreteOrWithVariable normalized variable] ->
[ConcreteOrWithVariable normalized variable] ->
[ConcreteOrWithVariable normalized variable] ->
a
nonEmptyRemainderError first second input1 input2 remainder =
(error . unlines)
[ "Unexpected unused elements, should have been caught"
, "by checks above:"
, "first=" ++ unparseToString first
, "second=" ++ unparseToString second
, "input1=" ++ unlines (map unparseWrapped input1)
, "input2=" ++ unlines (map unparseWrapped input2)
, "remainder=" ++ unlines (map unparseWrapped remainder)
]
where
unparseWrapped =
Unparser.renderDefault . unparsePair . fromConcreteOrWithVariable
unparsePair = unparseElement unparse . wrapElement
newtype UnitSymbol = UnitSymbol {getUnitSymbol :: Symbol}
newtype ConcatSymbol = ConcatSymbol {getConcatSymbol :: Symbol}
newtype ConcreteElements variable = ConcreteElements {getConcreteElements :: [TermLike variable]}
newtype VariableElements variable = VariableElements {getVariableElements :: [TermLike variable]}
newtype Opaque variable = Opaque {getOpaque :: [TermLike variable]}
|
f9796195a4ab4419c2d242b92deb401a2a1bdc787aa358b907b935659755bd1a | proger/lxperf | connmatch.hs | # LANGUAGE OverloadedStrings , ScopedTypeVariables #
-----------------------------------------------------------------------------
---- |
---- Module : Main
----
-- ` connmatch ' parses the file that maps local IPs to hostnames and
-- a directory of lsof outputs where files are named exactly as
---- hostnames. `lsof' outputs are connected into a list of connections
-- which are used as graphviz edges .
---- The current implementation doesn't take any outgoing connections into
---- account yet.
----
-------------------------------------------------------------------------------
--
module Main where
import System.Environment (getArgs)
import System.Directory (getDirectoryContents)
import Control.Monad (join)
import qualified Data.ByteString as BS
import qualified Data.ByteString.Char8 as C
import qualified Data.Map.Strict as M
import qualified Data.List as L
import Data.Maybe (catMaybes)
import Data.Word (Word8)
newtype Process = Process BS.ByteString deriving (Show, Eq)
newtype Host = Host BS.ByteString deriving (Show, Eq)
newtype Addr = Addr (IP, BS.ByteString) deriving (Show, Ord, Eq)
-- | 'lsof' entry
data OpenFile = Connection Host Process Addr Addr
| Listen Host Process Addr
deriving (Show, Eq)
data IP = IP BS.ByteString
| Any
deriving (Show, Ord, Eq)
type IPMap = M.Map IP Host
-- | How an OpenFile links to the network: locally, connects somewhere else
-- or does not link at all (listening socket).
data Link = Link OpenFile | External | Empty deriving (Show)
sIP :: BS.ByteString -> IP
sIP "*" = Any
sIP s = IP s
sAddr :: BS.ByteString -> Addr
sAddr s = Addr (sIP ip, port)
where
[ip, port] = C.split ':' s
-- | Extract a source address from an 'OpenFile'.
openFileSrc :: OpenFile -> Addr
openFileSrc (Connection _ _ src _) = src
openFileSrc (Listen _ _ src) = src
-- | Checks if an address is IPv6, which is not supported.
addrNotIp6 :: BS.ByteString -> Bool
addrNotIp6 a = (BS.head a) /= (BS.head "[")
matchAddr :: IPMap -> Host -> Addr -> Addr
matchAddr ipmap (Host defaultHost) addr@(Addr (ip, port)) = maybe addr toAddr $ M.lookup ip ipmap
where toAddr (Host host) = Addr (IP host, port)
sOpenFile :: IPMap
-> String -- ^ hostname that will turn into a 'Host'
-> [BS.ByteString] -- ^ tokenized line of lsof: COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME (STATE)
-> Maybe OpenFile
sOpenFile ipmap hostname [comm, _, _, _, _, _, _, "TCP", name, state]
| addrNotIp6 name = let hostS = C.pack hostname
host = Host hostS
addr s = case sAddr s of -- cleanup ambiguous addresses
Addr (IP "127.0.0.1", port) -> Addr (IP hostS, port)
Addr (Any, port) -> Addr (IP hostS, port)
a -> matchAddr ipmap host a
in case state of
"(LISTEN)" ->
Just $ Listen host (Process comm) (addr name)
_ ->
Just $ Connection host (Process comm) (addr src) (addr dst)
where
dst = C.drop 2 dst'
(src, dst') = C.breakSubstring "->" name
| otherwise = Nothing
sOpenFile _ _ _ = Nothing
srcMap :: [OpenFile] -> M.Map Addr OpenFile
srcMap = M.fromList . map (\c -> (openFileSrc c, c))
linkFiles :: [OpenFile] -> M.Map Addr OpenFile -> [(OpenFile, Link)]
linkFiles conns srcmap = [(c, pair c) | c <- conns]
where
pair (Listen _ _ _) = Empty
pair conn@(Connection _ _ _ dst) = case M.lookup dst srcmap of
Just f -> Link f
Nothing -> External
mapFromIpaddrs :: BS.ByteString -> IPMap
mapFromIpaddrs = M.fromList . map ((\[a,b] -> (sIP b, Host a)) . C.words) . C.lines
lsofOpenFiles :: IPMap -> String -> BS.ByteString -> [OpenFile]
lsofOpenFiles ipmap h = catMaybes . map (sOpenFile ipmap h . C.words) . drop 1 . C.lines
data Stream = Stream Process Addr Process Addr deriving (Show, Eq)
stream :: IPMap -> (OpenFile, Link) -> Maybe Stream
stream ipmap connpair = uncurry link connpair
where
link c Empty = Nothing
link c (Link l) = Just $ streamLink c l
link (Connection h p src dst@(Addr (IP ipD, portD)))
External = Just $ Stream p src (Process portD) dst
streamLink (Connection hA pA srcA dstA)
(Connection hB pB srcB dstB) = Stream pA srcA pB srcB
streamLink (Connection hA pA srcA dstA) (Listen hB pB srcB) = Stream pA srcA pB srcB
streamLink (Listen hA pA srcA) (Connection hB pB srcB dstB) = Stream pA srcA pB srcB
data Edge = Edge BS.ByteString BS.ByteString deriving (Show)
instance Eq Edge where
(Edge a1 a2) == (Edge b1 b2) = (a1 == b1 && a2 == b2) || (a1 == b2 && a2 == b1)
edge (Stream (Process commA) (Addr (IP addrA, _)) (Process commB) (Addr (IP addrB, _))) = Edge (C.concat [addrA, ":", commA]) (C.concat [addrB, ":", commB])
isJustListen (Just (Listen _ _ _)) = True
isJustListen _ = False
inputs :: String -> String -> IO (IPMap, [OpenFile])
inputs ipaddrPairsFile lsofPath = do
ipmap <- BS.readFile ipaddrPairsFile >>= return . mapFromIpaddrs
_:_:lsofs <- getDirectoryContents lsofPath
connections <- mapM (\f -> BS.readFile (lsofPath ++ "/" ++ f) >>= return . lsofOpenFiles ipmap f) lsofs >>= return . concat
return (ipmap, connections)
graph :: IPMap -> [OpenFile] -> [Edge]
graph ipaddrs connections = L.nub $ map edge $ catMaybes $ map (stream ipaddrs) pairs
where
srcmap = srcMap connections
pairs = linkFiles connections srcmap
-- nice to have: actually show lonely nodes (i.e. daemons that
-- nobody's connected to) and connections that go outside
graphStr edges = iolist [["graph G {\n"], map render edges, ["}\n"]]
where
iolist = C.concat . join
render (Edge a b) = C.concat ["\"", a, "\" -- \"", b, "\";\n"]
main :: IO ()
main = do
[ipaddrPairsFile, lsofPath] <- getArgs
(ipaddrs, connections) <- inputs ipaddrPairsFile lsofPath
C.putStrLn $ graphStr $ graph ipaddrs connections
| null | https://raw.githubusercontent.com/proger/lxperf/46fdc9951ad759882af33378d569ba86d5f6af2f/connmatch/connmatch.hs | haskell | ---------------------------------------------------------------------------
-- |
-- Module : Main
--
` connmatch ' parses the file that maps local IPs to hostnames and
a directory of lsof outputs where files are named exactly as
-- hostnames. `lsof' outputs are connected into a list of connections
which are used as graphviz edges .
-- The current implementation doesn't take any outgoing connections into
-- account yet.
--
-----------------------------------------------------------------------------
| 'lsof' entry
| How an OpenFile links to the network: locally, connects somewhere else
or does not link at all (listening socket).
| Extract a source address from an 'OpenFile'.
| Checks if an address is IPv6, which is not supported.
^ hostname that will turn into a 'Host'
^ tokenized line of lsof: COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME (STATE)
cleanup ambiguous addresses
nice to have: actually show lonely nodes (i.e. daemons that
nobody's connected to) and connections that go outside | # LANGUAGE OverloadedStrings , ScopedTypeVariables #
module Main where
import System.Environment (getArgs)
import System.Directory (getDirectoryContents)
import Control.Monad (join)
import qualified Data.ByteString as BS
import qualified Data.ByteString.Char8 as C
import qualified Data.Map.Strict as M
import qualified Data.List as L
import Data.Maybe (catMaybes)
import Data.Word (Word8)
newtype Process = Process BS.ByteString deriving (Show, Eq)
newtype Host = Host BS.ByteString deriving (Show, Eq)
newtype Addr = Addr (IP, BS.ByteString) deriving (Show, Ord, Eq)
data OpenFile = Connection Host Process Addr Addr
| Listen Host Process Addr
deriving (Show, Eq)
data IP = IP BS.ByteString
| Any
deriving (Show, Ord, Eq)
type IPMap = M.Map IP Host
data Link = Link OpenFile | External | Empty deriving (Show)
sIP :: BS.ByteString -> IP
sIP "*" = Any
sIP s = IP s
sAddr :: BS.ByteString -> Addr
sAddr s = Addr (sIP ip, port)
where
[ip, port] = C.split ':' s
openFileSrc :: OpenFile -> Addr
openFileSrc (Connection _ _ src _) = src
openFileSrc (Listen _ _ src) = src
addrNotIp6 :: BS.ByteString -> Bool
addrNotIp6 a = (BS.head a) /= (BS.head "[")
matchAddr :: IPMap -> Host -> Addr -> Addr
matchAddr ipmap (Host defaultHost) addr@(Addr (ip, port)) = maybe addr toAddr $ M.lookup ip ipmap
where toAddr (Host host) = Addr (IP host, port)
sOpenFile :: IPMap
-> Maybe OpenFile
sOpenFile ipmap hostname [comm, _, _, _, _, _, _, "TCP", name, state]
| addrNotIp6 name = let hostS = C.pack hostname
host = Host hostS
Addr (IP "127.0.0.1", port) -> Addr (IP hostS, port)
Addr (Any, port) -> Addr (IP hostS, port)
a -> matchAddr ipmap host a
in case state of
"(LISTEN)" ->
Just $ Listen host (Process comm) (addr name)
_ ->
Just $ Connection host (Process comm) (addr src) (addr dst)
where
dst = C.drop 2 dst'
(src, dst') = C.breakSubstring "->" name
| otherwise = Nothing
sOpenFile _ _ _ = Nothing
srcMap :: [OpenFile] -> M.Map Addr OpenFile
srcMap = M.fromList . map (\c -> (openFileSrc c, c))
linkFiles :: [OpenFile] -> M.Map Addr OpenFile -> [(OpenFile, Link)]
linkFiles conns srcmap = [(c, pair c) | c <- conns]
where
pair (Listen _ _ _) = Empty
pair conn@(Connection _ _ _ dst) = case M.lookup dst srcmap of
Just f -> Link f
Nothing -> External
mapFromIpaddrs :: BS.ByteString -> IPMap
mapFromIpaddrs = M.fromList . map ((\[a,b] -> (sIP b, Host a)) . C.words) . C.lines
lsofOpenFiles :: IPMap -> String -> BS.ByteString -> [OpenFile]
lsofOpenFiles ipmap h = catMaybes . map (sOpenFile ipmap h . C.words) . drop 1 . C.lines
data Stream = Stream Process Addr Process Addr deriving (Show, Eq)
stream :: IPMap -> (OpenFile, Link) -> Maybe Stream
stream ipmap connpair = uncurry link connpair
where
link c Empty = Nothing
link c (Link l) = Just $ streamLink c l
link (Connection h p src dst@(Addr (IP ipD, portD)))
External = Just $ Stream p src (Process portD) dst
streamLink (Connection hA pA srcA dstA)
(Connection hB pB srcB dstB) = Stream pA srcA pB srcB
streamLink (Connection hA pA srcA dstA) (Listen hB pB srcB) = Stream pA srcA pB srcB
streamLink (Listen hA pA srcA) (Connection hB pB srcB dstB) = Stream pA srcA pB srcB
data Edge = Edge BS.ByteString BS.ByteString deriving (Show)
instance Eq Edge where
(Edge a1 a2) == (Edge b1 b2) = (a1 == b1 && a2 == b2) || (a1 == b2 && a2 == b1)
edge (Stream (Process commA) (Addr (IP addrA, _)) (Process commB) (Addr (IP addrB, _))) = Edge (C.concat [addrA, ":", commA]) (C.concat [addrB, ":", commB])
isJustListen (Just (Listen _ _ _)) = True
isJustListen _ = False
inputs :: String -> String -> IO (IPMap, [OpenFile])
inputs ipaddrPairsFile lsofPath = do
ipmap <- BS.readFile ipaddrPairsFile >>= return . mapFromIpaddrs
_:_:lsofs <- getDirectoryContents lsofPath
connections <- mapM (\f -> BS.readFile (lsofPath ++ "/" ++ f) >>= return . lsofOpenFiles ipmap f) lsofs >>= return . concat
return (ipmap, connections)
graph :: IPMap -> [OpenFile] -> [Edge]
graph ipaddrs connections = L.nub $ map edge $ catMaybes $ map (stream ipaddrs) pairs
where
srcmap = srcMap connections
pairs = linkFiles connections srcmap
graphStr edges = iolist [["graph G {\n"], map render edges, ["}\n"]]
where
iolist = C.concat . join
render (Edge a b) = C.concat ["\"", a, "\" -- \"", b, "\";\n"]
main :: IO ()
main = do
[ipaddrPairsFile, lsofPath] <- getArgs
(ipaddrs, connections) <- inputs ipaddrPairsFile lsofPath
C.putStrLn $ graphStr $ graph ipaddrs connections
|
cdcbbca2826e6224ab044650c078e71891fde8001ebc6dbd12c2b62c702d473d | juspay/atlas | StartRide.hs | |
Copyright 2022 Juspay Technologies Pvt Ltd
Licensed under the Apache License , Version 2.0 ( the " License " ) ;
you may not use this file except in compliance with the License .
You may obtain a copy of the License at
-2.0
Unless required by applicable law or agreed to in writing , software
distributed under the License is distributed on an " AS IS " BASIS ,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND , either express or implied .
See the License for the specific language governing permissions and
limitations under the License .
Module : Product . RideAPI.Handlers . StartRide
Copyright : ( C ) Juspay Technologies Pvt Ltd 2019 - 2022
License : Apache 2.0 ( see the file LICENSE )
Maintainer :
Stability : experimental
Portability : non - portable
Copyright 2022 Juspay Technologies Pvt Ltd
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
Module : Product.RideAPI.Handlers.StartRide
Copyright : (C) Juspay Technologies Pvt Ltd 2019-2022
License : Apache 2.0 (see the file LICENSE)
Maintainer :
Stability : experimental
Portability : non-portable
-}
module Product.RideAPI.Handlers.StartRide where
import qualified Beckn.Types.APISuccess as APISuccess
import Beckn.Types.Common
import Beckn.Types.Id
import qualified Domain.Types.Person as Person
import qualified Domain.Types.Ride as SRide
import qualified Domain.Types.RideBooking as SRB
import EulerHS.Prelude
import Types.Error
import Utils.Common
data ServiceHandle m = ServiceHandle
{ findById :: Id Person.Person -> m (Maybe Person.Person),
findRideBookingById :: Id SRB.RideBooking -> m (Maybe SRB.RideBooking),
findRideById :: Id SRide.Ride -> m (Maybe SRide.Ride),
startRide :: Id SRide.Ride -> Id SRB.RideBooking -> Id Person.Person -> m (),
notifyBAPRideStarted :: SRB.RideBooking -> SRide.Ride -> m (),
rateLimitStartRide :: Id Person.Person -> Id SRide.Ride -> m ()
}
startRideHandler :: (MonadThrow m, Log m) => ServiceHandle m -> Id Person.Person -> Id SRide.Ride -> Text -> m APISuccess.APISuccess
startRideHandler ServiceHandle {..} requestorId rideId otp = do
rateLimitStartRide requestorId rideId
requestor <- findById requestorId >>= fromMaybeM (PersonNotFound requestorId.getId)
ride <- findRideById rideId >>= fromMaybeM (RideDoesNotExist rideId.getId)
case requestor.role of
Person.DRIVER -> do
let rideDriver = ride.driverId
unless (rideDriver == requestorId) $ throwError NotAnExecutor
_ -> throwError AccessDenied
unless (isValidRideStatus (ride.status)) $ throwError $ RideInvalidStatus "This ride cannot be started"
rideBooking <- findRideBookingById ride.bookingId >>= fromMaybeM (RideBookingNotFound ride.bookingId.getId)
let inAppOtp = ride.otp
when (otp /= inAppOtp) $ throwError IncorrectOTP
logTagInfo "startRide" ("DriverId " <> getId requestorId <> ", RideId " <> getId rideId)
startRide ride.id rideBooking.id requestorId
notifyBAPRideStarted rideBooking ride
pure APISuccess.Success
where
isValidRideStatus status = status == SRide.NEW
| null | https://raw.githubusercontent.com/juspay/atlas/e64b227dc17887fb01c2554db21c08284d18a806/app/atlas-transport/src/Product/RideAPI/Handlers/StartRide.hs | haskell | |
Copyright 2022 Juspay Technologies Pvt Ltd
Licensed under the Apache License , Version 2.0 ( the " License " ) ;
you may not use this file except in compliance with the License .
You may obtain a copy of the License at
-2.0
Unless required by applicable law or agreed to in writing , software
distributed under the License is distributed on an " AS IS " BASIS ,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND , either express or implied .
See the License for the specific language governing permissions and
limitations under the License .
Module : Product . RideAPI.Handlers . StartRide
Copyright : ( C ) Juspay Technologies Pvt Ltd 2019 - 2022
License : Apache 2.0 ( see the file LICENSE )
Maintainer :
Stability : experimental
Portability : non - portable
Copyright 2022 Juspay Technologies Pvt Ltd
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
Module : Product.RideAPI.Handlers.StartRide
Copyright : (C) Juspay Technologies Pvt Ltd 2019-2022
License : Apache 2.0 (see the file LICENSE)
Maintainer :
Stability : experimental
Portability : non-portable
-}
module Product.RideAPI.Handlers.StartRide where
import qualified Beckn.Types.APISuccess as APISuccess
import Beckn.Types.Common
import Beckn.Types.Id
import qualified Domain.Types.Person as Person
import qualified Domain.Types.Ride as SRide
import qualified Domain.Types.RideBooking as SRB
import EulerHS.Prelude
import Types.Error
import Utils.Common
data ServiceHandle m = ServiceHandle
{ findById :: Id Person.Person -> m (Maybe Person.Person),
findRideBookingById :: Id SRB.RideBooking -> m (Maybe SRB.RideBooking),
findRideById :: Id SRide.Ride -> m (Maybe SRide.Ride),
startRide :: Id SRide.Ride -> Id SRB.RideBooking -> Id Person.Person -> m (),
notifyBAPRideStarted :: SRB.RideBooking -> SRide.Ride -> m (),
rateLimitStartRide :: Id Person.Person -> Id SRide.Ride -> m ()
}
startRideHandler :: (MonadThrow m, Log m) => ServiceHandle m -> Id Person.Person -> Id SRide.Ride -> Text -> m APISuccess.APISuccess
startRideHandler ServiceHandle {..} requestorId rideId otp = do
rateLimitStartRide requestorId rideId
requestor <- findById requestorId >>= fromMaybeM (PersonNotFound requestorId.getId)
ride <- findRideById rideId >>= fromMaybeM (RideDoesNotExist rideId.getId)
case requestor.role of
Person.DRIVER -> do
let rideDriver = ride.driverId
unless (rideDriver == requestorId) $ throwError NotAnExecutor
_ -> throwError AccessDenied
unless (isValidRideStatus (ride.status)) $ throwError $ RideInvalidStatus "This ride cannot be started"
rideBooking <- findRideBookingById ride.bookingId >>= fromMaybeM (RideBookingNotFound ride.bookingId.getId)
let inAppOtp = ride.otp
when (otp /= inAppOtp) $ throwError IncorrectOTP
logTagInfo "startRide" ("DriverId " <> getId requestorId <> ", RideId " <> getId rideId)
startRide ride.id rideBooking.id requestorId
notifyBAPRideStarted rideBooking ride
pure APISuccess.Success
where
isValidRideStatus status = status == SRide.NEW
|
|
bd9ff620e57e58d752bf446016a2c8b8447bddb369425be710f210f9e23c27aa | CrossRef/cayenne | transform.clj | (ns cayenne.api.transform
(:require [cayenne.util :as util]
[cayenne.conf :as conf]
[cayenne.formats.rdf :as rdf]
[cayenne.formats.ris :as ris]
[cayenne.formats.citation :as citation]
[cayenne.formats.bibtex :as bibtex]
[clojure.data.json :as json]
[org.httpkit.client :as hc]))
(def legacy-styles
{"mla" "modern-language-association"
"harvard3" "harvard1"})
(def csl-type
{:journal-article :article-journal
:book-chapter :chapter
:posted-conent :manuscript
:proceedings-article :paper-conference})
(defmulti ->format :media-type)
(defmethod ->format "text/turtle" [representation metadata]
(rdf/->turtle metadata))
(defmethod ->format "text/n3" [representation metadata]
(rdf/->n3 metadata))
(defmethod ->format "text/n-triples" [representation metadata]
(rdf/->n-triples metadata))
(defmethod ->format "application/rdf+xml" [representation metadata]
(rdf/->xml metadata))
(defmethod ->format "application/vnd.citationstyles.csl+json" [representation metadata]
(json/write-str
(cond-> metadata
(-> metadata :type csl-type)
(assoc :type (csl-type (:type metadata)))
(seq (:title metadata))
(assoc :title (first (:title metadata)))
(seq (:container-title metadata))
(assoc :container-title (first (:container-title metadata)))
(seq (:short-container-title metadata))
(assoc :container-title-short (first (:short-container-title metadata)))
(seq (:event metadata))
(assoc :event (get-in metadata [:event :name]))
:always
(dissoc :short-container-title :archive :issn-type))))
(defmethod ->format "application/x-research-info-systems" [representation metadata]
(ris/->ris metadata))
(defmethod ->format "text/x-bibliography" [representation metadata]
(let [args (concat
(when-let [style (get-in representation [:parameters :style])]
[:style (or (legacy-styles style) style)])
(when-let [lang (get-in representation [:parameters :locale])]
[:language lang])
(when-let [format (get-in representation [:parameters :format])]
[:format format]))]
(apply citation/->citation metadata args)))
(defmethod ->format "application/x-bibtex" [representation metadata]
(bibtex/->bibtex metadata))
;; legacy formats
(defmethod ->format "text/bibliography" [representation metadata]
(->format (assoc representation :media-type "text/x-bibliography")
metadata))
(defmethod ->format "application/citeproc+json" [representation metadata]
(->format (assoc representation :media-type "application/vnd.citationstyles.csl+json")
metadata))
(defmethod ->format "application/json" [representation metadata]
(->format (assoc representation :media-type "application/vnd.citationstyles.csl+json")
metadata))
(defmethod ->format "application/unixref+xml" [representation metadata]
(->format (assoc representation :media-type "application/vnd.crossref.unixref+xml")
metadata))
(defmethod ->format "text/plain" [representation metadata]
(->format (assoc representation :media-type "text/x-bibliography")
metadata))
;; for now we retrieve original unixref and unixsd, but in future perhaps we
will generate from citeproc
(defmethod ->format "application/vnd.crossref.unixref+xml" [representation metadata]
(-> (str (conf/get-param [:upstream :unixref-url]) (:DOI metadata))
(hc/get {:timeout 4000})
(deref)
(:body)))
(defmethod ->format "application/vnd.crossref.unixsd+xml" [representation metadata]
(-> (str (conf/get-param [:upstream :unixsd-url]) (:DOI metadata))
(hc/get {:timeout 4000})
(deref)
(:body)))
| null | https://raw.githubusercontent.com/CrossRef/cayenne/02321ad23dbb1edd3f203a415f4a4b11ebf810d7/src/cayenne/api/transform.clj | clojure | legacy formats
for now we retrieve original unixref and unixsd, but in future perhaps we | (ns cayenne.api.transform
(:require [cayenne.util :as util]
[cayenne.conf :as conf]
[cayenne.formats.rdf :as rdf]
[cayenne.formats.ris :as ris]
[cayenne.formats.citation :as citation]
[cayenne.formats.bibtex :as bibtex]
[clojure.data.json :as json]
[org.httpkit.client :as hc]))
(def legacy-styles
{"mla" "modern-language-association"
"harvard3" "harvard1"})
(def csl-type
{:journal-article :article-journal
:book-chapter :chapter
:posted-conent :manuscript
:proceedings-article :paper-conference})
(defmulti ->format :media-type)
(defmethod ->format "text/turtle" [representation metadata]
(rdf/->turtle metadata))
(defmethod ->format "text/n3" [representation metadata]
(rdf/->n3 metadata))
(defmethod ->format "text/n-triples" [representation metadata]
(rdf/->n-triples metadata))
(defmethod ->format "application/rdf+xml" [representation metadata]
(rdf/->xml metadata))
(defmethod ->format "application/vnd.citationstyles.csl+json" [representation metadata]
(json/write-str
(cond-> metadata
(-> metadata :type csl-type)
(assoc :type (csl-type (:type metadata)))
(seq (:title metadata))
(assoc :title (first (:title metadata)))
(seq (:container-title metadata))
(assoc :container-title (first (:container-title metadata)))
(seq (:short-container-title metadata))
(assoc :container-title-short (first (:short-container-title metadata)))
(seq (:event metadata))
(assoc :event (get-in metadata [:event :name]))
:always
(dissoc :short-container-title :archive :issn-type))))
(defmethod ->format "application/x-research-info-systems" [representation metadata]
(ris/->ris metadata))
(defmethod ->format "text/x-bibliography" [representation metadata]
(let [args (concat
(when-let [style (get-in representation [:parameters :style])]
[:style (or (legacy-styles style) style)])
(when-let [lang (get-in representation [:parameters :locale])]
[:language lang])
(when-let [format (get-in representation [:parameters :format])]
[:format format]))]
(apply citation/->citation metadata args)))
(defmethod ->format "application/x-bibtex" [representation metadata]
(bibtex/->bibtex metadata))
(defmethod ->format "text/bibliography" [representation metadata]
(->format (assoc representation :media-type "text/x-bibliography")
metadata))
(defmethod ->format "application/citeproc+json" [representation metadata]
(->format (assoc representation :media-type "application/vnd.citationstyles.csl+json")
metadata))
(defmethod ->format "application/json" [representation metadata]
(->format (assoc representation :media-type "application/vnd.citationstyles.csl+json")
metadata))
(defmethod ->format "application/unixref+xml" [representation metadata]
(->format (assoc representation :media-type "application/vnd.crossref.unixref+xml")
metadata))
(defmethod ->format "text/plain" [representation metadata]
(->format (assoc representation :media-type "text/x-bibliography")
metadata))
will generate from citeproc
(defmethod ->format "application/vnd.crossref.unixref+xml" [representation metadata]
(-> (str (conf/get-param [:upstream :unixref-url]) (:DOI metadata))
(hc/get {:timeout 4000})
(deref)
(:body)))
(defmethod ->format "application/vnd.crossref.unixsd+xml" [representation metadata]
(-> (str (conf/get-param [:upstream :unixsd-url]) (:DOI metadata))
(hc/get {:timeout 4000})
(deref)
(:body)))
|
8dae09fc9ab8a3ac0a4552ea4efe8d6019b3e9b0191edb73023ca323b9b7625a | haskell/zlib | gunzip.hs | module Main where
import qualified Data.ByteString.Lazy as B
import qualified Codec.Compression.GZip as GZip
main = B.interact GZip.decompress
| null | https://raw.githubusercontent.com/haskell/zlib/7fe9bd49c28be0b5b523e7e78a91638ecea4d28d/examples/gunzip.hs | haskell | module Main where
import qualified Data.ByteString.Lazy as B
import qualified Codec.Compression.GZip as GZip
main = B.interact GZip.decompress
|
|
190e6b0cc2fad24c1f4b17224ecd8a933c382dc97256e1f6207e05a1c684550c | tweag/ormolu | inline-comment-1.hs | 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
| null | https://raw.githubusercontent.com/tweag/ormolu/34bdf62429768f24b70d0f8ba7730fc4d8ae73ba/data/examples/other/inline-comment-1.hs | haskell | normalise ctxt env
normalise ctxt env
normalise ctxt 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
|
d5e96ac54c70c846dba161ccb65815be4a0ba24f9ee3c1162b685311feeba77d | velveteer/slacker | Section.hs | # LANGUAGE FlexibleInstances #
# LANGUAGE TypeFamilies #
module Slacker.Blocks.Section
( SectionBlock(..)
, SectionAccessory(..)
, SectionAccessoryTypes
, SectionFields(..)
, field
, asAccessory
, defaultSection
) where
import qualified Data.Aeson as Aeson
import Data.Text (Text)
import Data.WorldPeace
import GHC.Generics (Generic)
import Slacker.Blocks.Fields
import Slacker.Blocks.Elements.Button
import Slacker.Blocks.Elements.Image
import Slacker.Blocks.Elements.TextObject
import Slacker.Util (toJSONWithTypeField)
data SectionBlock
= SectionBlock
{ text :: !TextObject
, block_id :: !(Maybe Text)
, fields :: !(Maybe SectionFields)
, accessory :: !(Maybe SectionAccessory)
} deriving stock (Generic)
defaultSection :: TextObject -> SectionBlock
defaultSection txt
= SectionBlock
{ text = txt
, block_id = Nothing
, fields = Nothing
, accessory = Nothing
}
instance Aeson.ToJSON SectionBlock where
toJSON
= toJSONWithTypeField "section"
. Aeson.genericToJSON Aeson.defaultOptions
{ Aeson.omitNothingFields = True
}
type SectionAccessoryTypes
= '[ ButtonElement
, ImageElement
]
newtype SectionAccessory
= SectionAccessory
{ unSectionAccessory :: OpenUnion SectionAccessoryTypes
} deriving newtype (Aeson.ToJSON)
instance HasButton SectionAccessory where
button = asAccessory
instance HasImage ImageElement SectionAccessory where
image = asAccessory
image_ url alt = image $ defaultImage url alt
asAccessory :: forall a. IsMember a SectionAccessoryTypes => a -> SectionAccessory
asAccessory = SectionAccessory . openUnionLift
| null | https://raw.githubusercontent.com/velveteer/slacker/4770be507cef60df6ab76e8331efe683f67f0ef2/src/Slacker/Blocks/Section.hs | haskell | # LANGUAGE FlexibleInstances #
# LANGUAGE TypeFamilies #
module Slacker.Blocks.Section
( SectionBlock(..)
, SectionAccessory(..)
, SectionAccessoryTypes
, SectionFields(..)
, field
, asAccessory
, defaultSection
) where
import qualified Data.Aeson as Aeson
import Data.Text (Text)
import Data.WorldPeace
import GHC.Generics (Generic)
import Slacker.Blocks.Fields
import Slacker.Blocks.Elements.Button
import Slacker.Blocks.Elements.Image
import Slacker.Blocks.Elements.TextObject
import Slacker.Util (toJSONWithTypeField)
data SectionBlock
= SectionBlock
{ text :: !TextObject
, block_id :: !(Maybe Text)
, fields :: !(Maybe SectionFields)
, accessory :: !(Maybe SectionAccessory)
} deriving stock (Generic)
defaultSection :: TextObject -> SectionBlock
defaultSection txt
= SectionBlock
{ text = txt
, block_id = Nothing
, fields = Nothing
, accessory = Nothing
}
instance Aeson.ToJSON SectionBlock where
toJSON
= toJSONWithTypeField "section"
. Aeson.genericToJSON Aeson.defaultOptions
{ Aeson.omitNothingFields = True
}
type SectionAccessoryTypes
= '[ ButtonElement
, ImageElement
]
newtype SectionAccessory
= SectionAccessory
{ unSectionAccessory :: OpenUnion SectionAccessoryTypes
} deriving newtype (Aeson.ToJSON)
instance HasButton SectionAccessory where
button = asAccessory
instance HasImage ImageElement SectionAccessory where
image = asAccessory
image_ url alt = image $ defaultImage url alt
asAccessory :: forall a. IsMember a SectionAccessoryTypes => a -> SectionAccessory
asAccessory = SectionAccessory . openUnionLift
|
|
3594010c6fa5d72881057d57ea2ef25c219d6f8c238cf46f5c02c6a7c6d5b4c4 | Swizec/random-coding | 3.clj |
The prime factors of 13195 are 5 , 7 , 13 and 29 .
What is the largest prime factor of the number 600851475143 ?
(defn any? [l]
(reduce #(or %1 %2) l))
(defn prime? [n known]
(loop [cnt (dec (count known)) acc []]
(if (< cnt 0) (not (any? acc))
(recur (dec cnt) (concat acc [(zero? (mod n (nth known cnt)))])))))
(defn next-prime [primes]
(let [n (inc (count primes))]
(let [lk (if (even? (inc (last primes))) (+ 2 (last primes)) (inc (last primes)))]
(loop [cnt lk p primes]
(if (>= (count p) n) (last p)
(recur (+ cnt 2) (if (prime? cnt p) (concat p [cnt]) p)))))))
(memoize next-prime)
(defn n-primes [n]
(loop [cnt 1 p [2]]
(if (>= cnt n) p
(recur (inc cnt) (concat p [(next-prime p)])))))
(defn factor [n factors primes]
(if (== n 1) factors
(loop [p primes]
(if (== 0 (mod n (last p))) (factor
(/ n (last p))
(concat [(last p)] factors)
p)
(recur (concat p [(next-prime p)]))))))
(println (factor 600851475143 [] (n-primes 1))) | null | https://raw.githubusercontent.com/Swizec/random-coding/adeb72d35c52a7792a596ddc0a5241035ba9dda8/project-euler/3.clj | clojure |
The prime factors of 13195 are 5 , 7 , 13 and 29 .
What is the largest prime factor of the number 600851475143 ?
(defn any? [l]
(reduce #(or %1 %2) l))
(defn prime? [n known]
(loop [cnt (dec (count known)) acc []]
(if (< cnt 0) (not (any? acc))
(recur (dec cnt) (concat acc [(zero? (mod n (nth known cnt)))])))))
(defn next-prime [primes]
(let [n (inc (count primes))]
(let [lk (if (even? (inc (last primes))) (+ 2 (last primes)) (inc (last primes)))]
(loop [cnt lk p primes]
(if (>= (count p) n) (last p)
(recur (+ cnt 2) (if (prime? cnt p) (concat p [cnt]) p)))))))
(memoize next-prime)
(defn n-primes [n]
(loop [cnt 1 p [2]]
(if (>= cnt n) p
(recur (inc cnt) (concat p [(next-prime p)])))))
(defn factor [n factors primes]
(if (== n 1) factors
(loop [p primes]
(if (== 0 (mod n (last p))) (factor
(/ n (last p))
(concat [(last p)] factors)
p)
(recur (concat p [(next-prime p)]))))))
(println (factor 600851475143 [] (n-primes 1))) |
|
06e21d2a01f6f42b336d95310f3e6b31876c586292aaa43ed575151ff1d88a5c | RefactoringTools/HaRe | SimpPatMatchProp.hs | module SimpPatMatchProp where
import SimpPatMatch
import Recursive(struct)
import PropSyntaxRec(HsExpI)
import )
HasDef [ HsDeclI i ] ( HsDeclI i )
import PrettyPrint(PrintableOp)
instance (Eq i,PrintableOp i,
HasSrcLoc i,ValueId i,HasIdTy n i,HasOrig i,HasOrig n)
=> SimpPatMatch i (HsExpI i) where
simpPatMatch ids = simpPatMatchE ids . struct
| null | https://raw.githubusercontent.com/RefactoringTools/HaRe/ef5dee64c38fb104e6e5676095946279fbce381c/old/tools/property/transforms/SimpPatMatchProp.hs | haskell | module SimpPatMatchProp where
import SimpPatMatch
import Recursive(struct)
import PropSyntaxRec(HsExpI)
import )
HasDef [ HsDeclI i ] ( HsDeclI i )
import PrettyPrint(PrintableOp)
instance (Eq i,PrintableOp i,
HasSrcLoc i,ValueId i,HasIdTy n i,HasOrig i,HasOrig n)
=> SimpPatMatch i (HsExpI i) where
simpPatMatch ids = simpPatMatchE ids . struct
|
|
0dfd5f532b8d6341237c0e992d3cc9e5122e7e14486958b7f3c47074d5e404b3 | philnguyen/soft-contract | map.rkt | #lang racket
(require soft-contract/fake-contract)
(define (map f xs)
(if (empty? xs) empty
(cons (f (car xs)) (map f (cdr xs)))))
(provide/contract
[map (->i ([_ (any/c . -> . any/c)] [l (listof any/c)])
(res (_ l)
(and/c (listof any/c)
(λ (r) (equal? (empty? l) (empty? r))))))])
| null | https://raw.githubusercontent.com/philnguyen/soft-contract/5e07dc2d622ee80b961f4e8aebd04ce950720239/soft-contract/test/programs/safe/sym-exe/map.rkt | racket | #lang racket
(require soft-contract/fake-contract)
(define (map f xs)
(if (empty? xs) empty
(cons (f (car xs)) (map f (cdr xs)))))
(provide/contract
[map (->i ([_ (any/c . -> . any/c)] [l (listof any/c)])
(res (_ l)
(and/c (listof any/c)
(λ (r) (equal? (empty? l) (empty? r))))))])
|
|
cc3812c4421197dda183e4e7aea4eb59cea79b019015853800027951bb4cd037 | fukamachi/datafly | util.lisp | (in-package :cl-user)
(defpackage datafly.util
(:use :cl))
(in-package :datafly.util)
(syntax:use-syntax :annot)
@export
(defun partition-if (pred sequence &key from-end (start 0) end (key #'identity))
(let ((yes nil)
(no nil)
(sequence (if (or (not (zerop start))
end)
(subseq sequence start end)
sequence)))
(map nil
#'(lambda (x)
(if (funcall pred (funcall key x))
(push x yes)
(push x no)))
(if from-end
(nreverse sequence)
sequence))
(values yes no)))
@export
(defun partition (item sequence &key from-end (start 0) end (key #'identity) (test #'eql))
(partition-if
(lambda (x)
(funcall test x item))
sequence
:from-end from-end
:start start
:end end
:key key))
| null | https://raw.githubusercontent.com/fukamachi/datafly/adece27fcbc4b5ea39ad1a105048b6b7166e3b0d/src/util.lisp | lisp | (in-package :cl-user)
(defpackage datafly.util
(:use :cl))
(in-package :datafly.util)
(syntax:use-syntax :annot)
@export
(defun partition-if (pred sequence &key from-end (start 0) end (key #'identity))
(let ((yes nil)
(no nil)
(sequence (if (or (not (zerop start))
end)
(subseq sequence start end)
sequence)))
(map nil
#'(lambda (x)
(if (funcall pred (funcall key x))
(push x yes)
(push x no)))
(if from-end
(nreverse sequence)
sequence))
(values yes no)))
@export
(defun partition (item sequence &key from-end (start 0) end (key #'identity) (test #'eql))
(partition-if
(lambda (x)
(funcall test x item))
sequence
:from-end from-end
:start start
:end end
:key key))
|
|
6f3eea65152a8d34742c6f28466bbf6418dbcfc428d91f7870900f1ba70b7ddc | progman1/genprintlib | printval.mli | (**************************************************************************)
(* *)
(* OCaml *)
(* *)
, projet Cristal , INRIA Rocquencourt
OCaml port by and
(* *)
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 Format
val max_printer_depth : int ref
val max_printer_steps : int ref
val print_exception: formatter -> Debugcom.Remote_value.t -> unit
val print_named_value :
int -> Parser_aux.expression -> Env.t ->
Debugcom.Remote_value.t -> formatter -> Types.type_expr ->
unit
val reset_named_values : unit -> unit
val find_named_value : int -> Debugcom.Remote_value.t * Types.type_expr
val install_printer :
Path.t -> Types.type_expr -> formatter ->
(formatter -> Obj.t -> unit) -> unit
val remove_printer : Path.t -> unit
| null | https://raw.githubusercontent.com/progman1/genprintlib/acc1e5cc46b9ce6191d0306f51337581c93ffe94/debugger/4.07.1/printval.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.
************************************************************************ | , projet Cristal , INRIA Rocquencourt
OCaml port by and
Copyright 1996 Institut National de Recherche en Informatique et
the GNU Lesser General Public License version 2.1 , with the
open Format
val max_printer_depth : int ref
val max_printer_steps : int ref
val print_exception: formatter -> Debugcom.Remote_value.t -> unit
val print_named_value :
int -> Parser_aux.expression -> Env.t ->
Debugcom.Remote_value.t -> formatter -> Types.type_expr ->
unit
val reset_named_values : unit -> unit
val find_named_value : int -> Debugcom.Remote_value.t * Types.type_expr
val install_printer :
Path.t -> Types.type_expr -> formatter ->
(formatter -> Obj.t -> unit) -> unit
val remove_printer : Path.t -> unit
|
46816fdd9c9479b2934f7e85df46a6ec7133f061eaf897c76db9e38a0650d838 | camllight/camllight | valeur.mli | type valeur =
Inconnue
| Ent of int
| Bool of bool
| Tableau of int * valeur vect;;
value ent_val: valeur -> int
and bool_val: valeur -> bool
and tableau_val: valeur -> int * valeur vect
and affiche_valeur: valeur -> unit
and lire_valeur: unit -> valeur;;
| null | https://raw.githubusercontent.com/camllight/camllight/0cc537de0846393322058dbb26449427bfc76786/windows/examples/pascal/valeur.mli | ocaml | type valeur =
Inconnue
| Ent of int
| Bool of bool
| Tableau of int * valeur vect;;
value ent_val: valeur -> int
and bool_val: valeur -> bool
and tableau_val: valeur -> int * valeur vect
and affiche_valeur: valeur -> unit
and lire_valeur: unit -> valeur;;
|
|
97fcec4253acc646f11f78cf792b462d6654d25fd3554136cb048b9bc0225343 | MinaProtocol/mina | bulletproof_challenge.ml | [%%versioned
module Stable = struct
module V1 = struct
type 'challenge t =
'challenge Mina_wire_types.Pickles_bulletproof_challenge.V1.t =
{ prechallenge : 'challenge }
[@@deriving sexp, compare, yojson, hash, equal]
end
end]
let pack { prechallenge } = prechallenge
let unpack prechallenge = { prechallenge }
let map { prechallenge } ~f = { prechallenge = f prechallenge }
let typ chal =
let there = pack in
let back = unpack in
let open Snarky_backendless in
Typ.transport ~there ~back (Kimchi_backend_common.Scalar_challenge.typ chal)
|> Typ.transport_var ~there ~back
| null | https://raw.githubusercontent.com/MinaProtocol/mina/b19a220d87caa129ed5dcffc94f89204ae874661/src/lib/pickles/composition_types/bulletproof_challenge.ml | ocaml | [%%versioned
module Stable = struct
module V1 = struct
type 'challenge t =
'challenge Mina_wire_types.Pickles_bulletproof_challenge.V1.t =
{ prechallenge : 'challenge }
[@@deriving sexp, compare, yojson, hash, equal]
end
end]
let pack { prechallenge } = prechallenge
let unpack prechallenge = { prechallenge }
let map { prechallenge } ~f = { prechallenge = f prechallenge }
let typ chal =
let there = pack in
let back = unpack in
let open Snarky_backendless in
Typ.transport ~there ~back (Kimchi_backend_common.Scalar_challenge.typ chal)
|> Typ.transport_var ~there ~back
|
|
d74a19d7199af0eea32544eda7a1c1e993e7552385252b0c5c62658393c91d9a | grwlf/htvm | Main.hs | # LANGUAGE LambdaCase #
# LANGUAGE RecordWildCards #
# LANGUAGE ScopedTypeVariables #
{-# LANGUAGE OverloadedStrings #-}
# LANGUAGE NondecreasingIndentation #
# LANGUAGE TypeApplications #
module Main where
import qualified Data.Text.IO as Text
import Control.Monad(when)
import Control.Monad.Trans(liftIO)
import Control.Concurrent(forkIO)
import Data.Text(Text)
import HTVM
import MNIST
printFunction :: LoweredFunc -> IO ()
printFunction f =
Text.putStrLn =<< withLineNumbers <$> showLoweredFuncCpp defaultConfig f
demo1 :: StmtT IO LModule
demo1 = do
sa <- shapevar [5]
a <- assign $ placeholder "A" float32 sa
c <- compute sa $ \i -> (a![i])*(a![i])
f1 <- lower "asquare" (schedule [c]) [a,c]
liftIO $ putStrLn "asquare" >> printFunction f1
dc <- assign $ (differentiate c [a]) ! 0
f2 <- lower "d_asquare" (schedule [dc]) [a,dc]
liftIO $ putStrLn "d_asquare" >> printFunction f2
lmodul [f1,f2]
model : : IO ( ModuleLib LModule )
model = do
buildLModule CPU defaultConfig " demo1.so " > > = do
withLModule
sa < - shapevar [ 1 ]
function " difftest " [ ( " A",float32,sa ) ] $ \[a ] - > do
c < - compute sa $ \i - > ( a![i])*(a![i ] )
dc < - assign $ differentiate c [ a ]
return ( dc!0 )
conv2d : : IO ( ModuleLib LModule )
conv2d = do
stageBuildFunction defaultConfig " model.so " $
let
num_classes = 10
batch_size = 10
img_h = 28
img_w = 28
img_c = 1
f1_c = 4
-- f2_c = 5
-- f3_units = 16
in do
x_shape < - shapevar [ batch_size , img_h , img_w , img_c ]
y_shape < - shapevar [ batch_size , num_classes ]
function " demo " [ ( " X " , float32 , x_shape )
, ( " y " , float32 , y_shape )
, ( " w1 " , float32 , shp [ 3,3,img_c , f1_c ] )
, ( " b1 " , float32 , shp [ f1_c ] )
] $ \[x , y , w1,b1 ] - > do
t < - assign $ conv2d_nchw x w1 def
t < - assign $ t + broadcast_to b1 ( shp [ batch_size,1,1,f1_c ] )
t < - assign $ relu t
t < - assign $ flatten t
return t
model :: IO (ModuleLib LModule)
model = do
buildLModule CPU defaultConfig "demo1.so" demo1 >>= do
withLModule
sa <- shapevar [1]
function "difftest" [("A",float32,sa) ] $ \[a] -> do
c <- compute sa $ \i -> (a![i])*(a![i])
dc <- assign $ differentiate c [a]
return (dc!0)
conv2d :: IO (ModuleLib LModule)
conv2d = do
stageBuildFunction defaultConfig "model.so" $
let
num_classes = 10
batch_size = 10
img_h = 28
img_w = 28
img_c = 1
f1_c = 4
-- f2_c = 5
-- f3_units = 16
in do
x_shape <- shapevar [batch_size, img_h, img_w, img_c]
y_shape <- shapevar [batch_size, num_classes]
function "demo" [("X", float32, x_shape)
,("y", float32, y_shape)
,("w1", float32, shp [3,3,img_c,f1_c])
,("b1", float32, shp [f1_c])
] $ \[x,y,w1,b1] -> do
t <- assign $ conv2d_nchw x w1 def
t <- assign $ t + broadcast_to b1 (shp [batch_size,1,1,f1_c])
t <- assign $ relu t
t <- assign $ flatten t
return t
-}
main :: IO ()
main = do
smod <- stageStmtT demo1
bmod <- buildLModule defaultBackend defaultConfig "demo" smod
hmod <- loadModule bmod
a <- newTensor BackendLLVM 0 TD_Float32L1 [1..5 :: Word32]
c <- newEmptyTensor BackendLLVM 0 TD_Float32L1 [5]
callModule hmod "asquare" [a,c]
putStrLn . show =<< getTensor @[Float] c
return ()
| null | https://raw.githubusercontent.com/grwlf/htvm/90cff0ebde0bdff3e8048a82a5b1b0d46fc7d66e/app/demo/Main.hs | haskell | # LANGUAGE OverloadedStrings #
f2_c = 5
f3_units = 16
f2_c = 5
f3_units = 16 | # LANGUAGE LambdaCase #
# LANGUAGE RecordWildCards #
# LANGUAGE ScopedTypeVariables #
# LANGUAGE NondecreasingIndentation #
# LANGUAGE TypeApplications #
module Main where
import qualified Data.Text.IO as Text
import Control.Monad(when)
import Control.Monad.Trans(liftIO)
import Control.Concurrent(forkIO)
import Data.Text(Text)
import HTVM
import MNIST
printFunction :: LoweredFunc -> IO ()
printFunction f =
Text.putStrLn =<< withLineNumbers <$> showLoweredFuncCpp defaultConfig f
demo1 :: StmtT IO LModule
demo1 = do
sa <- shapevar [5]
a <- assign $ placeholder "A" float32 sa
c <- compute sa $ \i -> (a![i])*(a![i])
f1 <- lower "asquare" (schedule [c]) [a,c]
liftIO $ putStrLn "asquare" >> printFunction f1
dc <- assign $ (differentiate c [a]) ! 0
f2 <- lower "d_asquare" (schedule [dc]) [a,dc]
liftIO $ putStrLn "d_asquare" >> printFunction f2
lmodul [f1,f2]
model : : IO ( ModuleLib LModule )
model = do
buildLModule CPU defaultConfig " demo1.so " > > = do
withLModule
sa < - shapevar [ 1 ]
function " difftest " [ ( " A",float32,sa ) ] $ \[a ] - > do
c < - compute sa $ \i - > ( a![i])*(a![i ] )
dc < - assign $ differentiate c [ a ]
return ( dc!0 )
conv2d : : IO ( ModuleLib LModule )
conv2d = do
stageBuildFunction defaultConfig " model.so " $
let
num_classes = 10
batch_size = 10
img_h = 28
img_w = 28
img_c = 1
f1_c = 4
in do
x_shape < - shapevar [ batch_size , img_h , img_w , img_c ]
y_shape < - shapevar [ batch_size , num_classes ]
function " demo " [ ( " X " , float32 , x_shape )
, ( " y " , float32 , y_shape )
, ( " w1 " , float32 , shp [ 3,3,img_c , f1_c ] )
, ( " b1 " , float32 , shp [ f1_c ] )
] $ \[x , y , w1,b1 ] - > do
t < - assign $ conv2d_nchw x w1 def
t < - assign $ t + broadcast_to b1 ( shp [ batch_size,1,1,f1_c ] )
t < - assign $ relu t
t < - assign $ flatten t
return t
model :: IO (ModuleLib LModule)
model = do
buildLModule CPU defaultConfig "demo1.so" demo1 >>= do
withLModule
sa <- shapevar [1]
function "difftest" [("A",float32,sa) ] $ \[a] -> do
c <- compute sa $ \i -> (a![i])*(a![i])
dc <- assign $ differentiate c [a]
return (dc!0)
conv2d :: IO (ModuleLib LModule)
conv2d = do
stageBuildFunction defaultConfig "model.so" $
let
num_classes = 10
batch_size = 10
img_h = 28
img_w = 28
img_c = 1
f1_c = 4
in do
x_shape <- shapevar [batch_size, img_h, img_w, img_c]
y_shape <- shapevar [batch_size, num_classes]
function "demo" [("X", float32, x_shape)
,("y", float32, y_shape)
,("w1", float32, shp [3,3,img_c,f1_c])
,("b1", float32, shp [f1_c])
] $ \[x,y,w1,b1] -> do
t <- assign $ conv2d_nchw x w1 def
t <- assign $ t + broadcast_to b1 (shp [batch_size,1,1,f1_c])
t <- assign $ relu t
t <- assign $ flatten t
return t
-}
main :: IO ()
main = do
smod <- stageStmtT demo1
bmod <- buildLModule defaultBackend defaultConfig "demo" smod
hmod <- loadModule bmod
a <- newTensor BackendLLVM 0 TD_Float32L1 [1..5 :: Word32]
c <- newEmptyTensor BackendLLVM 0 TD_Float32L1 [5]
callModule hmod "asquare" [a,c]
putStrLn . show =<< getTensor @[Float] c
return ()
|
971ea73c14704049bdfafc09eaac7ab28f244728dc8a15cbd4ac77a3629a096c | blindglobe/clocc | scroller.lisp | -*- Mode : Lisp ; Package : CLIO - OPEN ; ; Lowercase : T ; Fonts:(CPTFONT ) ; Syntax : Common - Lisp -*-
;;;----------------------------------------------------------------------------------+
;;; |
;;; TEXAS INSTRUMENTS INCORPORATED |
;;; P.O. BOX 149149 |
, TEXAS 78714 |
;;; |
Copyright ( C ) 1989 , 1990 Texas Instruments Incorporated . |
;;; |
;;; Permission is granted to any individual or institution to use, copy, modify, and |
;;; distribute this software, provided that this complete copyright and permission |
;;; notice is maintained, intact, in all copies and supporting documentation. |
;;; |
Texas Instruments Incorporated provides this software " as is " without express or |
;;; implied warranty. |
;;; |
;;;----------------------------------------------------------------------------------+
(in-package "CLIO-OPEN")
(export '(
make-scroller
scale-increment
scale-indicator-size
scale-maximum
scale-minimum
scale-orientation
scale-update
scale-update-delay
scale-value
scroller
)
'clio-open)
;;;----------------------------------------------------------------------------+
;;; |
;;; Scroller |
;;; |
;;;----------------------------------------------------------------------------+
;; Implementation Strategy:
;;
;; Elevator and anchor controls are implemented as non-contact subwindows (i.e.
;; scroller is NOT a composite). Overall, this strategy simplifies the tasks
;; of determining which control is receiving input and of confining the pointer
;; cursor to controls during continuous scrolling, without unnecessarily
;; incurring the full cost of a sub-contact.
;; The elevator is represented as an :input-output subwindow; the imagery of all
;; elevator controls is drawn to this subwindow. The less/more arrow and drag
;; area controls are represented as :input-only subwindows of the elevator
;; subwindow. Subwindows are used for these controls only for use as :confine-to
;; windows while the pointer is grabbed.
All control subwindows are recorded in the regions vector of the scroller .
;; The scroller subwindow receiving a :button-press is determined from the child
;; slot of the button event. During event handling, the regions vector is
;; searched to look up the vector index of the event window (see FIND-REGION).
;; If the event child is the elevator, then a further search based on elevator
;; geometry is necessary to determine which elevator subwindow is the event
;; window. The resulting vector index is used to select an element from a
;; vector of functions to handle the :button-press (see PRESS-HANDLERS).
(defcontact scroller (core contact)
((increment :type number
setf defined below
:initarg :increment
:initform 1)
(indicator-size
:type (or number (member :off))
setf defined below
:initarg :indicator-size
:initform 0)
(maximum :type number
setf defined below
:initarg :maximum
:initform 1)
(minimum :type number
setf defined below
:initarg :minimum
:initform 0)
(orientation :type (member :horizontal :vertical)
setf defined below
:initarg :orientation
:initform :vertical)
(update-delay :type (or number (member :until-done))
setf defined below
:initarg :update-delay
:initform 0)
(value :type number
setf defined below
:initarg :value
:initform 0)
(compress-exposures
:initform :on
:type (member :off :on)
:reader contact-compress-exposures
:allocation :class)
(regions :type (vector window)
:initform (make-array 6)))
(:resources
increment indicator-size maximum minimum orientation update-delay value
(border-width :initform 0)
(event-mask :initform #.(make-event-mask :pointer-motion-hint :exposure))))
;; Index values for accessing region vector and press handler vector
(defconstant *elevator-region* 0)
(defconstant *min-anchor-region* 1)
(defconstant *max-anchor-region* 2)
(defconstant *less-arrow-region* 3)
(defconstant *drag-area-region* 4)
(defconstant *more-arrow-region* 5)
(defconstant *cable-region* 6)
;;;----------------------------------------------------------------------------+
;;; |
;;; Initialization |
;;; |
;;;----------------------------------------------------------------------------+
(defun make-scroller (&rest initargs &key &allow-other-keys)
(apply #'make-contact 'scroller initargs))
(defmethod initialize-instance :after ((self scroller) &key &allow-other-keys)
(with-slots (width height) self
Initialize required geometry
(multiple-value-setq (width height) (preferred-size self))))
(labels
((min-anchor-geometry
(dimensions scroller orientation width height)
(declare (ignore scroller))
(let ((anchor-width (scrollbar-anchor-width dimensions))
(anchor-height (scrollbar-anchor-height dimensions)))
(if (eq orientation :vertical)
(values (pixel-round (- width anchor-width) 2) 0 (- anchor-width 2) (- anchor-height 2))
(values 0 (pixel-round (- height anchor-width) 2) (- anchor-height 2) (- anchor-width 2)))))
(max-anchor-geometry
(dimensions scroller orientation width height)
(declare (ignore scroller))
(let ((anchor-width (scrollbar-anchor-width dimensions))
(anchor-height (scrollbar-anchor-height dimensions)))
(if (eq orientation :vertical)
(values (pixel-round (- width anchor-width) 2) (- height anchor-height) (- anchor-width 2) (- anchor-height 2))
(values (- width anchor-height) (pixel-round (- height anchor-width) 2) (- anchor-height 2) (- anchor-width 2)))))
(elevator-geometry
(dimensions scroller orientation width height)
(let ((anchor-width (scrollbar-anchor-width dimensions)))
(if (eq orientation :vertical)
(values (pixel-round (- width anchor-width) 2) (scroller-value-position scroller) anchor-width (scrollbar-elevator-size scroller))
(values (scroller-value-position scroller) (pixel-round (- height anchor-width) 2) (scrollbar-elevator-size scroller) anchor-width))))
(less-arrow-geometry
(dimensions scroller orientation width height)
(declare (ignore scroller orientation width height))
(let ((anchor-width (scrollbar-anchor-width dimensions)))
(values 0 0 anchor-width anchor-width)))
(more-arrow-geometry
(dimensions scroller orientation width height)
(declare (ignore width height))
(let ((anchor-width (scrollbar-anchor-width dimensions))
(abbreviated-p (scrollbar-abbreviated-p scroller)))
(if (eq orientation :vertical)
(values 0 (+ anchor-width (if abbreviated-p 0 anchor-width)) anchor-width anchor-width)
(values (+ anchor-width (if abbreviated-p 0 anchor-width)) 0 anchor-width anchor-width))))
(drag-area-geometry
(dimensions scroller orientation width height)
(declare (ignore scroller width height))
(let ((anchor-width (scrollbar-anchor-width dimensions)))
(if (eq orientation :vertical)
(values 0 anchor-width anchor-width anchor-width)
(values anchor-width 0 anchor-width anchor-width))))
(reconfigure-controls (self)
(declare (type scroller self))
(with-slots (regions width height orientation) (the scroller self)
(let ((dimensions (getf *scrollbar-dimensions* (contact-scale self))))
(let ((window (svref regions *min-anchor-region*)))
(with-state (window)
(multiple-value-bind (window-x window-y window-width window-height)
(min-anchor-geometry dimensions self orientation width height)
(setf (drawable-x window) window-x
(drawable-y window) window-y
(drawable-width window) window-width
(drawable-height window) window-height))))
(let ((window (svref regions *max-anchor-region*)))
(with-state (window)
(multiple-value-bind (window-x window-y window-width window-height)
(max-anchor-geometry dimensions self orientation width height)
(setf (drawable-x window) window-x
(drawable-y window) window-y
(drawable-width window) window-width
(drawable-height window) window-height))))
(let ((window (svref regions *elevator-region*)))
(with-state (window)
(multiple-value-bind (window-x window-y window-width window-height)
(elevator-geometry dimensions self orientation width height)
(setf (drawable-x window) window-x
(drawable-y window) window-y
(drawable-width window) window-width
(drawable-height window) window-height))))
(let ((window (svref regions *drag-area-region*)))
(with-state (window)
(multiple-value-bind (window-x window-y window-width window-height)
(drag-area-geometry dimensions self orientation width height)
(setf (drawable-x window) window-x
(drawable-y window) window-y
(drawable-width window) window-width
(drawable-height window) window-height))))
(let ((window (svref regions *less-arrow-region*)))
(with-state (window)
(multiple-value-bind (window-x window-y window-width window-height)
(less-arrow-geometry dimensions self orientation width height)
(setf (drawable-x window) window-x
(drawable-y window) window-y
(drawable-width window) window-width
(drawable-height window) window-height))))
(let ((window (svref regions *more-arrow-region*)))
(with-state (window)
(multiple-value-bind (window-x window-y window-width window-height)
(more-arrow-geometry dimensions self orientation width height)
(setf (drawable-x window) window-x
(drawable-y window) window-y
(drawable-width window) window-width
(drawable-height window) window-height))))))))
(defmethod realize :after ((self scroller))
;; Create control region windows
(with-slots (regions width height orientation foreground) self
(let*
((dimensions (getf *scrollbar-dimensions* (contact-scale self)))
(min-anchor (multiple-value-bind (region-x region-y region-width region-height)
(min-anchor-geometry dimensions self orientation width height)
(create-window
:parent self
:x region-x
:y region-y
:width region-width
:height region-height
:background :parent-relative
:border-width 1
:border foreground
:gravity (if (eq orientation :vertical) :north :west))))
(max-anchor (multiple-value-bind (region-x region-y region-width region-height)
(max-anchor-geometry dimensions self orientation width height)
(create-window
:parent self
:x region-x
:y region-y
:width region-width
:height region-height
:background :parent-relative
:border-width 1
:border foreground
:gravity (if (eq orientation :vertical) :north :west))))
(elevator (multiple-value-bind (region-x region-y region-width region-height)
(elevator-geometry dimensions self orientation width height)
(create-window
:parent self
:x region-x
:y region-y
:width region-width
:height region-height
:border-width 0
:gravity (if (eq orientation :vertical) :north :west))))
(drag-area (multiple-value-bind (region-x region-y region-width region-height)
(drag-area-geometry dimensions self orientation width height)
(create-window
:parent elevator
:class :input-only
:x region-x
:y region-y
:width region-width
:height region-height
:border-width 0)))
(less-arrow (multiple-value-bind (region-x region-y region-width region-height)
(less-arrow-geometry dimensions self orientation width height)
(create-window
:parent elevator
:class :input-only
:x region-x
:y region-y
:width region-width
:height region-height
:border-width 0)))
(more-arrow (multiple-value-bind (region-x region-y region-width region-height)
(more-arrow-geometry dimensions self orientation width height)
(create-window
:parent elevator
:class :input-only
:x region-x
:y region-y
:width region-width
:height region-height
:border-width 0))))
(setf (svref regions *min-anchor-region*) min-anchor)
(setf (svref regions *max-anchor-region*) max-anchor)
(setf (svref regions *elevator-region*) elevator)
(setf (svref regions *drag-area-region*) drag-area)
(setf (svref regions *less-arrow-region*) less-arrow)
(setf (svref regions *more-arrow-region*) more-arrow)
(map-subwindows self)
(map-subwindows elevator))))
(defmethod rescale ((self scroller))
(with-slots (orientation) self
;; Request change to preferred width/height, depending on orientation.
(multiple-value-bind (rw rh) (if (eq :vertical orientation) (values 0 nil) (values nil 0))
(multiple-value-bind (pw ph) (preferred-size self :width rw :height rh)
(change-geometry self :width pw :height ph :accept-p t))))
(when (realized-p self)
(reconfigure-controls self)))
(defmethod (setf scale-orientation) (new-orientation (scroller scroller))
(with-slots (orientation width height) scroller
(unless (eq orientation new-orientation)
(check-type new-orientation (member :horizontal :vertical))
(setf orientation new-orientation)
(multiple-value-bind (new-width new-height)
(preferred-size scroller :width height :height width)
(change-geometry scroller :width new-width :height new-height))
(reconfigure-controls scroller)))
new-orientation))
;;;----------------------------------------------------------------------------+
;;; |
;;; Accessors |
;;; |
;;;----------------------------------------------------------------------------+
(defmethod (setf scale-update-delay) (new-update-delay (scroller scroller))
(with-slots (update-delay) scroller
(assert (or (eq new-update-delay :until-done)
(and (numberp new-update-delay) (not (minusp new-update-delay)))) ()
"~a is neither :UNTIL-DONE or a non-negative number." new-update-delay)
(setf update-delay new-update-delay)))
(defmethod (setf scale-value) (new-value (scroller scroller))
(scale-update scroller :value new-value)
new-value)
(defmethod (setf scale-minimum) (new-minimum (scroller scroller))
(scale-update scroller :minimum new-minimum)
new-minimum)
(defmethod (setf scale-maximum) (new-maximum (scroller scroller))
(scale-update scroller :maximum new-maximum)
new-maximum)
(defmethod (setf scale-increment) (new-increment (scroller scroller))
(scale-update scroller :increment new-increment)
new-increment)
(defmethod (setf scale-indicator-size) (new-indicator-size (scroller scroller))
(scale-update scroller :indicator-size new-indicator-size)
new-indicator-size)
(defmacro true-indicator-size (size)
`(if (eq ,size :off) 0 ,size))
(defmethod scale-update ((scroller scroller) &key value minimum maximum indicator-size increment)
(with-slots
((current-val value)
(current-min minimum)
(current-max maximum)
(current-ind indicator-size)
(current-inc increment)
regions
orientation)
scroller
(setf minimum (or minimum current-min)
maximum (or maximum current-max)
value (or value current-val)
indicator-size (or indicator-size current-ind)
increment (or increment current-inc))
(assert (numberp value) () "~s for :value is not a number" value)
(assert (numberp minimum) () "~s for :minimum is not a number" minimum)
(assert (numberp maximum) () "~s for :maximum is not a number" maximum)
(assert (and (numberp increment) (not (minusp increment))) ()
"~s for :increment is not a number" increment)
(assert (or (and (numberp indicator-size) (not (minusp indicator-size)))
(eq indicator-size :off))
() "~s for :indicator-size is not :off or a non-negative-number)" indicator-size)
(assert (<= minimum maximum) ()
"Minimum (~a) is greater than maximum (~a)."
minimum maximum)
(assert (<= minimum value maximum) ()
"Value (~a) must be in the range [~a, ~a]."
value minimum maximum)
(let*
((insensitive-p (not (sensitive-p scroller)))
(less-arrow-dim-p (or insensitive-p (= current-val current-min)))
(more-arrow-dim-p (or insensitive-p (= current-val current-max)))
(prev-min current-min)
(prev-max current-max)
(prev-ind current-ind)
(prev-val current-val))
(setf current-min minimum
current-max maximum
current-val value
current-ind indicator-size
current-inc increment)
;; Update display
(when (realized-p scroller)
(cond
((not (and (eql current-min prev-min) (eql current-max prev-max) (eql current-ind prev-ind)))
(display scroller))
((not (eql current-val prev-val))
;; Position elevator
(let ((position (scroller-value-position scroller))
(elevator (svref regions *elevator-region*)))
(if (eq :vertical orientation)
(setf (drawable-y elevator) position)
(setf (drawable-x elevator) position)))
;; Dim arrows, if necessary
(scrollbar-update-less-arrow scroller less-arrow-dim-p insensitive-p)
(scrollbar-update-more-arrow scroller more-arrow-dim-p insensitive-p)))))))
(defmethod (setf contact-foreground) :after (new-fg (self scroller))
(declare (ignore new-fg))
(with-slots (foreground regions) self
(setf (window-border (svref regions *min-anchor-region*)) foreground)
(setf (window-border (svref regions *max-anchor-region*)) foreground)))
;;;----------------------------------------------------------------------------+
;;; |
Geometry Management |
;;; |
;;;----------------------------------------------------------------------------+
(defmethod preferred-size ((self scroller) &key width height border-width)
(declare (ignore border-width))
(with-slots (orientation (current-height height) (current-width width)) self
(let*
((dimensions (getf *scrollbar-dimensions* (contact-scale self)))
(margin (scrollbar-margin dimensions))
(anchor-width (scrollbar-anchor-width dimensions))
(anchor-height (scrollbar-anchor-height dimensions))
;; Calculate geometry assuming :vertical orientation
(preferred-width (+ margin anchor-width margin))
(preferred-height (max
;; Suggested or current height
(or (if (eq orientation :vertical) height width)
(if (eq orientation :vertical) current-height current-width))
;; Size of abbreviated scrollbar (no drag area)
(+ anchor-height margin
anchor-width anchor-width
margin anchor-height))))
;; Return preferred geometry according to actual orientation
(values
(if (eq orientation :vertical) preferred-width preferred-height)
(if (eq orientation :vertical) preferred-height preferred-width)
0))))
(defmethod resize :around ((self scroller) new-width new-height new-border-width)
(if (realized-p self)
Reconfigure subwindows
(let* ((abbreviated-before-p (scrollbar-abbreviated-p self))
(resized-p (call-next-method)))
(with-slots (width height orientation regions) self
(let*
((scale (contact-scale self))
(max-anchor (svref regions *max-anchor-region*))
(dimensions (getf *scrollbar-dimensions* scale))
(anchor-position (- (if (eq orientation :vertical) height width)
(scrollbar-anchor-height dimensions)
1))
(elevator (svref regions *elevator-region*))
(elevator-position (scroller-value-position self)))
;; Reposition max anchor
(if (eq orientation :vertical)
(setf (drawable-y max-anchor) anchor-position)
(setf (drawable-x max-anchor) anchor-position))
;; Reconfigure elevator
(multiple-value-bind (elevator-size abbreviated-after-p)
(scrollbar-elevator-size self)
(with-state (elevator)
(case orientation
(:vertical
(setf (drawable-y elevator) elevator-position)
(setf (drawable-height elevator) elevator-size))
(:horizontal
(setf (drawable-x elevator) elevator-position)
(setf (drawable-width elevator) elevator-size))))
;; Changing abbreviation?
(unless (eq abbreviated-before-p abbreviated-after-p)
;; Reposition more-arrow region
(let* ((anchor-width (scrollbar-anchor-width dimensions))
(more-arrow-pos (+ anchor-width (if abbreviated-after-p 0 anchor-width))))
(if (eq orientation :vertical)
(setf (drawable-y (svref regions *more-arrow-region*)) more-arrow-pos)
(setf (drawable-x (svref regions *more-arrow-region*)) more-arrow-pos)))
;; Redisplay elevator image
(scrollbar-display-elevator self scale)))))
resized-p)
;; If not yet realized, just do it
(call-next-method)))
(defun scrollbar-abbreviated-p (scroller)
(with-slots (width height orientation) (the scroller scroller)
(let*
((dimensions (getf *scrollbar-dimensions* (contact-scale scroller)))
(margin (scrollbar-margin dimensions))
(anchor-width (scrollbar-anchor-width dimensions))
(anchor-height (scrollbar-anchor-height dimensions)))
(<= (if (eq orientation :vertical) height width)
(+ anchor-height margin
anchor-width anchor-width anchor-width
margin anchor-height)))))
(defun scrollbar-elevator-size (scroller)
(let ((abbreviated-p (scrollbar-abbreviated-p scroller)))
(values
(+ (* (scrollbar-anchor-width
(getf *scrollbar-dimensions* (contact-scale scroller)))
(if abbreviated-p 2 3))
2)
abbreviated-p)))
(defun scrollbar-less-arrow-geometry (scroller)
(let ((arrow-size (1- (scrollbar-anchor-width (getf *scrollbar-dimensions*
(contact-scale scroller))))))
(if (eq :vertical (scale-orientation scroller))
(values 1 1 (- arrow-size 2) arrow-size)
(values 1 1 arrow-size (- arrow-size 2)))))
(defun scrollbar-drag-area-geometry (scroller)
(let*
((area-size (scrollbar-anchor-width
(getf *scrollbar-dimensions* (contact-scale scroller))))
(area-position (1+ area-size)))
(if (eq :vertical (scale-orientation scroller))
(values 1 area-position (- area-size 3) (1- area-size))
(values area-position 1 (1- area-size) (- area-size 3)))))
(defun scrollbar-more-arrow-geometry (scroller)
(let*
((arrow-size (scrollbar-anchor-width
(getf *scrollbar-dimensions* (contact-scale scroller))))
(arrow-position (1+ (+ arrow-size (if (scrollbar-abbreviated-p scroller) 0 arrow-size)))))
(if (eq :vertical (scale-orientation scroller))
(values 1 arrow-position (- arrow-size 3) (1- arrow-size))
(values arrow-position 1 (1- arrow-size) (- arrow-size 3)))))
;;;----------------------------------------------------------------------------+
;;; |
Display |
;;; |
;;;----------------------------------------------------------------------------+
(defmethod display ((self scroller) &optional at-x at-y at-width at-height &key)
(with-slots (width height foreground regions orientation) self
;; Default exposed rectangle, if necessary
(setf at-x (or at-x 0)
at-y (or at-y 0)
at-width (or at-width (- width at-x))
at-height (or at-height (- height at-y)))
(let*
((scale (contact-scale self))
(dimensions (getf *scrollbar-dimensions* scale))
(anchor-width (scrollbar-anchor-width dimensions))
(anchor-height (scrollbar-anchor-height dimensions))
(margin (scrollbar-margin dimensions))
(cable-margin (scrollbar-cable-margin dimensions))
(cable-width (scrollbar-cable-width dimensions))
(elevator-position (scroller-value-position self))
(elevator-size (scrollbar-elevator-size self))
(elevator-end (+ elevator-position elevator-size)))
;;-----------------------------------------------------------------------------+
;; |
;; Draw cable. |
;; |
;; Stipple fill is relatively slow, so redrawing entire cable can cause |
;; annoying flicker. But computing the minimal cable area to redraw is |
;; complicated, because the display method is expected to update the image |
;; when the elevator moves (thus exposing a small region of the scroller |
;; previously obscured by the elevator). In this case, we must redraw the |
;; cable not only in the area exposed, but also elsewhere to cover up the |
;; previous gaps between elevator/proportion indicator/cable. |
;; |
;; The following algorithm is a compromise. If the exposed area is entirely |
on one side of the elevator ( as it is in the case of an elevator move ) , |
;; then we redraw the cable only on that side. |
;; |
;;-----------------------------------------------------------------------------+
(flet
((exposed-cable-segment
(exposed-position exposed-size scroller-size)
(let ((min (+ anchor-height margin))
(max (- scroller-size margin anchor-height)))
(cond
;; Exposed area before elevator?
((>= elevator-position (+ exposed-position exposed-size))
Redraw only first part of cable .
(values min (- elevator-position min)))
;; Exposed area behind elevator?
((>= exposed-position elevator-end)
;; Redraw only last part of cable.
(values elevator-end (- max elevator-end)))
(t
;; Redraw all of cable.
(values min (- max min)))))))
(multiple-value-bind (cable-x cable-y cable-width cable-height)
(if (eq orientation :vertical)
(multiple-value-bind (cy ch) (exposed-cable-segment at-y at-height height)
(values (pixel-round (- width cable-width) 2) cy cable-width ch))
(multiple-value-bind (cx cw) (exposed-cable-segment at-x at-width width)
(values cx (pixel-round (- height cable-width) 2) cw cable-width)))
;; Draw exposed cable area
(using-gcontext (gc :drawable self
:fill-style :stippled
:foreground foreground
:stipple (contact-image-mask self 50%gray :depth 1))
(clear-area self :x cable-x :y cable-y :width cable-width :height cable-height)
(draw-rectangle self gc cable-x cable-y cable-width cable-height :fill-p))
;; Draw proportion indicator
(let* ((pi-size (scroller-indicator-size self))
(pi-pos (scroller-indicator-position self pi-size)))
(multiple-value-bind (pi-x pi-y pi-width pi-height margin-x margin-y margin-width margin-height)
(if (eq orientation :vertical)
(values
cable-x
pi-pos
cable-width
pi-size
cable-x
(- pi-pos margin)
cable-width
(+ pi-size margin margin))
(values
pi-pos
cable-y
pi-size
cable-height
(- pi-pos margin)
cable-y
(+ pi-size margin margin)
cable-height))
(clear-area self :x margin-x :y margin-y :width margin-width :height margin-height)
(using-gcontext (gc :drawable self
:fill-style :solid
:foreground foreground)
(draw-rectangle self gc pi-x pi-y pi-width pi-height :fill-p))))))
Clear cable margin around elevator
(multiple-value-bind (gap-x gap-y gap-width gap-height)
(if (eq orientation :vertical)
(values
0 (- elevator-position cable-margin)
nil (+ cable-margin elevator-size cable-margin))
(values
(- elevator-position cable-margin) 0
(+ cable-margin elevator-size cable-margin) nil))
(clear-area self :x gap-x :y gap-y :width gap-width :height gap-height))
;; Compute elevator geometry
(multiple-value-bind (elevator-x elevator-y elevator-width elevator-height)
(if (eq orientation :vertical)
(values
(scrollbar-margin dimensions)
elevator-position
anchor-width
elevator-size)
(values
elevator-position
(scrollbar-margin dimensions)
elevator-size
anchor-width))
(when
;; Exposed area intersects elevator?
(and (< elevator-x (+ at-x at-width))
(< elevator-y (+ at-y at-height))
(> (+ elevator-x elevator-width) at-x)
(> (+ elevator-y elevator-height) at-y))
(scrollbar-display-elevator self scale))))))
(defun scrollbar-display-elevator (scroller &optional scale)
(setf scale (or scale (contact-scale scroller)))
(with-slots (orientation regions foreground) (the scroller scroller)
;; Draw elevator image
(let*
((image (getf (getf *scrollbar-images* orientation) scale))
(mask (contact-image-mask
scroller image
:foreground foreground
:background (contact-current-background-pixel scroller)))
(elevator (svref regions *elevator-region*)))
(using-gcontext (gc :drawable scroller :exposures :off)
(copy-area
mask gc
0 0
(image-width image) (image-height image)
elevator
0 0)
(when (scrollbar-abbreviated-p scroller)
(let ((copy-size (scrollbar-anchor-width (getf *scrollbar-dimensions* scale))))
(multiple-value-bind (from-x from-y copy-width copy-height)
(if (eq :vertical orientation)
(values 0 (+ copy-size copy-size) copy-size (+ copy-size 2))
(values (+ copy-size copy-size) 0 (+ copy-size 2) copy-size))
(multiple-value-bind (to-x to-y)
(if (eq :vertical orientation)
(values 0 copy-size)
(values copy-size 0))
(copy-area
mask gc
from-x from-y
copy-width copy-height
elevator
to-x to-y))))))))
;; Dim arrows, if necessary
(let ((insensitive-p (not (sensitive-p scroller))))
(scrollbar-update-less-arrow scroller nil insensitive-p)
(scrollbar-update-more-arrow scroller nil insensitive-p)))
(defun scrollbar-update-less-arrow (scroller dim-p insensitive-p)
(with-slots (value minimum foreground regions) (the scroller scroller)
(unless (eq dim-p (or insensitive-p (= value minimum)))
(multiple-value-bind (arrow-x arrow-y arrow-width arrow-height)
(scrollbar-less-arrow-geometry scroller)
(using-gcontext
(gc :drawable scroller
:function boole-xor
:fill-style :stippled
:foreground (logxor foreground (contact-current-background-pixel scroller))
:stipple (contact-image-mask scroller 25%gray :depth 1))
(draw-rectangle
(svref regions *elevator-region*) gc
arrow-x arrow-y
arrow-width arrow-height
:fill-p))))))
(defun scrollbar-update-more-arrow (scroller dim-p insensitive-p)
(with-slots (value maximum foreground regions) (the scroller scroller)
(unless (eq dim-p (or insensitive-p (= value maximum)))
(multiple-value-bind (arrow-x arrow-y arrow-width arrow-height)
(scrollbar-more-arrow-geometry scroller)
(using-gcontext
(gc :drawable scroller
:function boole-xor
:fill-style :stippled
:foreground (logxor foreground (contact-current-background-pixel scroller))
:stipple (contact-image-mask scroller 25%gray :depth 1))
(draw-rectangle
(svref regions *elevator-region*) gc
arrow-x arrow-y
arrow-width arrow-height
:fill-p))))))
;;;----------------------------------------------------------------------------+
;;; |
;;; Event Translations |
;;; |
;;;----------------------------------------------------------------------------+
(defevent scroller (:motion-notify :button-1) scroller-handle-motion)
(defevent scroller (:timer :update-delay) scroller-report-new-value)
(defevent scroller (:timer :click) (throw-action :click-timeout))
(defevent scroller (:button-release :button-1) scroller-handle-release)
(defevent scroller (:button-press :button-1) scroller-handle-press)
(defparameter *scroller-click-timeout* 0.2
"Number of seconds to wait before starting continuous scrolling")
(defparameter *scroller-hold-timeout* 0.05
"Number of seconds to wait during continuous scrolling before updating value")
(let ((press-handlers (make-array 7)))
(flet
((find-region (scroller)
;; Return index of scroller region containing the current event
(with-slots (regions orientation) scroller
(with-event (child x y)
(if child
;; Look up event child window among scroller regions
(let ((region (position child regions :test #'eq)))
(if (= region *elevator-region*)
;; Which part of elevator got the press: less-arrow, drag-area, or more-arrow?
(let
((region (+ *less-arrow-region*
(floor
(- (if (eq :vertical orientation) y x)
(scroller-value-position scroller))
(scrollbar-anchor-width
(getf *scrollbar-dimensions*
(contact-scale scroller)))))))
(if (and (= region *drag-area-region*)
(scrollbar-abbreviated-p scroller))
*more-arrow-region*
region))
;; Min/max anchor press
region))
;; Event occurred on non-child area of scroller
*cable-region*))))
(press-cable (scroller)
(with-slots (orientation increment width height indicator-size update-delay display value) scroller
(with-event (x y)
(multiple-value-bind (event-position max-position)
(if (eq :vertical orientation) (values y height) (values x width))
(let*
((anchor-height (scrollbar-anchor-height
(getf *scrollbar-dimensions* (contact-scale scroller))))
(min-position anchor-height)
(max-position (- max-position anchor-height))
(pane-size (let ((size (true-indicator-size indicator-size)))
(if (plusp size) size increment)))
(pane-increment (if (< event-position (scroller-value-position scroller))
;; Decrement by pane?
(when (>= event-position min-position)
(- pane-size))
;; Increment by pane?
(when (<= event-position max-position)
pane-size))))
(unless pane-increment
;; Just wait for release and do nothing
(catch :release (loop (process-next-event display)))
(return-from press-cable))
(if (catch :release
;; If user is clicking fast on cable, then we can arrive here
;; before all :exposure's from previous clicks have been processed.
;; Therefore, must use a timer, so we can continue processing :exposure's
;; while waiting for click release.
(add-timer scroller :click *scroller-click-timeout*)
(unwind-protect
(catch :click-timeout
(loop (process-next-event display)))
(delete-timer scroller :click))
t)
;; Perform continuous pane scrolling...
(let ((current-x x) (current-y y))
;; Set timer for update
(when (and (numberp update-delay) (plusp update-delay))
(add-timer scroller :update-delay update-delay))
;; Increment and warp pointer as needed, until release event
(apply-callback scroller :begin-continuous)
(catch :release
(loop
(scroller-increment-value scroller pane-increment)
(multiple-value-setq (current-x current-y)
(scrollbar-cable-warp
scroller pane-increment
current-x current-y
min-position max-position))
;; Wait for timeout to elapse
(do () ((not (process-next-event display *scroller-hold-timeout*))))))
(apply-callback scroller :end-continuous))
;; Single click -- increment value
(progn
(scroller-increment-value scroller pane-increment)
;; Warp pointer to keep it between elevator and anchor
(scrollbar-cable-warp
scroller pane-increment
x y
min-position max-position)))
;; Report final value, if necessary
(unless (eql 0 update-delay)
(delete-timer scroller :update-delay)
(apply-callback scroller :new-value value)))))))
(press-drag-area (scroller)
(with-slots (display regions value update-delay foreground orientation) scroller
(let
((highlight-pixel (logxor foreground (contact-current-background-pixel scroller)))
(elevator (svref regions *elevator-region*)))
(multiple-value-bind (drag-x drag-y drag-width drag-height)
(scrollbar-drag-area-geometry scroller)
(using-gcontext
(gc :drawable scroller
:function boole-xor
:foreground highlight-pixel)
;; Highlight drag area
(draw-rectangle
elevator gc
drag-x drag-y drag-width drag-height :fill-p)
(with-event (x y)
(let ((*previous-position* (if (eq :vertical orientation) y x))
(*drag-motion* t))
(declare (special *previous-position* *drag-motion*))
;; Set timer for update
(when (and (numberp update-delay) (plusp update-delay))
(add-timer scroller :update-delay update-delay))
;; Handle motion events until release.
(catch :release
(loop (process-next-event display)))))
;; Report final value.
(when (and (numberp update-delay) (plusp update-delay))
(delete-timer scroller :update-delay))
(apply-callback scroller :new-value value)
Unhighlight drag area
(draw-rectangle
elevator gc
drag-x drag-y drag-width drag-height :fill-p))))))
(press-less-arrow (scroller)
(with-slots (display regions value maximum increment update-delay foreground orientation) scroller
(let
((highlight-pixel (logxor foreground (contact-current-background-pixel scroller))))
(multiple-value-bind (arrow-x arrow-y arrow-width arrow-height)
(scrollbar-less-arrow-geometry scroller)
(using-gcontext
(gc :drawable scroller
:function boole-xor
:foreground highlight-pixel)
;; Highlight arrow
(draw-rectangle
(svref regions *elevator-region*) gc
arrow-x arrow-y arrow-width arrow-height :fill-p)
Force pointer to stay within arrow window
(grab-pointer scroller #.(make-event-mask :button-press :button-release)
:confine-to (svref regions *less-arrow-region*))
(if (catch :release (not (process-next-event display *scroller-click-timeout*)))
;; Perform continuous scrolling...
(progn
;; Set timer for update
(when (and (numberp update-delay) (plusp update-delay))
(add-timer scroller :update-delay update-delay))
;; Increment until release event
(apply-callback scroller :begin-continuous)
(catch :release
(loop
(scroller-increment-value scroller (- increment))
(do () ((not (process-next-event display *scroller-hold-timeout*))))))
(apply-callback scroller :end-continuous))
;; Single click -- increment value.
(scroller-increment-value scroller (- increment)))
;; Report final value, if necessary
(unless (eql 0 update-delay)
(delete-timer scroller :update-delay)
(apply-callback scroller :new-value value))
;; Release grab
(ungrab-pointer display)
Unhighlight arrow
(draw-rectangle
(svref regions *elevator-region*) gc
arrow-x arrow-y arrow-width arrow-height :fill-p))))))
(press-more-arrow (scroller)
(with-slots (display regions value maximum increment update-delay foreground orientation) scroller
(let
((highlight-pixel (logxor foreground (contact-current-background-pixel scroller))))
(multiple-value-bind (arrow-x arrow-y arrow-width arrow-height)
(scrollbar-more-arrow-geometry scroller)
(using-gcontext
(gc :drawable scroller
:function boole-xor
:foreground highlight-pixel)
;; Highlight arrow
(draw-rectangle
(svref regions *elevator-region*) gc
arrow-x arrow-y arrow-width arrow-height :fill-p)
Force pointer to stay within arrow window
(grab-pointer scroller #.(make-event-mask :button-press :button-release)
:confine-to (svref regions *more-arrow-region*))
(if (catch :release (not (process-next-event display *scroller-click-timeout*)))
;; Perform continuous scrolling...
(progn
;; Set timer for update
(when (and (numberp update-delay) (plusp update-delay))
(add-timer scroller :update-delay update-delay))
;; Increment until release event
(apply-callback scroller :begin-continuous)
(catch :release
(loop
(scroller-increment-value scroller increment)
(do () ((not (process-next-event display *scroller-hold-timeout*))))))
(apply-callback scroller :end-continuous))
;; Single click -- increment value.
(scroller-increment-value scroller increment))
;; Report final value, if necessary
(unless (eql 0 update-delay)
(delete-timer scroller :update-delay)
(apply-callback scroller :new-value value))
;; Release grab
(ungrab-pointer display)
Unhighlight arrow
(draw-rectangle
(svref regions *elevator-region*) gc
arrow-x arrow-y arrow-width arrow-height :fill-p))))))
(press-max-anchor (scroller)
(with-slots (display regions foreground maximum value) scroller
;; Highlight max anchor
(let
((max-anchor (svref regions *max-anchor-region*))
(highlight-size (scrollbar-anchor-width
(getf *scrollbar-dimensions* (contact-scale scroller)))))
;; This rectangle size is "too big", but we let the server clip it
(using-gcontext (gc :drawable scroller :foreground foreground)
(draw-rectangle
max-anchor gc
0 0 highlight-size highlight-size
:fill-p))
;; Wait for release event
(catch :release
(loop (process-next-event display)))
Unhighlight max anchor
(clear-area max-anchor)
;; Go to maximum position
(unless (= value maximum)
(setf (scale-value scroller) maximum)
(apply-callback scroller :new-value maximum)))))
(press-min-anchor (scroller)
(with-slots (display regions foreground minimum value) scroller
;; Highlight min anchor
(let
((min-anchor (svref regions *min-anchor-region*))
(highlight-size (scrollbar-anchor-width
(getf *scrollbar-dimensions* (contact-scale scroller)))))
;; This rectangle size is "too big", but we let the server clip it
(using-gcontext (gc :drawable scroller :foreground foreground)
(draw-rectangle
min-anchor gc
0 0 highlight-size highlight-size
:fill-p))
;; Wait for release event
(catch :release
(loop (process-next-event display)))
Unhighlight min anchor
(clear-area min-anchor)
;; Go to minimum position
(unless (= value minimum)
(setf (scale-value scroller) minimum)
(apply-callback scroller :new-value minimum))))))
Initialize press - handlers dispatch vector
(setf (svref press-handlers *elevator-region*) nil) ; should never be used!!
(setf (svref press-handlers *min-anchor-region*) #'press-min-anchor)
(setf (svref press-handlers *max-anchor-region*) #'press-max-anchor)
(setf (svref press-handlers *less-arrow-region*) #'press-less-arrow)
(setf (svref press-handlers *drag-area-region*) #'press-drag-area)
(setf (svref press-handlers *more-arrow-region*) #'press-more-arrow)
(setf (svref press-handlers *cable-region*) #'press-cable)
;; Define press action function
(defun scroller-handle-press (scroller)
(let ((*scroller-pressed-p* t))
(declare (special *scroller-pressed-p*))
(funcall (svref press-handlers (find-region scroller)) scroller)))))
(defun scroller-handle-release (scroller)
(declare (ignore scroller))
(declare (special *scroller-pressed-p*))
(when (boundp '*scroller-pressed-p*)
(throw :release nil)))
(defun scroller-handle-motion (scroller)
(declare (special *previous-position* *drag-motion*))
(when (boundp '*drag-motion*)
(with-slots (orientation) (the scroller scroller)
(with-event (state x y)
(multiple-value-bind (ptr-x ptr-y)
;; Is :button-1 still down?
(if (plusp (logand state #.(make-state-mask :button-1)))
;; Yes, query current pointer position
(query-pointer scroller)
;; No, use final x,y returned for button transition
(values x y))
(let* ((new-position (if (eq :vertical orientation) ptr-y ptr-x))
(increment (scroller-pixel-value scroller (- new-position *previous-position*))))
(unless (zerop increment)
(scroller-increment-value scroller increment)
(setf *previous-position* new-position))))))))
(defun scroller-report-new-value (scroller)
(with-slots (value) (the scroller scroller)
(apply-callback scroller :new-value value)))
(defun scroller-increment-value (scroller increment)
(with-slots (value minimum maximum update-delay) (the scroller scroller)
(let*
((new-value (+ value increment))
(adjusted (min (max (or (apply-callback scroller :adjust-value new-value)
new-value)
minimum)
maximum)))
(unless (= adjusted value)
(setf (scale-value scroller) adjusted)
(when (eql 0 update-delay)
(apply-callback scroller :new-value adjusted))))))
(defun scrollbar-cable-warp (scroller pane-increment current-x current-y min-position max-position)
(with-slots (orientation) (the scroller scroller)
(let*
((current-position
(if (eq :vertical orientation) current-y current-x))
(new-pointer-position
(if (plusp pane-increment)
(when (< current-position (setf min-position
(+ (scroller-value-position scroller)
(scrollbar-elevator-size scroller))))
(1+ min-position))
(when (> current-position (setf max-position
(scroller-value-position scroller)))
(1- max-position)))))
(when new-pointer-position
(if (eq :vertical orientation)
(setf current-y new-pointer-position)
(setf current-x new-pointer-position))
(warp-pointer scroller current-x current-y))
(values current-x current-y))))
(defun scroller-value-position (scroller)
(with-slots (width height orientation value minimum maximum) (the scroller scroller)
(let*
((dimensions (getf *scrollbar-dimensions* (contact-scale scroller)))
(margin (scrollbar-margin dimensions))
(anchor-height (scrollbar-anchor-height dimensions))
(range (- maximum minimum)))
(+ anchor-height
margin
(if (zerop range) 0
(pixel-round
(* (- value minimum)
Pixels per value unit
(/ (- (if (eq orientation :vertical) height width)
anchor-height margin
(* (scrollbar-anchor-width dimensions)
(if (scrollbar-abbreviated-p scroller) 2 3))
2
margin anchor-height)
range))))))))
(defun scroller-pixel-value (scroller pixels)
(with-slots (width height orientation minimum maximum increment) (the scroller scroller)
(let*
((dimensions (getf *scrollbar-dimensions* (contact-scale scroller)))
(margin (scrollbar-margin dimensions))
(anchor-height (scrollbar-anchor-height dimensions)))
;; pixels times value-units-per-pixel, rounded to nearest multiple of increment
(* (pixel-round
(/ (* pixels (- maximum minimum))
(- (if (eq orientation :vertical) height width)
anchor-height margin
(* (scrollbar-anchor-width dimensions)
(if (scrollbar-abbreviated-p scroller) 2 3))
2
margin anchor-height))
increment)
increment))))
(defun scroller-indicator-position (scroller &optional size)
(setf size (or size (scroller-indicator-size scroller)))
(with-slots (width height orientation value minimum maximum) (the scroller scroller)
(let*
((dimensions (getf *scrollbar-dimensions* (contact-scale scroller)))
(margin (scrollbar-margin dimensions))
(anchor-height (scrollbar-anchor-height dimensions))
(range (- maximum minimum)))
(+ anchor-height
margin
(if (zerop range) 0
(pixel-round
(* (- value minimum)
Pixels per value unit for indicator position
(/ (- (if (eq orientation :vertical) height width)
anchor-height margin
size
margin anchor-height)
range))))))))
(defun scroller-indicator-size (scroller)
(with-slots (width height orientation minimum maximum indicator-size) (the scroller scroller)
(let*
((dimensions (getf *scrollbar-dimensions* (contact-scale scroller)))
(margin (scrollbar-margin dimensions))
(anchor-height (scrollbar-anchor-height dimensions))
(range (- maximum minimum)))
(pixel-round
(*
(min (true-indicator-size indicator-size) range) ; "clip" displayed size to cable range
(if (zerop range) 0
Pixels per value unit for indicator size
(/ (- (if (eq orientation :vertical) height width)
anchor-height margin
margin anchor-height)
range))))))) | null | https://raw.githubusercontent.com/blindglobe/clocc/a50bb75edb01039b282cf320e4505122a59c59a7/src/gui/clue/clio/scroller.lisp | lisp | Package : CLIO - OPEN ; ; Lowercase : T ; Fonts:(CPTFONT ) ; Syntax : Common - Lisp -*-
----------------------------------------------------------------------------------+
|
TEXAS INSTRUMENTS INCORPORATED |
P.O. BOX 149149 |
|
|
Permission is granted to any individual or institution to use, copy, modify, and |
distribute this software, provided that this complete copyright and permission |
notice is maintained, intact, in all copies and supporting documentation. |
|
implied warranty. |
|
----------------------------------------------------------------------------------+
----------------------------------------------------------------------------+
|
Scroller |
|
----------------------------------------------------------------------------+
Implementation Strategy:
Elevator and anchor controls are implemented as non-contact subwindows (i.e.
scroller is NOT a composite). Overall, this strategy simplifies the tasks
of determining which control is receiving input and of confining the pointer
cursor to controls during continuous scrolling, without unnecessarily
incurring the full cost of a sub-contact.
The elevator is represented as an :input-output subwindow; the imagery of all
elevator controls is drawn to this subwindow. The less/more arrow and drag
area controls are represented as :input-only subwindows of the elevator
subwindow. Subwindows are used for these controls only for use as :confine-to
windows while the pointer is grabbed.
The scroller subwindow receiving a :button-press is determined from the child
slot of the button event. During event handling, the regions vector is
searched to look up the vector index of the event window (see FIND-REGION).
If the event child is the elevator, then a further search based on elevator
geometry is necessary to determine which elevator subwindow is the event
window. The resulting vector index is used to select an element from a
vector of functions to handle the :button-press (see PRESS-HANDLERS).
Index values for accessing region vector and press handler vector
----------------------------------------------------------------------------+
|
Initialization |
|
----------------------------------------------------------------------------+
Create control region windows
Request change to preferred width/height, depending on orientation.
----------------------------------------------------------------------------+
|
Accessors |
|
----------------------------------------------------------------------------+
Update display
Position elevator
Dim arrows, if necessary
----------------------------------------------------------------------------+
|
|
----------------------------------------------------------------------------+
Calculate geometry assuming :vertical orientation
Suggested or current height
Size of abbreviated scrollbar (no drag area)
Return preferred geometry according to actual orientation
Reposition max anchor
Reconfigure elevator
Changing abbreviation?
Reposition more-arrow region
Redisplay elevator image
If not yet realized, just do it
----------------------------------------------------------------------------+
|
|
----------------------------------------------------------------------------+
Default exposed rectangle, if necessary
-----------------------------------------------------------------------------+
|
Draw cable. |
|
Stipple fill is relatively slow, so redrawing entire cable can cause |
annoying flicker. But computing the minimal cable area to redraw is |
complicated, because the display method is expected to update the image |
when the elevator moves (thus exposing a small region of the scroller |
previously obscured by the elevator). In this case, we must redraw the |
cable not only in the area exposed, but also elsewhere to cover up the |
previous gaps between elevator/proportion indicator/cable. |
|
The following algorithm is a compromise. If the exposed area is entirely |
then we redraw the cable only on that side. |
|
-----------------------------------------------------------------------------+
Exposed area before elevator?
Exposed area behind elevator?
Redraw only last part of cable.
Redraw all of cable.
Draw exposed cable area
Draw proportion indicator
Compute elevator geometry
Exposed area intersects elevator?
Draw elevator image
Dim arrows, if necessary
----------------------------------------------------------------------------+
|
Event Translations |
|
----------------------------------------------------------------------------+
Return index of scroller region containing the current event
Look up event child window among scroller regions
Which part of elevator got the press: less-arrow, drag-area, or more-arrow?
Min/max anchor press
Event occurred on non-child area of scroller
Decrement by pane?
Increment by pane?
Just wait for release and do nothing
If user is clicking fast on cable, then we can arrive here
before all :exposure's from previous clicks have been processed.
Therefore, must use a timer, so we can continue processing :exposure's
while waiting for click release.
Perform continuous pane scrolling...
Set timer for update
Increment and warp pointer as needed, until release event
Wait for timeout to elapse
Single click -- increment value
Warp pointer to keep it between elevator and anchor
Report final value, if necessary
Highlight drag area
Set timer for update
Handle motion events until release.
Report final value.
Highlight arrow
Perform continuous scrolling...
Set timer for update
Increment until release event
Single click -- increment value.
Report final value, if necessary
Release grab
Highlight arrow
Perform continuous scrolling...
Set timer for update
Increment until release event
Single click -- increment value.
Report final value, if necessary
Release grab
Highlight max anchor
This rectangle size is "too big", but we let the server clip it
Wait for release event
Go to maximum position
Highlight min anchor
This rectangle size is "too big", but we let the server clip it
Wait for release event
Go to minimum position
should never be used!!
Define press action function
Is :button-1 still down?
Yes, query current pointer position
No, use final x,y returned for button transition
pixels times value-units-per-pixel, rounded to nearest multiple of increment
"clip" displayed size to cable range |
, TEXAS 78714 |
Copyright ( C ) 1989 , 1990 Texas Instruments Incorporated . |
Texas Instruments Incorporated provides this software " as is " without express or |
(in-package "CLIO-OPEN")
(export '(
make-scroller
scale-increment
scale-indicator-size
scale-maximum
scale-minimum
scale-orientation
scale-update
scale-update-delay
scale-value
scroller
)
'clio-open)
All control subwindows are recorded in the regions vector of the scroller .
(defcontact scroller (core contact)
((increment :type number
setf defined below
:initarg :increment
:initform 1)
(indicator-size
:type (or number (member :off))
setf defined below
:initarg :indicator-size
:initform 0)
(maximum :type number
setf defined below
:initarg :maximum
:initform 1)
(minimum :type number
setf defined below
:initarg :minimum
:initform 0)
(orientation :type (member :horizontal :vertical)
setf defined below
:initarg :orientation
:initform :vertical)
(update-delay :type (or number (member :until-done))
setf defined below
:initarg :update-delay
:initform 0)
(value :type number
setf defined below
:initarg :value
:initform 0)
(compress-exposures
:initform :on
:type (member :off :on)
:reader contact-compress-exposures
:allocation :class)
(regions :type (vector window)
:initform (make-array 6)))
(:resources
increment indicator-size maximum minimum orientation update-delay value
(border-width :initform 0)
(event-mask :initform #.(make-event-mask :pointer-motion-hint :exposure))))
(defconstant *elevator-region* 0)
(defconstant *min-anchor-region* 1)
(defconstant *max-anchor-region* 2)
(defconstant *less-arrow-region* 3)
(defconstant *drag-area-region* 4)
(defconstant *more-arrow-region* 5)
(defconstant *cable-region* 6)
(defun make-scroller (&rest initargs &key &allow-other-keys)
(apply #'make-contact 'scroller initargs))
(defmethod initialize-instance :after ((self scroller) &key &allow-other-keys)
(with-slots (width height) self
Initialize required geometry
(multiple-value-setq (width height) (preferred-size self))))
(labels
((min-anchor-geometry
(dimensions scroller orientation width height)
(declare (ignore scroller))
(let ((anchor-width (scrollbar-anchor-width dimensions))
(anchor-height (scrollbar-anchor-height dimensions)))
(if (eq orientation :vertical)
(values (pixel-round (- width anchor-width) 2) 0 (- anchor-width 2) (- anchor-height 2))
(values 0 (pixel-round (- height anchor-width) 2) (- anchor-height 2) (- anchor-width 2)))))
(max-anchor-geometry
(dimensions scroller orientation width height)
(declare (ignore scroller))
(let ((anchor-width (scrollbar-anchor-width dimensions))
(anchor-height (scrollbar-anchor-height dimensions)))
(if (eq orientation :vertical)
(values (pixel-round (- width anchor-width) 2) (- height anchor-height) (- anchor-width 2) (- anchor-height 2))
(values (- width anchor-height) (pixel-round (- height anchor-width) 2) (- anchor-height 2) (- anchor-width 2)))))
(elevator-geometry
(dimensions scroller orientation width height)
(let ((anchor-width (scrollbar-anchor-width dimensions)))
(if (eq orientation :vertical)
(values (pixel-round (- width anchor-width) 2) (scroller-value-position scroller) anchor-width (scrollbar-elevator-size scroller))
(values (scroller-value-position scroller) (pixel-round (- height anchor-width) 2) (scrollbar-elevator-size scroller) anchor-width))))
(less-arrow-geometry
(dimensions scroller orientation width height)
(declare (ignore scroller orientation width height))
(let ((anchor-width (scrollbar-anchor-width dimensions)))
(values 0 0 anchor-width anchor-width)))
(more-arrow-geometry
(dimensions scroller orientation width height)
(declare (ignore width height))
(let ((anchor-width (scrollbar-anchor-width dimensions))
(abbreviated-p (scrollbar-abbreviated-p scroller)))
(if (eq orientation :vertical)
(values 0 (+ anchor-width (if abbreviated-p 0 anchor-width)) anchor-width anchor-width)
(values (+ anchor-width (if abbreviated-p 0 anchor-width)) 0 anchor-width anchor-width))))
(drag-area-geometry
(dimensions scroller orientation width height)
(declare (ignore scroller width height))
(let ((anchor-width (scrollbar-anchor-width dimensions)))
(if (eq orientation :vertical)
(values 0 anchor-width anchor-width anchor-width)
(values anchor-width 0 anchor-width anchor-width))))
(reconfigure-controls (self)
(declare (type scroller self))
(with-slots (regions width height orientation) (the scroller self)
(let ((dimensions (getf *scrollbar-dimensions* (contact-scale self))))
(let ((window (svref regions *min-anchor-region*)))
(with-state (window)
(multiple-value-bind (window-x window-y window-width window-height)
(min-anchor-geometry dimensions self orientation width height)
(setf (drawable-x window) window-x
(drawable-y window) window-y
(drawable-width window) window-width
(drawable-height window) window-height))))
(let ((window (svref regions *max-anchor-region*)))
(with-state (window)
(multiple-value-bind (window-x window-y window-width window-height)
(max-anchor-geometry dimensions self orientation width height)
(setf (drawable-x window) window-x
(drawable-y window) window-y
(drawable-width window) window-width
(drawable-height window) window-height))))
(let ((window (svref regions *elevator-region*)))
(with-state (window)
(multiple-value-bind (window-x window-y window-width window-height)
(elevator-geometry dimensions self orientation width height)
(setf (drawable-x window) window-x
(drawable-y window) window-y
(drawable-width window) window-width
(drawable-height window) window-height))))
(let ((window (svref regions *drag-area-region*)))
(with-state (window)
(multiple-value-bind (window-x window-y window-width window-height)
(drag-area-geometry dimensions self orientation width height)
(setf (drawable-x window) window-x
(drawable-y window) window-y
(drawable-width window) window-width
(drawable-height window) window-height))))
(let ((window (svref regions *less-arrow-region*)))
(with-state (window)
(multiple-value-bind (window-x window-y window-width window-height)
(less-arrow-geometry dimensions self orientation width height)
(setf (drawable-x window) window-x
(drawable-y window) window-y
(drawable-width window) window-width
(drawable-height window) window-height))))
(let ((window (svref regions *more-arrow-region*)))
(with-state (window)
(multiple-value-bind (window-x window-y window-width window-height)
(more-arrow-geometry dimensions self orientation width height)
(setf (drawable-x window) window-x
(drawable-y window) window-y
(drawable-width window) window-width
(drawable-height window) window-height))))))))
(defmethod realize :after ((self scroller))
(with-slots (regions width height orientation foreground) self
(let*
((dimensions (getf *scrollbar-dimensions* (contact-scale self)))
(min-anchor (multiple-value-bind (region-x region-y region-width region-height)
(min-anchor-geometry dimensions self orientation width height)
(create-window
:parent self
:x region-x
:y region-y
:width region-width
:height region-height
:background :parent-relative
:border-width 1
:border foreground
:gravity (if (eq orientation :vertical) :north :west))))
(max-anchor (multiple-value-bind (region-x region-y region-width region-height)
(max-anchor-geometry dimensions self orientation width height)
(create-window
:parent self
:x region-x
:y region-y
:width region-width
:height region-height
:background :parent-relative
:border-width 1
:border foreground
:gravity (if (eq orientation :vertical) :north :west))))
(elevator (multiple-value-bind (region-x region-y region-width region-height)
(elevator-geometry dimensions self orientation width height)
(create-window
:parent self
:x region-x
:y region-y
:width region-width
:height region-height
:border-width 0
:gravity (if (eq orientation :vertical) :north :west))))
(drag-area (multiple-value-bind (region-x region-y region-width region-height)
(drag-area-geometry dimensions self orientation width height)
(create-window
:parent elevator
:class :input-only
:x region-x
:y region-y
:width region-width
:height region-height
:border-width 0)))
(less-arrow (multiple-value-bind (region-x region-y region-width region-height)
(less-arrow-geometry dimensions self orientation width height)
(create-window
:parent elevator
:class :input-only
:x region-x
:y region-y
:width region-width
:height region-height
:border-width 0)))
(more-arrow (multiple-value-bind (region-x region-y region-width region-height)
(more-arrow-geometry dimensions self orientation width height)
(create-window
:parent elevator
:class :input-only
:x region-x
:y region-y
:width region-width
:height region-height
:border-width 0))))
(setf (svref regions *min-anchor-region*) min-anchor)
(setf (svref regions *max-anchor-region*) max-anchor)
(setf (svref regions *elevator-region*) elevator)
(setf (svref regions *drag-area-region*) drag-area)
(setf (svref regions *less-arrow-region*) less-arrow)
(setf (svref regions *more-arrow-region*) more-arrow)
(map-subwindows self)
(map-subwindows elevator))))
(defmethod rescale ((self scroller))
(with-slots (orientation) self
(multiple-value-bind (rw rh) (if (eq :vertical orientation) (values 0 nil) (values nil 0))
(multiple-value-bind (pw ph) (preferred-size self :width rw :height rh)
(change-geometry self :width pw :height ph :accept-p t))))
(when (realized-p self)
(reconfigure-controls self)))
(defmethod (setf scale-orientation) (new-orientation (scroller scroller))
(with-slots (orientation width height) scroller
(unless (eq orientation new-orientation)
(check-type new-orientation (member :horizontal :vertical))
(setf orientation new-orientation)
(multiple-value-bind (new-width new-height)
(preferred-size scroller :width height :height width)
(change-geometry scroller :width new-width :height new-height))
(reconfigure-controls scroller)))
new-orientation))
(defmethod (setf scale-update-delay) (new-update-delay (scroller scroller))
(with-slots (update-delay) scroller
(assert (or (eq new-update-delay :until-done)
(and (numberp new-update-delay) (not (minusp new-update-delay)))) ()
"~a is neither :UNTIL-DONE or a non-negative number." new-update-delay)
(setf update-delay new-update-delay)))
(defmethod (setf scale-value) (new-value (scroller scroller))
(scale-update scroller :value new-value)
new-value)
(defmethod (setf scale-minimum) (new-minimum (scroller scroller))
(scale-update scroller :minimum new-minimum)
new-minimum)
(defmethod (setf scale-maximum) (new-maximum (scroller scroller))
(scale-update scroller :maximum new-maximum)
new-maximum)
(defmethod (setf scale-increment) (new-increment (scroller scroller))
(scale-update scroller :increment new-increment)
new-increment)
(defmethod (setf scale-indicator-size) (new-indicator-size (scroller scroller))
(scale-update scroller :indicator-size new-indicator-size)
new-indicator-size)
(defmacro true-indicator-size (size)
`(if (eq ,size :off) 0 ,size))
(defmethod scale-update ((scroller scroller) &key value minimum maximum indicator-size increment)
(with-slots
((current-val value)
(current-min minimum)
(current-max maximum)
(current-ind indicator-size)
(current-inc increment)
regions
orientation)
scroller
(setf minimum (or minimum current-min)
maximum (or maximum current-max)
value (or value current-val)
indicator-size (or indicator-size current-ind)
increment (or increment current-inc))
(assert (numberp value) () "~s for :value is not a number" value)
(assert (numberp minimum) () "~s for :minimum is not a number" minimum)
(assert (numberp maximum) () "~s for :maximum is not a number" maximum)
(assert (and (numberp increment) (not (minusp increment))) ()
"~s for :increment is not a number" increment)
(assert (or (and (numberp indicator-size) (not (minusp indicator-size)))
(eq indicator-size :off))
() "~s for :indicator-size is not :off or a non-negative-number)" indicator-size)
(assert (<= minimum maximum) ()
"Minimum (~a) is greater than maximum (~a)."
minimum maximum)
(assert (<= minimum value maximum) ()
"Value (~a) must be in the range [~a, ~a]."
value minimum maximum)
(let*
((insensitive-p (not (sensitive-p scroller)))
(less-arrow-dim-p (or insensitive-p (= current-val current-min)))
(more-arrow-dim-p (or insensitive-p (= current-val current-max)))
(prev-min current-min)
(prev-max current-max)
(prev-ind current-ind)
(prev-val current-val))
(setf current-min minimum
current-max maximum
current-val value
current-ind indicator-size
current-inc increment)
(when (realized-p scroller)
(cond
((not (and (eql current-min prev-min) (eql current-max prev-max) (eql current-ind prev-ind)))
(display scroller))
((not (eql current-val prev-val))
(let ((position (scroller-value-position scroller))
(elevator (svref regions *elevator-region*)))
(if (eq :vertical orientation)
(setf (drawable-y elevator) position)
(setf (drawable-x elevator) position)))
(scrollbar-update-less-arrow scroller less-arrow-dim-p insensitive-p)
(scrollbar-update-more-arrow scroller more-arrow-dim-p insensitive-p)))))))
(defmethod (setf contact-foreground) :after (new-fg (self scroller))
(declare (ignore new-fg))
(with-slots (foreground regions) self
(setf (window-border (svref regions *min-anchor-region*)) foreground)
(setf (window-border (svref regions *max-anchor-region*)) foreground)))
Geometry Management |
(defmethod preferred-size ((self scroller) &key width height border-width)
(declare (ignore border-width))
(with-slots (orientation (current-height height) (current-width width)) self
(let*
((dimensions (getf *scrollbar-dimensions* (contact-scale self)))
(margin (scrollbar-margin dimensions))
(anchor-width (scrollbar-anchor-width dimensions))
(anchor-height (scrollbar-anchor-height dimensions))
(preferred-width (+ margin anchor-width margin))
(preferred-height (max
(or (if (eq orientation :vertical) height width)
(if (eq orientation :vertical) current-height current-width))
(+ anchor-height margin
anchor-width anchor-width
margin anchor-height))))
(values
(if (eq orientation :vertical) preferred-width preferred-height)
(if (eq orientation :vertical) preferred-height preferred-width)
0))))
(defmethod resize :around ((self scroller) new-width new-height new-border-width)
(if (realized-p self)
Reconfigure subwindows
(let* ((abbreviated-before-p (scrollbar-abbreviated-p self))
(resized-p (call-next-method)))
(with-slots (width height orientation regions) self
(let*
((scale (contact-scale self))
(max-anchor (svref regions *max-anchor-region*))
(dimensions (getf *scrollbar-dimensions* scale))
(anchor-position (- (if (eq orientation :vertical) height width)
(scrollbar-anchor-height dimensions)
1))
(elevator (svref regions *elevator-region*))
(elevator-position (scroller-value-position self)))
(if (eq orientation :vertical)
(setf (drawable-y max-anchor) anchor-position)
(setf (drawable-x max-anchor) anchor-position))
(multiple-value-bind (elevator-size abbreviated-after-p)
(scrollbar-elevator-size self)
(with-state (elevator)
(case orientation
(:vertical
(setf (drawable-y elevator) elevator-position)
(setf (drawable-height elevator) elevator-size))
(:horizontal
(setf (drawable-x elevator) elevator-position)
(setf (drawable-width elevator) elevator-size))))
(unless (eq abbreviated-before-p abbreviated-after-p)
(let* ((anchor-width (scrollbar-anchor-width dimensions))
(more-arrow-pos (+ anchor-width (if abbreviated-after-p 0 anchor-width))))
(if (eq orientation :vertical)
(setf (drawable-y (svref regions *more-arrow-region*)) more-arrow-pos)
(setf (drawable-x (svref regions *more-arrow-region*)) more-arrow-pos)))
(scrollbar-display-elevator self scale)))))
resized-p)
(call-next-method)))
(defun scrollbar-abbreviated-p (scroller)
(with-slots (width height orientation) (the scroller scroller)
(let*
((dimensions (getf *scrollbar-dimensions* (contact-scale scroller)))
(margin (scrollbar-margin dimensions))
(anchor-width (scrollbar-anchor-width dimensions))
(anchor-height (scrollbar-anchor-height dimensions)))
(<= (if (eq orientation :vertical) height width)
(+ anchor-height margin
anchor-width anchor-width anchor-width
margin anchor-height)))))
(defun scrollbar-elevator-size (scroller)
(let ((abbreviated-p (scrollbar-abbreviated-p scroller)))
(values
(+ (* (scrollbar-anchor-width
(getf *scrollbar-dimensions* (contact-scale scroller)))
(if abbreviated-p 2 3))
2)
abbreviated-p)))
(defun scrollbar-less-arrow-geometry (scroller)
(let ((arrow-size (1- (scrollbar-anchor-width (getf *scrollbar-dimensions*
(contact-scale scroller))))))
(if (eq :vertical (scale-orientation scroller))
(values 1 1 (- arrow-size 2) arrow-size)
(values 1 1 arrow-size (- arrow-size 2)))))
(defun scrollbar-drag-area-geometry (scroller)
(let*
((area-size (scrollbar-anchor-width
(getf *scrollbar-dimensions* (contact-scale scroller))))
(area-position (1+ area-size)))
(if (eq :vertical (scale-orientation scroller))
(values 1 area-position (- area-size 3) (1- area-size))
(values area-position 1 (1- area-size) (- area-size 3)))))
(defun scrollbar-more-arrow-geometry (scroller)
(let*
((arrow-size (scrollbar-anchor-width
(getf *scrollbar-dimensions* (contact-scale scroller))))
(arrow-position (1+ (+ arrow-size (if (scrollbar-abbreviated-p scroller) 0 arrow-size)))))
(if (eq :vertical (scale-orientation scroller))
(values 1 arrow-position (- arrow-size 3) (1- arrow-size))
(values arrow-position 1 (1- arrow-size) (- arrow-size 3)))))
Display |
(defmethod display ((self scroller) &optional at-x at-y at-width at-height &key)
(with-slots (width height foreground regions orientation) self
(setf at-x (or at-x 0)
at-y (or at-y 0)
at-width (or at-width (- width at-x))
at-height (or at-height (- height at-y)))
(let*
((scale (contact-scale self))
(dimensions (getf *scrollbar-dimensions* scale))
(anchor-width (scrollbar-anchor-width dimensions))
(anchor-height (scrollbar-anchor-height dimensions))
(margin (scrollbar-margin dimensions))
(cable-margin (scrollbar-cable-margin dimensions))
(cable-width (scrollbar-cable-width dimensions))
(elevator-position (scroller-value-position self))
(elevator-size (scrollbar-elevator-size self))
(elevator-end (+ elevator-position elevator-size)))
on one side of the elevator ( as it is in the case of an elevator move ) , |
(flet
((exposed-cable-segment
(exposed-position exposed-size scroller-size)
(let ((min (+ anchor-height margin))
(max (- scroller-size margin anchor-height)))
(cond
((>= elevator-position (+ exposed-position exposed-size))
Redraw only first part of cable .
(values min (- elevator-position min)))
((>= exposed-position elevator-end)
(values elevator-end (- max elevator-end)))
(t
(values min (- max min)))))))
(multiple-value-bind (cable-x cable-y cable-width cable-height)
(if (eq orientation :vertical)
(multiple-value-bind (cy ch) (exposed-cable-segment at-y at-height height)
(values (pixel-round (- width cable-width) 2) cy cable-width ch))
(multiple-value-bind (cx cw) (exposed-cable-segment at-x at-width width)
(values cx (pixel-round (- height cable-width) 2) cw cable-width)))
(using-gcontext (gc :drawable self
:fill-style :stippled
:foreground foreground
:stipple (contact-image-mask self 50%gray :depth 1))
(clear-area self :x cable-x :y cable-y :width cable-width :height cable-height)
(draw-rectangle self gc cable-x cable-y cable-width cable-height :fill-p))
(let* ((pi-size (scroller-indicator-size self))
(pi-pos (scroller-indicator-position self pi-size)))
(multiple-value-bind (pi-x pi-y pi-width pi-height margin-x margin-y margin-width margin-height)
(if (eq orientation :vertical)
(values
cable-x
pi-pos
cable-width
pi-size
cable-x
(- pi-pos margin)
cable-width
(+ pi-size margin margin))
(values
pi-pos
cable-y
pi-size
cable-height
(- pi-pos margin)
cable-y
(+ pi-size margin margin)
cable-height))
(clear-area self :x margin-x :y margin-y :width margin-width :height margin-height)
(using-gcontext (gc :drawable self
:fill-style :solid
:foreground foreground)
(draw-rectangle self gc pi-x pi-y pi-width pi-height :fill-p))))))
Clear cable margin around elevator
(multiple-value-bind (gap-x gap-y gap-width gap-height)
(if (eq orientation :vertical)
(values
0 (- elevator-position cable-margin)
nil (+ cable-margin elevator-size cable-margin))
(values
(- elevator-position cable-margin) 0
(+ cable-margin elevator-size cable-margin) nil))
(clear-area self :x gap-x :y gap-y :width gap-width :height gap-height))
(multiple-value-bind (elevator-x elevator-y elevator-width elevator-height)
(if (eq orientation :vertical)
(values
(scrollbar-margin dimensions)
elevator-position
anchor-width
elevator-size)
(values
elevator-position
(scrollbar-margin dimensions)
elevator-size
anchor-width))
(when
(and (< elevator-x (+ at-x at-width))
(< elevator-y (+ at-y at-height))
(> (+ elevator-x elevator-width) at-x)
(> (+ elevator-y elevator-height) at-y))
(scrollbar-display-elevator self scale))))))
(defun scrollbar-display-elevator (scroller &optional scale)
(setf scale (or scale (contact-scale scroller)))
(with-slots (orientation regions foreground) (the scroller scroller)
(let*
((image (getf (getf *scrollbar-images* orientation) scale))
(mask (contact-image-mask
scroller image
:foreground foreground
:background (contact-current-background-pixel scroller)))
(elevator (svref regions *elevator-region*)))
(using-gcontext (gc :drawable scroller :exposures :off)
(copy-area
mask gc
0 0
(image-width image) (image-height image)
elevator
0 0)
(when (scrollbar-abbreviated-p scroller)
(let ((copy-size (scrollbar-anchor-width (getf *scrollbar-dimensions* scale))))
(multiple-value-bind (from-x from-y copy-width copy-height)
(if (eq :vertical orientation)
(values 0 (+ copy-size copy-size) copy-size (+ copy-size 2))
(values (+ copy-size copy-size) 0 (+ copy-size 2) copy-size))
(multiple-value-bind (to-x to-y)
(if (eq :vertical orientation)
(values 0 copy-size)
(values copy-size 0))
(copy-area
mask gc
from-x from-y
copy-width copy-height
elevator
to-x to-y))))))))
(let ((insensitive-p (not (sensitive-p scroller))))
(scrollbar-update-less-arrow scroller nil insensitive-p)
(scrollbar-update-more-arrow scroller nil insensitive-p)))
(defun scrollbar-update-less-arrow (scroller dim-p insensitive-p)
(with-slots (value minimum foreground regions) (the scroller scroller)
(unless (eq dim-p (or insensitive-p (= value minimum)))
(multiple-value-bind (arrow-x arrow-y arrow-width arrow-height)
(scrollbar-less-arrow-geometry scroller)
(using-gcontext
(gc :drawable scroller
:function boole-xor
:fill-style :stippled
:foreground (logxor foreground (contact-current-background-pixel scroller))
:stipple (contact-image-mask scroller 25%gray :depth 1))
(draw-rectangle
(svref regions *elevator-region*) gc
arrow-x arrow-y
arrow-width arrow-height
:fill-p))))))
(defun scrollbar-update-more-arrow (scroller dim-p insensitive-p)
(with-slots (value maximum foreground regions) (the scroller scroller)
(unless (eq dim-p (or insensitive-p (= value maximum)))
(multiple-value-bind (arrow-x arrow-y arrow-width arrow-height)
(scrollbar-more-arrow-geometry scroller)
(using-gcontext
(gc :drawable scroller
:function boole-xor
:fill-style :stippled
:foreground (logxor foreground (contact-current-background-pixel scroller))
:stipple (contact-image-mask scroller 25%gray :depth 1))
(draw-rectangle
(svref regions *elevator-region*) gc
arrow-x arrow-y
arrow-width arrow-height
:fill-p))))))
(defevent scroller (:motion-notify :button-1) scroller-handle-motion)
(defevent scroller (:timer :update-delay) scroller-report-new-value)
(defevent scroller (:timer :click) (throw-action :click-timeout))
(defevent scroller (:button-release :button-1) scroller-handle-release)
(defevent scroller (:button-press :button-1) scroller-handle-press)
(defparameter *scroller-click-timeout* 0.2
"Number of seconds to wait before starting continuous scrolling")
(defparameter *scroller-hold-timeout* 0.05
"Number of seconds to wait during continuous scrolling before updating value")
(let ((press-handlers (make-array 7)))
(flet
((find-region (scroller)
(with-slots (regions orientation) scroller
(with-event (child x y)
(if child
(let ((region (position child regions :test #'eq)))
(if (= region *elevator-region*)
(let
((region (+ *less-arrow-region*
(floor
(- (if (eq :vertical orientation) y x)
(scroller-value-position scroller))
(scrollbar-anchor-width
(getf *scrollbar-dimensions*
(contact-scale scroller)))))))
(if (and (= region *drag-area-region*)
(scrollbar-abbreviated-p scroller))
*more-arrow-region*
region))
region))
*cable-region*))))
(press-cable (scroller)
(with-slots (orientation increment width height indicator-size update-delay display value) scroller
(with-event (x y)
(multiple-value-bind (event-position max-position)
(if (eq :vertical orientation) (values y height) (values x width))
(let*
((anchor-height (scrollbar-anchor-height
(getf *scrollbar-dimensions* (contact-scale scroller))))
(min-position anchor-height)
(max-position (- max-position anchor-height))
(pane-size (let ((size (true-indicator-size indicator-size)))
(if (plusp size) size increment)))
(pane-increment (if (< event-position (scroller-value-position scroller))
(when (>= event-position min-position)
(- pane-size))
(when (<= event-position max-position)
pane-size))))
(unless pane-increment
(catch :release (loop (process-next-event display)))
(return-from press-cable))
(if (catch :release
(add-timer scroller :click *scroller-click-timeout*)
(unwind-protect
(catch :click-timeout
(loop (process-next-event display)))
(delete-timer scroller :click))
t)
(let ((current-x x) (current-y y))
(when (and (numberp update-delay) (plusp update-delay))
(add-timer scroller :update-delay update-delay))
(apply-callback scroller :begin-continuous)
(catch :release
(loop
(scroller-increment-value scroller pane-increment)
(multiple-value-setq (current-x current-y)
(scrollbar-cable-warp
scroller pane-increment
current-x current-y
min-position max-position))
(do () ((not (process-next-event display *scroller-hold-timeout*))))))
(apply-callback scroller :end-continuous))
(progn
(scroller-increment-value scroller pane-increment)
(scrollbar-cable-warp
scroller pane-increment
x y
min-position max-position)))
(unless (eql 0 update-delay)
(delete-timer scroller :update-delay)
(apply-callback scroller :new-value value)))))))
(press-drag-area (scroller)
(with-slots (display regions value update-delay foreground orientation) scroller
(let
((highlight-pixel (logxor foreground (contact-current-background-pixel scroller)))
(elevator (svref regions *elevator-region*)))
(multiple-value-bind (drag-x drag-y drag-width drag-height)
(scrollbar-drag-area-geometry scroller)
(using-gcontext
(gc :drawable scroller
:function boole-xor
:foreground highlight-pixel)
(draw-rectangle
elevator gc
drag-x drag-y drag-width drag-height :fill-p)
(with-event (x y)
(let ((*previous-position* (if (eq :vertical orientation) y x))
(*drag-motion* t))
(declare (special *previous-position* *drag-motion*))
(when (and (numberp update-delay) (plusp update-delay))
(add-timer scroller :update-delay update-delay))
(catch :release
(loop (process-next-event display)))))
(when (and (numberp update-delay) (plusp update-delay))
(delete-timer scroller :update-delay))
(apply-callback scroller :new-value value)
Unhighlight drag area
(draw-rectangle
elevator gc
drag-x drag-y drag-width drag-height :fill-p))))))
(press-less-arrow (scroller)
(with-slots (display regions value maximum increment update-delay foreground orientation) scroller
(let
((highlight-pixel (logxor foreground (contact-current-background-pixel scroller))))
(multiple-value-bind (arrow-x arrow-y arrow-width arrow-height)
(scrollbar-less-arrow-geometry scroller)
(using-gcontext
(gc :drawable scroller
:function boole-xor
:foreground highlight-pixel)
(draw-rectangle
(svref regions *elevator-region*) gc
arrow-x arrow-y arrow-width arrow-height :fill-p)
Force pointer to stay within arrow window
(grab-pointer scroller #.(make-event-mask :button-press :button-release)
:confine-to (svref regions *less-arrow-region*))
(if (catch :release (not (process-next-event display *scroller-click-timeout*)))
(progn
(when (and (numberp update-delay) (plusp update-delay))
(add-timer scroller :update-delay update-delay))
(apply-callback scroller :begin-continuous)
(catch :release
(loop
(scroller-increment-value scroller (- increment))
(do () ((not (process-next-event display *scroller-hold-timeout*))))))
(apply-callback scroller :end-continuous))
(scroller-increment-value scroller (- increment)))
(unless (eql 0 update-delay)
(delete-timer scroller :update-delay)
(apply-callback scroller :new-value value))
(ungrab-pointer display)
Unhighlight arrow
(draw-rectangle
(svref regions *elevator-region*) gc
arrow-x arrow-y arrow-width arrow-height :fill-p))))))
(press-more-arrow (scroller)
(with-slots (display regions value maximum increment update-delay foreground orientation) scroller
(let
((highlight-pixel (logxor foreground (contact-current-background-pixel scroller))))
(multiple-value-bind (arrow-x arrow-y arrow-width arrow-height)
(scrollbar-more-arrow-geometry scroller)
(using-gcontext
(gc :drawable scroller
:function boole-xor
:foreground highlight-pixel)
(draw-rectangle
(svref regions *elevator-region*) gc
arrow-x arrow-y arrow-width arrow-height :fill-p)
Force pointer to stay within arrow window
(grab-pointer scroller #.(make-event-mask :button-press :button-release)
:confine-to (svref regions *more-arrow-region*))
(if (catch :release (not (process-next-event display *scroller-click-timeout*)))
(progn
(when (and (numberp update-delay) (plusp update-delay))
(add-timer scroller :update-delay update-delay))
(apply-callback scroller :begin-continuous)
(catch :release
(loop
(scroller-increment-value scroller increment)
(do () ((not (process-next-event display *scroller-hold-timeout*))))))
(apply-callback scroller :end-continuous))
(scroller-increment-value scroller increment))
(unless (eql 0 update-delay)
(delete-timer scroller :update-delay)
(apply-callback scroller :new-value value))
(ungrab-pointer display)
Unhighlight arrow
(draw-rectangle
(svref regions *elevator-region*) gc
arrow-x arrow-y arrow-width arrow-height :fill-p))))))
(press-max-anchor (scroller)
(with-slots (display regions foreground maximum value) scroller
(let
((max-anchor (svref regions *max-anchor-region*))
(highlight-size (scrollbar-anchor-width
(getf *scrollbar-dimensions* (contact-scale scroller)))))
(using-gcontext (gc :drawable scroller :foreground foreground)
(draw-rectangle
max-anchor gc
0 0 highlight-size highlight-size
:fill-p))
(catch :release
(loop (process-next-event display)))
Unhighlight max anchor
(clear-area max-anchor)
(unless (= value maximum)
(setf (scale-value scroller) maximum)
(apply-callback scroller :new-value maximum)))))
(press-min-anchor (scroller)
(with-slots (display regions foreground minimum value) scroller
(let
((min-anchor (svref regions *min-anchor-region*))
(highlight-size (scrollbar-anchor-width
(getf *scrollbar-dimensions* (contact-scale scroller)))))
(using-gcontext (gc :drawable scroller :foreground foreground)
(draw-rectangle
min-anchor gc
0 0 highlight-size highlight-size
:fill-p))
(catch :release
(loop (process-next-event display)))
Unhighlight min anchor
(clear-area min-anchor)
(unless (= value minimum)
(setf (scale-value scroller) minimum)
(apply-callback scroller :new-value minimum))))))
Initialize press - handlers dispatch vector
(setf (svref press-handlers *min-anchor-region*) #'press-min-anchor)
(setf (svref press-handlers *max-anchor-region*) #'press-max-anchor)
(setf (svref press-handlers *less-arrow-region*) #'press-less-arrow)
(setf (svref press-handlers *drag-area-region*) #'press-drag-area)
(setf (svref press-handlers *more-arrow-region*) #'press-more-arrow)
(setf (svref press-handlers *cable-region*) #'press-cable)
(defun scroller-handle-press (scroller)
(let ((*scroller-pressed-p* t))
(declare (special *scroller-pressed-p*))
(funcall (svref press-handlers (find-region scroller)) scroller)))))
(defun scroller-handle-release (scroller)
(declare (ignore scroller))
(declare (special *scroller-pressed-p*))
(when (boundp '*scroller-pressed-p*)
(throw :release nil)))
(defun scroller-handle-motion (scroller)
(declare (special *previous-position* *drag-motion*))
(when (boundp '*drag-motion*)
(with-slots (orientation) (the scroller scroller)
(with-event (state x y)
(multiple-value-bind (ptr-x ptr-y)
(if (plusp (logand state #.(make-state-mask :button-1)))
(query-pointer scroller)
(values x y))
(let* ((new-position (if (eq :vertical orientation) ptr-y ptr-x))
(increment (scroller-pixel-value scroller (- new-position *previous-position*))))
(unless (zerop increment)
(scroller-increment-value scroller increment)
(setf *previous-position* new-position))))))))
(defun scroller-report-new-value (scroller)
(with-slots (value) (the scroller scroller)
(apply-callback scroller :new-value value)))
(defun scroller-increment-value (scroller increment)
(with-slots (value minimum maximum update-delay) (the scroller scroller)
(let*
((new-value (+ value increment))
(adjusted (min (max (or (apply-callback scroller :adjust-value new-value)
new-value)
minimum)
maximum)))
(unless (= adjusted value)
(setf (scale-value scroller) adjusted)
(when (eql 0 update-delay)
(apply-callback scroller :new-value adjusted))))))
(defun scrollbar-cable-warp (scroller pane-increment current-x current-y min-position max-position)
(with-slots (orientation) (the scroller scroller)
(let*
((current-position
(if (eq :vertical orientation) current-y current-x))
(new-pointer-position
(if (plusp pane-increment)
(when (< current-position (setf min-position
(+ (scroller-value-position scroller)
(scrollbar-elevator-size scroller))))
(1+ min-position))
(when (> current-position (setf max-position
(scroller-value-position scroller)))
(1- max-position)))))
(when new-pointer-position
(if (eq :vertical orientation)
(setf current-y new-pointer-position)
(setf current-x new-pointer-position))
(warp-pointer scroller current-x current-y))
(values current-x current-y))))
(defun scroller-value-position (scroller)
(with-slots (width height orientation value minimum maximum) (the scroller scroller)
(let*
((dimensions (getf *scrollbar-dimensions* (contact-scale scroller)))
(margin (scrollbar-margin dimensions))
(anchor-height (scrollbar-anchor-height dimensions))
(range (- maximum minimum)))
(+ anchor-height
margin
(if (zerop range) 0
(pixel-round
(* (- value minimum)
Pixels per value unit
(/ (- (if (eq orientation :vertical) height width)
anchor-height margin
(* (scrollbar-anchor-width dimensions)
(if (scrollbar-abbreviated-p scroller) 2 3))
2
margin anchor-height)
range))))))))
(defun scroller-pixel-value (scroller pixels)
(with-slots (width height orientation minimum maximum increment) (the scroller scroller)
(let*
((dimensions (getf *scrollbar-dimensions* (contact-scale scroller)))
(margin (scrollbar-margin dimensions))
(anchor-height (scrollbar-anchor-height dimensions)))
(* (pixel-round
(/ (* pixels (- maximum minimum))
(- (if (eq orientation :vertical) height width)
anchor-height margin
(* (scrollbar-anchor-width dimensions)
(if (scrollbar-abbreviated-p scroller) 2 3))
2
margin anchor-height))
increment)
increment))))
(defun scroller-indicator-position (scroller &optional size)
(setf size (or size (scroller-indicator-size scroller)))
(with-slots (width height orientation value minimum maximum) (the scroller scroller)
(let*
((dimensions (getf *scrollbar-dimensions* (contact-scale scroller)))
(margin (scrollbar-margin dimensions))
(anchor-height (scrollbar-anchor-height dimensions))
(range (- maximum minimum)))
(+ anchor-height
margin
(if (zerop range) 0
(pixel-round
(* (- value minimum)
Pixels per value unit for indicator position
(/ (- (if (eq orientation :vertical) height width)
anchor-height margin
size
margin anchor-height)
range))))))))
(defun scroller-indicator-size (scroller)
(with-slots (width height orientation minimum maximum indicator-size) (the scroller scroller)
(let*
((dimensions (getf *scrollbar-dimensions* (contact-scale scroller)))
(margin (scrollbar-margin dimensions))
(anchor-height (scrollbar-anchor-height dimensions))
(range (- maximum minimum)))
(pixel-round
(*
(if (zerop range) 0
Pixels per value unit for indicator size
(/ (- (if (eq orientation :vertical) height width)
anchor-height margin
margin anchor-height)
range))))))) |
1ba1a218afec91cbf5efb172abda44cb6a23bc22e78ecdcfd802ff19b9379f38 | EgorDm/fp-pacman | Loading.hs | module Engine.Graphics.Loading (
loadStaticSprite,
loadAnimatedSprite,
loadStaticSpriteFile
) where
import Text.Printf
import Graphics.Gloss.Game
import Graphics.Gloss (Picture(..))
import Engine.Graphics.Sprite
import Engine.Graphics.Animation
import Constants
-- | Loads creates filenames for given resource by identifier and amount of sprites
spriteFileNames :: String -> Int -> [String]
spriteFileNames identifier n = (\i -> resourceDir ++ identifier ++ "/" ++ printf "%02d" i ++ ".png") <$> [0.. n]
-- | Loads an image from file. If failed, then throws errors
loadImage :: String -> Picture
loadImage file = case img of Bitmap{} -> Scale spriteScale spriteScale img
_ -> error ("Cannot load " ++ file)
where img = png file
-- | Load Sprites
loadStaticSpriteFromPath :: String -> Sprite
loadStaticSpriteFromPath path = createStaticSprite (loadImage path) path
loadStaticSprite :: String -> Sprite
loadStaticSprite identifier = loadStaticSpriteFromPath source
where source = head (spriteFileNames identifier 0)
loadStaticSpriteFile :: String -> Sprite
loadStaticSpriteFile identifier = loadStaticSpriteFromPath (resourceDir ++ identifier ++ ".png")
loadAnimatedSprite :: String -> Int -> AnimationType -> Float -> Sprite
loadAnimatedSprite identifier n animType interval = createAnimatedSprite animType frames interval
where frames = map loadStaticSpriteFromPath (spriteFileNames identifier n)
| null | https://raw.githubusercontent.com/EgorDm/fp-pacman/19781c92c97641b0a01b8f1554f50f19ff6d3bf4/src/Engine/Graphics/Loading.hs | haskell | | Loads creates filenames for given resource by identifier and amount of sprites
| Loads an image from file. If failed, then throws errors
| Load Sprites | module Engine.Graphics.Loading (
loadStaticSprite,
loadAnimatedSprite,
loadStaticSpriteFile
) where
import Text.Printf
import Graphics.Gloss.Game
import Graphics.Gloss (Picture(..))
import Engine.Graphics.Sprite
import Engine.Graphics.Animation
import Constants
spriteFileNames :: String -> Int -> [String]
spriteFileNames identifier n = (\i -> resourceDir ++ identifier ++ "/" ++ printf "%02d" i ++ ".png") <$> [0.. n]
loadImage :: String -> Picture
loadImage file = case img of Bitmap{} -> Scale spriteScale spriteScale img
_ -> error ("Cannot load " ++ file)
where img = png file
loadStaticSpriteFromPath :: String -> Sprite
loadStaticSpriteFromPath path = createStaticSprite (loadImage path) path
loadStaticSprite :: String -> Sprite
loadStaticSprite identifier = loadStaticSpriteFromPath source
where source = head (spriteFileNames identifier 0)
loadStaticSpriteFile :: String -> Sprite
loadStaticSpriteFile identifier = loadStaticSpriteFromPath (resourceDir ++ identifier ++ ".png")
loadAnimatedSprite :: String -> Int -> AnimationType -> Float -> Sprite
loadAnimatedSprite identifier n animType interval = createAnimatedSprite animType frames interval
where frames = map loadStaticSpriteFromPath (spriteFileNames identifier n)
|
c564ae7bbd975515e5da48d6c802fd8832e873a34bf22bd7401e206536ba77ed | darrenldl/ProVerif-ATP | reduction_interact.mli | * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* *
* Cryptographic protocol verifier *
* *
* , , and *
* *
* Copyright ( C ) INRIA , CNRS 2000 - 2018 *
* *
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* *
* Cryptographic protocol verifier *
* *
* Bruno Blanchet, Vincent Cheval, and Marc Sylvestre *
* *
* Copyright (C) INRIA, CNRS 2000-2018 *
* *
*************************************************************)
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 ( in file LICENSE ) .
You should have received a copy of the GNU General Public License
along with this program ; if not , write to the Free Software
Foundation , Inc. , 59 Temple Place , Suite 330 , Boston , MA 02111 - 1307 USA
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 (in file LICENSE).
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*)
open Types
val max_proc_nb: int
val do_one_reduction_step : term Pitypes.reduc_state -> int -> (unit -> unit) -> (unit -> unit) -> term Pitypes.reduc_state
val do_all_auto_reduction: term Pitypes.reduc_state -> term Pitypes.reduc_state
val up_proc_nb: int -> unit
val get_proc_nb: unit -> int
| null | https://raw.githubusercontent.com/darrenldl/ProVerif-ATP/7af6cfb9e0550ecdb072c471e15b8f22b07408bd/proverif2.00/src/reduction_interact.mli | ocaml | * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* *
* Cryptographic protocol verifier *
* *
* , , and *
* *
* Copyright ( C ) INRIA , CNRS 2000 - 2018 *
* *
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* *
* Cryptographic protocol verifier *
* *
* Bruno Blanchet, Vincent Cheval, and Marc Sylvestre *
* *
* Copyright (C) INRIA, CNRS 2000-2018 *
* *
*************************************************************)
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 ( in file LICENSE ) .
You should have received a copy of the GNU General Public License
along with this program ; if not , write to the Free Software
Foundation , Inc. , 59 Temple Place , Suite 330 , Boston , MA 02111 - 1307 USA
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 (in file LICENSE).
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*)
open Types
val max_proc_nb: int
val do_one_reduction_step : term Pitypes.reduc_state -> int -> (unit -> unit) -> (unit -> unit) -> term Pitypes.reduc_state
val do_all_auto_reduction: term Pitypes.reduc_state -> term Pitypes.reduc_state
val up_proc_nb: int -> unit
val get_proc_nb: unit -> int
|
|
2b43767d4da711128e85e23501e83a1eb8e655f7a40037156e09cd819c5f187a | NoRedInk/haskell-libraries | NriPrelude.hs | # OPTIONS_HADDOCK not - home #
| These are functions and types that in Elm are in scope by default , without
needing to import anything . In we refer to such imports as a
" Prelude " .
module NriPrelude
* Elm - like Prelude
Platform.Internal.Task,
module Basics,
module Internal.Shortcut,
List.List,
Maybe.Maybe (..),
Result.Result (..),
Text.Text,
Char.Char,
-- * Other essentials
Prelude.Show,
GHC.Generics.Generic,
fmap,
(<*>),
(>>=),
)
where
import Basics
import qualified Char
import qualified GHC.Generics
import Internal.Shortcut
import qualified List
import qualified Maybe
import qualified Platform.Internal
import qualified Result
import qualified Text
import Prelude
( fmap,
(<*>),
(>>=),
)
import qualified Prelude
| null | https://raw.githubusercontent.com/NoRedInk/haskell-libraries/7af1e05549e09d519b08ab49dff956b5a97d4f7e/nri-prelude/src/NriPrelude.hs | haskell | * Other essentials | # OPTIONS_HADDOCK not - home #
| These are functions and types that in Elm are in scope by default , without
needing to import anything . In we refer to such imports as a
" Prelude " .
module NriPrelude
* Elm - like Prelude
Platform.Internal.Task,
module Basics,
module Internal.Shortcut,
List.List,
Maybe.Maybe (..),
Result.Result (..),
Text.Text,
Char.Char,
Prelude.Show,
GHC.Generics.Generic,
fmap,
(<*>),
(>>=),
)
where
import Basics
import qualified Char
import qualified GHC.Generics
import Internal.Shortcut
import qualified List
import qualified Maybe
import qualified Platform.Internal
import qualified Result
import qualified Text
import Prelude
( fmap,
(<*>),
(>>=),
)
import qualified Prelude
|
06bbd62e96933381ad00cbc50ed84f7d0ac77f65d804c7b3f12f7eefb0af290f | haskell-tools/haskell-tools | PolymorphSub_res.hs | module Refactor.GenerateTypeSignature.PolymorphSub where
f :: Num a => a -> a
f a = g a where
g :: Num a => a -> a
g a = a + 1
| null | https://raw.githubusercontent.com/haskell-tools/haskell-tools/b1189ab4f63b29bbf1aa14af4557850064931e32/src/builtin-refactorings/examples/Refactor/GenerateTypeSignature/PolymorphSub_res.hs | haskell | module Refactor.GenerateTypeSignature.PolymorphSub where
f :: Num a => a -> a
f a = g a where
g :: Num a => a -> a
g a = a + 1
|
|
c159f1e40fb7debb084e8d213ddf8951f18eac6e03ee91e871f762ee2c76267f | hgoes/vvt | MkMake.hs | import Data.List
data Result = Inserted
| Found
| Full
| Or Result Result
deriving (Eq,Ord,Show)
data TestCase = TestCase { name :: String
, table :: [Int]
, probeMax :: Int
, threads :: [(Int,Result)]
} deriving (Eq,Ord,Show)
data Config = Config { clangBin :: String
, liptonBin :: String
, optBin :: String
, vvtInclude :: String
, optPre :: String
, optPost :: String
, simplification :: String
, runs :: Int
, flags :: [Maybe String]
, timeout :: Maybe String
} deriving (Eq,Ord,Show)
defaultConfig :: Config
defaultConfig = Config { clangBin = "clang-3.5"
, optBin = "opt-3.5"
, liptonBin = "/home/eq/repos/Liptonizer/LiptonPass"
, vvtInclude = "../../../include"
, optPre = "-mem2reg -loops -loop-simplify -loop-rotate -lcssa"
, optPost = "-mem2reg -constprop -instsimplify -correlated-propagation -die -simplifycfg -globaldce -instnamer"
, simplification = " simplify inline slice value-set=2 simplify inline"
, runs = 4
, flags = [Nothing,Just "n"]
, timeout = Just "15m"
}
mkCLang :: TestCase -> String
mkCLang tc = "$(CLANG) -I$(VVT_INCLUDE) -O0 -emit-llvm -c ht.cpp -o - -DTABLE_INIT=\"{"++
intercalate "," (fmap show (table tc))++
"}\" -DPROBE_MAX="++
show (probeMax tc)++
" -DSEQUENCE=\""++
foldl (\seq (val,res) -> "SPAWN("++show val++",("++renderResult res++"),"++seq++")"
) "0" (threads tc)++
"\""
renderResult :: Result -> String
renderResult Inserted = "IsInserted"
renderResult Found = "IsFound"
renderResult Full = "IsFull"
renderResult (Or r1 r2) = "IsOr<"++renderResult r1++","++renderResult r2++">"
mkVars :: Config -> String
mkVars cfg = unlines ["CLANG="++clangBin cfg
,"OPT="++optBin cfg
,"LIPTON="++liptonBin cfg
,"VVT_INCLUDE="++vvtInclude cfg
,"OPT_PRE="++optPre cfg
,"OPT_POST="++optPost cfg
,"SIMPLIFICATION="++simplification cfg]
flagName :: Maybe String -> TestCase -> String -> String
flagName flag tc post
= name tc++"."++
(case flag of
Nothing -> ""
Just f -> f++".")++post
mkCompile :: Maybe String -> TestCase -> String
mkCompile flag tc
= unlines [flagName flag tc "l"++": ht.cpp"
,"\t"++mkCLang tc++" |\\"
,"\t vvt-svcomp inline |\\"
,"\t $(OPT) $(OPT_PRE) |\\"
,"\t $(LIPTON)"++
(case flag of
Nothing -> ""
Just f -> " -"++f)++
" |\\"
,"\t $(OPT) $(OPT_POST) |\\"
,"\t vvt-enc |\\"
,"\t vvt-opt $(SIMPLIFICATION) |\\"
,"\t vvt-predicates -ioff -bon |\\"
,"\t vvt-pp > "++flagName flag tc "l"]
allLisp :: [TestCase] -> String
allLisp cases = unwords [ flagName flag tc "l"
| tc <- cases
, flag <- [Nothing,Just "n"]]
allOutputIC3 :: Int -> [TestCase] -> String
allOutputIC3 runs cases
= unwords [ flagName flag tc (show run++".output-ic3")
| tc <- cases
, flag <- [Nothing,Just "n"]
, run <- [0..runs-1]]
allOutputBMC :: Int -> [TestCase] -> String
allOutputBMC runs cases
= unwords [ flagName flag tc (show run++".output-bmc")
| tc <- cases
, flag <- [Nothing,Just "n"]
, run <- [0..runs-1]]
mkIC3 :: Config -> Int -> Maybe String -> TestCase -> String
mkIC3 cfg run flag tc
= unlines [oname++": "++flagName flag tc "l"
,"\tvvt-verify --stats"++
(case timeout cfg of
Nothing -> ""
Just to -> " --timeout="++to)++
" < "++flagName flag tc "l"++" > "++oname]
where
oname = flagName flag tc (show run++".output-ic3")
mkBMC :: Config -> Int -> Maybe String -> TestCase -> String
mkBMC cfg run flag tc
= unlines [oname++": "++flagName flag tc "l"
,"\tvvt-bmc -d -1 -i -t -c"++
(case timeout cfg of
Nothing -> ""
Just to -> " --timeout="++to)++
" < "++flagName flag tc "l"++" > "++oname]
where
oname = flagName flag tc (show run++".output-bmc")
mkResults :: Config -> Maybe String -> String -> [TestCase] -> String
mkResults cfg flag post cases
= unlines [fn++": "++files
,"\t./extracts.sh "++show (runs cfg)++" "++post++" "++
intercalate " " [ name tc++(case flag of
Nothing -> ""
Just f -> "."++f)
| tc <- cases ]++" > "++fn
]
where
sflag = case flag of
Nothing -> ""
Just f -> "-"++f
fn = "results-"++post++sflag
files = intercalate " " [ flagName flag tc (show run++".output-"++post)
| tc <- cases
, run <- [0..runs cfg-1] ]
mkMake :: Config -> [TestCase] -> IO ()
mkMake cfg cases = do
putStrLn $ mkVars cfg
putStrLn $ "ALL: "++allLisp cases
putStrLn $ "output-ic3: "++allOutputIC3 (runs cfg) cases
putStrLn $ "output-bmc: "++allOutputBMC (runs cfg) cases
putStrLn "include extra.mk"
putStrLn ""
putStrLn "clean:"
putStrLn $ "\trm -f "++allLisp cases++" "++
allOutputIC3 (runs cfg) cases++" "++
allOutputBMC (runs cfg) cases
putStrLn ""
mapM_ (\flag -> do
putStrLn $ mkResults cfg flag "ic3" cases
putStrLn ""
putStrLn $ mkResults cfg flag "bmc" cases
putStrLn ""
) (flags cfg)
mapM_ (\tc -> mapM_ (\flag -> do
putStrLn $ mkCompile flag tc
mapM_ (\n -> putStrLn $ mkIC3 cfg n flag tc
) [0..runs cfg]
mapM_ (\n -> putStrLn $ mkBMC cfg n flag tc
) [0..runs cfg]
) (flags cfg)
) cases
cases :: [TestCase]
cases = [TestCase { name = "t"++show n++"-empty"++show n++"-p1"
, table = take n (repeat 0)
, probeMax = 1
, threads = [ (i,Inserted) | i <- [1..n] ]
}
| n <- [1..5] ]++
[TestCase { name = "t"++show n++"-full"++show l++"-p"++show p
, table = take l [1..]
, probeMax = p
, threads = [ (i,Full) | i <- [1..n] ]
}
| n <- [1..5]
, l <- [7]
, p <- [1..6] ]++
[TestCase { name = "t"++show n++"-mixed"++show l++"-p"++show p
, table = take l [0,0,13,29,0,4,0,10]
, probeMax = p
, threads = take n [ (1,Or Inserted Full)
, (9,Or Inserted Full)
, (33,Or Inserted Full)
, (7,Or Inserted Full)
, (14,Or Inserted Full) ]
}
| n <- [1..5]
, l <- [5]
, p <- [4] ]
main = mkMake defaultConfig cases
| null | https://raw.githubusercontent.com/hgoes/vvt/dd2809753d7e5059d9103ea578f36afa8294cd84/test/parallel/hashtable/MkMake.hs | haskell | import Data.List
data Result = Inserted
| Found
| Full
| Or Result Result
deriving (Eq,Ord,Show)
data TestCase = TestCase { name :: String
, table :: [Int]
, probeMax :: Int
, threads :: [(Int,Result)]
} deriving (Eq,Ord,Show)
data Config = Config { clangBin :: String
, liptonBin :: String
, optBin :: String
, vvtInclude :: String
, optPre :: String
, optPost :: String
, simplification :: String
, runs :: Int
, flags :: [Maybe String]
, timeout :: Maybe String
} deriving (Eq,Ord,Show)
defaultConfig :: Config
defaultConfig = Config { clangBin = "clang-3.5"
, optBin = "opt-3.5"
, liptonBin = "/home/eq/repos/Liptonizer/LiptonPass"
, vvtInclude = "../../../include"
, optPre = "-mem2reg -loops -loop-simplify -loop-rotate -lcssa"
, optPost = "-mem2reg -constprop -instsimplify -correlated-propagation -die -simplifycfg -globaldce -instnamer"
, simplification = " simplify inline slice value-set=2 simplify inline"
, runs = 4
, flags = [Nothing,Just "n"]
, timeout = Just "15m"
}
mkCLang :: TestCase -> String
mkCLang tc = "$(CLANG) -I$(VVT_INCLUDE) -O0 -emit-llvm -c ht.cpp -o - -DTABLE_INIT=\"{"++
intercalate "," (fmap show (table tc))++
"}\" -DPROBE_MAX="++
show (probeMax tc)++
" -DSEQUENCE=\""++
foldl (\seq (val,res) -> "SPAWN("++show val++",("++renderResult res++"),"++seq++")"
) "0" (threads tc)++
"\""
renderResult :: Result -> String
renderResult Inserted = "IsInserted"
renderResult Found = "IsFound"
renderResult Full = "IsFull"
renderResult (Or r1 r2) = "IsOr<"++renderResult r1++","++renderResult r2++">"
mkVars :: Config -> String
mkVars cfg = unlines ["CLANG="++clangBin cfg
,"OPT="++optBin cfg
,"LIPTON="++liptonBin cfg
,"VVT_INCLUDE="++vvtInclude cfg
,"OPT_PRE="++optPre cfg
,"OPT_POST="++optPost cfg
,"SIMPLIFICATION="++simplification cfg]
flagName :: Maybe String -> TestCase -> String -> String
flagName flag tc post
= name tc++"."++
(case flag of
Nothing -> ""
Just f -> f++".")++post
mkCompile :: Maybe String -> TestCase -> String
mkCompile flag tc
= unlines [flagName flag tc "l"++": ht.cpp"
,"\t"++mkCLang tc++" |\\"
,"\t vvt-svcomp inline |\\"
,"\t $(OPT) $(OPT_PRE) |\\"
,"\t $(LIPTON)"++
(case flag of
Nothing -> ""
Just f -> " -"++f)++
" |\\"
,"\t $(OPT) $(OPT_POST) |\\"
,"\t vvt-enc |\\"
,"\t vvt-opt $(SIMPLIFICATION) |\\"
,"\t vvt-predicates -ioff -bon |\\"
,"\t vvt-pp > "++flagName flag tc "l"]
allLisp :: [TestCase] -> String
allLisp cases = unwords [ flagName flag tc "l"
| tc <- cases
, flag <- [Nothing,Just "n"]]
allOutputIC3 :: Int -> [TestCase] -> String
allOutputIC3 runs cases
= unwords [ flagName flag tc (show run++".output-ic3")
| tc <- cases
, flag <- [Nothing,Just "n"]
, run <- [0..runs-1]]
allOutputBMC :: Int -> [TestCase] -> String
allOutputBMC runs cases
= unwords [ flagName flag tc (show run++".output-bmc")
| tc <- cases
, flag <- [Nothing,Just "n"]
, run <- [0..runs-1]]
mkIC3 :: Config -> Int -> Maybe String -> TestCase -> String
mkIC3 cfg run flag tc
= unlines [oname++": "++flagName flag tc "l"
,"\tvvt-verify --stats"++
(case timeout cfg of
Nothing -> ""
Just to -> " --timeout="++to)++
" < "++flagName flag tc "l"++" > "++oname]
where
oname = flagName flag tc (show run++".output-ic3")
mkBMC :: Config -> Int -> Maybe String -> TestCase -> String
mkBMC cfg run flag tc
= unlines [oname++": "++flagName flag tc "l"
,"\tvvt-bmc -d -1 -i -t -c"++
(case timeout cfg of
Nothing -> ""
Just to -> " --timeout="++to)++
" < "++flagName flag tc "l"++" > "++oname]
where
oname = flagName flag tc (show run++".output-bmc")
mkResults :: Config -> Maybe String -> String -> [TestCase] -> String
mkResults cfg flag post cases
= unlines [fn++": "++files
,"\t./extracts.sh "++show (runs cfg)++" "++post++" "++
intercalate " " [ name tc++(case flag of
Nothing -> ""
Just f -> "."++f)
| tc <- cases ]++" > "++fn
]
where
sflag = case flag of
Nothing -> ""
Just f -> "-"++f
fn = "results-"++post++sflag
files = intercalate " " [ flagName flag tc (show run++".output-"++post)
| tc <- cases
, run <- [0..runs cfg-1] ]
mkMake :: Config -> [TestCase] -> IO ()
mkMake cfg cases = do
putStrLn $ mkVars cfg
putStrLn $ "ALL: "++allLisp cases
putStrLn $ "output-ic3: "++allOutputIC3 (runs cfg) cases
putStrLn $ "output-bmc: "++allOutputBMC (runs cfg) cases
putStrLn "include extra.mk"
putStrLn ""
putStrLn "clean:"
putStrLn $ "\trm -f "++allLisp cases++" "++
allOutputIC3 (runs cfg) cases++" "++
allOutputBMC (runs cfg) cases
putStrLn ""
mapM_ (\flag -> do
putStrLn $ mkResults cfg flag "ic3" cases
putStrLn ""
putStrLn $ mkResults cfg flag "bmc" cases
putStrLn ""
) (flags cfg)
mapM_ (\tc -> mapM_ (\flag -> do
putStrLn $ mkCompile flag tc
mapM_ (\n -> putStrLn $ mkIC3 cfg n flag tc
) [0..runs cfg]
mapM_ (\n -> putStrLn $ mkBMC cfg n flag tc
) [0..runs cfg]
) (flags cfg)
) cases
cases :: [TestCase]
cases = [TestCase { name = "t"++show n++"-empty"++show n++"-p1"
, table = take n (repeat 0)
, probeMax = 1
, threads = [ (i,Inserted) | i <- [1..n] ]
}
| n <- [1..5] ]++
[TestCase { name = "t"++show n++"-full"++show l++"-p"++show p
, table = take l [1..]
, probeMax = p
, threads = [ (i,Full) | i <- [1..n] ]
}
| n <- [1..5]
, l <- [7]
, p <- [1..6] ]++
[TestCase { name = "t"++show n++"-mixed"++show l++"-p"++show p
, table = take l [0,0,13,29,0,4,0,10]
, probeMax = p
, threads = take n [ (1,Or Inserted Full)
, (9,Or Inserted Full)
, (33,Or Inserted Full)
, (7,Or Inserted Full)
, (14,Or Inserted Full) ]
}
| n <- [1..5]
, l <- [5]
, p <- [4] ]
main = mkMake defaultConfig cases
|
|
6a71bf6903c6a3afb1d74cd955459b78e3863b126ce1702892ca64927473d6ed | untangled-web/untangled-ui | parser.clj | (ns untangled.ui.server.image-library.parser
(:require
[untangled.ui.server.image-library.storage :as storage])
(:import
(java.util Base64)))
(defn decode-base64 [data]
(.decode (Base64/getDecoder) data))
(defn build-mutate [{:keys [owner-fn auth-fn] :as this}]
(fn [env k params]
(case k
'untangled.component.image-library/store
{:action
(fn []
(let [params (update params :content/data decode-base64)
im (owner-fn env (storage/make-image-meta params))]
(auth-fn env im :store)
(let [img-meta (storage/save (::storage/meta env) im)]
(storage/store (::storage/blob env) img-meta (:content/data params))
{:tempids {(:db/id params) (:id img-meta)}})))}
nil)))
(defn build-read [{:keys [auth-fn owner-fn] :as this}]
(fn [env k params]
(case k
:images
(let [im (owner-fn env (storage/make-image-meta params))]
(auth-fn env im :read-all)
{:value (mapv storage/unravel-image-meta (storage/grab (::storage/meta env) im))})
nil)))
| null | https://raw.githubusercontent.com/untangled-web/untangled-ui/ae101f90cd9b7bf5d0c80e9453595fdfe784923c/src/main/untangled/ui/server/image_library/parser.clj | clojure | (ns untangled.ui.server.image-library.parser
(:require
[untangled.ui.server.image-library.storage :as storage])
(:import
(java.util Base64)))
(defn decode-base64 [data]
(.decode (Base64/getDecoder) data))
(defn build-mutate [{:keys [owner-fn auth-fn] :as this}]
(fn [env k params]
(case k
'untangled.component.image-library/store
{:action
(fn []
(let [params (update params :content/data decode-base64)
im (owner-fn env (storage/make-image-meta params))]
(auth-fn env im :store)
(let [img-meta (storage/save (::storage/meta env) im)]
(storage/store (::storage/blob env) img-meta (:content/data params))
{:tempids {(:db/id params) (:id img-meta)}})))}
nil)))
(defn build-read [{:keys [auth-fn owner-fn] :as this}]
(fn [env k params]
(case k
:images
(let [im (owner-fn env (storage/make-image-meta params))]
(auth-fn env im :read-all)
{:value (mapv storage/unravel-image-meta (storage/grab (::storage/meta env) im))})
nil)))
|
|
1b83c7f8f553748cf3df1718fff3e5744fe2af02a0ee3ecc58fc99843f20bd7e | hyperfiddle/electric | missionary.clj | (ns dustin.missionary.missionary
(:require
[missionary.core :as m]
[hyperfiddle.rcf :refer [tests tap %]]))
(tests
(def hello-task (m/sp (println "Hello")))
(hello-task #(print ::success %) #(print ::failure %))
(def sleep-task (m/sleep 1000))
(def async-hello-task
(m/sp ; async Sequential Process
(m/? hello-task)
(m/? sleep-task)
(println "World")
(m/? sleep-task)
(println "!")))
(async-hello-task #(print ::success %) #(print ::failure %))
( ? - world )
(def chatty-hello-world (join vector slowmo-hello-world slowmo-hello-world))
(? chatty-hello-world)
(? (m/join vector
(m/sp (inc (m/? (m/sleep 1000 1))))
(m/sp (inc (m/? (m/sleep 100 2))))))
(? (join vector
(m/sleep 1000 1)
(m/sleep 100 2)))
(def unreliable-hello-world
(sp (println "hello")
(? (m/sleep 300))
(throw (ex-info "Something went wrong." {}))))
(? (sp (try (? unreliable-hello-world)
(catch Exception e e))))
? outside sp blocks on jvm
(try (? unreliable-hello-world)
(catch Exception e :caught))
(def t (sp
(try
(println "hello")
(? (m/sleep 100))
(println "world")
(? (m/sleep 100))
(finally
(println "!")))))
(t prn prn)
(? (m/absolve t)) ;?
; flow
(def input (enumerate (range 10)))
(? (aggregate + input))
(? (aggregate conj '() input))
(? (aggregate conj [] (m/zip vector input input)))
(? (->> (m/zip vector
(enumerate [1 2 3])
(enumerate [:a :b :c]))
(aggregate conj)))
;(? input)
(? (aggregate conj (m/transform (partition-all 4) input)))
(def >s
(ap
(let [x (?? (enumerate [1 2 3]))]
(println x)
(inc (? (m/sleep 300 x))))))
(? (aggregate conj >s))
(defn debounce [n >a]
(ap
(let [a (?! >a)]
(? (m/sleep n a))
#_(try
(? (m/sleep n a))
(catch Exception _ (?? m/none))))))
(defn clock [intervals]
(ap (let [n (?? (enumerate intervals))]
(? (m/sleep n n)))))
(? (aggregate (constantly :done) (clock [100 200 100 200])))
(? (->> (clock [24 79 67 34 18 9 99 37])
(debounce 50)
(aggregate conj)))
(def >as (clock [100 200 100 200]))
(>as prn prn)
(? (->>
(ap
(let [x (?= (enumerate [19 57 28 6 87]))] ; fork in a way that will emit asap, out of order
(? (m/sleep x x))))
(aggregate conj)))
(? (aggregate conj (ap (?= (enumerate [19 57 28 6 87])))))
)
(comment
(defn sleep-emit [delays]
(ap (let [n (?? (enumerate delays))]
(? (m/sleep n n)))))
(? (aggregate conj
(m/sample vector
(sleep-emit [24 79 67 34])
(sleep-emit [86 12 37 93])
#_(m/watch r)
)))
(? (->>
(m/sample vector
(sleep-emit [24 79 67 34])
(sleep-emit [86 12 37 93]))
(aggregate conj)))
)
| null | https://raw.githubusercontent.com/hyperfiddle/electric/1c6c3891cbf13123fef8d33e6555d300f0dac134/scratch/dustin/y2021/missionary/missionary.clj | clojure | async Sequential Process
?
flow
(? input)
fork in a way that will emit asap, out of order | (ns dustin.missionary.missionary
(:require
[missionary.core :as m]
[hyperfiddle.rcf :refer [tests tap %]]))
(tests
(def hello-task (m/sp (println "Hello")))
(hello-task #(print ::success %) #(print ::failure %))
(def sleep-task (m/sleep 1000))
(def async-hello-task
(m/? hello-task)
(m/? sleep-task)
(println "World")
(m/? sleep-task)
(println "!")))
(async-hello-task #(print ::success %) #(print ::failure %))
( ? - world )
(def chatty-hello-world (join vector slowmo-hello-world slowmo-hello-world))
(? chatty-hello-world)
(? (m/join vector
(m/sp (inc (m/? (m/sleep 1000 1))))
(m/sp (inc (m/? (m/sleep 100 2))))))
(? (join vector
(m/sleep 1000 1)
(m/sleep 100 2)))
(def unreliable-hello-world
(sp (println "hello")
(? (m/sleep 300))
(throw (ex-info "Something went wrong." {}))))
(? (sp (try (? unreliable-hello-world)
(catch Exception e e))))
? outside sp blocks on jvm
(try (? unreliable-hello-world)
(catch Exception e :caught))
(def t (sp
(try
(println "hello")
(? (m/sleep 100))
(println "world")
(? (m/sleep 100))
(finally
(println "!")))))
(t prn prn)
(def input (enumerate (range 10)))
(? (aggregate + input))
(? (aggregate conj '() input))
(? (aggregate conj [] (m/zip vector input input)))
(? (->> (m/zip vector
(enumerate [1 2 3])
(enumerate [:a :b :c]))
(aggregate conj)))
(? (aggregate conj (m/transform (partition-all 4) input)))
(def >s
(ap
(let [x (?? (enumerate [1 2 3]))]
(println x)
(inc (? (m/sleep 300 x))))))
(? (aggregate conj >s))
(defn debounce [n >a]
(ap
(let [a (?! >a)]
(? (m/sleep n a))
#_(try
(? (m/sleep n a))
(catch Exception _ (?? m/none))))))
(defn clock [intervals]
(ap (let [n (?? (enumerate intervals))]
(? (m/sleep n n)))))
(? (aggregate (constantly :done) (clock [100 200 100 200])))
(? (->> (clock [24 79 67 34 18 9 99 37])
(debounce 50)
(aggregate conj)))
(def >as (clock [100 200 100 200]))
(>as prn prn)
(? (->>
(ap
(? (m/sleep x x))))
(aggregate conj)))
(? (aggregate conj (ap (?= (enumerate [19 57 28 6 87])))))
)
(comment
(defn sleep-emit [delays]
(ap (let [n (?? (enumerate delays))]
(? (m/sleep n n)))))
(? (aggregate conj
(m/sample vector
(sleep-emit [24 79 67 34])
(sleep-emit [86 12 37 93])
#_(m/watch r)
)))
(? (->>
(m/sample vector
(sleep-emit [24 79 67 34])
(sleep-emit [86 12 37 93]))
(aggregate conj)))
)
|
941f88f8236ed2cfa82aeb4075c76fe6023049444e4954d7e148220e0d3a5e81 | nextjournal/freerange | fx_test.cljs | (ns re-frame.fx-test
(:require
[cljs.test :refer-macros [is deftest async use-fixtures]]
[re-frame.core :as re-frame]
[re-frame.fx]
[re-frame.interop :refer [set-timeout!]]
[re-frame.loggers :as log]
[clojure.string :as str]))
---- ---------------------------------------------------------------
;; This fixture uses the re-frame.core/make-restore-fn to checkpoint and reset
;; to cleanup any dynamically registered handlers from our tests.
(defn fixture-re-frame
[]
(let [restore-re-frame (atom nil)]
{:before #(reset! restore-re-frame (re-frame.core/make-restore-fn))
:after #(@restore-re-frame)}))
(use-fixtures :each (fixture-re-frame))
;; ---- TESTS ------------------------------------------------------------------
(deftest dispatch-later
(let [seen-events (atom [])]
;; Setup and exercise effects handler with :dispatch-later.
(re-frame/reg-event-fx
::later-test
(fn [_world _event-v]
(re-frame/reg-event-db
::watcher
(fn [db [_ token]]
(is (#{:event1 :event2 :event3} token) "unexpected: token passed through")
(swap! seen-events #(conj % token))
db))
{:dispatch-later [{:ms 100 :dispatch [::watcher :event1]}
{:ms 200 :dispatch [::watcher :event2]}
{:ms 200 :dispatch [::watcher :event3]}]}))
(async done
(set-timeout!
(fn []
(is (= @seen-events [:event1 :event2 :event3]) "All 3 events should have fired in order")
(done))
1000)
;; kick off main handler
(re-frame/dispatch [::later-test]))))
(re-frame/reg-event-fx
::missing-handler-test
(fn [_world _event-v]
{:fx-not-exist [:nothing :here]}))
(deftest report-missing-handler
(let [logs (atom [])
log-fn (fn [& args] (swap! logs conj (str/join args)))
original-loggers (log/get-loggers)]
(try
(log/set-loggers! {:error log-fn})
(re-frame/dispatch-sync [::missing-handler-test])
(is (re-matches #"re-frame: no handler registered for effect::fx-not-exist. Ignoring." (first @logs)))
(is (= (count @logs) 1))
(finally
(log/set-loggers! original-loggers)))))
| null | https://raw.githubusercontent.com/nextjournal/freerange/c43e848758d1e7cf259ed8ac06a0a9089317a6a6/test/re_frame/fx_test.cljs | clojure | This fixture uses the re-frame.core/make-restore-fn to checkpoint and reset
to cleanup any dynamically registered handlers from our tests.
---- TESTS ------------------------------------------------------------------
Setup and exercise effects handler with :dispatch-later.
kick off main handler | (ns re-frame.fx-test
(:require
[cljs.test :refer-macros [is deftest async use-fixtures]]
[re-frame.core :as re-frame]
[re-frame.fx]
[re-frame.interop :refer [set-timeout!]]
[re-frame.loggers :as log]
[clojure.string :as str]))
---- ---------------------------------------------------------------
(defn fixture-re-frame
[]
(let [restore-re-frame (atom nil)]
{:before #(reset! restore-re-frame (re-frame.core/make-restore-fn))
:after #(@restore-re-frame)}))
(use-fixtures :each (fixture-re-frame))
(deftest dispatch-later
(let [seen-events (atom [])]
(re-frame/reg-event-fx
::later-test
(fn [_world _event-v]
(re-frame/reg-event-db
::watcher
(fn [db [_ token]]
(is (#{:event1 :event2 :event3} token) "unexpected: token passed through")
(swap! seen-events #(conj % token))
db))
{:dispatch-later [{:ms 100 :dispatch [::watcher :event1]}
{:ms 200 :dispatch [::watcher :event2]}
{:ms 200 :dispatch [::watcher :event3]}]}))
(async done
(set-timeout!
(fn []
(is (= @seen-events [:event1 :event2 :event3]) "All 3 events should have fired in order")
(done))
1000)
(re-frame/dispatch [::later-test]))))
(re-frame/reg-event-fx
::missing-handler-test
(fn [_world _event-v]
{:fx-not-exist [:nothing :here]}))
(deftest report-missing-handler
(let [logs (atom [])
log-fn (fn [& args] (swap! logs conj (str/join args)))
original-loggers (log/get-loggers)]
(try
(log/set-loggers! {:error log-fn})
(re-frame/dispatch-sync [::missing-handler-test])
(is (re-matches #"re-frame: no handler registered for effect::fx-not-exist. Ignoring." (first @logs)))
(is (= (count @logs) 1))
(finally
(log/set-loggers! original-loggers)))))
|
c9e941bb5f467f1904bb881f8cab21ce7f90dfead01cb2d9a47c377963c18c75 | prg-titech/Kani-CUDA | diffusion3d-experiment.rkt | #lang rosette
(require "diffusion3d-baseline.rkt"
"../../lang.rkt"
(rename-in rosette/lib/synthax [choose ?])
racket/hash)
(current-bitwidth #f)
(define switch 0)
(define switch-seq #f)
(define switch-w #t);(or (eq? switch 0) (eq? switch-seq #f)))
( or ( eq ? switch 1 ) ( eq ? switch - seq # f ) ) )
( or ( eq ? switch 2 ) ( eq ? switch - seq # f ) ) )
( or ( eq ? switch 3 ) ( eq ? switch - seq # f ) ) )
( or ( eq ? switch 4 ) ( eq ? switch - seq # f ) ) )
( or ( eq ? switch 5 ) ( eq ? switch - seq # f ) ) )
( or ( eq ? switch 6 ) ( eq ? switch - seq # f ) ) )
( or ( eq ? switch 7 ) ( eq ? switch - seq # f ) ) )
(define switch-w2 #f);(or (eq? switch 8) (eq? switch-seq #f)))
( or ( eq ? switch 9 ) ( eq ? switch - seq # f ) ) )
( or ( eq ? switch 10 ) ( eq ? switch - seq # f ) ) )
( or ( eq ? switch 11 ) ( eq ? switch - seq # f ) ) )
(define (diffusion-kernel in
out
nx ny nz
ce cw cn cs ct cb cc)
(:= int BLOCKSIZE (*/LS (block-dim 0) (block-dim 1)))
(:= int tid-x (thread-idx 0))
(:= int tid-y (thread-idx 1))
; Shared memory
(:shared float [smem BLOCKSIZE])
(:= int i (+/LS (*/LS (block-dim 0) (block-idx 0)) tid-x))
(:= int j (+/LS (*/LS (block-dim 1) (block-idx 1)) tid-y))
; Index of a element to be updated on a global memory
(:= int c (+/LS (*/LS j nx) i))
; Index of a element to be updated on a shared memory
(:= int c2 (+/LS (*/LS tid-y (block-dim 0)) tid-x))
(:= int xy (*/LS nx ny))
(: int tb tc tt)
; Variables for register blocking
(= tt [in (+/LS c xy)])
(= tc [in c])
(= tb tc)
;(? (syncthreads) (void))
(= [smem c2] tc)
(syncthreads)
;(? (syncthreads) (void))
(:= bool bw (&&/LS (eq?/LS tid-x (? 0 (-/LS (block-dim 0) 1))) (!/LS (eq?/LS i (? 0 (-/LS nx 1))))))
(:= bool be (&&/LS (eq?/LS tid-x (? 0 (-/LS (block-dim 0) 1))) (!/LS (eq?/LS i (? 0 (-/LS nx 1))))))
(:= bool bn (&&/LS (eq?/LS tid-y (? 0 (-/LS (block-dim 1) 1))) (!/LS (eq?/LS j (? 0 (-/LS ny 1))))))
(:= bool bs (&&/LS (eq?/LS tid-y (? 0 (-/LS (block-dim 1) 1))) (!/LS (eq?/LS j (? 0 (-/LS ny 1))))))
(:= int sw (?: (eq?/LS i (? 0 ((? +/LS -/LS) (? nx ny nz) 1))) c2 ((? +/LS -/LS) c2 (? 1 (block-dim 0) SIZE))))
(:= int se (?: (eq?/LS i (? 0 ((? +/LS -/LS) (? nx ny nz) 1))) c2 ((? +/LS -/LS) c2 (? 1 (block-dim 0) SIZE))))
(:= int sn (?: (eq?/LS j (? 0 ((? +/LS -/LS) (? nx ny nz) 1))) c2 ((? +/LS -/LS) c2 (? 1 (block-dim 0) SIZE))))
(:= int ss (?: (eq?/LS j (? 0 ((? +/LS -/LS) (? nx ny nz) 1))) c2 ((? +/LS -/LS) c2 (? 1 (block-dim 0) SIZE))))
; (define w
; (if switch-w
; (*/LS cw (?: bw [in ((? +/LS -/LS) c 1)] [smem sw]))
( * /LS cw ( ? : ( & & /LS ( eq?/LS tid - x 0 ) ( ! /LS ( eq?/LS i 0 ) ) ) [ in ( -/LS c 1 ) ] [ smem ( ? : ( eq?/LS i 0 ) c2 ( -/LS c2 1 ) ) ] ) ) ) )
; (define e
; (if switch-e
; (*/LS ce (?: be [in ((? +/LS -/LS) c 1)] [smem se]))
( * /LS ce ( ? : ( & & /LS ( eq?/LS ( -/LS ( block - dim 0 ) 1 ) ) ( ! /LS ( eq?/LS i ( -/LS nx 1 ) ) ) ) [ in ( + /LS c 1 ) ] [ smem ( ? : ( eq?/LS i ( -/LS nx 1 ) ) c2 ( + /LS c2 1 ) ) ] ) ) ) )
; (define n
; (if switch-n
; (*/LS cn (?: bn [in ((? +/LS -/LS) c nx)] [smem sn]))
( * /LS cn ( ? : ( & & /LS ( eq?/LS tid - y 0 ) ( ! /LS ( eq?/LS j 0 ) ) ) [ in ( -/LS c nx ) ] [ smem ( ? : ( eq?/LS j 0 ) c2 ( -/LS c2 ( block - dim 0 ) ) ) ] ) ) ) )
; (define s
; (if switch-s
; (*/LS cs (?: bs [in ((? +/LS -/LS) c nx)] [smem ss]))
( * /LS cs ( ? : ( & & /LS ( eq?/LS tid - y ( -/LS ( block - dim 1 ) 1 ) ) ( ! /LS ( eq?/LS j ( -/LS ny 1 ) ) ) ) [ in ( + /LS c nx ) ] [ smem ( ? : ( eq?/LS j ( -/LS ny 1 ) ) c2 ( + /LS c2 ( block - dim 0 ) ) ) ] ) ) ) )
; (? (syncthreads) (void))
(= [out c] (+/LS (*/LS cc tc)
;(*/LS cw (?: bw [in ((? +/LS -/LS) c 1)] [smem sw]))
;(*/LS ce (?: be [in ((? +/LS -/LS) c 1)] [smem se]))
;(*/LS cn (?: bn [in ((? +/LS -/LS) c nx)] [smem sn]))
;(*/LS cs (?: bs [in ((? +/LS -/LS) c nx)] [smem ss]))
(if switch-w
(*/LS cw (?: bw [in ((? +/LS -/LS) c (? 1 0))] [smem sw]))
(*/LS cw (?: (&&/LS (eq?/LS tid-x 0) (!/LS (eq?/LS i 0))) [in (-/LS c 1)] [smem (?: (eq?/LS i 0) c2 (-/LS c2 1))])))
(if switch-e
(*/LS ce (?: be [in ((? +/LS -/LS) c 1)] [smem se]))
(*/LS ce (?: (&&/LS (eq?/LS tid-x (-/LS (block-dim 0) 1)) (!/LS (eq?/LS i (-/LS nx 1)))) [in (+/LS c 1)] [smem (?: (eq?/LS i (-/LS nx 1)) c2 (+/LS c2 1))])))
(if switch-n
(*/LS cn (?: bn [in ((? +/LS -/LS) c nx)] [smem sn]))
(*/LS cn (?: (&&/LS (eq?/LS tid-y 0) (!/LS (eq?/LS j 0))) [in (-/LS c nx)] [smem (?: (eq?/LS j 0) c2 (-/LS c2 (block-dim 0)))])))
(if switch-s
(*/LS cs (?: bs [in ((? +/LS -/LS) c nx)] [smem ss]))
(*/LS cs (?: (&&/LS (eq?/LS tid-y (-/LS (block-dim 1) 1)) (!/LS (eq?/LS j (-/LS ny 1)))) [in (+/LS c nx)] [smem (?: (eq?/LS j (-/LS ny 1)) c2 (+/LS c2 (block-dim 0)))])))
(*/LS cb tb)
(*/LS ct tt)))
(+=/LS c xy)
(:= int k 1)
(for- [: (</LS k (-/LS nz 1)): (++ k)]
(= tb tc)
(= tc tt)
;(? (syncthreads) (void))
(syncthreads)
(= [smem c2] tt)
(= tt [in (+/LS c xy)])
(syncthreads)
;(? (syncthreads) (void))
(= bw (&&/LS (eq?/LS tid-x (? 0 (-/LS (block-dim 0) 1))) (!/LS (eq?/LS i (? 0 (-/LS nx 1))))))
(= be (&&/LS (eq?/LS tid-x (? 0 (-/LS (block-dim 0) 1))) (!/LS (eq?/LS i (? 0 (-/LS nx 1))))))
(= bn (&&/LS (eq?/LS tid-y (? 0 (-/LS (block-dim 1) 1))) (!/LS (eq?/LS j (? 0 (-/LS ny 1))))))
(= bs (&&/LS (eq?/LS tid-y (? 0 (-/LS (block-dim 1) 1))) (!/LS (eq?/LS j (? 0 (-/LS ny 1))))))
(= sw (?: (eq?/LS i (? 0 ((? +/LS -/LS) (? nx ny nz) 1))) c2 ((? +/LS -/LS) c2 (? 1 (block-dim 0) SIZE))))
(= se (?: (eq?/LS i (? 0 ((? +/LS -/LS) (? nx ny nz) 1))) c2 ((? +/LS -/LS) c2 (? 1 (block-dim 0) SIZE))))
(= sn (?: (eq?/LS j (? 0 ((? +/LS -/LS) (? nx ny nz) 1))) c2 ((? +/LS -/LS) c2 (? 1 (block-dim 0) SIZE))))
(= ss (?: (eq?/LS j (? 0 ((? +/LS -/LS) (? nx ny nz) 1))) c2 ((? +/LS -/LS) c2 (? 1 (block-dim 0) SIZE))))
(= [out c] (+/LS (*/LS cc tc)
;(*/LS cw (?: bw [in ((? +/LS -/LS) c 1)] [smem sw]))
;(*/LS ce (?: be [in ((? +/LS -/LS) c 1)] [smem se]))
;(*/LS cn (?: bn [in ((? +/LS -/LS) c nx)] [smem sn]))
;(*/LS cs (?: bs [in ((? +/LS -/LS) c nx)] [smem ss]))
(if switch-w1
(*/LS cw (?: bw [in ((? +/LS -/LS) c 1)] [smem sw]))
(*/LS cw (?: (&&/LS (eq?/LS tid-x 0) (!/LS (eq?/LS i 0))) [in (-/LS c 1)] [smem (?: (eq?/LS i 0) c2 (-/LS c2 1))])))
(if switch-e1
(*/LS ce (?: be [in ((? +/LS -/LS) c 1)] [smem se]))
(*/LS ce (?: (&&/LS (eq?/LS tid-x (-/LS (block-dim 0) 1)) (!/LS (eq?/LS i (-/LS nx 1)))) [in (+/LS c 1)] [smem (?: (eq?/LS i (-/LS nx 1)) c2 (+/LS c2 1))])))
(if switch-n1
(*/LS cn (?: bn [in ((? +/LS -/LS) c nx)] [smem sn]))
(*/LS cn (?: (&&/LS (eq?/LS tid-y 0) (!/LS (eq?/LS j 0))) [in (-/LS c nx)] [smem (?: (eq?/LS j 0) c2 (-/LS c2 (block-dim 0)))])))
(if switch-s1
(*/LS cs (?: bs [in ((? +/LS -/LS) c nx)] [smem ss]))
(*/LS cs (?: (&&/LS (eq?/LS tid-y (-/LS (block-dim 1) 1)) (!/LS (eq?/LS j (-/LS ny 1)))) [in (+/LS c nx)] [smem (?: (eq?/LS j (-/LS ny 1)) c2 (+/LS c2 (block-dim 0)))])))
(*/LS cb tb)
(*/LS ct tt)))
(syncthreads)
;(? (syncthreads) (void))
(+=/LS c xy))
(= tb tc)
(= tc tt)
;(? (syncthreads) (void))
(= [smem c2] tt)
(syncthreads)
;(? (syncthreads) (void))
(= bw (&&/LS (eq?/LS tid-x (? 0 (-/LS (block-dim 0) 1))) (!/LS (eq?/LS i (? 0 (-/LS nx 1))))))
(= be (&&/LS (eq?/LS tid-x (? 0 (-/LS (block-dim 0) 1))) (!/LS (eq?/LS i (? 0 (-/LS nx 1))))))
(= bn (&&/LS (eq?/LS tid-y (? 0 (-/LS (block-dim 1) 1))) (!/LS (eq?/LS j (? 0 (-/LS ny 1))))))
(= bs (&&/LS (eq?/LS tid-y (? 0 (-/LS (block-dim 1) 1))) (!/LS (eq?/LS j (? 0 (-/LS ny 1))))))
(= sw (?: (eq?/LS i (? 0 ((? +/LS -/LS) (? nx ny nz) 1))) c2 ((? +/LS -/LS) c2 (? 1 (block-dim 0) SIZE))))
(= se (?: (eq?/LS i (? 0 ((? +/LS -/LS) (? nx ny nz) 1))) c2 ((? +/LS -/LS) c2 (? 1 (block-dim 0) SIZE))))
(= sn (?: (eq?/LS j (? 0 ((? +/LS -/LS) (? nx ny nz) 1))) c2 ((? +/LS -/LS) c2 (? 1 (block-dim 0) SIZE))))
(= ss (?: (eq?/LS j (? 0 ((? +/LS -/LS) (? nx ny nz) 1))) c2 ((? +/LS -/LS) c2 (? 1 (block-dim 0) SIZE))))
(= [out c] (+/LS (*/LS cc tc)
;(*/LS cw (?: bw [in ((? +/LS -/LS) c 1)] [smem sw]))
;(*/LS ce (?: be [in ((? +/LS -/LS) c 1)] [smem se]))
;(*/LS cn (?: bn [in ((? +/LS -/LS) c nx)] [smem sn]))
;(*/LS cs (?: bs [in ((? +/LS -/LS) c nx)] [smem ss]))
(if switch-w2
(*/LS cw (?: bw [in ((? +/LS -/LS) c 1)] [smem sw]))
(*/LS cw (?: (&&/LS (eq?/LS tid-x 0) (!/LS (eq?/LS i 0))) [in (-/LS c 1)] [smem (?: (eq?/LS i 0) c2 (-/LS c2 1))])))
(if switch-e2
(*/LS ce (?: be [in ((? +/LS -/LS) c 1)] [smem se]))
(*/LS ce (?: (&&/LS (eq?/LS tid-x (-/LS (block-dim 0) 1)) (!/LS (eq?/LS i (-/LS nx 1)))) [in (+/LS c 1)] [smem (?: (eq?/LS i (-/LS nx 1)) c2 (+/LS c2 1))])))
(if switch-n2
(*/LS cn (?: bn [in ((? +/LS -/LS) c nx)] [smem sn]))
(*/LS cn (?: (&&/LS (eq?/LS tid-y 0) (!/LS (eq?/LS j 0))) [in (-/LS c nx)] [smem (?: (eq?/LS j 0) c2 (-/LS c2 (block-dim 0)))])))
(if switch-s2
(*/LS cs (?: bs [in ((? +/LS -/LS) c nx)] [smem ss]))
(*/LS cs (?: (&&/LS (eq?/LS tid-y (-/LS (block-dim 1) 1)) (!/LS (eq?/LS j (-/LS ny 1)))) [in (+/LS c nx)] [smem (?: (eq?/LS j (-/LS ny 1)) c2 (+/LS c2 (block-dim 0)))])))
(*/LS cb tb)
(*/LS ct tt))))
(define (diffusion-run-kernel grid
block
count
in out
nx ny nz
ce cw cn cs ct cb cc)
(for ([i (in-range count)])
(invoke-kernel diffusion-kernel
grid
block
in out
nx ny nz
ce cw cn cs ct cb cc)
(define temp in)
(set! in out)
(set! out temp)))
;; Add a constraint that it is equal to each of the elements of
two arrays , arr1 and arr2 , to asserts .
(define (array-eq-verify arr1 arr2 len)
(for ([i (in-range len)])
(assert
(eq?
(array-ref-host arr1 i)
(array-ref-host arr2 i)))))
(define (r)
(define-symbolic* r real?)
r)
(define-values (SIZEX SIZEY SIZEZ) (values 12 9 3))
(define SIZE (* SIZEX SIZEY SIZEZ))
(define-values (BLOCKSIZEX BLOCKSIZEY) (values 4 3))
;; Input array on CPU
(define CPU-in (make-array (for/vector ([i SIZE]) (make-element (r))) SIZE))
;; Input array on GPU
(define GPU-in (make-array (for/vector ([i SIZE]) (make-element (array-ref-host CPU-in i))) SIZE))
;; Output array on CPU
(define CPU-out (make-array (for/vector ([i SIZE]) (make-element i)) SIZE))
;; Output array on GPU
(define GPU-out (make-array (for/vector ([i SIZE]) (make-element i)) SIZE))
(define-symbolic e w n s t b c real?)
( define - values ( e w n s t b c ) ( values 1 1 1 1 1 1 1 ) )
(define lst
(for/list ([i SIZE])
(array-ref-host CPU-in i)))
(define (synth-stencil)
(time
(synthesize #:forall (append lst (list e w n s t b c))
#:guarantee (begin
;; Execute a diffusion program on CPU
(time
(diffusion3d-baseline 1
CPU-in CPU-out
SIZEX SIZEY SIZEZ
e w n s t b c)
;; Execute a diffusion program on GPU
(diffusion-run-kernel (list (quotient SIZEX BLOCKSIZEX) (quotient SIZEY BLOCKSIZEY))
(list BLOCKSIZEX BLOCKSIZEY)
1
GPU-in GPU-out
SIZEX SIZEY SIZEZ
e w n s t b c)
(array-eq-verify
CPU-out GPU-out SIZE))))))
;(println (length (asserts)))))))
409
484
599
764
836
908
1016
1160
1233
1308
1387
;(map syntax->datum (generate-forms (synth-stencil)))
(define (seq-synth-stencil n)
(time
(define ans (model (synth-stencil)))
(for ([i (- n 1)])
(set! switch (+ i 1))
(set! ans (hash-union ans (model (synth-stencil))
#:combine/key (lambda (k v1 v2) (and v1 v2))))
)
(map syntax->datum (generate-forms (sat ans)))))
(generate-forms (synth-stencil))
( seq - synth - stencil 4 ) | null | https://raw.githubusercontent.com/prg-titech/Kani-CUDA/e97c4bede43a5fc4031a7d2cfc32d71b01ac26c4/Emulator/Examples/Diffusion3d/diffusion3d-experiment.rkt | racket | (or (eq? switch 0) (eq? switch-seq #f)))
(or (eq? switch 8) (eq? switch-seq #f)))
Shared memory
Index of a element to be updated on a global memory
Index of a element to be updated on a shared memory
Variables for register blocking
(? (syncthreads) (void))
(? (syncthreads) (void))
(define w
(if switch-w
(*/LS cw (?: bw [in ((? +/LS -/LS) c 1)] [smem sw]))
(define e
(if switch-e
(*/LS ce (?: be [in ((? +/LS -/LS) c 1)] [smem se]))
(define n
(if switch-n
(*/LS cn (?: bn [in ((? +/LS -/LS) c nx)] [smem sn]))
(define s
(if switch-s
(*/LS cs (?: bs [in ((? +/LS -/LS) c nx)] [smem ss]))
(? (syncthreads) (void))
(*/LS cw (?: bw [in ((? +/LS -/LS) c 1)] [smem sw]))
(*/LS ce (?: be [in ((? +/LS -/LS) c 1)] [smem se]))
(*/LS cn (?: bn [in ((? +/LS -/LS) c nx)] [smem sn]))
(*/LS cs (?: bs [in ((? +/LS -/LS) c nx)] [smem ss]))
(? (syncthreads) (void))
(? (syncthreads) (void))
(*/LS cw (?: bw [in ((? +/LS -/LS) c 1)] [smem sw]))
(*/LS ce (?: be [in ((? +/LS -/LS) c 1)] [smem se]))
(*/LS cn (?: bn [in ((? +/LS -/LS) c nx)] [smem sn]))
(*/LS cs (?: bs [in ((? +/LS -/LS) c nx)] [smem ss]))
(? (syncthreads) (void))
(? (syncthreads) (void))
(? (syncthreads) (void))
(*/LS cw (?: bw [in ((? +/LS -/LS) c 1)] [smem sw]))
(*/LS ce (?: be [in ((? +/LS -/LS) c 1)] [smem se]))
(*/LS cn (?: bn [in ((? +/LS -/LS) c nx)] [smem sn]))
(*/LS cs (?: bs [in ((? +/LS -/LS) c nx)] [smem ss]))
Add a constraint that it is equal to each of the elements of
Input array on CPU
Input array on GPU
Output array on CPU
Output array on GPU
Execute a diffusion program on CPU
Execute a diffusion program on GPU
(println (length (asserts)))))))
(map syntax->datum (generate-forms (synth-stencil))) | #lang rosette
(require "diffusion3d-baseline.rkt"
"../../lang.rkt"
(rename-in rosette/lib/synthax [choose ?])
racket/hash)
(current-bitwidth #f)
(define switch 0)
(define switch-seq #f)
( or ( eq ? switch 1 ) ( eq ? switch - seq # f ) ) )
( or ( eq ? switch 2 ) ( eq ? switch - seq # f ) ) )
( or ( eq ? switch 3 ) ( eq ? switch - seq # f ) ) )
( or ( eq ? switch 4 ) ( eq ? switch - seq # f ) ) )
( or ( eq ? switch 5 ) ( eq ? switch - seq # f ) ) )
( or ( eq ? switch 6 ) ( eq ? switch - seq # f ) ) )
( or ( eq ? switch 7 ) ( eq ? switch - seq # f ) ) )
( or ( eq ? switch 9 ) ( eq ? switch - seq # f ) ) )
( or ( eq ? switch 10 ) ( eq ? switch - seq # f ) ) )
( or ( eq ? switch 11 ) ( eq ? switch - seq # f ) ) )
(define (diffusion-kernel in
out
nx ny nz
ce cw cn cs ct cb cc)
(:= int BLOCKSIZE (*/LS (block-dim 0) (block-dim 1)))
(:= int tid-x (thread-idx 0))
(:= int tid-y (thread-idx 1))
(:shared float [smem BLOCKSIZE])
(:= int i (+/LS (*/LS (block-dim 0) (block-idx 0)) tid-x))
(:= int j (+/LS (*/LS (block-dim 1) (block-idx 1)) tid-y))
(:= int c (+/LS (*/LS j nx) i))
(:= int c2 (+/LS (*/LS tid-y (block-dim 0)) tid-x))
(:= int xy (*/LS nx ny))
(: int tb tc tt)
(= tt [in (+/LS c xy)])
(= tc [in c])
(= tb tc)
(= [smem c2] tc)
(syncthreads)
(:= bool bw (&&/LS (eq?/LS tid-x (? 0 (-/LS (block-dim 0) 1))) (!/LS (eq?/LS i (? 0 (-/LS nx 1))))))
(:= bool be (&&/LS (eq?/LS tid-x (? 0 (-/LS (block-dim 0) 1))) (!/LS (eq?/LS i (? 0 (-/LS nx 1))))))
(:= bool bn (&&/LS (eq?/LS tid-y (? 0 (-/LS (block-dim 1) 1))) (!/LS (eq?/LS j (? 0 (-/LS ny 1))))))
(:= bool bs (&&/LS (eq?/LS tid-y (? 0 (-/LS (block-dim 1) 1))) (!/LS (eq?/LS j (? 0 (-/LS ny 1))))))
(:= int sw (?: (eq?/LS i (? 0 ((? +/LS -/LS) (? nx ny nz) 1))) c2 ((? +/LS -/LS) c2 (? 1 (block-dim 0) SIZE))))
(:= int se (?: (eq?/LS i (? 0 ((? +/LS -/LS) (? nx ny nz) 1))) c2 ((? +/LS -/LS) c2 (? 1 (block-dim 0) SIZE))))
(:= int sn (?: (eq?/LS j (? 0 ((? +/LS -/LS) (? nx ny nz) 1))) c2 ((? +/LS -/LS) c2 (? 1 (block-dim 0) SIZE))))
(:= int ss (?: (eq?/LS j (? 0 ((? +/LS -/LS) (? nx ny nz) 1))) c2 ((? +/LS -/LS) c2 (? 1 (block-dim 0) SIZE))))
( * /LS cw ( ? : ( & & /LS ( eq?/LS tid - x 0 ) ( ! /LS ( eq?/LS i 0 ) ) ) [ in ( -/LS c 1 ) ] [ smem ( ? : ( eq?/LS i 0 ) c2 ( -/LS c2 1 ) ) ] ) ) ) )
( * /LS ce ( ? : ( & & /LS ( eq?/LS ( -/LS ( block - dim 0 ) 1 ) ) ( ! /LS ( eq?/LS i ( -/LS nx 1 ) ) ) ) [ in ( + /LS c 1 ) ] [ smem ( ? : ( eq?/LS i ( -/LS nx 1 ) ) c2 ( + /LS c2 1 ) ) ] ) ) ) )
( * /LS cn ( ? : ( & & /LS ( eq?/LS tid - y 0 ) ( ! /LS ( eq?/LS j 0 ) ) ) [ in ( -/LS c nx ) ] [ smem ( ? : ( eq?/LS j 0 ) c2 ( -/LS c2 ( block - dim 0 ) ) ) ] ) ) ) )
( * /LS cs ( ? : ( & & /LS ( eq?/LS tid - y ( -/LS ( block - dim 1 ) 1 ) ) ( ! /LS ( eq?/LS j ( -/LS ny 1 ) ) ) ) [ in ( + /LS c nx ) ] [ smem ( ? : ( eq?/LS j ( -/LS ny 1 ) ) c2 ( + /LS c2 ( block - dim 0 ) ) ) ] ) ) ) )
(= [out c] (+/LS (*/LS cc tc)
(if switch-w
(*/LS cw (?: bw [in ((? +/LS -/LS) c (? 1 0))] [smem sw]))
(*/LS cw (?: (&&/LS (eq?/LS tid-x 0) (!/LS (eq?/LS i 0))) [in (-/LS c 1)] [smem (?: (eq?/LS i 0) c2 (-/LS c2 1))])))
(if switch-e
(*/LS ce (?: be [in ((? +/LS -/LS) c 1)] [smem se]))
(*/LS ce (?: (&&/LS (eq?/LS tid-x (-/LS (block-dim 0) 1)) (!/LS (eq?/LS i (-/LS nx 1)))) [in (+/LS c 1)] [smem (?: (eq?/LS i (-/LS nx 1)) c2 (+/LS c2 1))])))
(if switch-n
(*/LS cn (?: bn [in ((? +/LS -/LS) c nx)] [smem sn]))
(*/LS cn (?: (&&/LS (eq?/LS tid-y 0) (!/LS (eq?/LS j 0))) [in (-/LS c nx)] [smem (?: (eq?/LS j 0) c2 (-/LS c2 (block-dim 0)))])))
(if switch-s
(*/LS cs (?: bs [in ((? +/LS -/LS) c nx)] [smem ss]))
(*/LS cs (?: (&&/LS (eq?/LS tid-y (-/LS (block-dim 1) 1)) (!/LS (eq?/LS j (-/LS ny 1)))) [in (+/LS c nx)] [smem (?: (eq?/LS j (-/LS ny 1)) c2 (+/LS c2 (block-dim 0)))])))
(*/LS cb tb)
(*/LS ct tt)))
(+=/LS c xy)
(:= int k 1)
(for- [: (</LS k (-/LS nz 1)): (++ k)]
(= tb tc)
(= tc tt)
(syncthreads)
(= [smem c2] tt)
(= tt [in (+/LS c xy)])
(syncthreads)
(= bw (&&/LS (eq?/LS tid-x (? 0 (-/LS (block-dim 0) 1))) (!/LS (eq?/LS i (? 0 (-/LS nx 1))))))
(= be (&&/LS (eq?/LS tid-x (? 0 (-/LS (block-dim 0) 1))) (!/LS (eq?/LS i (? 0 (-/LS nx 1))))))
(= bn (&&/LS (eq?/LS tid-y (? 0 (-/LS (block-dim 1) 1))) (!/LS (eq?/LS j (? 0 (-/LS ny 1))))))
(= bs (&&/LS (eq?/LS tid-y (? 0 (-/LS (block-dim 1) 1))) (!/LS (eq?/LS j (? 0 (-/LS ny 1))))))
(= sw (?: (eq?/LS i (? 0 ((? +/LS -/LS) (? nx ny nz) 1))) c2 ((? +/LS -/LS) c2 (? 1 (block-dim 0) SIZE))))
(= se (?: (eq?/LS i (? 0 ((? +/LS -/LS) (? nx ny nz) 1))) c2 ((? +/LS -/LS) c2 (? 1 (block-dim 0) SIZE))))
(= sn (?: (eq?/LS j (? 0 ((? +/LS -/LS) (? nx ny nz) 1))) c2 ((? +/LS -/LS) c2 (? 1 (block-dim 0) SIZE))))
(= ss (?: (eq?/LS j (? 0 ((? +/LS -/LS) (? nx ny nz) 1))) c2 ((? +/LS -/LS) c2 (? 1 (block-dim 0) SIZE))))
(= [out c] (+/LS (*/LS cc tc)
(if switch-w1
(*/LS cw (?: bw [in ((? +/LS -/LS) c 1)] [smem sw]))
(*/LS cw (?: (&&/LS (eq?/LS tid-x 0) (!/LS (eq?/LS i 0))) [in (-/LS c 1)] [smem (?: (eq?/LS i 0) c2 (-/LS c2 1))])))
(if switch-e1
(*/LS ce (?: be [in ((? +/LS -/LS) c 1)] [smem se]))
(*/LS ce (?: (&&/LS (eq?/LS tid-x (-/LS (block-dim 0) 1)) (!/LS (eq?/LS i (-/LS nx 1)))) [in (+/LS c 1)] [smem (?: (eq?/LS i (-/LS nx 1)) c2 (+/LS c2 1))])))
(if switch-n1
(*/LS cn (?: bn [in ((? +/LS -/LS) c nx)] [smem sn]))
(*/LS cn (?: (&&/LS (eq?/LS tid-y 0) (!/LS (eq?/LS j 0))) [in (-/LS c nx)] [smem (?: (eq?/LS j 0) c2 (-/LS c2 (block-dim 0)))])))
(if switch-s1
(*/LS cs (?: bs [in ((? +/LS -/LS) c nx)] [smem ss]))
(*/LS cs (?: (&&/LS (eq?/LS tid-y (-/LS (block-dim 1) 1)) (!/LS (eq?/LS j (-/LS ny 1)))) [in (+/LS c nx)] [smem (?: (eq?/LS j (-/LS ny 1)) c2 (+/LS c2 (block-dim 0)))])))
(*/LS cb tb)
(*/LS ct tt)))
(syncthreads)
(+=/LS c xy))
(= tb tc)
(= tc tt)
(= [smem c2] tt)
(syncthreads)
(= bw (&&/LS (eq?/LS tid-x (? 0 (-/LS (block-dim 0) 1))) (!/LS (eq?/LS i (? 0 (-/LS nx 1))))))
(= be (&&/LS (eq?/LS tid-x (? 0 (-/LS (block-dim 0) 1))) (!/LS (eq?/LS i (? 0 (-/LS nx 1))))))
(= bn (&&/LS (eq?/LS tid-y (? 0 (-/LS (block-dim 1) 1))) (!/LS (eq?/LS j (? 0 (-/LS ny 1))))))
(= bs (&&/LS (eq?/LS tid-y (? 0 (-/LS (block-dim 1) 1))) (!/LS (eq?/LS j (? 0 (-/LS ny 1))))))
(= sw (?: (eq?/LS i (? 0 ((? +/LS -/LS) (? nx ny nz) 1))) c2 ((? +/LS -/LS) c2 (? 1 (block-dim 0) SIZE))))
(= se (?: (eq?/LS i (? 0 ((? +/LS -/LS) (? nx ny nz) 1))) c2 ((? +/LS -/LS) c2 (? 1 (block-dim 0) SIZE))))
(= sn (?: (eq?/LS j (? 0 ((? +/LS -/LS) (? nx ny nz) 1))) c2 ((? +/LS -/LS) c2 (? 1 (block-dim 0) SIZE))))
(= ss (?: (eq?/LS j (? 0 ((? +/LS -/LS) (? nx ny nz) 1))) c2 ((? +/LS -/LS) c2 (? 1 (block-dim 0) SIZE))))
(= [out c] (+/LS (*/LS cc tc)
(if switch-w2
(*/LS cw (?: bw [in ((? +/LS -/LS) c 1)] [smem sw]))
(*/LS cw (?: (&&/LS (eq?/LS tid-x 0) (!/LS (eq?/LS i 0))) [in (-/LS c 1)] [smem (?: (eq?/LS i 0) c2 (-/LS c2 1))])))
(if switch-e2
(*/LS ce (?: be [in ((? +/LS -/LS) c 1)] [smem se]))
(*/LS ce (?: (&&/LS (eq?/LS tid-x (-/LS (block-dim 0) 1)) (!/LS (eq?/LS i (-/LS nx 1)))) [in (+/LS c 1)] [smem (?: (eq?/LS i (-/LS nx 1)) c2 (+/LS c2 1))])))
(if switch-n2
(*/LS cn (?: bn [in ((? +/LS -/LS) c nx)] [smem sn]))
(*/LS cn (?: (&&/LS (eq?/LS tid-y 0) (!/LS (eq?/LS j 0))) [in (-/LS c nx)] [smem (?: (eq?/LS j 0) c2 (-/LS c2 (block-dim 0)))])))
(if switch-s2
(*/LS cs (?: bs [in ((? +/LS -/LS) c nx)] [smem ss]))
(*/LS cs (?: (&&/LS (eq?/LS tid-y (-/LS (block-dim 1) 1)) (!/LS (eq?/LS j (-/LS ny 1)))) [in (+/LS c nx)] [smem (?: (eq?/LS j (-/LS ny 1)) c2 (+/LS c2 (block-dim 0)))])))
(*/LS cb tb)
(*/LS ct tt))))
(define (diffusion-run-kernel grid
block
count
in out
nx ny nz
ce cw cn cs ct cb cc)
(for ([i (in-range count)])
(invoke-kernel diffusion-kernel
grid
block
in out
nx ny nz
ce cw cn cs ct cb cc)
(define temp in)
(set! in out)
(set! out temp)))
two arrays , arr1 and arr2 , to asserts .
(define (array-eq-verify arr1 arr2 len)
(for ([i (in-range len)])
(assert
(eq?
(array-ref-host arr1 i)
(array-ref-host arr2 i)))))
(define (r)
(define-symbolic* r real?)
r)
(define-values (SIZEX SIZEY SIZEZ) (values 12 9 3))
(define SIZE (* SIZEX SIZEY SIZEZ))
(define-values (BLOCKSIZEX BLOCKSIZEY) (values 4 3))
(define CPU-in (make-array (for/vector ([i SIZE]) (make-element (r))) SIZE))
(define GPU-in (make-array (for/vector ([i SIZE]) (make-element (array-ref-host CPU-in i))) SIZE))
(define CPU-out (make-array (for/vector ([i SIZE]) (make-element i)) SIZE))
(define GPU-out (make-array (for/vector ([i SIZE]) (make-element i)) SIZE))
(define-symbolic e w n s t b c real?)
( define - values ( e w n s t b c ) ( values 1 1 1 1 1 1 1 ) )
(define lst
(for/list ([i SIZE])
(array-ref-host CPU-in i)))
(define (synth-stencil)
(time
(synthesize #:forall (append lst (list e w n s t b c))
#:guarantee (begin
(time
(diffusion3d-baseline 1
CPU-in CPU-out
SIZEX SIZEY SIZEZ
e w n s t b c)
(diffusion-run-kernel (list (quotient SIZEX BLOCKSIZEX) (quotient SIZEY BLOCKSIZEY))
(list BLOCKSIZEX BLOCKSIZEY)
1
GPU-in GPU-out
SIZEX SIZEY SIZEZ
e w n s t b c)
(array-eq-verify
CPU-out GPU-out SIZE))))))
409
484
599
764
836
908
1016
1160
1233
1308
1387
(define (seq-synth-stencil n)
(time
(define ans (model (synth-stencil)))
(for ([i (- n 1)])
(set! switch (+ i 1))
(set! ans (hash-union ans (model (synth-stencil))
#:combine/key (lambda (k v1 v2) (and v1 v2))))
)
(map syntax->datum (generate-forms (sat ans)))))
(generate-forms (synth-stencil))
( seq - synth - stencil 4 ) |
0a2e3457919378c6350dd987abfa6a418d0a8c7c806e4cfb931f199c5b40e0a3 | scalaris-team/scalaris | optorset.erl | 2008 - 2018 Zuse Institute Berlin
Licensed under the Apache License , Version 2.0 ( the " License " ) ;
% you may not use this file except in compliance with the License.
% You may obtain a copy of the License at
%
% -2.0
%
% Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an " AS IS " BASIS ,
% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
% See the License for the specific language governing permissions and
% limitations under the License.
@author < >
@doc Implementation of an optimized OR - Set state - based CRDT
as specified by
%% @end
%% @version $Id$
-module(optorset).
-author('').
-vsn('Id$').
-include("scalaris.hrl").
-define(R, config:read(replication_factor)).
-define(SET, ordsets).
-export([lteq2/2]).
-export([update_add/3]).
-export([update_remove/2]).
-export([query_contains/2]).
-export([query_elements/1]).
-behaviour(crdt_beh).
-type vector() :: [non_neg_integer()].
-type element() :: {Element::term(), TimeStamp::term(), ReplicaID::term()}.
-opaque crdt() :: {E::?SET:ordset(element()), V::vector()}.
-include("crdt_beh.hrl").
-spec new() -> crdt().
new() -> {?SET:new(), [0 || _ <- lists:seq(1, ?R)]}.
-spec merge(crdt(), crdt()) -> crdt().
merge(_CRDT1={E1, V1}, _CRDT2={E2, V2}) ->
%% TODO: make this more efficient?
M = ?SET:union(E1, E2),
T2 = ?SET:subtract(E1, E2),
M2 = ?SET:filter(fun({_E, C, I}) -> C > vector_get(I, V2) end, T2),
T3 = ?SET:subtract(E2, E1),
M3 = ?SET:filter(fun({_E, C, I}) -> C > vector_get(I, V1) end, T3),
U = ?SET:union([M, M2, M3]),
% find the largest C of all {E, _, I} tripples in linear time
D = ?SET:fold(fun({E, C, I}, DictAcc) ->
dict:update({E,I}, fun(A) -> max(A, C) end, C, DictAcc)
end, dict:new(), U),
% from dict to set again...
NewE = dict:fold(fun({E, I}, C, SetAcc) ->
?SET:add_element({E, C, I}, SetAcc)
end, ?SET:new(), D),
NewV = vector_max(V1, V2),
{NewE, NewV}.
-spec eq(crdt(), crdt()) -> boolean().
eq(_CRDT1={E1, V1}, _CRDT2={E2, V2}) ->
vector_eq(V1, V2) andalso ?SET:is_subset(E1, E2) andalso ?SET:is_subset(E2, E1).
-spec lteq(crdt(), crdt()) -> boolean().
lteq(_CRDT1={E1, V1}, _CRDT2={E2, V2}) ->
case vector_lteq(V1, V2) of
false -> false;
true ->
%% optimized implementation compared to paper exploiting the fact
that V1 = < V2
Fun = fun({_, C, I}, SetAcc) ->
case C =< vector_get(I, V1) of
true -> ?SET:add_element({C, I}, SetAcc);
false -> SetAcc
end
end,
X = ?SET:fold(Fun, ?SET:new(), E1),
X2 = ?SET:fold(Fun, ?SET:new(), E2),
%% Is the same as is_subset(D - X,D - X2) with
%% D = set of all possible (C,I) pairs
?SET:is_subset(X2, X)
end.
lteq implementation as specified in paper ... used for testing purposes
-spec lteq2(crdt(), crdt()) -> boolean().
lteq2(_CRDT1={E1, V1}, _CRDT2={E2, V2}) ->
case vector_lteq(V1, V2) of
false -> false;
true ->
TFun = fun({_, C, I}, SetAcc) -> ?SET:add_element({C,I}, SetAcc) end,
X1 = ?SET:fold(TFun, ?SET:new(), E1),
X2 = ?SET:fold(TFun, ?SET:new(), E2),
Possible1 = [{B, A} || A <- lists:seq(1, ?R), B <- lists:seq(1, vector_get(A, V1))],
Possible2 = [{B, A} || A <- lists:seq(1, ?R), B <- lists:seq(1, vector_get(A, V2))],
R1 = lists:foldl(fun(E, Acc) ->
case ?SET:is_element(E, X1) of
true -> Acc;
false -> ?SET:add_element(E, Acc)
end
end, ?SET:new(), Possible1),
R2 = lists:foldl(fun(E, Acc) ->
case ?SET:is_element(E, X2) of
true -> Acc;
false -> ?SET:add_element(E, Acc)
end
end, ?SET:new(), Possible2),
?SET:is_subset(R1, R2)
end.
%%%%%%%%%%%%%%%%%%%%% Update and Query functions
-spec update_add(ReplicaId::non_neg_integer(), Element::term(), CRDT::crdt()) -> crdt().
update_add(ReplicaId, Element, _CRDT={E, V}) ->
{TimeStamp, V2} = vector_inc_and_get(ReplicaId, V),
E2 = ?SET:add_element({Element, TimeStamp, ReplicaId}, E),
E3 = ?SET:filter(fun({TE, TC, _TI}) ->
not (TE =:= Element andalso TC < TimeStamp)
end, E2),
{E3, V2}.
-spec update_remove(Element::term(), C::crdt()) -> crdt().
update_remove(Element, _CRDT={E, V}) ->
E2 = ?SET:filter(fun({TE, _TC, _TI}) -> Element =/= TE end, E),
{E2, V}.
-spec query_elements(crdt()) -> ?SET:ordset(element()).
query_elements(_CRDT={Elements, _V}) ->
?SET:fold(fun({E, _C, _I}, AccSet) -> ?SET:add_element(E, AccSet) end,
?SET:new(), Elements).
-spec query_contains(term(), crdt()) -> boolean().
query_contains(Element, _CRDT={Elements, _V}) ->
?SET:fold(fun({E, _C, _I}, _Acc) when Element =:= E -> true;
(_C, Acc) -> Acc
end, false, Elements).
%%%%%%%%%%%%%%%%%%%%% Some helper funcitons for vector manipulation
TODO use dict instead of list ?
-spec vector_max(vector(), vector()) -> vector().
vector_max([], []) -> [];
vector_max([H1 | T1], [H2 | T2]) -> [max(H1, H2) | vector_max(T1, T2)].
-spec vector_get(non_neg_integer(), vector()) -> non_neg_integer().
vector_get(Idx, V) -> lists:nth(Idx, V).
-spec vector_inc_and_get(non_neg_integer(), vector()) -> {non_neg_integer(), vector()}.
vector_inc_and_get(Idx, V) ->
TimeStamp = lists:nth(Idx, V) + 1,
V2 = lists:sublist(V, Idx - 1) ++ [TimeStamp] ++ lists:nthtail(Idx, V),
{TimeStamp, V2}.
-spec vector_eq(vector(), vector()) -> boolean().
vector_eq(V1, V2) -> V1 =:= V2.
-spec vector_lteq(vector(), vector()) -> boolean().
vector_lteq([], []) -> true;
vector_lteq([H1 | _T1], [H2 | _T2]) when H1 > H2 -> false;
vector_lteq([_H1 | T1], [_H2 | T2]) -> vector_lteq(T1, T2).
| null | https://raw.githubusercontent.com/scalaris-team/scalaris/feb894d54e642bb3530e709e730156b0ecc1635f/src/crdt/types/optorset.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.
@end
@version $Id$
TODO: make this more efficient?
find the largest C of all {E, _, I} tripples in linear time
from dict to set again...
optimized implementation compared to paper exploiting the fact
Is the same as is_subset(D - X,D - X2) with
D = set of all possible (C,I) pairs
Update and Query functions
Some helper funcitons for vector manipulation | 2008 - 2018 Zuse Institute Berlin
Licensed under the Apache License , Version 2.0 ( the " License " ) ;
distributed under the License is distributed on an " AS IS " BASIS ,
@author < >
@doc Implementation of an optimized OR - Set state - based CRDT
as specified by
-module(optorset).
-author('').
-vsn('Id$').
-include("scalaris.hrl").
-define(R, config:read(replication_factor)).
-define(SET, ordsets).
-export([lteq2/2]).
-export([update_add/3]).
-export([update_remove/2]).
-export([query_contains/2]).
-export([query_elements/1]).
-behaviour(crdt_beh).
-type vector() :: [non_neg_integer()].
-type element() :: {Element::term(), TimeStamp::term(), ReplicaID::term()}.
-opaque crdt() :: {E::?SET:ordset(element()), V::vector()}.
-include("crdt_beh.hrl").
-spec new() -> crdt().
new() -> {?SET:new(), [0 || _ <- lists:seq(1, ?R)]}.
-spec merge(crdt(), crdt()) -> crdt().
merge(_CRDT1={E1, V1}, _CRDT2={E2, V2}) ->
M = ?SET:union(E1, E2),
T2 = ?SET:subtract(E1, E2),
M2 = ?SET:filter(fun({_E, C, I}) -> C > vector_get(I, V2) end, T2),
T3 = ?SET:subtract(E2, E1),
M3 = ?SET:filter(fun({_E, C, I}) -> C > vector_get(I, V1) end, T3),
U = ?SET:union([M, M2, M3]),
D = ?SET:fold(fun({E, C, I}, DictAcc) ->
dict:update({E,I}, fun(A) -> max(A, C) end, C, DictAcc)
end, dict:new(), U),
NewE = dict:fold(fun({E, I}, C, SetAcc) ->
?SET:add_element({E, C, I}, SetAcc)
end, ?SET:new(), D),
NewV = vector_max(V1, V2),
{NewE, NewV}.
-spec eq(crdt(), crdt()) -> boolean().
eq(_CRDT1={E1, V1}, _CRDT2={E2, V2}) ->
vector_eq(V1, V2) andalso ?SET:is_subset(E1, E2) andalso ?SET:is_subset(E2, E1).
-spec lteq(crdt(), crdt()) -> boolean().
lteq(_CRDT1={E1, V1}, _CRDT2={E2, V2}) ->
case vector_lteq(V1, V2) of
false -> false;
true ->
that V1 = < V2
Fun = fun({_, C, I}, SetAcc) ->
case C =< vector_get(I, V1) of
true -> ?SET:add_element({C, I}, SetAcc);
false -> SetAcc
end
end,
X = ?SET:fold(Fun, ?SET:new(), E1),
X2 = ?SET:fold(Fun, ?SET:new(), E2),
?SET:is_subset(X2, X)
end.
lteq implementation as specified in paper ... used for testing purposes
-spec lteq2(crdt(), crdt()) -> boolean().
lteq2(_CRDT1={E1, V1}, _CRDT2={E2, V2}) ->
case vector_lteq(V1, V2) of
false -> false;
true ->
TFun = fun({_, C, I}, SetAcc) -> ?SET:add_element({C,I}, SetAcc) end,
X1 = ?SET:fold(TFun, ?SET:new(), E1),
X2 = ?SET:fold(TFun, ?SET:new(), E2),
Possible1 = [{B, A} || A <- lists:seq(1, ?R), B <- lists:seq(1, vector_get(A, V1))],
Possible2 = [{B, A} || A <- lists:seq(1, ?R), B <- lists:seq(1, vector_get(A, V2))],
R1 = lists:foldl(fun(E, Acc) ->
case ?SET:is_element(E, X1) of
true -> Acc;
false -> ?SET:add_element(E, Acc)
end
end, ?SET:new(), Possible1),
R2 = lists:foldl(fun(E, Acc) ->
case ?SET:is_element(E, X2) of
true -> Acc;
false -> ?SET:add_element(E, Acc)
end
end, ?SET:new(), Possible2),
?SET:is_subset(R1, R2)
end.
-spec update_add(ReplicaId::non_neg_integer(), Element::term(), CRDT::crdt()) -> crdt().
update_add(ReplicaId, Element, _CRDT={E, V}) ->
{TimeStamp, V2} = vector_inc_and_get(ReplicaId, V),
E2 = ?SET:add_element({Element, TimeStamp, ReplicaId}, E),
E3 = ?SET:filter(fun({TE, TC, _TI}) ->
not (TE =:= Element andalso TC < TimeStamp)
end, E2),
{E3, V2}.
-spec update_remove(Element::term(), C::crdt()) -> crdt().
update_remove(Element, _CRDT={E, V}) ->
E2 = ?SET:filter(fun({TE, _TC, _TI}) -> Element =/= TE end, E),
{E2, V}.
-spec query_elements(crdt()) -> ?SET:ordset(element()).
query_elements(_CRDT={Elements, _V}) ->
?SET:fold(fun({E, _C, _I}, AccSet) -> ?SET:add_element(E, AccSet) end,
?SET:new(), Elements).
-spec query_contains(term(), crdt()) -> boolean().
query_contains(Element, _CRDT={Elements, _V}) ->
?SET:fold(fun({E, _C, _I}, _Acc) when Element =:= E -> true;
(_C, Acc) -> Acc
end, false, Elements).
TODO use dict instead of list ?
-spec vector_max(vector(), vector()) -> vector().
vector_max([], []) -> [];
vector_max([H1 | T1], [H2 | T2]) -> [max(H1, H2) | vector_max(T1, T2)].
-spec vector_get(non_neg_integer(), vector()) -> non_neg_integer().
vector_get(Idx, V) -> lists:nth(Idx, V).
-spec vector_inc_and_get(non_neg_integer(), vector()) -> {non_neg_integer(), vector()}.
vector_inc_and_get(Idx, V) ->
TimeStamp = lists:nth(Idx, V) + 1,
V2 = lists:sublist(V, Idx - 1) ++ [TimeStamp] ++ lists:nthtail(Idx, V),
{TimeStamp, V2}.
-spec vector_eq(vector(), vector()) -> boolean().
vector_eq(V1, V2) -> V1 =:= V2.
-spec vector_lteq(vector(), vector()) -> boolean().
vector_lteq([], []) -> true;
vector_lteq([H1 | _T1], [H2 | _T2]) when H1 > H2 -> false;
vector_lteq([_H1 | T1], [_H2 | T2]) -> vector_lteq(T1, T2).
|
3d314ef2aec06630c2633bd9a9082e89ad4dc9871aec3e039a23d56f0d6ad4c8 | patricoferris/ocaml-multicore-monorepo | test.ml | let pp_chr =
Fmt.using (function '\032' .. '\126' as x -> x | _ -> '.') Fmt.char
let pp_scalar : type buffer.
get:(buffer -> int -> char) -> length:(buffer -> int) -> buffer Fmt.t =
fun ~get ~length ppf b ->
let l = length b in
for i = 0 to l / 16 do
Fmt.pf ppf "%08x: " (i * 16) ;
let j = ref 0 in
while !j < 16 do
if (i * 16) + !j < l then
Fmt.pf ppf "%02x" (Char.code @@ get b ((i * 16) + !j))
else Fmt.pf ppf " " ;
if !j mod 2 <> 0 then Fmt.pf ppf " " ;
incr j
done ;
Fmt.pf ppf " " ;
j := 0 ;
while !j < 16 do
if (i * 16) + !j < l then Fmt.pf ppf "%a" pp_chr (get b ((i * 16) + !j))
else Fmt.pf ppf " " ;
incr j
done ;
Fmt.pf ppf "@\n"
done
let pp_raw = pp_scalar ~get:String.get ~length:String.length
exception Bigger_than_80_column of string
exception Malformed of string
let pp_value ppf = function
| `Line_break -> Fmt.string ppf "`Line_break"
| `Char chr -> Fmt.pf ppf "(`Char @[%02X@])" (Char.code chr)
| `End -> Fmt.string ppf "`End"
let iso input =
let encoder = Pecu.encoder `Manual in
let decoder = Pecu.decoder `Manual in
let tmp = Bytes.create 0x8000 in
let res = Bytes.create (String.length input) in
let buf = Buffer.create (String.length input * 2) in
let rec decode dpos epos =
if Pecu.decoder_dangerous decoder then
raise (Bigger_than_80_column (Buffer.contents buf)) ;
match Pecu.decode decoder with
| `Await -> encode dpos epos (Pecu.encode encoder `Await)
| `Data data ->
Bytes.blit_string data 0 res dpos (String.length data) ;
decode (dpos + String.length data) epos
| `Line line ->
Bytes.blit_string line 0 res dpos (String.length line) ;
Bytes.set res (dpos + String.length line) '\n' ;
decode (dpos + String.length line + 1) epos
| `End -> (Bytes.sub_string res 0 dpos, Buffer.contents buf)
| `Malformed s -> raise (Malformed s)
and encode dpos epos = function
| `Ok ->
if epos > String.length input
then
( Pecu.src decoder tmp 0 0
; decode dpos epos )
else
let cmd =
if epos >= String.length input then `End
else if input.[epos] = '\n' then `Line_break
else `Char input.[epos] in
encode dpos (succ epos) (Pecu.encode encoder cmd)
| `Partial ->
Buffer.add_subbytes buf tmp 0 (0x8000 - Pecu.dst_rem encoder) ;
Pecu.src decoder tmp 0 (0x8000 - Pecu.dst_rem encoder) ;
Pecu.dst encoder tmp 0 0x8000 ;
decode dpos epos in
Pecu.dst encoder tmp 0 0x8000 ;
let cmd = if String.length input > 0 then `Char input.[0] else `End in
encode 0 1 (Pecu.encode encoder cmd)
let ensure str =
Astring.String.cuts ~sep:"\r\n" str
|> List.iter (fun line ->
if String.length line > 76 then raise (Bigger_than_80_column line) )
let load_file file =
let ic = open_in file in
let ln = in_channel_length ic in
let rs = Bytes.create ln in
really_input ic rs 0 ln ; close_in ic ; Bytes.unsafe_to_string rs
let raw = Alcotest.testable pp_raw String.equal
let walk directory =
let rec go acc = function
| [] -> acc
| dir :: rest ->
let contents = Array.to_list (Sys.readdir dir) in
let contents = List.rev_map (Filename.concat dir) contents in
let dirs, files =
List.fold_left
(fun (dirs, files) kind ->
match (Unix.stat kind).Unix.st_kind with
| Unix.S_REG -> (dirs, kind :: files)
| Unix.S_DIR -> (kind :: dirs, files)
| Unix.S_BLK | Unix.S_CHR | Unix.S_FIFO | Unix.S_LNK
|Unix.S_SOCK ->
(dirs, files)
| exception Unix.Unix_error _ -> (dirs, files) )
([], []) contents
in
go (files @ acc) (dirs @ rest)
in
go [] [directory]
let test file =
Alcotest.test_case file `Quick
@@ fun () ->
let u = load_file file in
let v, o = iso u in
let () = ensure o in
Alcotest.(check raw) "iso" u v
let rfc2047 =
let make i (value, expect) =
Alcotest.test_case (Fmt.strf "rfc2047:%d" i) `Quick
@@ fun () ->
let decoder = Pecu.Inline.decoder (`String value) in
let buffer = Buffer.create (String.length value) in
let rec go () =
match Pecu.Inline.decode decoder with
| `Await -> assert false
| `Char chr -> Buffer.add_char buffer chr ; go ()
| `Malformed s -> raise (Malformed s)
| `End -> ()
in
go () ;
let result0 = Buffer.contents buffer in
Buffer.clear buffer ;
let encoder = Pecu.Inline.encoder (`Buffer buffer) in
String.iter (fun chr -> match Pecu.Inline.encode encoder (`Char chr) with
| `Ok -> ()
| `Partial -> assert false) result0 ;
let () = ignore @@ Pecu.Inline.encode encoder `End in
let result1 = Buffer.contents buffer in
Alcotest.(check string)
(Fmt.strf "compare %s with %s" result0 expect)
result0 expect ;
Alcotest.(check string)
(Fmt.strf "compare %s with %s" result1 value)
result1 value ;
in
List.mapi make
[ ("a", "a")
; ("a_b", "a b")
; ("Keith_Moore", "Keith Moore")
; ("Keld_J=F8rn_Simonsen", "Keld J\xf8rn Simonsen")
; ("Andr=E9", "Andr\xe9")
; ("Olle_J=E4rnefors", "Olle J\xe4rnefors")
; ("Patrick_F=E4ltstr=F6m", "Patrick F\xe4ltstr\xf6m") ]
let qp =
{qp|J'interdis aux marchands de vanter trop leurs marchandises. Car ils se font=
vite p=C3=A9dagogues et t'enseignent comme but ce qui n'est par essence qu=
'un moyen, et te trompant ainsi sur la route =C3=A0 suivre les voil=C3=A0 =
bient=C3=B4t qui te d=C3=A9gradent, car si leur musique est vulgaire il=
s te fabriquent pour te la vendre une =C3=A2me vulgaire.
=E2=80=94=E2=80=89Antoine de Saint-Exup=C3=A9ry, Citadelle (1948)
|qp}
let citadelle = {unicode|J'interdis aux marchands de vanter trop leurs marchandises. Car ils se font vite pédagogues et t'enseignent comme but ce qui n'est par essence qu'un moyen, et te trompant ainsi sur la route à suivre les voilà bientôt qui te dégradent, car si leur musique est vulgaire ils te fabriquent pour te la vendre une âme vulgaire.
— Antoine de Saint-Exupéry, Citadelle (1948)
|unicode}
let simple =
Alcotest.test_case "simple example" `Quick @@ fun () ->
let decoder = Pecu.decoder (`String qp) in
let rec fill decoder buf = match Pecu.decode decoder with
| `Await -> assert false
| `Line line ->
Buffer.add_string buf line ;
Buffer.add_char buf '\n' ;
fill decoder buf
| `Data str ->
Buffer.add_string buf str ;
fill decoder buf
| `Malformed err -> Alcotest.fail err
| `End -> Buffer.contents buf in
let result = fill decoder (Buffer.create 0x100) in
Alcotest.(check string) "contents" result citadelle
type pecu = [ `Await | `Data of string | `Line of string | `Malformed of string | `End ]
let print_and_return v = match v with
| `Await -> Fmt.pr "`Await.\n%!" ; v
| `Data data -> Fmt.pr "`Data %S.\n%!" data ; v
| `Line line -> Fmt.pr "`Line %S.\n%!" line ; v
| `Malformed err -> Fmt.pr "`Malformed %S.\n%!" err ; v
| `End -> Fmt.pr "`End.\n%!" ; v
[@@@warning "-8"]
let split_at_cr =
Alcotest.test_case "split at cr" `Quick @@ fun () ->
let decoder = Pecu.decoder `Manual in
let[@warning "-8"] `Await : pecu = Pecu.decode decoder in
Pecu.src decoder (Bytes.of_string "Hello=20World!\r") 0 15 ;
let[@warning "-8"] `Await : pecu = Pecu.decode decoder in
Pecu.src decoder (Bytes.of_string "\n") 0 1 ;
let[@warning "-8"] (`Line line : pecu) = print_and_return (Pecu.decode decoder) in
Alcotest.(check string) "Hello World!" line "Hello World!" ;
let[@warning "-8"] `Await : pecu = Pecu.decode decoder in
Pecu.src decoder Bytes.empty 0 0 ;
let[@warning "-8"] (`Data str : pecu) = Pecu.decode decoder in
Alcotest.(check string) "trailer" str "" ;
let[@warning "-8"] `End : pecu = print_and_return (Pecu.decode decoder) in
Alcotest.(check pass) "end of input" () ()
[@@@warning "+8"]
let tests () =
Alcotest.run "pecu"
[("input fuzz", List.map test (walk "contents")); ("simple", [ simple; split_at_cr ]); ("rfc2047", rfc2047)]
let () = tests ()
| null | https://raw.githubusercontent.com/patricoferris/ocaml-multicore-monorepo/22b441e6727bc303950b3b37c8fbc024c748fe55/duniverse/pecu/test/test.ml | ocaml | let pp_chr =
Fmt.using (function '\032' .. '\126' as x -> x | _ -> '.') Fmt.char
let pp_scalar : type buffer.
get:(buffer -> int -> char) -> length:(buffer -> int) -> buffer Fmt.t =
fun ~get ~length ppf b ->
let l = length b in
for i = 0 to l / 16 do
Fmt.pf ppf "%08x: " (i * 16) ;
let j = ref 0 in
while !j < 16 do
if (i * 16) + !j < l then
Fmt.pf ppf "%02x" (Char.code @@ get b ((i * 16) + !j))
else Fmt.pf ppf " " ;
if !j mod 2 <> 0 then Fmt.pf ppf " " ;
incr j
done ;
Fmt.pf ppf " " ;
j := 0 ;
while !j < 16 do
if (i * 16) + !j < l then Fmt.pf ppf "%a" pp_chr (get b ((i * 16) + !j))
else Fmt.pf ppf " " ;
incr j
done ;
Fmt.pf ppf "@\n"
done
let pp_raw = pp_scalar ~get:String.get ~length:String.length
exception Bigger_than_80_column of string
exception Malformed of string
let pp_value ppf = function
| `Line_break -> Fmt.string ppf "`Line_break"
| `Char chr -> Fmt.pf ppf "(`Char @[%02X@])" (Char.code chr)
| `End -> Fmt.string ppf "`End"
let iso input =
let encoder = Pecu.encoder `Manual in
let decoder = Pecu.decoder `Manual in
let tmp = Bytes.create 0x8000 in
let res = Bytes.create (String.length input) in
let buf = Buffer.create (String.length input * 2) in
let rec decode dpos epos =
if Pecu.decoder_dangerous decoder then
raise (Bigger_than_80_column (Buffer.contents buf)) ;
match Pecu.decode decoder with
| `Await -> encode dpos epos (Pecu.encode encoder `Await)
| `Data data ->
Bytes.blit_string data 0 res dpos (String.length data) ;
decode (dpos + String.length data) epos
| `Line line ->
Bytes.blit_string line 0 res dpos (String.length line) ;
Bytes.set res (dpos + String.length line) '\n' ;
decode (dpos + String.length line + 1) epos
| `End -> (Bytes.sub_string res 0 dpos, Buffer.contents buf)
| `Malformed s -> raise (Malformed s)
and encode dpos epos = function
| `Ok ->
if epos > String.length input
then
( Pecu.src decoder tmp 0 0
; decode dpos epos )
else
let cmd =
if epos >= String.length input then `End
else if input.[epos] = '\n' then `Line_break
else `Char input.[epos] in
encode dpos (succ epos) (Pecu.encode encoder cmd)
| `Partial ->
Buffer.add_subbytes buf tmp 0 (0x8000 - Pecu.dst_rem encoder) ;
Pecu.src decoder tmp 0 (0x8000 - Pecu.dst_rem encoder) ;
Pecu.dst encoder tmp 0 0x8000 ;
decode dpos epos in
Pecu.dst encoder tmp 0 0x8000 ;
let cmd = if String.length input > 0 then `Char input.[0] else `End in
encode 0 1 (Pecu.encode encoder cmd)
let ensure str =
Astring.String.cuts ~sep:"\r\n" str
|> List.iter (fun line ->
if String.length line > 76 then raise (Bigger_than_80_column line) )
let load_file file =
let ic = open_in file in
let ln = in_channel_length ic in
let rs = Bytes.create ln in
really_input ic rs 0 ln ; close_in ic ; Bytes.unsafe_to_string rs
let raw = Alcotest.testable pp_raw String.equal
let walk directory =
let rec go acc = function
| [] -> acc
| dir :: rest ->
let contents = Array.to_list (Sys.readdir dir) in
let contents = List.rev_map (Filename.concat dir) contents in
let dirs, files =
List.fold_left
(fun (dirs, files) kind ->
match (Unix.stat kind).Unix.st_kind with
| Unix.S_REG -> (dirs, kind :: files)
| Unix.S_DIR -> (kind :: dirs, files)
| Unix.S_BLK | Unix.S_CHR | Unix.S_FIFO | Unix.S_LNK
|Unix.S_SOCK ->
(dirs, files)
| exception Unix.Unix_error _ -> (dirs, files) )
([], []) contents
in
go (files @ acc) (dirs @ rest)
in
go [] [directory]
let test file =
Alcotest.test_case file `Quick
@@ fun () ->
let u = load_file file in
let v, o = iso u in
let () = ensure o in
Alcotest.(check raw) "iso" u v
let rfc2047 =
let make i (value, expect) =
Alcotest.test_case (Fmt.strf "rfc2047:%d" i) `Quick
@@ fun () ->
let decoder = Pecu.Inline.decoder (`String value) in
let buffer = Buffer.create (String.length value) in
let rec go () =
match Pecu.Inline.decode decoder with
| `Await -> assert false
| `Char chr -> Buffer.add_char buffer chr ; go ()
| `Malformed s -> raise (Malformed s)
| `End -> ()
in
go () ;
let result0 = Buffer.contents buffer in
Buffer.clear buffer ;
let encoder = Pecu.Inline.encoder (`Buffer buffer) in
String.iter (fun chr -> match Pecu.Inline.encode encoder (`Char chr) with
| `Ok -> ()
| `Partial -> assert false) result0 ;
let () = ignore @@ Pecu.Inline.encode encoder `End in
let result1 = Buffer.contents buffer in
Alcotest.(check string)
(Fmt.strf "compare %s with %s" result0 expect)
result0 expect ;
Alcotest.(check string)
(Fmt.strf "compare %s with %s" result1 value)
result1 value ;
in
List.mapi make
[ ("a", "a")
; ("a_b", "a b")
; ("Keith_Moore", "Keith Moore")
; ("Keld_J=F8rn_Simonsen", "Keld J\xf8rn Simonsen")
; ("Andr=E9", "Andr\xe9")
; ("Olle_J=E4rnefors", "Olle J\xe4rnefors")
; ("Patrick_F=E4ltstr=F6m", "Patrick F\xe4ltstr\xf6m") ]
let qp =
{qp|J'interdis aux marchands de vanter trop leurs marchandises. Car ils se font=
vite p=C3=A9dagogues et t'enseignent comme but ce qui n'est par essence qu=
'un moyen, et te trompant ainsi sur la route =C3=A0 suivre les voil=C3=A0 =
bient=C3=B4t qui te d=C3=A9gradent, car si leur musique est vulgaire il=
s te fabriquent pour te la vendre une =C3=A2me vulgaire.
=E2=80=94=E2=80=89Antoine de Saint-Exup=C3=A9ry, Citadelle (1948)
|qp}
let citadelle = {unicode|J'interdis aux marchands de vanter trop leurs marchandises. Car ils se font vite pédagogues et t'enseignent comme but ce qui n'est par essence qu'un moyen, et te trompant ainsi sur la route à suivre les voilà bientôt qui te dégradent, car si leur musique est vulgaire ils te fabriquent pour te la vendre une âme vulgaire.
— Antoine de Saint-Exupéry, Citadelle (1948)
|unicode}
let simple =
Alcotest.test_case "simple example" `Quick @@ fun () ->
let decoder = Pecu.decoder (`String qp) in
let rec fill decoder buf = match Pecu.decode decoder with
| `Await -> assert false
| `Line line ->
Buffer.add_string buf line ;
Buffer.add_char buf '\n' ;
fill decoder buf
| `Data str ->
Buffer.add_string buf str ;
fill decoder buf
| `Malformed err -> Alcotest.fail err
| `End -> Buffer.contents buf in
let result = fill decoder (Buffer.create 0x100) in
Alcotest.(check string) "contents" result citadelle
type pecu = [ `Await | `Data of string | `Line of string | `Malformed of string | `End ]
let print_and_return v = match v with
| `Await -> Fmt.pr "`Await.\n%!" ; v
| `Data data -> Fmt.pr "`Data %S.\n%!" data ; v
| `Line line -> Fmt.pr "`Line %S.\n%!" line ; v
| `Malformed err -> Fmt.pr "`Malformed %S.\n%!" err ; v
| `End -> Fmt.pr "`End.\n%!" ; v
[@@@warning "-8"]
let split_at_cr =
Alcotest.test_case "split at cr" `Quick @@ fun () ->
let decoder = Pecu.decoder `Manual in
let[@warning "-8"] `Await : pecu = Pecu.decode decoder in
Pecu.src decoder (Bytes.of_string "Hello=20World!\r") 0 15 ;
let[@warning "-8"] `Await : pecu = Pecu.decode decoder in
Pecu.src decoder (Bytes.of_string "\n") 0 1 ;
let[@warning "-8"] (`Line line : pecu) = print_and_return (Pecu.decode decoder) in
Alcotest.(check string) "Hello World!" line "Hello World!" ;
let[@warning "-8"] `Await : pecu = Pecu.decode decoder in
Pecu.src decoder Bytes.empty 0 0 ;
let[@warning "-8"] (`Data str : pecu) = Pecu.decode decoder in
Alcotest.(check string) "trailer" str "" ;
let[@warning "-8"] `End : pecu = print_and_return (Pecu.decode decoder) in
Alcotest.(check pass) "end of input" () ()
[@@@warning "+8"]
let tests () =
Alcotest.run "pecu"
[("input fuzz", List.map test (walk "contents")); ("simple", [ simple; split_at_cr ]); ("rfc2047", rfc2047)]
let () = tests ()
|
|
cf5f5c81025d5d55db210a6d4363f7c6e075697f5f5b1226c47a4e7ad8c62133 | ocaml-ppx/ppx | history.mli | * Represents the history of AST grammars in the OCaml compiler .
type t
(** Produces an association list of grammars, paired with their version numbers. *)
val versioned_grammars : t -> (Version.t * Grammar.t) list
(** Produces the grammar corresponding to a given version number. Raises if there is no
such version in the history. *)
val find_grammar : t -> version:Version.t -> Grammar.t
(** Converts the given AST from [src_version]'s grammar to [dst_version]'s grammar, using
the conversion functions stored in [t]. Converts ['node] to traverse and/or construct
subtrees using [unwrap] and [wrap], which may themselves call [convert] as
appropriate. *)
val convert
: t
-> 'node Ast.t
-> src_version:Version.t
-> dst_version:Version.t
-> unwrap:(version:Version.t -> 'node -> 'node Ast.t option)
-> wrap:(version:Version.t -> 'node Ast.t -> 'node)
-> Version.t * 'node Ast.t
(**/**)
(** Constructors for internal use and for testing. *)
type 'node conversion_function
= 'node Ast.t
-> unwrap:('node -> 'node Ast.t option)
-> wrap:('node Ast.t -> 'node)
-> 'node Ast.t option
type conversion =
{ src_version : Version.t
; dst_version : Version.t
; f : 'node . 'node conversion_function
}
* It is expected that [ versioned_grammars ] are provided consecutively in order , and that
[ conversions ] contains exactly one up - conversion and one down - conversion for each
consecutive pair of versions . Raises otherwise .
[conversions] contains exactly one up-conversion and one down-conversion for each
consecutive pair of versions. Raises otherwise. *)
val create
: versioned_grammars : (Version.t * Grammar.t) list
-> conversions : conversion list
-> t
| null | https://raw.githubusercontent.com/ocaml-ppx/ppx/40e5a35a4386d969effaf428078c900bd03b78ec/astlib/history.mli | ocaml | * Produces an association list of grammars, paired with their version numbers.
* Produces the grammar corresponding to a given version number. Raises if there is no
such version in the history.
* Converts the given AST from [src_version]'s grammar to [dst_version]'s grammar, using
the conversion functions stored in [t]. Converts ['node] to traverse and/or construct
subtrees using [unwrap] and [wrap], which may themselves call [convert] as
appropriate.
*/*
* Constructors for internal use and for testing. | * Represents the history of AST grammars in the OCaml compiler .
type t
val versioned_grammars : t -> (Version.t * Grammar.t) list
val find_grammar : t -> version:Version.t -> Grammar.t
val convert
: t
-> 'node Ast.t
-> src_version:Version.t
-> dst_version:Version.t
-> unwrap:(version:Version.t -> 'node -> 'node Ast.t option)
-> wrap:(version:Version.t -> 'node Ast.t -> 'node)
-> Version.t * 'node Ast.t
type 'node conversion_function
= 'node Ast.t
-> unwrap:('node -> 'node Ast.t option)
-> wrap:('node Ast.t -> 'node)
-> 'node Ast.t option
type conversion =
{ src_version : Version.t
; dst_version : Version.t
; f : 'node . 'node conversion_function
}
* It is expected that [ versioned_grammars ] are provided consecutively in order , and that
[ conversions ] contains exactly one up - conversion and one down - conversion for each
consecutive pair of versions . Raises otherwise .
[conversions] contains exactly one up-conversion and one down-conversion for each
consecutive pair of versions. Raises otherwise. *)
val create
: versioned_grammars : (Version.t * Grammar.t) list
-> conversions : conversion list
-> t
|
21069af0975abd3f99bdbec01bac242e46468c46f230a90cefecd80c712d1385 | Clozure/ccl | rubix.lisp | (in-package :cl-user)
(defparameter light0 nil)
(defparameter light0-pos (make-array 3 :initial-contents '(5.0 3.0 0.0) ;; default to distant light source
:element-type 'single-float))
(defparameter diffuse0 (make-array 4 :initial-contents '(0.0 0.0 0.0 1.0)
:element-type 'single-float))
(defparameter ambient0 (make-array 4 :initial-contents '(1.0 1.0 1.0 1.0)
:element-type 'single-float))
(defparameter specular0 (make-array 4 :initial-contents '(0.0 0.0 0.0 1.0)
:element-type 'single-float))
(defparameter global-ambient (make-array 4 :initial-contents '(1.0 1.0 1.0 1.0) :element-type 'single-float)) ;; really really dim grey light
(defclass rubix-opengl-view (ns:ns-opengl-view)
()
(:metaclass ns:+ns-object))
(objc:defmethod (#/prepareOpenGL :void) ((self rubix-opengl-view))
(declare (special *the-origin* *y-axis*))
default is
(#_glLoadIdentity)
(#_glFrustum -0.6d0 0.6d0 -0.6d0 0.6d0 10.0d0 20.0d0))
(#_glLoadIdentity)
(mylookat *camera-pos* *the-origin* *y-axis*)
(#_glShadeModel #$GL_SMOOTH)
(#_glClearColor 0.05 0.05 0.05 0.0)
these next three are all needed to enable the z - buffer
(#_glClearDepth 1.0d0)
(#_glEnable #$GL_DEPTH_TEST)
(#_glDepthFunc #$GL_LEQUAL)
(#_glHint #$GL_PERSPECTIVE_CORRECTION_HINT #$GL_NICEST)
(setf *cube* (make-instance 'rubix-cube))
(#_glEnable #$GL_LIGHTING)
(setf light0 (make-instance 'light :lightid #$GL_LIGHT0))
(setpointsource light0 t)
(setlocation light0 light0-pos)
(setdiffuse light0 diffuse0)
(setambient light0 ambient0)
(setspecular light0 specular0)
(on light0)
make room for 4 single - floats
(ccl::%copy-ivector-to-ptr global-ambient ; source
offset to first element ( alignment padding )
foreign-float-vector ; destination
0 ; byte offset in destination
(* 4 4)) ; number of bytes to copy
(#_glLightModelfv #$GL_LIGHT_MODEL_AMBIENT foreign-float-vector)) ;; <- coersion issue
(#_glFlush))
(objc:defmethod (#/drawRect: :void) ((self rubix-opengl-view) (a-rect :ns-rect))
(declare (ignorable a-rect))
;; drawing callback
(#_glClear (logior #$GL_COLOR_BUFFER_BIT #$GL_DEPTH_BUFFER_BIT))
(render *cube*)
(#_glFlush))
;; want to be able to send keystrokes to the rubix cube
#+ignore
(objc:defmethod (#/acceptsFirstResponder :<BOOL>) ((self rubix-opengl-view))
t)
;; want to be able to click and start dragging (without moving the window)
(objc:defmethod (#/acceptsFirstMouse: :<BOOL>) ((self rubix-opengl-view)
event)
(declare (ignore event))
t)
(defparameter *rubix-face-snap* 8.0) ; degrees
(objc:defmethod (#/mouseDown: :void) ((self rubix-opengl-view) the-event)
;; this makes dragging spin the cube
(cond ((zerop (logand #$NSControlKeyMask (#/modifierFlags the-event))) ; not ctrl-click
(let ((dragging-p t))
(let ((last-loc (#/locationInWindow the-event)))
(loop while dragging-p do
(let ((the-event (#/nextEventMatchingMask:
(#/window self)
(logior #$NSLeftMouseUpMask
#$NSLeftMouseDraggedMask))))
(let ((mouse-loc (#/locationInWindow the-event)))
(cond ((eq #$NSLeftMouseDragged (#/type the-event))
(let ((deltax (float
(- (pref mouse-loc :<NSP>oint.x)
(pref last-loc :<NSP>oint.x))
0.0f0))
(deltay (float
(- (pref last-loc :<NSP>oint.y)
(pref mouse-loc :<NSP>oint.y))
0.0f0))
(vert-rot-axis (cross *y-axis* *camera-pos*)))
(setf (pref last-loc :<NSP>oint.x) (pref mouse-loc :<NSP>oint.x)
(pref last-loc :<NSP>oint.y) (pref mouse-loc :<NSP>oint.y))
(rotate-relative *cube*
(mulquats (axis-angle->quat vert-rot-axis deltay)
(axis-angle->quat *y-axis* deltax))))
(#/setNeedsDisplay: self t))
(t
(setf dragging-p nil))))))
(#/setNeedsDisplay: self t))))
(t;; ctrl-click, do what right-click does... note that once
;; ctrl-click is done dragging will not require ctrl be held down
;; NOTE THE GRATUITOUS CUT-AND-PASTE, debug the right-mouse-down
;; version preferentially and update this one with fixes as needed
(let* ((first-loc (#/locationInWindow the-event))
(pick-loc (#/convertPoint:fromView: self first-loc +null-ptr+)))
(let ((dragging-p t)
(reference-snap 0))
(setf (turning-face *cube*) (render-for-selection
*cube*
(opengl:unproject (pref pick-loc :<NSP>oint.x)
(pref pick-loc :<NSP>oint.y)))
(face-turning-p *cube*) (when (numberp (turning-face *cube*)) t)
(face-theta *cube*) 0.0)
(loop while (and dragging-p (face-turning-p *cube*)) do
(let ((the-event (#/nextEventMatchingMask:
(#/window self)
(logior #$NSLeftMouseUpMask
#$NSLeftMouseDraggedMask))))
(let ((mouse-loc (#/locationInWindow the-event)))
(cond ((eq #$NSLeftMouseDragged (#/type the-event))
(let ((deltax (float
(- (ns:ns-point-x mouse-loc)
(ns:ns-point-x first-loc))
0.0f0)))
(multiple-value-bind (snap-to snap-dist) (round deltax 90.0)
(cond ((>= *rubix-face-snap* (abs snap-dist)) ; snap
;; update cube structure
(let ((rotations (- snap-to reference-snap)))
(cond ((zerop rotations) nil)
((< 0 rotations)
(dotimes (i rotations)
(turnfaceclockwise *cube* (turning-face *cube*)))
(setf reference-snap snap-to))
((> 0 rotations)
(dotimes (i (abs rotations))
(turnfacecounterclockwise *cube* (turning-face *cube*)))
(setf reference-snap snap-to))))
;; determine where face will be drawn
(setf (face-theta *cube*) 0.0))
(t ; no snap
(setf (face-theta *cube*) (- deltax (* 90.0 reference-snap))))
)))
(#/setNeedsDisplay: self t))
(t
(setf (face-turning-p *cube*) nil
(turning-face *cube*) nil
(face-theta *cube*) nil
dragging-p nil))))))
(#/setNeedsDisplay: self t)))
)))
(objc:defmethod (#/rightMouseDown: :void) ((self rubix-opengl-view) the-event)
;; this makes dragging left/right turn a face counterclockwise/clockwise
;; ... clicked-on face determines face turned
;; ... with an n-degree "snap"
;; ... with the snap updating the data structure
;; ... releasing the mouse clears rotation angle (face will snap to last position)
(let* ((first-loc (#/locationInWindow the-event))
(pick-loc (#/convertPoint:fromView: self first-loc +null-ptr+)))
(let ((dragging-p t)
(reference-snap 0))
(setf (turning-face *cube*) (render-for-selection
*cube*
(opengl:unproject (pref pick-loc :<NSP>oint.x)
(pref pick-loc :<NSP>oint.y)))
(face-turning-p *cube*) (when (numberp (turning-face *cube*)) t)
(face-theta *cube*) 0.0)
(loop while (and dragging-p (face-turning-p *cube*)) do
(let ((the-event (#/nextEventMatchingMask:
(#/window self)
(logior #$NSRightMouseUpMask
#$NSRightMouseDraggedMask))))
(let ((mouse-loc (#/locationInWindow the-event)))
(cond ((eq #$NSRightMouseDragged (#/type the-event))
(let ((deltax (float
(- (pref mouse-loc :<NSP>oint.x)
(pref first-loc :<NSP>oint.x))
0.0f0)))
(multiple-value-bind (snap-to snap-dist) (round deltax 90.0)
(cond ((>= *rubix-face-snap* (abs snap-dist)) ; snap
;; update cube structure
(let ((rotations (- snap-to reference-snap)))
(cond ((zerop rotations) nil)
((< 0 rotations)
(dotimes (i rotations)
(turnfaceclockwise *cube* (turning-face *cube*)))
(setf reference-snap snap-to))
((> 0 rotations)
(dotimes (i (abs rotations))
(turnfacecounterclockwise *cube* (turning-face *cube*)))
(setf reference-snap snap-to))))
;; determine where face will be drawn
(setf (face-theta *cube*) 0.0))
(t ; no snap
(setf (face-theta *cube*) (- deltax (* 90.0 reference-snap))))
)))
(#/setNeedsDisplay: self t))
(t
(setf (face-turning-p *cube*) nil
(turning-face *cube*) nil
(face-theta *cube*) nil
dragging-p nil))))))
(#/setNeedsDisplay: self t))))
(defclass rubix-window (ns:ns-window)
()
(:metaclass ns:+ns-object))
(defparameter *aluminum-margin* 5.0f0)
(defun run-rubix-demo ()
(let* ((w (gui::new-cocoa-window :class (find-class 'rubix-window)
:title "Rubix Cube"
:height 250
:width 250
:expandable nil))
(w-content-view (#/contentView w)))
(let ((w-frame (#/frame w-content-view)))
(ns:with-ns-rect (glview-rect *aluminum-margin*
*aluminum-margin*
(- (pref w-frame :<NSR>ect.size.width)
(* 2 *aluminum-margin*))
(- (pref w-frame :<NSR>ect.size.height)
*aluminum-margin*))
;; Q: why make-objc-instance here?
(let ((glview (make-instance 'rubix-opengl-view
:with-frame glview-rect
:pixel-format #+ignore
(#/defaultPixelFormat nsLns-opengl-view)
# $ NSOpenGLPFADoubleBuffer
#$NSOpenGLPFAAccelerated
#$NSOpenGLPFAColorSize 32
#$NSOpenGLPFADepthSize 32))))
(#/addSubview: w-content-view glview)
w)))))
| null | https://raw.githubusercontent.com/Clozure/ccl/6c1a9458f7a5437b73ec227e989aa5b825f32fd3/examples/rubix/rubix.lisp | lisp | default to distant light source
really really dim grey light
source
destination
byte offset in destination
number of bytes to copy
<- coersion issue
drawing callback
want to be able to send keystrokes to the rubix cube
want to be able to click and start dragging (without moving the window)
degrees
this makes dragging spin the cube
not ctrl-click
ctrl-click, do what right-click does... note that once
ctrl-click is done dragging will not require ctrl be held down
NOTE THE GRATUITOUS CUT-AND-PASTE, debug the right-mouse-down
version preferentially and update this one with fixes as needed
snap
update cube structure
determine where face will be drawn
no snap
this makes dragging left/right turn a face counterclockwise/clockwise
... clicked-on face determines face turned
... with an n-degree "snap"
... with the snap updating the data structure
... releasing the mouse clears rotation angle (face will snap to last position)
snap
update cube structure
determine where face will be drawn
no snap
Q: why make-objc-instance here? | (in-package :cl-user)
(defparameter light0 nil)
:element-type 'single-float))
(defparameter diffuse0 (make-array 4 :initial-contents '(0.0 0.0 0.0 1.0)
:element-type 'single-float))
(defparameter ambient0 (make-array 4 :initial-contents '(1.0 1.0 1.0 1.0)
:element-type 'single-float))
(defparameter specular0 (make-array 4 :initial-contents '(0.0 0.0 0.0 1.0)
:element-type 'single-float))
(defclass rubix-opengl-view (ns:ns-opengl-view)
()
(:metaclass ns:+ns-object))
(objc:defmethod (#/prepareOpenGL :void) ((self rubix-opengl-view))
(declare (special *the-origin* *y-axis*))
default is
(#_glLoadIdentity)
(#_glFrustum -0.6d0 0.6d0 -0.6d0 0.6d0 10.0d0 20.0d0))
(#_glLoadIdentity)
(mylookat *camera-pos* *the-origin* *y-axis*)
(#_glShadeModel #$GL_SMOOTH)
(#_glClearColor 0.05 0.05 0.05 0.0)
these next three are all needed to enable the z - buffer
(#_glClearDepth 1.0d0)
(#_glEnable #$GL_DEPTH_TEST)
(#_glDepthFunc #$GL_LEQUAL)
(#_glHint #$GL_PERSPECTIVE_CORRECTION_HINT #$GL_NICEST)
(setf *cube* (make-instance 'rubix-cube))
(#_glEnable #$GL_LIGHTING)
(setf light0 (make-instance 'light :lightid #$GL_LIGHT0))
(setpointsource light0 t)
(setlocation light0 light0-pos)
(setdiffuse light0 diffuse0)
(setambient light0 ambient0)
(setspecular light0 specular0)
(on light0)
make room for 4 single - floats
offset to first element ( alignment padding )
(#_glFlush))
(objc:defmethod (#/drawRect: :void) ((self rubix-opengl-view) (a-rect :ns-rect))
(declare (ignorable a-rect))
(#_glClear (logior #$GL_COLOR_BUFFER_BIT #$GL_DEPTH_BUFFER_BIT))
(render *cube*)
(#_glFlush))
#+ignore
(objc:defmethod (#/acceptsFirstResponder :<BOOL>) ((self rubix-opengl-view))
t)
(objc:defmethod (#/acceptsFirstMouse: :<BOOL>) ((self rubix-opengl-view)
event)
(declare (ignore event))
t)
(objc:defmethod (#/mouseDown: :void) ((self rubix-opengl-view) the-event)
(let ((dragging-p t))
(let ((last-loc (#/locationInWindow the-event)))
(loop while dragging-p do
(let ((the-event (#/nextEventMatchingMask:
(#/window self)
(logior #$NSLeftMouseUpMask
#$NSLeftMouseDraggedMask))))
(let ((mouse-loc (#/locationInWindow the-event)))
(cond ((eq #$NSLeftMouseDragged (#/type the-event))
(let ((deltax (float
(- (pref mouse-loc :<NSP>oint.x)
(pref last-loc :<NSP>oint.x))
0.0f0))
(deltay (float
(- (pref last-loc :<NSP>oint.y)
(pref mouse-loc :<NSP>oint.y))
0.0f0))
(vert-rot-axis (cross *y-axis* *camera-pos*)))
(setf (pref last-loc :<NSP>oint.x) (pref mouse-loc :<NSP>oint.x)
(pref last-loc :<NSP>oint.y) (pref mouse-loc :<NSP>oint.y))
(rotate-relative *cube*
(mulquats (axis-angle->quat vert-rot-axis deltay)
(axis-angle->quat *y-axis* deltax))))
(#/setNeedsDisplay: self t))
(t
(setf dragging-p nil))))))
(#/setNeedsDisplay: self t))))
(let* ((first-loc (#/locationInWindow the-event))
(pick-loc (#/convertPoint:fromView: self first-loc +null-ptr+)))
(let ((dragging-p t)
(reference-snap 0))
(setf (turning-face *cube*) (render-for-selection
*cube*
(opengl:unproject (pref pick-loc :<NSP>oint.x)
(pref pick-loc :<NSP>oint.y)))
(face-turning-p *cube*) (when (numberp (turning-face *cube*)) t)
(face-theta *cube*) 0.0)
(loop while (and dragging-p (face-turning-p *cube*)) do
(let ((the-event (#/nextEventMatchingMask:
(#/window self)
(logior #$NSLeftMouseUpMask
#$NSLeftMouseDraggedMask))))
(let ((mouse-loc (#/locationInWindow the-event)))
(cond ((eq #$NSLeftMouseDragged (#/type the-event))
(let ((deltax (float
(- (ns:ns-point-x mouse-loc)
(ns:ns-point-x first-loc))
0.0f0)))
(multiple-value-bind (snap-to snap-dist) (round deltax 90.0)
(let ((rotations (- snap-to reference-snap)))
(cond ((zerop rotations) nil)
((< 0 rotations)
(dotimes (i rotations)
(turnfaceclockwise *cube* (turning-face *cube*)))
(setf reference-snap snap-to))
((> 0 rotations)
(dotimes (i (abs rotations))
(turnfacecounterclockwise *cube* (turning-face *cube*)))
(setf reference-snap snap-to))))
(setf (face-theta *cube*) 0.0))
(setf (face-theta *cube*) (- deltax (* 90.0 reference-snap))))
)))
(#/setNeedsDisplay: self t))
(t
(setf (face-turning-p *cube*) nil
(turning-face *cube*) nil
(face-theta *cube*) nil
dragging-p nil))))))
(#/setNeedsDisplay: self t)))
)))
(objc:defmethod (#/rightMouseDown: :void) ((self rubix-opengl-view) the-event)
(let* ((first-loc (#/locationInWindow the-event))
(pick-loc (#/convertPoint:fromView: self first-loc +null-ptr+)))
(let ((dragging-p t)
(reference-snap 0))
(setf (turning-face *cube*) (render-for-selection
*cube*
(opengl:unproject (pref pick-loc :<NSP>oint.x)
(pref pick-loc :<NSP>oint.y)))
(face-turning-p *cube*) (when (numberp (turning-face *cube*)) t)
(face-theta *cube*) 0.0)
(loop while (and dragging-p (face-turning-p *cube*)) do
(let ((the-event (#/nextEventMatchingMask:
(#/window self)
(logior #$NSRightMouseUpMask
#$NSRightMouseDraggedMask))))
(let ((mouse-loc (#/locationInWindow the-event)))
(cond ((eq #$NSRightMouseDragged (#/type the-event))
(let ((deltax (float
(- (pref mouse-loc :<NSP>oint.x)
(pref first-loc :<NSP>oint.x))
0.0f0)))
(multiple-value-bind (snap-to snap-dist) (round deltax 90.0)
(let ((rotations (- snap-to reference-snap)))
(cond ((zerop rotations) nil)
((< 0 rotations)
(dotimes (i rotations)
(turnfaceclockwise *cube* (turning-face *cube*)))
(setf reference-snap snap-to))
((> 0 rotations)
(dotimes (i (abs rotations))
(turnfacecounterclockwise *cube* (turning-face *cube*)))
(setf reference-snap snap-to))))
(setf (face-theta *cube*) 0.0))
(setf (face-theta *cube*) (- deltax (* 90.0 reference-snap))))
)))
(#/setNeedsDisplay: self t))
(t
(setf (face-turning-p *cube*) nil
(turning-face *cube*) nil
(face-theta *cube*) nil
dragging-p nil))))))
(#/setNeedsDisplay: self t))))
(defclass rubix-window (ns:ns-window)
()
(:metaclass ns:+ns-object))
(defparameter *aluminum-margin* 5.0f0)
(defun run-rubix-demo ()
(let* ((w (gui::new-cocoa-window :class (find-class 'rubix-window)
:title "Rubix Cube"
:height 250
:width 250
:expandable nil))
(w-content-view (#/contentView w)))
(let ((w-frame (#/frame w-content-view)))
(ns:with-ns-rect (glview-rect *aluminum-margin*
*aluminum-margin*
(- (pref w-frame :<NSR>ect.size.width)
(* 2 *aluminum-margin*))
(- (pref w-frame :<NSR>ect.size.height)
*aluminum-margin*))
(let ((glview (make-instance 'rubix-opengl-view
:with-frame glview-rect
:pixel-format #+ignore
(#/defaultPixelFormat nsLns-opengl-view)
# $ NSOpenGLPFADoubleBuffer
#$NSOpenGLPFAAccelerated
#$NSOpenGLPFAColorSize 32
#$NSOpenGLPFADepthSize 32))))
(#/addSubview: w-content-view glview)
w)))))
|
36c676fe5c809d12e329d30d3bfaa0a72c60044e9ff571ca806b8baec5b51fab | ocramz/xeno | CPS.hs | {-# LANGUAGE MultiWayIf #-}
# LANGUAGE NamedFieldPuns #
# LANGUAGE ScopedTypeVariables #
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE BangPatterns #-}
# LANGUAGE TypeFamilies #
{-# LANGUAGE GADTs #-}
| SAX parser and API for XML .
module Xeno.SAX.CPS
( cps
) where
import Control.Exception
import Control.Monad.State.Strict
import Control.Monad.ST.Strict
import Control.Spork
import Data.ByteString (ByteString)
import qualified Data.ByteString as S
import qualified Data.ByteString.Char8 as S8
import qualified Data.ByteString.Unsafe as SU
import Data.Char(isSpace)
import Data.Functor.Identity
import Data.Monoid
import Data.Word
import Xeno.Types
import Data . Mutable
import Data.STRef
import Data . Vector . ( ( ! ) )
import qualified Data . Vector . as UV
import qualified Data.Vector.Unboxed as UV -}
import qualified Data.Vector.Unboxed.Mutable as UMV
import Xeno.SAX
cps :: Process (ST s b) -- initial processor
-> ST s (Process (ST s b), -- mutable processor
Process (ST s b) -> ST s () -- assign next processor
)
cps p = do
current <- newSTRef p
let next anotherProcess = writeSTRef current anotherProcess
return (Process {
openF = wrap1 current openF
, endOpenF = wrap1 current endOpenF
, closeF = wrap1 current closeF
, textF = wrap1 current textF
, cdataF = wrap1 current cdataF
, attrF = wrap2 current attrF
}, next)
: : ( t - > a - > ST s b ) - > a - > ST s b
wrap1 current aField arg = do
rec <- readSTRef current
aField rec arg
--wrap2 :: (t -> a -> b -> ST s c) -> a -> b -> ST s c
wrap2 current aField arg1 arg2 = do
rec <- readSTRef current
aField rec arg1 arg2
pushdown p = do
( proc , next ) < - cps p
stackSize < - newSTRef 0
stackAlloc < - newSTRef 16
stack < -
let call aProc = do
pushdown p = do
(proc, next) <- cps p
stackSize <- newSTRef 0
stackAlloc <- newSTRef 16
stack <-
let call aProc = do
-}
| null | https://raw.githubusercontent.com/ocramz/xeno/5a2607b6769f9e004a94348cabb4718e4c949747/src/Xeno/SAX/CPS.hs | haskell | # LANGUAGE MultiWayIf #
# LANGUAGE OverloadedStrings #
# LANGUAGE BangPatterns #
# LANGUAGE GADTs #
initial processor
mutable processor
assign next processor
wrap2 :: (t -> a -> b -> ST s c) -> a -> b -> ST s c | # LANGUAGE NamedFieldPuns #
# LANGUAGE ScopedTypeVariables #
# LANGUAGE TypeFamilies #
| SAX parser and API for XML .
module Xeno.SAX.CPS
( cps
) where
import Control.Exception
import Control.Monad.State.Strict
import Control.Monad.ST.Strict
import Control.Spork
import Data.ByteString (ByteString)
import qualified Data.ByteString as S
import qualified Data.ByteString.Char8 as S8
import qualified Data.ByteString.Unsafe as SU
import Data.Char(isSpace)
import Data.Functor.Identity
import Data.Monoid
import Data.Word
import Xeno.Types
import Data . Mutable
import Data.STRef
import Data . Vector . ( ( ! ) )
import qualified Data . Vector . as UV
import qualified Data.Vector.Unboxed as UV -}
import qualified Data.Vector.Unboxed.Mutable as UMV
import Xeno.SAX
)
cps p = do
current <- newSTRef p
let next anotherProcess = writeSTRef current anotherProcess
return (Process {
openF = wrap1 current openF
, endOpenF = wrap1 current endOpenF
, closeF = wrap1 current closeF
, textF = wrap1 current textF
, cdataF = wrap1 current cdataF
, attrF = wrap2 current attrF
}, next)
: : ( t - > a - > ST s b ) - > a - > ST s b
wrap1 current aField arg = do
rec <- readSTRef current
aField rec arg
wrap2 current aField arg1 arg2 = do
rec <- readSTRef current
aField rec arg1 arg2
pushdown p = do
( proc , next ) < - cps p
stackSize < - newSTRef 0
stackAlloc < - newSTRef 16
stack < -
let call aProc = do
pushdown p = do
(proc, next) <- cps p
stackSize <- newSTRef 0
stackAlloc <- newSTRef 16
stack <-
let call aProc = do
-}
|
9d515b2fe306cb521359832411fdc90b8eb8a11a21ac5da45f45ace38f4731cd | haskell-repa/repa | Binary.hs | # LANGUAGE FlexibleInstances , ScopedTypeVariables #
{-# OPTIONS -fno-warn-orphans #-}
| Reading and writing arrays as binary files .
module Data.Array.Repa.IO.Binary
( readArrayFromStorableFile
, writeArrayToStorableFile)
where
import Foreign.Storable
import Foreign.Ptr
import Foreign.ForeignPtr
import Foreign.Marshal.Alloc
import System.IO
import Data.Array.Repa as R
import Data.Array.Repa.Repr.ForeignPtr as R
import Prelude as P
import Control.Monad
-- | Read an array from a file.
Data appears in host byte order .
-- If the file size does match the provided shape then `error`.
readArrayFromStorableFile
:: forall a sh
. (Shape sh, Storable a)
=> FilePath
-> sh
-> IO (Array F sh a)
readArrayFromStorableFile filePath sh
= do
-- Determine number of bytes per element.
let (fake :: a) = undefined
let (bytes1 :: Integer) = fromIntegral $ sizeOf fake
-- Determine how many elements the whole file will give us.
h :: Handle <- openBinaryFile filePath ReadMode
bytesTotal <- hFileSize h
let lenTotal = bytesTotal `div` bytes1
let bytesExpected = bytes1 * lenTotal
when (bytesTotal /= bytesExpected)
$ error $ unlines
["Data.Array.Repa.IO.Binary.readArrayFromStorableFile: not a whole number of elements in file"
, "element length = " P.++ show bytes1
, "file size = " P.++ show bytesTotal
, "slack space = " P.++ show (bytesTotal `mod` bytes1) ]
let bytesTotal' = fromIntegral bytesTotal
buf :: Ptr a <- mallocBytes bytesTotal'
bytesRead <- hGetBuf h buf bytesTotal'
when (bytesTotal' /= bytesRead)
$ error "Data.Array.Repa.IO.Binary.readArrayFromStorableFile: read failed"
hClose h
fptr <- newForeignPtr finalizerFree buf
-- Converting the foreign ptr like this means that the array
-- elements are used directly from the buffer, and not copied.
let arr = R.fromForeignPtr sh fptr
return $ arr
-- | Write an array to a file.
Data appears in host byte order .
writeArrayToStorableFile
:: forall sh a r
. (Shape sh, Source r a, Storable a)
=> FilePath
-> Array r sh a
-> IO ()
writeArrayToStorableFile filePath arr
= do let bytes1 = sizeOf (arr R.! R.zeroDim)
let bytesTotal = bytes1 * (R.size $ R.extent arr)
buf :: Ptr a <- mallocBytes bytesTotal
fptr <- newForeignPtr finalizerFree buf
R.computeIntoP fptr (delay arr)
h <- openBinaryFile filePath WriteMode
hPutBuf h buf bytesTotal
hClose h
| null | https://raw.githubusercontent.com/haskell-repa/repa/c867025e99fd008f094a5b18ce4dabd29bed00ba/repa-io/Data/Array/Repa/IO/Binary.hs | haskell | # OPTIONS -fno-warn-orphans #
| Read an array from a file.
If the file size does match the provided shape then `error`.
Determine number of bytes per element.
Determine how many elements the whole file will give us.
Converting the foreign ptr like this means that the array
elements are used directly from the buffer, and not copied.
| Write an array to a file. | # LANGUAGE FlexibleInstances , ScopedTypeVariables #
| Reading and writing arrays as binary files .
module Data.Array.Repa.IO.Binary
( readArrayFromStorableFile
, writeArrayToStorableFile)
where
import Foreign.Storable
import Foreign.Ptr
import Foreign.ForeignPtr
import Foreign.Marshal.Alloc
import System.IO
import Data.Array.Repa as R
import Data.Array.Repa.Repr.ForeignPtr as R
import Prelude as P
import Control.Monad
Data appears in host byte order .
readArrayFromStorableFile
:: forall a sh
. (Shape sh, Storable a)
=> FilePath
-> sh
-> IO (Array F sh a)
readArrayFromStorableFile filePath sh
= do
let (fake :: a) = undefined
let (bytes1 :: Integer) = fromIntegral $ sizeOf fake
h :: Handle <- openBinaryFile filePath ReadMode
bytesTotal <- hFileSize h
let lenTotal = bytesTotal `div` bytes1
let bytesExpected = bytes1 * lenTotal
when (bytesTotal /= bytesExpected)
$ error $ unlines
["Data.Array.Repa.IO.Binary.readArrayFromStorableFile: not a whole number of elements in file"
, "element length = " P.++ show bytes1
, "file size = " P.++ show bytesTotal
, "slack space = " P.++ show (bytesTotal `mod` bytes1) ]
let bytesTotal' = fromIntegral bytesTotal
buf :: Ptr a <- mallocBytes bytesTotal'
bytesRead <- hGetBuf h buf bytesTotal'
when (bytesTotal' /= bytesRead)
$ error "Data.Array.Repa.IO.Binary.readArrayFromStorableFile: read failed"
hClose h
fptr <- newForeignPtr finalizerFree buf
let arr = R.fromForeignPtr sh fptr
return $ arr
Data appears in host byte order .
writeArrayToStorableFile
:: forall sh a r
. (Shape sh, Source r a, Storable a)
=> FilePath
-> Array r sh a
-> IO ()
writeArrayToStorableFile filePath arr
= do let bytes1 = sizeOf (arr R.! R.zeroDim)
let bytesTotal = bytes1 * (R.size $ R.extent arr)
buf :: Ptr a <- mallocBytes bytesTotal
fptr <- newForeignPtr finalizerFree buf
R.computeIntoP fptr (delay arr)
h <- openBinaryFile filePath WriteMode
hPutBuf h buf bytesTotal
hClose h
|
bea795736bbc29bf4f0ea5e8f09c1586caff9babbd31ac4dc414f187bf424146 | duct-framework/scheduler.simple | simple.clj | (ns duct.scheduler.simple
(:require [integrant.core :as ig])
(:import [java.util.concurrent Executors ExecutorService TimeUnit]))
(defmethod ig/init-key :duct.scheduler/simple
[_ {:keys [thread-pool-size jobs] :or {thread-pool-size 32}}]
(let [executor (Executors/newScheduledThreadPool thread-pool-size)]
(doseq [{:keys [delay interval run]} jobs]
(let [delay-ms (long (* 1000 (or delay interval)))
interval-ms (long (* 1000 interval))]
(.scheduleAtFixedRate executor
^Runnable run
delay-ms
interval-ms
TimeUnit/MILLISECONDS)))
executor))
(defmethod ig/halt-key! :duct.scheduler/simple [_ ^ExecutorService service]
(.shutdownNow service))
| null | https://raw.githubusercontent.com/duct-framework/scheduler.simple/44e2f9c9b90fa1177158ed9fca11f55a220025db/src/duct/scheduler/simple.clj | clojure | (ns duct.scheduler.simple
(:require [integrant.core :as ig])
(:import [java.util.concurrent Executors ExecutorService TimeUnit]))
(defmethod ig/init-key :duct.scheduler/simple
[_ {:keys [thread-pool-size jobs] :or {thread-pool-size 32}}]
(let [executor (Executors/newScheduledThreadPool thread-pool-size)]
(doseq [{:keys [delay interval run]} jobs]
(let [delay-ms (long (* 1000 (or delay interval)))
interval-ms (long (* 1000 interval))]
(.scheduleAtFixedRate executor
^Runnable run
delay-ms
interval-ms
TimeUnit/MILLISECONDS)))
executor))
(defmethod ig/halt-key! :duct.scheduler/simple [_ ^ExecutorService service]
(.shutdownNow service))
|
|
262e24e3748ee25cd5f53b945fa0d9b188fbe265f414ab2fef1f3ca7ffe57ff7 | opencog/opencog | filter-#2.scm | ;; antecedent is "pronoun"
;; Example:
;; "He is good at math. She is good at math as well."
;; "She" cannot refer to "He".
(define filter-#2
(BindLink
(VariableList
(TypedVariableLink
(VariableNode "$word-inst-antecedent")
(TypeNode "WordInstanceNode")
)
(TypedVariableLink
(VariableNode "$word-inst-anaphor")
(TypeNode "WordInstanceNode")
)
)
(AndLink
Connection between two clauses
(ListLink
(AnchorNode "CurrentResolution")
(VariableNode "$word-inst-anaphor")
(VariableNode "$word-inst-antecedent")
)
(ListLink
(AnchorNode "CurrentPronoun")
(VariableNode "$word-inst-anaphor")
)
(ListLink
(AnchorNode "CurrentProposal")
(VariableNode "$word-inst-antecedent")
)
;; filter
(InheritanceLink
(VariableNode "$word-inst-antecedent")
(DefinedLinguisticConceptNode "pronoun")
)
)
(ListLink
(AnchorNode "CurrentResult")
(VariableNode "$word-inst-antecedent")
)
)
)
| null | https://raw.githubusercontent.com/opencog/opencog/53f2c2c8e26160e3321b399250afb0e3dbc64d4c/opencog/nlp/anaphora/rules/filters/filter-%232.scm | scheme | antecedent is "pronoun"
Example:
"He is good at math. She is good at math as well."
"She" cannot refer to "He".
filter |
(define filter-#2
(BindLink
(VariableList
(TypedVariableLink
(VariableNode "$word-inst-antecedent")
(TypeNode "WordInstanceNode")
)
(TypedVariableLink
(VariableNode "$word-inst-anaphor")
(TypeNode "WordInstanceNode")
)
)
(AndLink
Connection between two clauses
(ListLink
(AnchorNode "CurrentResolution")
(VariableNode "$word-inst-anaphor")
(VariableNode "$word-inst-antecedent")
)
(ListLink
(AnchorNode "CurrentPronoun")
(VariableNode "$word-inst-anaphor")
)
(ListLink
(AnchorNode "CurrentProposal")
(VariableNode "$word-inst-antecedent")
)
(InheritanceLink
(VariableNode "$word-inst-antecedent")
(DefinedLinguisticConceptNode "pronoun")
)
)
(ListLink
(AnchorNode "CurrentResult")
(VariableNode "$word-inst-antecedent")
)
)
)
|
175ef44af55d433cacb77075058d3f2e45714a3014debb05c39aec86375c04d7 | clash-lang/clash-prelude | ROM.hs | |
Copyright : ( C ) 2015 - 2016 , University of Twente ,
2017 , Google Inc.
License : BSD2 ( see the file LICENSE )
Maintainer : < >
ROMs
Copyright : (C) 2015-2016, University of Twente,
2017 , Google Inc.
License : BSD2 (see the file LICENSE)
Maintainer : Christiaan Baaij <>
ROMs
-}
# LANGUAGE DataKinds #
{-# LANGUAGE GADTs #-}
# LANGUAGE MagicHash #
# LANGUAGE TypeOperators #
# LANGUAGE Trustworthy #
# OPTIONS_GHC -fplugin GHC.TypeLits . KnownNat . Solver #
{-# OPTIONS_HADDOCK show-extensions #-}
module Clash.Explicit.ROM
( -- * Synchronous ROM synchronised to an arbitrary clock
rom
, romPow2
-- * Internal
, rom#
)
where
import Data.Array ((!),listArray)
import GHC.Stack (withFrozenCallStack)
import GHC.TypeLits (KnownNat, type (^))
import Prelude hiding (length)
import Clash.Signal.Internal (Clock (..), Signal (..))
import Clash.Sized.Unsigned (Unsigned)
import Clash.Sized.Vector (Vec, length, toList)
import Clash.XException (errorX, seqX)
| A ROM with a synchronous read port , with space for 2^@n@ elements
--
* _ _ NB _ _ : Read value is delayed by 1 cycle
-- * __NB__: Initial output value is 'undefined'
--
-- Additional helpful information:
--
* See " Clash . Sized . Fixed#creatingdatafiles " and " Clash . Explicit . BlockRam#usingrams "
-- for ideas on how to use ROMs and RAMs
romPow2
:: KnownNat n
=> Clock domain gated -- ^ 'Clock' to synchronize to
-> Vec (2^n) a -- ^ ROM content
--
-- __NB:__ must be a constant
-> Signal domain (Unsigned n) -- ^ Read address @rd@
-> Signal domain a -- ^ The value of the ROM at address @rd@
romPow2 = rom
# INLINE romPow2 #
| A ROM with a synchronous read port , with space for @n@ elements
--
* _ _ NB _ _ : Read value is delayed by 1 cycle
-- * __NB__: Initial output value is 'undefined'
--
-- Additional helpful information:
--
* See " Clash . Sized . Fixed#creatingdatafiles " and " Clash . Explicit . BlockRam#usingrams "
-- for ideas on how to use ROMs and RAMs
rom
:: (KnownNat n, Enum addr)
=> Clock domain gated -- ^ 'Clock' to synchronize to
-> Vec n a -- ^ ROM content
--
-- __NB:__ must be a constant
-> Signal domain addr -- ^ Read address @rd@
-> Signal domain a
-- ^ The value of the ROM at address @rd@ from the previous clock cycle
rom = \clk content rd -> rom# clk content (fromEnum <$> rd)
# INLINE rom #
-- | ROM primitive
rom#
:: KnownNat n
=> Clock domain gated -- ^ 'Clock' to synchronize to
-> Vec n a -- ^ ROM content
--
-- __NB:__ must be a constant
-> Signal domain Int -- ^ Read address @rd@
-> Signal domain a
-- ^ The value of the ROM at address @rd@ from the previous clock cycle
rom# clk content rd = go clk ((arr !) <$> rd)
where
szI = length content
arr = listArray (0,szI-1) (toList content)
go :: Clock domain gated
-> Signal domain a
-> Signal domain a
go Clock {} =
\s -> withFrozenCallStack (errorX "rom: initial value undefined") :- s
go (GatedClock _ _ en) =
go' (withFrozenCallStack (errorX "rom: initial value undefined")) en
go' o (e :- es) as@(~(x :- xs)) =
-- See [Note: register strictness annotations]
o `seqX` o :- (as `seq` if e then go' x es xs else go' o es xs)
# NOINLINE rom # #
| null | https://raw.githubusercontent.com/clash-lang/clash-prelude/5645d8417ab495696cf4e0293796133c7fe2a9a7/src/Clash/Explicit/ROM.hs | haskell | # LANGUAGE GADTs #
# OPTIONS_HADDOCK show-extensions #
* Synchronous ROM synchronised to an arbitrary clock
* Internal
* __NB__: Initial output value is 'undefined'
Additional helpful information:
for ideas on how to use ROMs and RAMs
^ 'Clock' to synchronize to
^ ROM content
__NB:__ must be a constant
^ Read address @rd@
^ The value of the ROM at address @rd@
* __NB__: Initial output value is 'undefined'
Additional helpful information:
for ideas on how to use ROMs and RAMs
^ 'Clock' to synchronize to
^ ROM content
__NB:__ must be a constant
^ Read address @rd@
^ The value of the ROM at address @rd@ from the previous clock cycle
| ROM primitive
^ 'Clock' to synchronize to
^ ROM content
__NB:__ must be a constant
^ Read address @rd@
^ The value of the ROM at address @rd@ from the previous clock cycle
See [Note: register strictness annotations] | |
Copyright : ( C ) 2015 - 2016 , University of Twente ,
2017 , Google Inc.
License : BSD2 ( see the file LICENSE )
Maintainer : < >
ROMs
Copyright : (C) 2015-2016, University of Twente,
2017 , Google Inc.
License : BSD2 (see the file LICENSE)
Maintainer : Christiaan Baaij <>
ROMs
-}
# LANGUAGE DataKinds #
# LANGUAGE MagicHash #
# LANGUAGE TypeOperators #
# LANGUAGE Trustworthy #
# OPTIONS_GHC -fplugin GHC.TypeLits . KnownNat . Solver #
module Clash.Explicit.ROM
rom
, romPow2
, rom#
)
where
import Data.Array ((!),listArray)
import GHC.Stack (withFrozenCallStack)
import GHC.TypeLits (KnownNat, type (^))
import Prelude hiding (length)
import Clash.Signal.Internal (Clock (..), Signal (..))
import Clash.Sized.Unsigned (Unsigned)
import Clash.Sized.Vector (Vec, length, toList)
import Clash.XException (errorX, seqX)
| A ROM with a synchronous read port , with space for 2^@n@ elements
* _ _ NB _ _ : Read value is delayed by 1 cycle
* See " Clash . Sized . Fixed#creatingdatafiles " and " Clash . Explicit . BlockRam#usingrams "
romPow2
:: KnownNat n
romPow2 = rom
# INLINE romPow2 #
| A ROM with a synchronous read port , with space for @n@ elements
* _ _ NB _ _ : Read value is delayed by 1 cycle
* See " Clash . Sized . Fixed#creatingdatafiles " and " Clash . Explicit . BlockRam#usingrams "
rom
:: (KnownNat n, Enum addr)
-> Signal domain a
rom = \clk content rd -> rom# clk content (fromEnum <$> rd)
# INLINE rom #
rom#
:: KnownNat n
-> Signal domain a
rom# clk content rd = go clk ((arr !) <$> rd)
where
szI = length content
arr = listArray (0,szI-1) (toList content)
go :: Clock domain gated
-> Signal domain a
-> Signal domain a
go Clock {} =
\s -> withFrozenCallStack (errorX "rom: initial value undefined") :- s
go (GatedClock _ _ en) =
go' (withFrozenCallStack (errorX "rom: initial value undefined")) en
go' o (e :- es) as@(~(x :- xs)) =
o `seqX` o :- (as `seq` if e then go' x es xs else go' o es xs)
# NOINLINE rom # #
|
0270ba2dc90190f7f4d47c850cd1fc7899d38a219b633ae14e5c7e0abf7ad0c4 | alanz/ghc-exactprint | Test10312.hs | {-# LANGUAGE ParallelListComp,
TransformListComp,
RecordWildCards #-}
module Test10312 where
-- From
-- -posts/2014-12-07-list-comprehensions.html
import GHC.Exts
import qualified Data.Map as M
import Data.Ord (comparing)
import Data.List (sortBy)
-- Let’s look at a simple, normal list comprehension to start:
regularListComp :: [Int]
regularListComp = [ x + y * z
| x <- [0..10]
, y <- [10..20]
, z <- [20..30]
]
parallelListComp :: [Int]
parallelListComp = [ x + y * z
| x <- [0..10]
| y <- [10..20]
| z <- [20..30]
]
fibs : : [ Int ]
fibs = 0 : 1 : zipWith ( + ) fibs ( tail fibs )
fibs :: [Int]
fibs = 0 : 1 : [ x + y
| x <- fibs
| y <- tail fibs
]
fiblikes :: [Int]
fiblikes = 0 : 1 : [ x + y + z
| x <- fibs
| y <- tail fibs
| z <- tail (tail fibs)
]
-- TransformListComp
data Character = Character
{ firstName :: String
, lastName :: String
, birthYear :: Int
} deriving (Show, Eq)
friends :: [Character]
friends = [ Character "Phoebe" "Buffay" 1963
, Character "Chandler" "Bing" 1969
, Character "Rachel" "Green" 1969
, Character "Joey" "Tribbiani" 1967
, Character "Monica" "Geller" 1964
, Character "Ross" "Geller" 1966
]
oldest :: Int -> [Character] -> [String]
oldest k tbl = [ firstName ++ " " ++ lastName
| Character{..} <- tbl
, then sortWith by birthYear
, then take k
]
groupByLargest :: Ord b => (a -> b) -> [a] -> [[a]]
groupByLargest f = sortBy (comparing (negate . length)) . groupWith f
bestBirthYears :: [Character] -> [(Int, [String])]
bestBirthYears tbl = [ (the birthYear, firstName)
| Character{..} <- tbl
, then group by birthYear using groupByLargest
]
uniq_fs = [ (n, the p, the d') | (n, Fixity p d) <- fs
, let d' = ppDir d
, then group by Down (p,d') using groupWith ]
| null | https://raw.githubusercontent.com/alanz/ghc-exactprint/b6b75027811fa4c336b34122a7a7b1a8df462563/tests/examples/ghc80/Test10312.hs | haskell | # LANGUAGE ParallelListComp,
TransformListComp,
RecordWildCards #
From
-posts/2014-12-07-list-comprehensions.html
Let’s look at a simple, normal list comprehension to start:
TransformListComp | module Test10312 where
import GHC.Exts
import qualified Data.Map as M
import Data.Ord (comparing)
import Data.List (sortBy)
regularListComp :: [Int]
regularListComp = [ x + y * z
| x <- [0..10]
, y <- [10..20]
, z <- [20..30]
]
parallelListComp :: [Int]
parallelListComp = [ x + y * z
| x <- [0..10]
| y <- [10..20]
| z <- [20..30]
]
fibs : : [ Int ]
fibs = 0 : 1 : zipWith ( + ) fibs ( tail fibs )
fibs :: [Int]
fibs = 0 : 1 : [ x + y
| x <- fibs
| y <- tail fibs
]
fiblikes :: [Int]
fiblikes = 0 : 1 : [ x + y + z
| x <- fibs
| y <- tail fibs
| z <- tail (tail fibs)
]
data Character = Character
{ firstName :: String
, lastName :: String
, birthYear :: Int
} deriving (Show, Eq)
friends :: [Character]
friends = [ Character "Phoebe" "Buffay" 1963
, Character "Chandler" "Bing" 1969
, Character "Rachel" "Green" 1969
, Character "Joey" "Tribbiani" 1967
, Character "Monica" "Geller" 1964
, Character "Ross" "Geller" 1966
]
oldest :: Int -> [Character] -> [String]
oldest k tbl = [ firstName ++ " " ++ lastName
| Character{..} <- tbl
, then sortWith by birthYear
, then take k
]
groupByLargest :: Ord b => (a -> b) -> [a] -> [[a]]
groupByLargest f = sortBy (comparing (negate . length)) . groupWith f
bestBirthYears :: [Character] -> [(Int, [String])]
bestBirthYears tbl = [ (the birthYear, firstName)
| Character{..} <- tbl
, then group by birthYear using groupByLargest
]
uniq_fs = [ (n, the p, the d') | (n, Fixity p d) <- fs
, let d' = ppDir d
, then group by Down (p,d') using groupWith ]
|
f24f402cf059413b03c7d20b705855aaabbaf604d5e4804d3a467985f7cde843 | input-output-hk/cardano-sl | Communication.hs | -- | Re-exports of Pos.Communication.*
module Pos.Communication
( module M
) where
import Pos.Communication.Limits as M
import Pos.Communication.Server as M
import Pos.Communication.Types as M
import Pos.Infra.Communication.BiP as M
import Pos.Infra.Communication.Listener as M
import Pos.Infra.Communication.Protocol as M
import Pos.Infra.Communication.Relay as M
import Pos.Infra.Communication.Specs as M
| null | https://raw.githubusercontent.com/input-output-hk/cardano-sl/1499214d93767b703b9599369a431e67d83f10a2/lib/src/Pos/Communication.hs | haskell | | Re-exports of Pos.Communication.* |
module Pos.Communication
( module M
) where
import Pos.Communication.Limits as M
import Pos.Communication.Server as M
import Pos.Communication.Types as M
import Pos.Infra.Communication.BiP as M
import Pos.Infra.Communication.Listener as M
import Pos.Infra.Communication.Protocol as M
import Pos.Infra.Communication.Relay as M
import Pos.Infra.Communication.Specs as M
|
d81d1e13b3982de3f3a1a5277b39b91d5a7c3879832582ce3d845cf4d9ec2c16 | VisionsGlobalEmpowerment/webchange | icon_duplicate.cljs | (ns webchange.ui.components.icon.system.icon-duplicate)
(def data
[:svg {:xmlns ""
:width "24" :height "24" :viewBox "0 0 24 24"
:class-name "stroke-colored"
:fill "none" :stroke "#3453A1" :stroke-width "2" :stroke-linecap "round" :stroke-linejoin "round"}
[:path {:d "M15 15H16.3125H18V6H9V9"}]
[:path {:d "M15 9H6V18H15V9Z"}]])
| null | https://raw.githubusercontent.com/VisionsGlobalEmpowerment/webchange/e5747e187937d85e9c92c728d52a704f323f00ef/src/cljs/webchange/ui/components/icon/system/icon_duplicate.cljs | clojure | (ns webchange.ui.components.icon.system.icon-duplicate)
(def data
[:svg {:xmlns ""
:width "24" :height "24" :viewBox "0 0 24 24"
:class-name "stroke-colored"
:fill "none" :stroke "#3453A1" :stroke-width "2" :stroke-linecap "round" :stroke-linejoin "round"}
[:path {:d "M15 15H16.3125H18V6H9V9"}]
[:path {:d "M15 9H6V18H15V9Z"}]])
|
|
7ec6902d45ebf5a71cc7c5bd7c4011c6e416306bd028d306174d8d2da3f665db | cubicle-model-checker/cubicle | hstring.mli | (**************************************************************************)
(* *)
Cubicle
(* *)
Copyright ( C ) 2011 - 2014
(* *)
and
Universite Paris - Sud 11
(* *)
(* *)
This file is distributed under the terms of the Apache Software
(* License version 2.0 *)
(* *)
(**************************************************************************)
(** Hash-consed strings
Hash-consing is a technique to share values that are structurally
equal. More details on
{{:} Wikipedia} and
{{:/~filliatr/ftp/publis/hash-consing2.pdf} here}.
This module provides an easy way to use hash-consing for strings.
*)
open Hashcons
type t = string hash_consed
(** The type of Hash-consed string *)
val make : string -> t
(** [make s] builds ans returns a hash-consed string from [s].*)
val view : t -> string
(** [view hs] returns the string corresponding to [hs].*)
val equal : t -> t -> bool
(** [equal x y] returns [true] if [x] and [y] are the same hash-consed string
(constant time).*)
val compare : t -> t -> int
(** [compares x y] returns [0] if [x] and [y] are equal, and is unspecified
otherwise but provides a total ordering on hash-consed strings.*)
val hash : t -> int
(** [hash x] returns the integer (hash) associated to [x].*)
val empty : t
(** the empty ([""]) hash-consed string.*)
val list_assoc : t -> (t * 'a) list -> 'a
(** [list_assoc x l] returns the element associated with [x] in the list of
pairs [l].
@raise Not_found if there is no value associated with [x] in the list [l].*)
val list_assoc_inv : t -> ('a * t) list -> 'a
* [ list_assoc_inv x l ] returns the first element which is associated to [ x ]
in the list of pairs [ l ] .
@raise Not_found if there is no value associated to [ x ] in the list [ l ] .
in the list of pairs [l].
@raise Not_found if there is no value associated to [x] in the list [l].*)
val list_mem_assoc : t -> (t * 'a) list -> bool
(** Same as {! list_assoc}, but simply returns [true] if a binding exists, and
[false] if no bindings exist for the given key.*)
val list_mem : t -> t list -> bool
(** [list_mem x l] is [true] if and only if [x] is equal to an element of [l].*)
val list_mem_couple : t * t -> (t * t) list -> bool
(** [list_mem_couple (x,y) l] is [true] if and only if [(x,y)] is equal to an
element of [l].*)
val compare_list : t list -> t list -> int
(** [compare_list l1 l2] returns [0] if and only if [l1] is equal to [l2].*)
val list_equal : t list -> t list -> bool
(** [list_equal l1 l2] returns [true] if and only if [l1] is equal to [l2].*)
val print : Format.formatter -> t -> unit
(** Prints a hash-consed strings on a formatter. *)
val print_list : string -> Format.formatter -> t list -> unit
(** Prints a list of hash-consed strings on a formatter. *)
module H : Hashtbl.S with type key = t
(** Hash-tables indexed by hash-consed strings *)
module HSet : Set.S with type elt = t
(** Sets of hash-consed strings *)
module HMap : Map.S with type key = t
(** Maps indexed by hash-consed strings *)
| null | https://raw.githubusercontent.com/cubicle-model-checker/cubicle/00f09bb2d4bb496549775e770d7ada08bc1e4866/common/hstring.mli | ocaml | ************************************************************************
License version 2.0
************************************************************************
* Hash-consed strings
Hash-consing is a technique to share values that are structurally
equal. More details on
{{:} Wikipedia} and
{{:/~filliatr/ftp/publis/hash-consing2.pdf} here}.
This module provides an easy way to use hash-consing for strings.
* The type of Hash-consed string
* [make s] builds ans returns a hash-consed string from [s].
* [view hs] returns the string corresponding to [hs].
* [equal x y] returns [true] if [x] and [y] are the same hash-consed string
(constant time).
* [compares x y] returns [0] if [x] and [y] are equal, and is unspecified
otherwise but provides a total ordering on hash-consed strings.
* [hash x] returns the integer (hash) associated to [x].
* the empty ([""]) hash-consed string.
* [list_assoc x l] returns the element associated with [x] in the list of
pairs [l].
@raise Not_found if there is no value associated with [x] in the list [l].
* Same as {! list_assoc}, but simply returns [true] if a binding exists, and
[false] if no bindings exist for the given key.
* [list_mem x l] is [true] if and only if [x] is equal to an element of [l].
* [list_mem_couple (x,y) l] is [true] if and only if [(x,y)] is equal to an
element of [l].
* [compare_list l1 l2] returns [0] if and only if [l1] is equal to [l2].
* [list_equal l1 l2] returns [true] if and only if [l1] is equal to [l2].
* Prints a hash-consed strings on a formatter.
* Prints a list of hash-consed strings on a formatter.
* Hash-tables indexed by hash-consed strings
* Sets of hash-consed strings
* Maps indexed by hash-consed strings | Cubicle
Copyright ( C ) 2011 - 2014
and
Universite Paris - Sud 11
This file is distributed under the terms of the Apache Software
open Hashcons
type t = string hash_consed
val make : string -> t
val view : t -> string
val equal : t -> t -> bool
val compare : t -> t -> int
val hash : t -> int
val empty : t
val list_assoc : t -> (t * 'a) list -> 'a
val list_assoc_inv : t -> ('a * t) list -> 'a
* [ list_assoc_inv x l ] returns the first element which is associated to [ x ]
in the list of pairs [ l ] .
@raise Not_found if there is no value associated to [ x ] in the list [ l ] .
in the list of pairs [l].
@raise Not_found if there is no value associated to [x] in the list [l].*)
val list_mem_assoc : t -> (t * 'a) list -> bool
val list_mem : t -> t list -> bool
val list_mem_couple : t * t -> (t * t) list -> bool
val compare_list : t list -> t list -> int
val list_equal : t list -> t list -> bool
val print : Format.formatter -> t -> unit
val print_list : string -> Format.formatter -> t list -> unit
module H : Hashtbl.S with type key = t
module HSet : Set.S with type elt = t
module HMap : Map.S with type key = t
|
ee30264fc027f719cf87d3649dfe0e0e1b39485ae9aa56c2026084f4d27dfcee | jimcrayne/jhc | Eta.hs | module E.Eta(
ArityType(ATop,ABottom),
etaExpandAp,
annotateArity,
deleteArity,
etaExpandDef,
etaExpandDef',
etaExpandProgram,
getArityInfo,
etaAnnotateProgram,
etaReduce
) where
import Control.Monad.Identity
import Control.Monad.State
import Control.Monad.Writer
import Data.Typeable
import DataConstructors
import E.Annotate
import E.E
import E.Inline
import E.Program
import E.Subst
import E.TypeCheck
import E.Values
import GenUtil hiding(replicateM_)
import Info.Types
import Name.Id
import Support.FreeVars
import Util.NameMonad
import Util.SetLike
import qualified Info.Info as Info
import qualified Stats
data ArityType = AFun Bool ArityType | ABottom | ATop
deriving(Eq,Ord,Typeable)
instance Show ArityType where
showsPrec _ ATop = ("ArT" ++)
showsPrec _ ABottom = ("ArB" ++)
showsPrec _ (AFun False r) = ('\\':) . shows r
showsPrec _ (AFun True r) = ("\\o" ++) . shows r
arity at = f at 0 where
f (AFun _ a) n = f a $! (1 + n)
f x n | n `seq` x `seq` True = (x,n)
f _ _ = error "Eta.arity: bad."
getArityInfo tvr
| Just at <- Info.lookup (tvrInfo tvr) = arity at
| otherwise = (ATop,0)
isOneShot x = getProperty prop_ONESHOT x
arityType :: E -> ArityType
arityType e = f e where
f EError {} = ABottom
f (ELam x e) = AFun (isOneShot x) (f e)
f (EAp a b) = case f a of
AFun _ xs | isCheap b -> xs
_ -> ATop
f ec@ECase { eCaseScrutinee = scrut } = case foldr1 andArityType (map f $ caseBodies ec) of
xs@(AFun True _) -> xs
xs | isCheap scrut -> xs
_ -> ATop
f (ELetRec ds e) = case f e of
xs@(AFun True _) -> xs
xs | all isCheap (snds ds) -> xs
_ -> ATop
f (EVar tvr) | Just at <- Info.lookup (tvrInfo tvr) = at
f _ = ATop
andArityType ABottom at2 = at2
andArityType ATop at2 = ATop
andArityType (AFun t1 at1) (AFun t2 at2) = AFun (t1 && t2) (andArityType at1 at2)
andArityType at1 at2 = andArityType at2 at1
annotateArity e nfo = annotateArity' (arityType e) nfo
annotateArity' at nfo = Info.insert (Arity n (b == ABottom)) $ Info.insert at nfo where
(b,n) = arity at
-- delety any arity information
deleteArity nfo = Info.delete (undefined :: Arity) $ Info.delete (undefined :: Arity) nfo
expandPis :: DataTable -> E -> E
expandPis dataTable e = f (followAliases dataTable e) where
f (EPi v r) = EPi v (f (followAliases dataTable r))
f e = e
fromPi ' : : DataTable - > E - > ( E,[TVr ] )
fromPi ' dataTable e = f [ ] ( followAliases dataTable e ) where
f as ( EPi v e ) = f ( v : as ) ( followAliases dataTable e )
f as e = ( e , reverse as )
fromPi' :: DataTable -> E -> (E,[TVr])
fromPi' dataTable e = f [] (followAliases dataTable e) where
f as (EPi v e) = f (v:as) (followAliases dataTable e)
f as e = (e,reverse as)
-}
-- this annotates, but only expands top-level definitions
etaExpandProgram :: Stats.MonadStats m => Program -> m Program
--etaExpandProgram prog = runNameMT (programMapDs f (etaAnnotateProgram prog)) where
etaExpandProgram prog = runNameMT (programMapDs f prog) where
f (t,e) = do etaExpandDef' (progDataTable prog) 0 t e
-- this annotates a program with its arity information, iterating until a fixpoint is reached.
etaAnnotateProgram :: Program -> Program
etaAnnotateProgram prog = runIdentity $ programMapRecGroups mempty pass iletann pass f prog where
pass _ = return
iletann e nfo = return $ annotateArity e nfo
letann e nfo = case Info.lookup nfo of
Nothing -> put True >> return (annotateArity e nfo)
Just at -> do
let at' = arityType e
when (at /= at') (put True)
return $ annotateArity' at' nfo
f (rg,ts) = do
let (ts',fs) = runState (annotateCombs mempty pass letann pass ts) False
if fs then f (rg,ts') else return ts'
-- | eta reduce as much as possible
etaReduce :: E -> E
etaReduce e = f e where
f (ELam t (EAp x (EVar t'))) | t == t' && (tvrIdent t `notMember` (freeVars x :: IdSet)) = f x
f e = e
-- | only reduce if all lambdas can be discarded. otherwise leave them in place
etaReduce ' : : E - > ( E , Int )
etaReduce ' e = case f e 0 of
( ELam { } , _ ) - > ( e,0 )
x - > x
where
f ( ELam t ( EAp x ( EVar t ' ) ) ) n | n ` seq ` True , t = = t ' & & ( tvrIdent t ` notMember ` ( freeVars x : : IdSet ) ) = f x ( n + 1 )
f e n = ( e , n )
etaReduce' :: E -> (E,Int)
etaReduce' e = case f e 0 of
(ELam {},_) -> (e,0)
x -> x
where
f (ELam t (EAp x (EVar t'))) n | n `seq` True, t == t' && (tvrIdent t `notMember` (freeVars x :: IdSet)) = f x (n + 1)
f e n = (e,n)
-}
etaExpandDef' dataTable n t e = etaExpandDef dataTable n t e >>= \x -> case x of
Nothing -> return (tvrInfo_u (annotateArity e) t,e)
Just x -> return x
--collectIds :: E -> IdSet
collectIds e = execWriter $ annotate mempty ( \id nfo - > tell ( singleton i d ) > > return nfo ) ( \ _ - > return ) ( \ _ - > return ) e
-- | eta expand a definition
etaExpandDef :: (NameMonad Id m,Stats.MonadStats m)
=> DataTable
-> Int -- ^ eta expand at least this far, independent of calculated amount
-> TVr
-> E
-> m (Maybe (TVr,E))
etaExpandDef _ _ _ e | isAtomic e = return Nothing -- will be inlined
etaExpandDef dataTable min t e = ans where
fvs = foldr insert ( freeVars ( b , map getType rs,(tvrType t , e ) ) ) ( map tvrIdent rs ) ` mappend ` collectIds e
--(b,rs) = fromLam e
at = arityType e
zeroName = case fromAp e of
(EVar v,_) -> "use.{" ++ tvrShowName v
_ -> "random"
nameSupply = [ n | n < - [ 2,4 : : Int .. ] , n ` notMember ` fvs ]
nameSupply = undefined
ans = do
-- note that we can't use the type in the tvr, because it will not have the right free typevars.
(ne,flag) <- f min at e (expandPis dataTable $ infertype dataTable e) nameSupply
if flag then return (Just (tvrInfo_u (annotateArity' at) t,ne)) else return Nothing
f min (AFun _ a) (ELam tvr e) (EPi tvr' rt) _ns = do
(ne,flag) <- f (min - 1) a e (subst tvr' (EVar tvr) rt) _ns
return (ELam tvr ne,flag)
f min (AFun _ a) e (EPi tt rt) _nns = do
if tvrIdent t == emptyId
then Stats.mtick ("EtaExpand." ++ zeroName)
else Stats.mtick ("EtaExpand.def.{" ++ tvrShowName t)
n <- newName
let nv = tt { tvrIdent = n }
eb = EAp e (EVar nv)
(ne,_) <- f (min - 1) a eb (subst tt (EVar nv) rt) _nns
return (ELam nv ne,True)
f min a e (EPi tt rt) _nns | min > 0 = do
if tvrIdent t == emptyId
then Stats.mtick ("EtaExpand.min." ++ zeroName)
else Stats.mtick ("EtaExpand.min.def.{" ++ tvrShowName t)
n <- newName
let nv = tt { tvrIdent = n }
eb = EAp e (EVar nv)
(ne,_) <- f (min - 1) a eb (subst tt (EVar nv) rt) _nns
return (ELam nv ne,True)
f _ _ e _ _ = do
return (e,False)
-- | eta expand a use of a value
etaExpandAp :: (NameMonad Id m,Stats.MonadStats m) => DataTable -> TVr -> [E] -> m (Maybe E)
etaExpandAp dataTable tvr xs = do
r <- etaExpandDef dataTable 0 tvr { tvrIdent = emptyId} (foldl EAp (EVar tvr) xs)
return (fmap snd r)
etaExpandAp _ _ [ ] = return Nothing -- so simple renames do n't get eta - expanded
etaExpandAp dataTable t as | Just ( Arity n err ) < - Info.lookup ( tvrInfo t ) = case ( ) of
( ) | n > length as - > do
let e = foldl EAp ( EVar t ) as
let ( _ , ts ) = fromPi ' dataTable ( infertype dataTable e )
ets = ( take ( n - length as ) ts )
mticks ( length ets ) ( " EtaExpand.use . { " + + tvrShowName t )
let = f [ ( tvrIdent t , t { tvrIdent = n } ) | n < - [ 2,4 : : Int .. ] , not $ n ` Set.member ` freeVars ( e , ets ) | t < - ets ]
f map ( ( n , t):rs ) = t { tvrType = substMap map ( tvrType t ) } : f ( Map.insert n ( EVar t ) map ) rs
f _ [ ] = [ ]
return ( Just $ foldr ELam ( foldl EAp e ( map EVar tvrs ) ) tvrs )
| err & & length as > n - > do
let ot = ( foldl EAp ( EVar t ) as )
mticks ( length as - n ) ( " EtaExpand.bottoming . { " + + tvrShowName t )
return $ Just ( prim_unsafeCoerce ot ( foldl EAp ( EVar t ) ( take n as ) ) ) -- we can drop any extra arguments applied to something that bottoms out .
| otherwise - > return Nothing
etaExpandAp _ t as = return Nothing
etaExpandAp _ _ [] = return Nothing -- so simple renames don't get eta-expanded
etaExpandAp dataTable t as | Just (Arity n err) <- Info.lookup (tvrInfo t) = case () of
() | n > length as -> do
let e = foldl EAp (EVar t) as
let (_,ts) = fromPi' dataTable (infertype dataTable e)
ets = (take (n - length as) ts)
mticks (length ets) ("EtaExpand.use.{" ++ tvrShowName t)
let tvrs = f mempty [ (tvrIdent t,t { tvrIdent = n }) | n <- [2,4 :: Int ..], not $ n `Set.member` freeVars (e,ets) | t <- ets ]
f map ((n,t):rs) = t { tvrType = substMap map (tvrType t)} : f (Map.insert n (EVar t) map) rs
f _ [] = []
return (Just $ foldr ELam (foldl EAp e (map EVar tvrs)) tvrs)
| err && length as > n -> do
let ot = infertype dataTable (foldl EAp (EVar t) as)
mticks (length as - n) ("EtaExpand.bottoming.{" ++ tvrShowName t)
return $ Just (prim_unsafeCoerce ot (foldl EAp (EVar t) (take n as))) -- we can drop any extra arguments applied to something that bottoms out.
| otherwise -> return Nothing
etaExpandAp _ t as = return Nothing
-}
| null | https://raw.githubusercontent.com/jimcrayne/jhc/1ff035af3d697f9175f8761c8d08edbffde03b4e/src/E/Eta.hs | haskell | delety any arity information
this annotates, but only expands top-level definitions
etaExpandProgram prog = runNameMT (programMapDs f (etaAnnotateProgram prog)) where
this annotates a program with its arity information, iterating until a fixpoint is reached.
| eta reduce as much as possible
| only reduce if all lambdas can be discarded. otherwise leave them in place
collectIds :: E -> IdSet
| eta expand a definition
^ eta expand at least this far, independent of calculated amount
will be inlined
(b,rs) = fromLam e
note that we can't use the type in the tvr, because it will not have the right free typevars.
| eta expand a use of a value
so simple renames do n't get eta - expanded
we can drop any extra arguments applied to something that bottoms out .
so simple renames don't get eta-expanded
we can drop any extra arguments applied to something that bottoms out. | module E.Eta(
ArityType(ATop,ABottom),
etaExpandAp,
annotateArity,
deleteArity,
etaExpandDef,
etaExpandDef',
etaExpandProgram,
getArityInfo,
etaAnnotateProgram,
etaReduce
) where
import Control.Monad.Identity
import Control.Monad.State
import Control.Monad.Writer
import Data.Typeable
import DataConstructors
import E.Annotate
import E.E
import E.Inline
import E.Program
import E.Subst
import E.TypeCheck
import E.Values
import GenUtil hiding(replicateM_)
import Info.Types
import Name.Id
import Support.FreeVars
import Util.NameMonad
import Util.SetLike
import qualified Info.Info as Info
import qualified Stats
data ArityType = AFun Bool ArityType | ABottom | ATop
deriving(Eq,Ord,Typeable)
instance Show ArityType where
showsPrec _ ATop = ("ArT" ++)
showsPrec _ ABottom = ("ArB" ++)
showsPrec _ (AFun False r) = ('\\':) . shows r
showsPrec _ (AFun True r) = ("\\o" ++) . shows r
arity at = f at 0 where
f (AFun _ a) n = f a $! (1 + n)
f x n | n `seq` x `seq` True = (x,n)
f _ _ = error "Eta.arity: bad."
getArityInfo tvr
| Just at <- Info.lookup (tvrInfo tvr) = arity at
| otherwise = (ATop,0)
isOneShot x = getProperty prop_ONESHOT x
arityType :: E -> ArityType
arityType e = f e where
f EError {} = ABottom
f (ELam x e) = AFun (isOneShot x) (f e)
f (EAp a b) = case f a of
AFun _ xs | isCheap b -> xs
_ -> ATop
f ec@ECase { eCaseScrutinee = scrut } = case foldr1 andArityType (map f $ caseBodies ec) of
xs@(AFun True _) -> xs
xs | isCheap scrut -> xs
_ -> ATop
f (ELetRec ds e) = case f e of
xs@(AFun True _) -> xs
xs | all isCheap (snds ds) -> xs
_ -> ATop
f (EVar tvr) | Just at <- Info.lookup (tvrInfo tvr) = at
f _ = ATop
andArityType ABottom at2 = at2
andArityType ATop at2 = ATop
andArityType (AFun t1 at1) (AFun t2 at2) = AFun (t1 && t2) (andArityType at1 at2)
andArityType at1 at2 = andArityType at2 at1
annotateArity e nfo = annotateArity' (arityType e) nfo
annotateArity' at nfo = Info.insert (Arity n (b == ABottom)) $ Info.insert at nfo where
(b,n) = arity at
deleteArity nfo = Info.delete (undefined :: Arity) $ Info.delete (undefined :: Arity) nfo
expandPis :: DataTable -> E -> E
expandPis dataTable e = f (followAliases dataTable e) where
f (EPi v r) = EPi v (f (followAliases dataTable r))
f e = e
fromPi ' : : DataTable - > E - > ( E,[TVr ] )
fromPi ' dataTable e = f [ ] ( followAliases dataTable e ) where
f as ( EPi v e ) = f ( v : as ) ( followAliases dataTable e )
f as e = ( e , reverse as )
fromPi' :: DataTable -> E -> (E,[TVr])
fromPi' dataTable e = f [] (followAliases dataTable e) where
f as (EPi v e) = f (v:as) (followAliases dataTable e)
f as e = (e,reverse as)
-}
etaExpandProgram :: Stats.MonadStats m => Program -> m Program
etaExpandProgram prog = runNameMT (programMapDs f prog) where
f (t,e) = do etaExpandDef' (progDataTable prog) 0 t e
etaAnnotateProgram :: Program -> Program
etaAnnotateProgram prog = runIdentity $ programMapRecGroups mempty pass iletann pass f prog where
pass _ = return
iletann e nfo = return $ annotateArity e nfo
letann e nfo = case Info.lookup nfo of
Nothing -> put True >> return (annotateArity e nfo)
Just at -> do
let at' = arityType e
when (at /= at') (put True)
return $ annotateArity' at' nfo
f (rg,ts) = do
let (ts',fs) = runState (annotateCombs mempty pass letann pass ts) False
if fs then f (rg,ts') else return ts'
etaReduce :: E -> E
etaReduce e = f e where
f (ELam t (EAp x (EVar t'))) | t == t' && (tvrIdent t `notMember` (freeVars x :: IdSet)) = f x
f e = e
etaReduce ' : : E - > ( E , Int )
etaReduce ' e = case f e 0 of
( ELam { } , _ ) - > ( e,0 )
x - > x
where
f ( ELam t ( EAp x ( EVar t ' ) ) ) n | n ` seq ` True , t = = t ' & & ( tvrIdent t ` notMember ` ( freeVars x : : IdSet ) ) = f x ( n + 1 )
f e n = ( e , n )
etaReduce' :: E -> (E,Int)
etaReduce' e = case f e 0 of
(ELam {},_) -> (e,0)
x -> x
where
f (ELam t (EAp x (EVar t'))) n | n `seq` True, t == t' && (tvrIdent t `notMember` (freeVars x :: IdSet)) = f x (n + 1)
f e n = (e,n)
-}
etaExpandDef' dataTable n t e = etaExpandDef dataTable n t e >>= \x -> case x of
Nothing -> return (tvrInfo_u (annotateArity e) t,e)
Just x -> return x
collectIds e = execWriter $ annotate mempty ( \id nfo - > tell ( singleton i d ) > > return nfo ) ( \ _ - > return ) ( \ _ - > return ) e
etaExpandDef :: (NameMonad Id m,Stats.MonadStats m)
=> DataTable
-> TVr
-> E
-> m (Maybe (TVr,E))
etaExpandDef dataTable min t e = ans where
fvs = foldr insert ( freeVars ( b , map getType rs,(tvrType t , e ) ) ) ( map tvrIdent rs ) ` mappend ` collectIds e
at = arityType e
zeroName = case fromAp e of
(EVar v,_) -> "use.{" ++ tvrShowName v
_ -> "random"
nameSupply = [ n | n < - [ 2,4 : : Int .. ] , n ` notMember ` fvs ]
nameSupply = undefined
ans = do
(ne,flag) <- f min at e (expandPis dataTable $ infertype dataTable e) nameSupply
if flag then return (Just (tvrInfo_u (annotateArity' at) t,ne)) else return Nothing
f min (AFun _ a) (ELam tvr e) (EPi tvr' rt) _ns = do
(ne,flag) <- f (min - 1) a e (subst tvr' (EVar tvr) rt) _ns
return (ELam tvr ne,flag)
f min (AFun _ a) e (EPi tt rt) _nns = do
if tvrIdent t == emptyId
then Stats.mtick ("EtaExpand." ++ zeroName)
else Stats.mtick ("EtaExpand.def.{" ++ tvrShowName t)
n <- newName
let nv = tt { tvrIdent = n }
eb = EAp e (EVar nv)
(ne,_) <- f (min - 1) a eb (subst tt (EVar nv) rt) _nns
return (ELam nv ne,True)
f min a e (EPi tt rt) _nns | min > 0 = do
if tvrIdent t == emptyId
then Stats.mtick ("EtaExpand.min." ++ zeroName)
else Stats.mtick ("EtaExpand.min.def.{" ++ tvrShowName t)
n <- newName
let nv = tt { tvrIdent = n }
eb = EAp e (EVar nv)
(ne,_) <- f (min - 1) a eb (subst tt (EVar nv) rt) _nns
return (ELam nv ne,True)
f _ _ e _ _ = do
return (e,False)
etaExpandAp :: (NameMonad Id m,Stats.MonadStats m) => DataTable -> TVr -> [E] -> m (Maybe E)
etaExpandAp dataTable tvr xs = do
r <- etaExpandDef dataTable 0 tvr { tvrIdent = emptyId} (foldl EAp (EVar tvr) xs)
return (fmap snd r)
etaExpandAp dataTable t as | Just ( Arity n err ) < - Info.lookup ( tvrInfo t ) = case ( ) of
( ) | n > length as - > do
let e = foldl EAp ( EVar t ) as
let ( _ , ts ) = fromPi ' dataTable ( infertype dataTable e )
ets = ( take ( n - length as ) ts )
mticks ( length ets ) ( " EtaExpand.use . { " + + tvrShowName t )
let = f [ ( tvrIdent t , t { tvrIdent = n } ) | n < - [ 2,4 : : Int .. ] , not $ n ` Set.member ` freeVars ( e , ets ) | t < - ets ]
f map ( ( n , t):rs ) = t { tvrType = substMap map ( tvrType t ) } : f ( Map.insert n ( EVar t ) map ) rs
f _ [ ] = [ ]
return ( Just $ foldr ELam ( foldl EAp e ( map EVar tvrs ) ) tvrs )
| err & & length as > n - > do
let ot = ( foldl EAp ( EVar t ) as )
mticks ( length as - n ) ( " EtaExpand.bottoming . { " + + tvrShowName t )
| otherwise - > return Nothing
etaExpandAp _ t as = return Nothing
etaExpandAp dataTable t as | Just (Arity n err) <- Info.lookup (tvrInfo t) = case () of
() | n > length as -> do
let e = foldl EAp (EVar t) as
let (_,ts) = fromPi' dataTable (infertype dataTable e)
ets = (take (n - length as) ts)
mticks (length ets) ("EtaExpand.use.{" ++ tvrShowName t)
let tvrs = f mempty [ (tvrIdent t,t { tvrIdent = n }) | n <- [2,4 :: Int ..], not $ n `Set.member` freeVars (e,ets) | t <- ets ]
f map ((n,t):rs) = t { tvrType = substMap map (tvrType t)} : f (Map.insert n (EVar t) map) rs
f _ [] = []
return (Just $ foldr ELam (foldl EAp e (map EVar tvrs)) tvrs)
| err && length as > n -> do
let ot = infertype dataTable (foldl EAp (EVar t) as)
mticks (length as - n) ("EtaExpand.bottoming.{" ++ tvrShowName t)
| otherwise -> return Nothing
etaExpandAp _ t as = return Nothing
-}
|
0576f9310c8fee88d9306c95bea858fa3abfebe721ad4d9b47edbcf429298e1f | poroh/ersip | ersip_hdr_via.erl | %%%
Copyright ( c ) 2018 , 2020 Dmitry Poroh
%%% All rights reserved.
Distributed under the terms of the MIT License . See the LICENSE file .
%%%
SIP Via header
%%%
-module(ersip_hdr_via).
-export([new/3,
new/4,
topmost_via/1,
take_topmost/1,
sent_protocol/1,
branch/1,
set_branch/2,
received/1,
set_received/2,
has_rport/1,
rport/1,
set_rport/2,
maddr/1,
set_maddr/2,
ttl/1,
set_ttl/2,
raw_param/2,
all_raw_params/1,
set_param/3,
sent_by/1,
sent_by_key/1,
make_key/1,
assemble/1,
assemble_bin/1,
make/1,
parse/1,
raw/1
]).
-export_type([via/0,
via_key/0,
sent_by/0,
raw/0
]).
%%===================================================================
%% Types
%%===================================================================
-record(via, {sent_protocol :: sent_protocol(),
sent_by :: internal_sent_by(),
hparams :: ersip_hparams:hparams()
}).
-type via() :: #via{}.
-type sent_protocol() :: {sent_protocol, Protocol :: binary(), ProtocolVersion :: binary(), ersip_transport:transport()}.
-type sent_by() :: {sent_by, ersip_host:host(), Port :: inet:port_number()}.
-type internal_sent_by() :: {sent_by, ersip_host:host(), Port :: inet:port_number() | default_port}.
-type known_via_params() :: branch
| maddr
| received
| ttl
| rport.
-type rport_value() :: inet:port_number() | true.
-type ttl_value() :: 0..255.
-type via_key() :: {sent_protocol(), sent_by(), via_params_key()}.
-type via_params_key() :: #{branch => ersip_branch:branch(),
maddr => ersip_host:host(),
received => ersip_host:host(),
ttl => non_neg_integer(),
rport => inet:port_number() | true,
binary() => binary()
}.
-type raw() :: #{protocol := binary(),
version := binary(),
transport := binary(),
host := binary(),
port := inet:port_number(),
params := ersip_hparams:raw(),
branch => binary(),
maddr => binary(),
received => binary(),
ttl => non_neg_integer(),
rport => rport_value()
}.
%%===================================================================
%% API
%%===================================================================
@doc Create new Via haeder by Host , Port and SIP transport .
-spec new(ersip_host:host(), inet:port_number(), ersip_transport:transport()) -> via().
new(Address, Port, Transport) ->
#via{sent_protocol = {sent_protocol, <<"SIP">>, <<"2.0">>, Transport},
sent_by = {sent_by, Address, Port},
hparams = ersip_hparams:new()
}.
@doc Create new Via haeder by Host , Port , SIP transport and branch parameter .
-spec new(ersip_host:host(), inet:port_number(), ersip_transport:transport(), ersip_branch:branch()) -> via().
new(Address, Port, Transport, Branch) ->
HParams0 = ersip_hparams:new(),
HParams = ersip_hparams:set(branch, Branch, <<"branch">>, ersip_branch:assemble(Branch), HParams0),
#via{sent_protocol = {sent_protocol, <<"SIP">>, <<"2.0">>, Transport},
sent_by = {sent_by, Address, Port},
hparams = HParams
}.
%% @doc Get topmost Via from SIP raw headers.
-spec topmost_via(ersip_hdr:header()) -> {ok, via()} | {error, no_via}.
topmost_via(Header) ->
case ersip_hdr:raw_values(Header) of
[] -> {error, no_via};
[TopVia | _] ->
case parse_via_with_rest(iolist_to_binary(TopVia)) of
{error, _} = Error -> Error;
{ok, Via, Rest} ->
case validate_topmost_via(Via, Rest) of
ok -> {ok, Via};
{error, Reason} ->
{error, {invalid_via, Reason}}
end
end
end.
-spec take_topmost(iolist() | binary()) -> ersip_parser_aux:parse_result(via()).
take_topmost(IOList) ->
Bin = iolist_to_binary(IOList),
case parse_via_with_rest(Bin) of
{ok, Via, <<",", Rest/binary>>} ->
case validate_topmost_via(Via) of
ok -> {ok, Via, Rest};
{error, Reason} -> {error, {invalid_via, Reason}}
end;
{ok, Via, <<>>} ->
case validate_topmost_via(Via) of
ok -> {ok, Via, <<>>};
{error, Reason} -> {error, {invalid_via, Reason}}
end;
{ok, _, Rest} ->
{error, {invalid_via, {invalid_via, {garbage_at_the_end, Rest}}}};
{error, Reason} ->
{error, {invalid_via, Reason}}
end.
%% @doc Get sent protocol.
-spec sent_protocol(via()) -> sent_protocol().
sent_protocol(#via{sent_protocol = Sp}) ->
Sp.
%% @doc Get Via parametr by it's name.
-spec raw_param(ParamName :: binary(), via()) -> {ok, ParamValue :: binary()} | not_found.
raw_param(ParamName, #via{hparams = HParams}) when is_binary(ParamName) ->
ersip_hparams:find_raw(ParamName, HParams).
%% @doc Get all Via parameters.
-spec all_raw_params(via()) -> [{binary(), binary()} | binary()].
all_raw_params(#via{hparams = HParams}) ->
ersip_hparams:to_raw_list(HParams).
@doc Get Via parameter . This function supports known paramters
%% (deprecated) and binary parameters.
-spec set_param(known_via_params() | binary(), term(), via()) -> via().
set_param(received, Value, Via) when is_binary(Value) ->
case ersip_host:parse(Value) of
{ok, Host, <<>>} -> set_param(received, Host, Via);
{ok, _, _} -> error({invalid_received, Value});
{error, Reason} -> error({invalid_received, Reason})
end;
set_param(received, {Type, _} = Value , #via{hparams = HP} = Via)
when Type =:= ipv4 orelse Type =:= ipv6 ->
HPNew = ersip_hparams:set(received, Value, <<"received">>, assemble_received(Value), HP),
Via#via{hparams = HPNew};
set_param(received, Value, _) ->
error({invalid_received, Value});
set_param(rport, Value, #via{hparams = HP} = Via)
when is_integer(Value) andalso Value >= 1 andalso Value =< 65535 orelse Value == true ->
HPNew = ersip_hparams:set(rport, Value, <<"rport">>, assemble_rport(Value), HP),
Via#via{hparams = HPNew};
set_param(maddr, Host , #via{hparams = HP} = Via) ->
HPNew = ersip_hparams:set(maddr, Host, <<"maddr">>, assemble_maddr(Host), HP),
Via#via{hparams = HPNew};
set_param(ttl, Value, #via{hparams = HP} = Via)
when is_integer(Value) andalso Value >= 0 andalso Value =< 255 ->
HPNew = ersip_hparams:set(ttl, Value, <<"ttl">>, assemble_ttl(Value), HP),
Via#via{hparams = HPNew};
set_param(branch, {branch, _} = Value, #via{hparams = HP} = Via) ->
HPNew = ersip_hparams:set(branch, Value, <<"branch">>, ersip_branch:assemble_bin(Value), HP),
Via#via{hparams = HPNew};
set_param(rport, Value, _) ->
error({invalid_rport, Value}).
%% @doc Get Host and port from Via header.
-spec sent_by(via()) -> sent_by().
sent_by(#via{sent_by = {sent_by,Host,default_port}} = Via) ->
{sent_protocol, _, _, Transport} = sent_protocol(Via),
{sent_by, Host, ersip_transport:default_port(Transport)};
sent_by(#via{sent_by = SentBy}) ->
SentBy.
@doc Make comparable sent_by ( adjusted to be comparable as erlang
%% terms).
-spec sent_by_key(via()) -> sent_by().
sent_by_key(#via{} = Via) ->
sent_by_make_key(sent_by(Via)).
%% @doc Get branch parameter.
-spec branch(via()) -> {ok, ersip_branch:branch()} | undefined.
branch(#via{hparams = HParams}) ->
case ersip_hparams:find(branch, HParams) of
{ok, BranchValue} -> {ok, BranchValue};
not_found -> undefined
end.
%% @doc Set branch parameter.
-spec set_branch(ersip_branch:branch(), via()) -> via().
set_branch(Branch, #via{} = Via) ->
set_param(branch, Branch, Via).
%% @doc Get received parameter.
-spec received(via()) -> {ok, ersip_host:host()} | undefined.
received(#via{hparams = HParams}) ->
case ersip_hparams:find(received, HParams) of
{ok, Host} -> {ok, Host};
not_found -> undefined
end.
%% @doc Set received parameter.
-spec set_received(ersip_host:host(), via()) -> via().
set_received(Host, #via{} = Via) ->
set_param(received, Host, Via).
%% @doc Check if Via has rport parameter.
-spec has_rport(via()) -> boolean().
has_rport(#via{hparams = HParams}) ->
case ersip_hparams:find(rport, HParams) of
{ok, _} -> true;
not_found -> false
end.
%% @doc Get rport parameter value. If rport parameter is set without
%% port number than functio returns {ok, true}.
-spec rport(via()) -> {ok, rport_value()} | undefined.
rport(#via{hparams = HParams}) ->
case ersip_hparams:find(rport, HParams) of
{ok, RPortVal} -> {ok, RPortVal};
not_found -> undefined
end.
%% @doc Set rport parameter value.
-spec set_rport(rport_value(), via()) -> via().
set_rport(RPort, #via{} = Via) ->
set_param(rport, RPort, Via).
%% @doc Get maddr parameter.
-spec maddr(via()) -> {ok, ersip_host:host()} | undefined.
maddr(#via{hparams = HParams}) ->
case ersip_hparams:find(maddr, HParams) of
{ok, Host} -> {ok, Host};
not_found -> undefined
end.
%% @doc Set maddr parameter.
-spec set_maddr(ersip_host:host(), via()) -> via().
set_maddr(Host, #via{} = Via) ->
set_param(maddr, Host, Via).
@doc Get parameter .
-spec ttl(via()) -> {ok, ttl_value()} | undefined.
ttl(#via{hparams = HParams}) ->
case ersip_hparams:find(ttl, HParams) of
{ok, TTL} -> {ok, TTL};
not_found -> undefined
end.
@doc Set parameter .
-spec set_ttl(ttl_value(), via()) -> via().
set_ttl(TTLValue, #via{} = Via) ->
set_param(ttl, TTLValue, Via).
%% @doc Make key that can be used to match transaction.
-spec make_key(via()) -> via_key().
make_key(#via{hparams = HParams} = Via) ->
{sent_protocol_make_key(sent_protocol(Via)),
sent_by_make_key(sent_by(Via)),
via_params_make_key(HParams)}.
%% @doc Assemble Via as iolist().
-spec assemble(via()) -> iolist().
assemble(#via{} = Via) ->
#via{
sent_protocol =
{sent_protocol, Protocol, ProtocolVersion, Transport},
sent_by = {sent_by, Host, Port},
hparams = HParams
} = Via,
[Protocol, $/, ProtocolVersion, $/, ersip_transport:assemble_upper(Transport),
<<" ">>, ersip_host:assemble(Host),
case Port of
default_port ->
[];
Port ->
[$:, integer_to_binary(Port)]
end,
assemble_params(HParams)
].
%% @doc Assemble Via as binary().
-spec assemble_bin(via()) -> binary().
assemble_bin(#via{} = Via) ->
iolist_to_binary(assemble(Via)).
@doc Parse single Via header
-spec parse(iolist() | binary()) -> {ok, via()} | {error, term()}.
parse(Binary) when is_binary(Binary) ->
parse_via(Binary);
parse(IOList) ->
parse_via(iolist_to_binary(IOList)).
%% @doc Make Via header from binary.
-spec make(binary() | raw()) -> via().
make(Bin) when is_binary(Bin) ->
case parse_via(Bin) of
{ok, Via} -> Via;
{error, Reason} -> error(Reason)
end.
%% @doc Represent via as raw SIP header.
-spec raw(via()) -> raw().
raw(#via{} = Via) ->
{sent_protocol, Proto, Ver, Transp} = Via#via.sent_protocol,
{sent_by, H, Prt} = Via#via.sent_by,
Raw = #{protocol => Proto,
version => Ver,
transport => ersip_transport:assemble_upper(Transp),
host => ersip_host:assemble_bin(H),
port => Prt,
params => ersip_hparams:raw(Via#via.hparams)
},
Opts = [{branch, branch(Via), fun(X) -> ersip_branch:assemble_bin(X) end},
{maddr, maddr(Via), fun(X) -> ersip_host:assemble_bin(X) end},
{received, received(Via), fun(X) -> ersip_host:assemble_bin(X) end},
{ttl, ttl(Via), fun(X) -> X end},
{rport, rport(Via), fun(X) -> X end}
],
OptsKVP = [{K, F(V)} || {K, {ok, V}, F} <- Opts],
maps:merge(maps:from_list(OptsKVP), Raw).
%%===================================================================
Internal implementation
%%===================================================================
-spec parse_via(binary()) -> {ok,via()} | {error, term()}.
parse_via(ViaBinary) ->
case parse_via_with_rest(ViaBinary) of
{ok, Via, <<>>} ->
{ok, Via};
{ok, _, _} -> {error, {invalid_via, ViaBinary}};
{error, Reason} -> {error, {invalid_via, Reason}}
end.
-spec parse_via_with_rest(binary()) -> ersip_parser_aux:parse_result(via()).
parse_via_with_rest(ViaBinary) ->
Parsers = [fun parse_sent_protocol/1,
fun ersip_parser_aux:parse_lws/1,
fun parse_sent_by/1,
fun ersip_parser_aux:trim_lws/1,
fun parse_params/1,
fun ersip_parser_aux:trim_lws/1
],
case ersip_parser_aux:parse_all(ViaBinary, Parsers) of
{ok, [SentProtocol, _, SentBy, _, HParams, _], Rest} ->
Via = #via{sent_protocol = SentProtocol,
sent_by = SentBy,
hparams = HParams},
{ok, Via, Rest};
{error, Reason} -> {error, {invalid_via, Reason}}
end.
%% sent-protocol = protocol-name SLASH protocol-version
%% SLASH transport
%% protocol-name = "SIP" / token
%% protocol-version = token
transport = " UDP " / " TCP " / " TLS " / " SCTP "
%% / other-transport
-spec parse_sent_protocol(binary()) -> ersip_parser_aux:parse_result().
parse_sent_protocol(Binary) ->
Parsers = [fun ersip_parser_aux:parse_token/1,
fun ersip_parser_aux:parse_slash/1,
fun ersip_parser_aux:parse_token/1,
fun ersip_parser_aux:parse_slash/1,
fun parse_transport/1
],
case ersip_parser_aux:parse_all(Binary, Parsers) of
{ok, [ProtocolName, _, ProtocolVersion, _, Transport], Rest} ->
{ok, {sent_protocol, ProtocolName, ProtocolVersion, Transport}, Rest};
{error, _} = Error ->
Error
end.
%% sent-by = host [COLON port]
%% this implementation is not pure. It uses sent-by context in via
header ( expects that either EOL or SEMI occur after sent - by ) .
-spec parse_sent_by(binary()) -> ersip_parser_aux:parse_result().
parse_sent_by(Binary) ->
case binary:match(Binary, <<";">>) of
{Pos, 1} ->
<<HostPort:Pos/binary, Rest/binary>> = Binary,
parse_sent_by_host_port(ersip_bin:trim_lws(HostPort), host, #{rest => Rest});
nomatch ->
case binary:match(Binary, <<",">>) of
{Pos, 1} ->
<<HostPort:Pos/binary, Rest/binary>> = Binary,
parse_sent_by_host_port(ersip_bin:trim_lws(HostPort), host, #{rest => Rest});
nomatch ->
parse_sent_by_host_port(ersip_bin:trim_lws(Binary), host, #{rest => <<>>})
end
end.
-spec parse_sent_by_host_port(binary() | [binary()], host | port | result, map()) -> ersip_parser_aux:parse_result().
parse_sent_by_host_port(<<$[, _/binary>> = IPv6RefPort, host, Acc) ->
case binary:match(IPv6RefPort, <<"]">>) of
nomatch ->
{error, {invalid_ipv6_reference, IPv6RefPort}};
{Pos, 1} ->
Size = Pos+1,
<<HostBin:Size/binary, Rest/binary>> = IPv6RefPort,
case ersip_host:parse(HostBin) of
{ok, Host, <<>>} ->
parse_sent_by_host_port(Rest, port, Acc#{host => Host});
{error, _} = Err ->
Err
end
end;
parse_sent_by_host_port(Binary, host, Acc) ->
[HostBin | MayBePort] = binary:split(Binary, <<":">>),
case ersip_host:parse(HostBin) of
{ok, Host, <<>>} ->
parse_sent_by_host_port(MayBePort, port, Acc#{host => Host});
{ok, _Host, _Rest} ->
{error, {invalid_host, HostBin}};
{error, _} = Err ->
Err
end;
parse_sent_by_host_port([], port, Acc) ->
parse_sent_by_host_port(<<>>, result, Acc);
parse_sent_by_host_port(<<>>, port, Acc) ->
parse_sent_by_host_port(<<>>, result, Acc);
parse_sent_by_host_port(<<":", Rest/binary>>, port, Acc) ->
parse_sent_by_host_port([Rest], port, Acc);
parse_sent_by_host_port(Bin, port, _Acc) when is_binary(Bin) ->
{error, {invalid_port, Bin}};
parse_sent_by_host_port([Bin], port, Acc) when is_binary(Bin) ->
case parse_port_number(ersip_bin:trim_lws(Bin)) of
{ok, PortNumber} ->
parse_sent_by_host_port(<<>>, result, Acc#{port => PortNumber});
{error, _} = Error ->
Error
end;
parse_sent_by_host_port(_, result, #{rest := Rest, host := Host} = Acc) ->
Port = maps:get(port, Acc, default_port),
{ok, {sent_by, Host, Port}, Rest}.
-spec parse_transport(binary()) -> ersip_parser_aux:parse_result(ersip_transport:transport()).
parse_transport(Binary) ->
case ersip_parser_aux:parse_token(Binary) of
{ok, Transp, Rest} ->
{ok, T} = ersip_transport:parse(Transp),
{ok, T, Rest};
{error, _} = Error ->
Error
end.
@private
-spec parse_params(binary()) -> ersip_parser_aux:parse_result(ersip_parser_aux:gen_param_list()).
parse_params(<<$;, Bin/binary>>) ->
ersip_hparams:parse(fun parse_known/2, Bin);
parse_params(Bin) ->
{ok, ersip_hparams:new(), Bin}.
%% via-params = via-ttl / via-maddr
%% / via-received / via-branch
%% / via-extension
-spec parse_known(binary(), binary()) -> ersip_hparams:parse_known_fun_result().
parse_known(<<"ttl">>, Value) ->
1 * 3DIGIT ; 0 to 255
case ersip_parser_aux:parse_non_neg_int(Value) of
{ok, TTL, <<>>}
when TTL >= 0 andalso TTL =< 255
-> {ok, {ttl, TTL}};
{ok, _, _} -> {error, {invalid_ttl, Value}};
{error, Reason} -> {error, {invalid_ttl, Reason}}
end;
parse_known(<<"received">>, Value) ->
" received " EQUAL ( IPv4address / IPv6address )
case ersip_host:parse(Value) of
{ok, {ipv4, _} = Host, <<>>} -> {ok, {received, Host}};
{ok, {ipv6, _} = Host, <<>>} -> {ok, {received, Host}};
{ok, _, _} -> {error, {invalid_received, Value}};
{error, Reason} -> {error, {invalid_received, Reason}}
end;
parse_known(<<"maddr">>, Value) ->
%% "maddr" EQUAL host
case ersip_host:parse(Value) of
{ok, Host, <<>>} -> {ok, {maddr, Host}};
{ok, _, _} -> {error, {invalid_maddr, Value}};
{error, Reason} -> {error, {invalid_maddr, Reason}}
end;
parse_known(<<"branch">>, Value) ->
%% "branch" EQUAL token
case ersip_parser_aux:check_token(Value) of
true -> {ok, {branch, ersip_branch:make(Value)}};
false -> {error, {invalid_branch, Value}}
end;
parse_known(<<"rport">>, <<>>) ->
{ok, {rport, true}};
parse_known(<<"rport">>, Value) ->
%% response-port = "rport" [EQUAL 1*DIGIT]
case parse_port_number(Value) of
{ok, Port} -> {ok, {rport, Port}};
{error, Reason} -> {error, {invalid_rport, Reason}}
end;
parse_known(_, _) ->
{ok, unknown}.
-spec sent_protocol_make_key(sent_protocol()) -> sent_protocol().
sent_protocol_make_key(Protocol) ->
Protocol.
-spec sent_by_make_key(sent_by()) -> sent_by().
sent_by_make_key({sent_by, Host, Port}) ->
{sent_by, ersip_host:make_key(Host), Port}.
-spec via_params_make_key(ersip_hparams:hparams()) -> via_params_key().
via_params_make_key(Params) ->
L = ersip_hparams:to_list(Params),
LKeys = lists:map(fun({Key, Value}) ->
via_param_make_key(Key, Value)
end,
L),
maps:from_list(LKeys).
-spec via_param_make_key(Key, Value) -> {NewKey, NewValue} when
Key :: known_via_params() | binary(),
Value :: term(),
NewKey :: known_via_params() | binary(),
NewValue :: term().
via_param_make_key(ttl, V) ->
{ttl, V};
via_param_make_key(branch, B) ->
{branch, ersip_branch:make_key(B)};
via_param_make_key(maddr, Maddr) ->
{maddr, ersip_host:make_key(Maddr)};
via_param_make_key(received, R) ->
{received, R};
via_param_make_key(rport, R) ->
{rport, R};
via_param_make_key(OtherKey, OtherValue) when is_binary(OtherKey) ->
{ersip_bin:to_lower(OtherKey), OtherValue}.
-spec assemble_params(ersip_hparams:hparams()) -> [iolist()].
assemble_params(HParams) ->
HParamsIO0 = ersip_hparams:assemble(HParams),
case ersip_iolist:is_empty(HParamsIO0) of
true -> [];
false -> [$; | HParamsIO0]
end.
-spec assemble_received(ersip_host:host()) -> binary().
assemble_received(Value) ->
iolist_to_binary(ersip_host:assemble_received(Value)).
-spec assemble_rport(rport_value()) -> binary().
assemble_rport(true) ->
<<>>;
assemble_rport(Value) ->
integer_to_binary(Value).
-spec assemble_ttl(ttl_value()) -> binary().
assemble_ttl(Value) ->
integer_to_binary(Value).
-spec assemble_maddr(ersip_host:host()) -> binary().
assemble_maddr(Value) ->
iolist_to_binary(ersip_host:assemble(Value)).
-spec validate_topmost_via(via(), binary()) -> ok | {error, term()}.
validate_topmost_via(#via{} = Via, <<>>) ->
validate_topmost_via(Via);
validate_topmost_via(#via{} = Via, <<",", _/binary>>) ->
validate_topmost_via(Via);
validate_topmost_via(#via{}, Rest) ->
{error, {garbage_at_the_end, Rest}}.
-spec validate_topmost_via(via()) -> ok | {error, term()}.
validate_topmost_via(#via{sent_protocol = SentProtocol}) ->
case SentProtocol of
{sent_protocol, <<"SIP">>, <<"2.0">>, T} ->
case ersip_transport:is_known_transport(T) of
true -> ok;
false -> {error, {unknown_transport, T}}
end;
{sent_protocol, Proto, Version, _} ->
{error, {unknown_protocol, Proto, Version}}
end.
-spec parse_port_number(binary()) -> {ok, inet:port_number()} | {error, term()}.
parse_port_number(Bin) ->
case ersip_parser_aux:parse_non_neg_int(Bin) of
{ok, Int, <<>>} when Int > 0 andalso Int =< 65535 -> {ok, Int};
_ -> {error, {invalid_port, Bin}}
end.
| null | https://raw.githubusercontent.com/poroh/ersip/60afa92a53898f6692f3a30d04b5b88a580c8153/src/message/ersip_hdr_via.erl | erlang |
All rights reserved.
===================================================================
Types
===================================================================
===================================================================
API
===================================================================
@doc Get topmost Via from SIP raw headers.
@doc Get sent protocol.
@doc Get Via parametr by it's name.
@doc Get all Via parameters.
(deprecated) and binary parameters.
@doc Get Host and port from Via header.
terms).
@doc Get branch parameter.
@doc Set branch parameter.
@doc Get received parameter.
@doc Set received parameter.
@doc Check if Via has rport parameter.
@doc Get rport parameter value. If rport parameter is set without
port number than functio returns {ok, true}.
@doc Set rport parameter value.
@doc Get maddr parameter.
@doc Set maddr parameter.
@doc Make key that can be used to match transaction.
@doc Assemble Via as iolist().
@doc Assemble Via as binary().
@doc Make Via header from binary.
@doc Represent via as raw SIP header.
===================================================================
===================================================================
sent-protocol = protocol-name SLASH protocol-version
SLASH transport
protocol-name = "SIP" / token
protocol-version = token
/ other-transport
sent-by = host [COLON port]
this implementation is not pure. It uses sent-by context in via
via-params = via-ttl / via-maddr
/ via-received / via-branch
/ via-extension
"maddr" EQUAL host
"branch" EQUAL token
response-port = "rport" [EQUAL 1*DIGIT] | Copyright ( c ) 2018 , 2020 Dmitry Poroh
Distributed under the terms of the MIT License . See the LICENSE file .
SIP Via header
-module(ersip_hdr_via).
-export([new/3,
new/4,
topmost_via/1,
take_topmost/1,
sent_protocol/1,
branch/1,
set_branch/2,
received/1,
set_received/2,
has_rport/1,
rport/1,
set_rport/2,
maddr/1,
set_maddr/2,
ttl/1,
set_ttl/2,
raw_param/2,
all_raw_params/1,
set_param/3,
sent_by/1,
sent_by_key/1,
make_key/1,
assemble/1,
assemble_bin/1,
make/1,
parse/1,
raw/1
]).
-export_type([via/0,
via_key/0,
sent_by/0,
raw/0
]).
-record(via, {sent_protocol :: sent_protocol(),
sent_by :: internal_sent_by(),
hparams :: ersip_hparams:hparams()
}).
-type via() :: #via{}.
-type sent_protocol() :: {sent_protocol, Protocol :: binary(), ProtocolVersion :: binary(), ersip_transport:transport()}.
-type sent_by() :: {sent_by, ersip_host:host(), Port :: inet:port_number()}.
-type internal_sent_by() :: {sent_by, ersip_host:host(), Port :: inet:port_number() | default_port}.
-type known_via_params() :: branch
| maddr
| received
| ttl
| rport.
-type rport_value() :: inet:port_number() | true.
-type ttl_value() :: 0..255.
-type via_key() :: {sent_protocol(), sent_by(), via_params_key()}.
-type via_params_key() :: #{branch => ersip_branch:branch(),
maddr => ersip_host:host(),
received => ersip_host:host(),
ttl => non_neg_integer(),
rport => inet:port_number() | true,
binary() => binary()
}.
-type raw() :: #{protocol := binary(),
version := binary(),
transport := binary(),
host := binary(),
port := inet:port_number(),
params := ersip_hparams:raw(),
branch => binary(),
maddr => binary(),
received => binary(),
ttl => non_neg_integer(),
rport => rport_value()
}.
@doc Create new Via haeder by Host , Port and SIP transport .
-spec new(ersip_host:host(), inet:port_number(), ersip_transport:transport()) -> via().
new(Address, Port, Transport) ->
#via{sent_protocol = {sent_protocol, <<"SIP">>, <<"2.0">>, Transport},
sent_by = {sent_by, Address, Port},
hparams = ersip_hparams:new()
}.
@doc Create new Via haeder by Host , Port , SIP transport and branch parameter .
-spec new(ersip_host:host(), inet:port_number(), ersip_transport:transport(), ersip_branch:branch()) -> via().
new(Address, Port, Transport, Branch) ->
HParams0 = ersip_hparams:new(),
HParams = ersip_hparams:set(branch, Branch, <<"branch">>, ersip_branch:assemble(Branch), HParams0),
#via{sent_protocol = {sent_protocol, <<"SIP">>, <<"2.0">>, Transport},
sent_by = {sent_by, Address, Port},
hparams = HParams
}.
-spec topmost_via(ersip_hdr:header()) -> {ok, via()} | {error, no_via}.
topmost_via(Header) ->
case ersip_hdr:raw_values(Header) of
[] -> {error, no_via};
[TopVia | _] ->
case parse_via_with_rest(iolist_to_binary(TopVia)) of
{error, _} = Error -> Error;
{ok, Via, Rest} ->
case validate_topmost_via(Via, Rest) of
ok -> {ok, Via};
{error, Reason} ->
{error, {invalid_via, Reason}}
end
end
end.
-spec take_topmost(iolist() | binary()) -> ersip_parser_aux:parse_result(via()).
take_topmost(IOList) ->
Bin = iolist_to_binary(IOList),
case parse_via_with_rest(Bin) of
{ok, Via, <<",", Rest/binary>>} ->
case validate_topmost_via(Via) of
ok -> {ok, Via, Rest};
{error, Reason} -> {error, {invalid_via, Reason}}
end;
{ok, Via, <<>>} ->
case validate_topmost_via(Via) of
ok -> {ok, Via, <<>>};
{error, Reason} -> {error, {invalid_via, Reason}}
end;
{ok, _, Rest} ->
{error, {invalid_via, {invalid_via, {garbage_at_the_end, Rest}}}};
{error, Reason} ->
{error, {invalid_via, Reason}}
end.
-spec sent_protocol(via()) -> sent_protocol().
sent_protocol(#via{sent_protocol = Sp}) ->
Sp.
-spec raw_param(ParamName :: binary(), via()) -> {ok, ParamValue :: binary()} | not_found.
raw_param(ParamName, #via{hparams = HParams}) when is_binary(ParamName) ->
ersip_hparams:find_raw(ParamName, HParams).
-spec all_raw_params(via()) -> [{binary(), binary()} | binary()].
all_raw_params(#via{hparams = HParams}) ->
ersip_hparams:to_raw_list(HParams).
@doc Get Via parameter . This function supports known paramters
-spec set_param(known_via_params() | binary(), term(), via()) -> via().
set_param(received, Value, Via) when is_binary(Value) ->
case ersip_host:parse(Value) of
{ok, Host, <<>>} -> set_param(received, Host, Via);
{ok, _, _} -> error({invalid_received, Value});
{error, Reason} -> error({invalid_received, Reason})
end;
set_param(received, {Type, _} = Value , #via{hparams = HP} = Via)
when Type =:= ipv4 orelse Type =:= ipv6 ->
HPNew = ersip_hparams:set(received, Value, <<"received">>, assemble_received(Value), HP),
Via#via{hparams = HPNew};
set_param(received, Value, _) ->
error({invalid_received, Value});
set_param(rport, Value, #via{hparams = HP} = Via)
when is_integer(Value) andalso Value >= 1 andalso Value =< 65535 orelse Value == true ->
HPNew = ersip_hparams:set(rport, Value, <<"rport">>, assemble_rport(Value), HP),
Via#via{hparams = HPNew};
set_param(maddr, Host , #via{hparams = HP} = Via) ->
HPNew = ersip_hparams:set(maddr, Host, <<"maddr">>, assemble_maddr(Host), HP),
Via#via{hparams = HPNew};
set_param(ttl, Value, #via{hparams = HP} = Via)
when is_integer(Value) andalso Value >= 0 andalso Value =< 255 ->
HPNew = ersip_hparams:set(ttl, Value, <<"ttl">>, assemble_ttl(Value), HP),
Via#via{hparams = HPNew};
set_param(branch, {branch, _} = Value, #via{hparams = HP} = Via) ->
HPNew = ersip_hparams:set(branch, Value, <<"branch">>, ersip_branch:assemble_bin(Value), HP),
Via#via{hparams = HPNew};
set_param(rport, Value, _) ->
error({invalid_rport, Value}).
-spec sent_by(via()) -> sent_by().
sent_by(#via{sent_by = {sent_by,Host,default_port}} = Via) ->
{sent_protocol, _, _, Transport} = sent_protocol(Via),
{sent_by, Host, ersip_transport:default_port(Transport)};
sent_by(#via{sent_by = SentBy}) ->
SentBy.
@doc Make comparable sent_by ( adjusted to be comparable as erlang
-spec sent_by_key(via()) -> sent_by().
sent_by_key(#via{} = Via) ->
sent_by_make_key(sent_by(Via)).
-spec branch(via()) -> {ok, ersip_branch:branch()} | undefined.
branch(#via{hparams = HParams}) ->
case ersip_hparams:find(branch, HParams) of
{ok, BranchValue} -> {ok, BranchValue};
not_found -> undefined
end.
-spec set_branch(ersip_branch:branch(), via()) -> via().
set_branch(Branch, #via{} = Via) ->
set_param(branch, Branch, Via).
-spec received(via()) -> {ok, ersip_host:host()} | undefined.
received(#via{hparams = HParams}) ->
case ersip_hparams:find(received, HParams) of
{ok, Host} -> {ok, Host};
not_found -> undefined
end.
-spec set_received(ersip_host:host(), via()) -> via().
set_received(Host, #via{} = Via) ->
set_param(received, Host, Via).
-spec has_rport(via()) -> boolean().
has_rport(#via{hparams = HParams}) ->
case ersip_hparams:find(rport, HParams) of
{ok, _} -> true;
not_found -> false
end.
-spec rport(via()) -> {ok, rport_value()} | undefined.
rport(#via{hparams = HParams}) ->
case ersip_hparams:find(rport, HParams) of
{ok, RPortVal} -> {ok, RPortVal};
not_found -> undefined
end.
-spec set_rport(rport_value(), via()) -> via().
set_rport(RPort, #via{} = Via) ->
set_param(rport, RPort, Via).
-spec maddr(via()) -> {ok, ersip_host:host()} | undefined.
maddr(#via{hparams = HParams}) ->
case ersip_hparams:find(maddr, HParams) of
{ok, Host} -> {ok, Host};
not_found -> undefined
end.
-spec set_maddr(ersip_host:host(), via()) -> via().
set_maddr(Host, #via{} = Via) ->
set_param(maddr, Host, Via).
@doc Get parameter .
-spec ttl(via()) -> {ok, ttl_value()} | undefined.
ttl(#via{hparams = HParams}) ->
case ersip_hparams:find(ttl, HParams) of
{ok, TTL} -> {ok, TTL};
not_found -> undefined
end.
@doc Set parameter .
-spec set_ttl(ttl_value(), via()) -> via().
set_ttl(TTLValue, #via{} = Via) ->
set_param(ttl, TTLValue, Via).
-spec make_key(via()) -> via_key().
make_key(#via{hparams = HParams} = Via) ->
{sent_protocol_make_key(sent_protocol(Via)),
sent_by_make_key(sent_by(Via)),
via_params_make_key(HParams)}.
-spec assemble(via()) -> iolist().
assemble(#via{} = Via) ->
#via{
sent_protocol =
{sent_protocol, Protocol, ProtocolVersion, Transport},
sent_by = {sent_by, Host, Port},
hparams = HParams
} = Via,
[Protocol, $/, ProtocolVersion, $/, ersip_transport:assemble_upper(Transport),
<<" ">>, ersip_host:assemble(Host),
case Port of
default_port ->
[];
Port ->
[$:, integer_to_binary(Port)]
end,
assemble_params(HParams)
].
-spec assemble_bin(via()) -> binary().
assemble_bin(#via{} = Via) ->
iolist_to_binary(assemble(Via)).
@doc Parse single Via header
-spec parse(iolist() | binary()) -> {ok, via()} | {error, term()}.
parse(Binary) when is_binary(Binary) ->
parse_via(Binary);
parse(IOList) ->
parse_via(iolist_to_binary(IOList)).
-spec make(binary() | raw()) -> via().
make(Bin) when is_binary(Bin) ->
case parse_via(Bin) of
{ok, Via} -> Via;
{error, Reason} -> error(Reason)
end.
-spec raw(via()) -> raw().
raw(#via{} = Via) ->
{sent_protocol, Proto, Ver, Transp} = Via#via.sent_protocol,
{sent_by, H, Prt} = Via#via.sent_by,
Raw = #{protocol => Proto,
version => Ver,
transport => ersip_transport:assemble_upper(Transp),
host => ersip_host:assemble_bin(H),
port => Prt,
params => ersip_hparams:raw(Via#via.hparams)
},
Opts = [{branch, branch(Via), fun(X) -> ersip_branch:assemble_bin(X) end},
{maddr, maddr(Via), fun(X) -> ersip_host:assemble_bin(X) end},
{received, received(Via), fun(X) -> ersip_host:assemble_bin(X) end},
{ttl, ttl(Via), fun(X) -> X end},
{rport, rport(Via), fun(X) -> X end}
],
OptsKVP = [{K, F(V)} || {K, {ok, V}, F} <- Opts],
maps:merge(maps:from_list(OptsKVP), Raw).
Internal implementation
-spec parse_via(binary()) -> {ok,via()} | {error, term()}.
parse_via(ViaBinary) ->
case parse_via_with_rest(ViaBinary) of
{ok, Via, <<>>} ->
{ok, Via};
{ok, _, _} -> {error, {invalid_via, ViaBinary}};
{error, Reason} -> {error, {invalid_via, Reason}}
end.
-spec parse_via_with_rest(binary()) -> ersip_parser_aux:parse_result(via()).
parse_via_with_rest(ViaBinary) ->
Parsers = [fun parse_sent_protocol/1,
fun ersip_parser_aux:parse_lws/1,
fun parse_sent_by/1,
fun ersip_parser_aux:trim_lws/1,
fun parse_params/1,
fun ersip_parser_aux:trim_lws/1
],
case ersip_parser_aux:parse_all(ViaBinary, Parsers) of
{ok, [SentProtocol, _, SentBy, _, HParams, _], Rest} ->
Via = #via{sent_protocol = SentProtocol,
sent_by = SentBy,
hparams = HParams},
{ok, Via, Rest};
{error, Reason} -> {error, {invalid_via, Reason}}
end.
transport = " UDP " / " TCP " / " TLS " / " SCTP "
-spec parse_sent_protocol(binary()) -> ersip_parser_aux:parse_result().
parse_sent_protocol(Binary) ->
Parsers = [fun ersip_parser_aux:parse_token/1,
fun ersip_parser_aux:parse_slash/1,
fun ersip_parser_aux:parse_token/1,
fun ersip_parser_aux:parse_slash/1,
fun parse_transport/1
],
case ersip_parser_aux:parse_all(Binary, Parsers) of
{ok, [ProtocolName, _, ProtocolVersion, _, Transport], Rest} ->
{ok, {sent_protocol, ProtocolName, ProtocolVersion, Transport}, Rest};
{error, _} = Error ->
Error
end.
header ( expects that either EOL or SEMI occur after sent - by ) .
-spec parse_sent_by(binary()) -> ersip_parser_aux:parse_result().
parse_sent_by(Binary) ->
case binary:match(Binary, <<";">>) of
{Pos, 1} ->
<<HostPort:Pos/binary, Rest/binary>> = Binary,
parse_sent_by_host_port(ersip_bin:trim_lws(HostPort), host, #{rest => Rest});
nomatch ->
case binary:match(Binary, <<",">>) of
{Pos, 1} ->
<<HostPort:Pos/binary, Rest/binary>> = Binary,
parse_sent_by_host_port(ersip_bin:trim_lws(HostPort), host, #{rest => Rest});
nomatch ->
parse_sent_by_host_port(ersip_bin:trim_lws(Binary), host, #{rest => <<>>})
end
end.
-spec parse_sent_by_host_port(binary() | [binary()], host | port | result, map()) -> ersip_parser_aux:parse_result().
parse_sent_by_host_port(<<$[, _/binary>> = IPv6RefPort, host, Acc) ->
case binary:match(IPv6RefPort, <<"]">>) of
nomatch ->
{error, {invalid_ipv6_reference, IPv6RefPort}};
{Pos, 1} ->
Size = Pos+1,
<<HostBin:Size/binary, Rest/binary>> = IPv6RefPort,
case ersip_host:parse(HostBin) of
{ok, Host, <<>>} ->
parse_sent_by_host_port(Rest, port, Acc#{host => Host});
{error, _} = Err ->
Err
end
end;
parse_sent_by_host_port(Binary, host, Acc) ->
[HostBin | MayBePort] = binary:split(Binary, <<":">>),
case ersip_host:parse(HostBin) of
{ok, Host, <<>>} ->
parse_sent_by_host_port(MayBePort, port, Acc#{host => Host});
{ok, _Host, _Rest} ->
{error, {invalid_host, HostBin}};
{error, _} = Err ->
Err
end;
parse_sent_by_host_port([], port, Acc) ->
parse_sent_by_host_port(<<>>, result, Acc);
parse_sent_by_host_port(<<>>, port, Acc) ->
parse_sent_by_host_port(<<>>, result, Acc);
parse_sent_by_host_port(<<":", Rest/binary>>, port, Acc) ->
parse_sent_by_host_port([Rest], port, Acc);
parse_sent_by_host_port(Bin, port, _Acc) when is_binary(Bin) ->
{error, {invalid_port, Bin}};
parse_sent_by_host_port([Bin], port, Acc) when is_binary(Bin) ->
case parse_port_number(ersip_bin:trim_lws(Bin)) of
{ok, PortNumber} ->
parse_sent_by_host_port(<<>>, result, Acc#{port => PortNumber});
{error, _} = Error ->
Error
end;
parse_sent_by_host_port(_, result, #{rest := Rest, host := Host} = Acc) ->
Port = maps:get(port, Acc, default_port),
{ok, {sent_by, Host, Port}, Rest}.
-spec parse_transport(binary()) -> ersip_parser_aux:parse_result(ersip_transport:transport()).
parse_transport(Binary) ->
case ersip_parser_aux:parse_token(Binary) of
{ok, Transp, Rest} ->
{ok, T} = ersip_transport:parse(Transp),
{ok, T, Rest};
{error, _} = Error ->
Error
end.
@private
-spec parse_params(binary()) -> ersip_parser_aux:parse_result(ersip_parser_aux:gen_param_list()).
parse_params(<<$;, Bin/binary>>) ->
ersip_hparams:parse(fun parse_known/2, Bin);
parse_params(Bin) ->
{ok, ersip_hparams:new(), Bin}.
-spec parse_known(binary(), binary()) -> ersip_hparams:parse_known_fun_result().
parse_known(<<"ttl">>, Value) ->
1 * 3DIGIT ; 0 to 255
case ersip_parser_aux:parse_non_neg_int(Value) of
{ok, TTL, <<>>}
when TTL >= 0 andalso TTL =< 255
-> {ok, {ttl, TTL}};
{ok, _, _} -> {error, {invalid_ttl, Value}};
{error, Reason} -> {error, {invalid_ttl, Reason}}
end;
parse_known(<<"received">>, Value) ->
" received " EQUAL ( IPv4address / IPv6address )
case ersip_host:parse(Value) of
{ok, {ipv4, _} = Host, <<>>} -> {ok, {received, Host}};
{ok, {ipv6, _} = Host, <<>>} -> {ok, {received, Host}};
{ok, _, _} -> {error, {invalid_received, Value}};
{error, Reason} -> {error, {invalid_received, Reason}}
end;
parse_known(<<"maddr">>, Value) ->
case ersip_host:parse(Value) of
{ok, Host, <<>>} -> {ok, {maddr, Host}};
{ok, _, _} -> {error, {invalid_maddr, Value}};
{error, Reason} -> {error, {invalid_maddr, Reason}}
end;
parse_known(<<"branch">>, Value) ->
case ersip_parser_aux:check_token(Value) of
true -> {ok, {branch, ersip_branch:make(Value)}};
false -> {error, {invalid_branch, Value}}
end;
parse_known(<<"rport">>, <<>>) ->
{ok, {rport, true}};
parse_known(<<"rport">>, Value) ->
case parse_port_number(Value) of
{ok, Port} -> {ok, {rport, Port}};
{error, Reason} -> {error, {invalid_rport, Reason}}
end;
parse_known(_, _) ->
{ok, unknown}.
-spec sent_protocol_make_key(sent_protocol()) -> sent_protocol().
sent_protocol_make_key(Protocol) ->
Protocol.
-spec sent_by_make_key(sent_by()) -> sent_by().
sent_by_make_key({sent_by, Host, Port}) ->
{sent_by, ersip_host:make_key(Host), Port}.
-spec via_params_make_key(ersip_hparams:hparams()) -> via_params_key().
via_params_make_key(Params) ->
L = ersip_hparams:to_list(Params),
LKeys = lists:map(fun({Key, Value}) ->
via_param_make_key(Key, Value)
end,
L),
maps:from_list(LKeys).
-spec via_param_make_key(Key, Value) -> {NewKey, NewValue} when
Key :: known_via_params() | binary(),
Value :: term(),
NewKey :: known_via_params() | binary(),
NewValue :: term().
via_param_make_key(ttl, V) ->
{ttl, V};
via_param_make_key(branch, B) ->
{branch, ersip_branch:make_key(B)};
via_param_make_key(maddr, Maddr) ->
{maddr, ersip_host:make_key(Maddr)};
via_param_make_key(received, R) ->
{received, R};
via_param_make_key(rport, R) ->
{rport, R};
via_param_make_key(OtherKey, OtherValue) when is_binary(OtherKey) ->
{ersip_bin:to_lower(OtherKey), OtherValue}.
-spec assemble_params(ersip_hparams:hparams()) -> [iolist()].
assemble_params(HParams) ->
HParamsIO0 = ersip_hparams:assemble(HParams),
case ersip_iolist:is_empty(HParamsIO0) of
true -> [];
false -> [$; | HParamsIO0]
end.
-spec assemble_received(ersip_host:host()) -> binary().
assemble_received(Value) ->
iolist_to_binary(ersip_host:assemble_received(Value)).
-spec assemble_rport(rport_value()) -> binary().
assemble_rport(true) ->
<<>>;
assemble_rport(Value) ->
integer_to_binary(Value).
-spec assemble_ttl(ttl_value()) -> binary().
assemble_ttl(Value) ->
integer_to_binary(Value).
-spec assemble_maddr(ersip_host:host()) -> binary().
assemble_maddr(Value) ->
iolist_to_binary(ersip_host:assemble(Value)).
-spec validate_topmost_via(via(), binary()) -> ok | {error, term()}.
validate_topmost_via(#via{} = Via, <<>>) ->
validate_topmost_via(Via);
validate_topmost_via(#via{} = Via, <<",", _/binary>>) ->
validate_topmost_via(Via);
validate_topmost_via(#via{}, Rest) ->
{error, {garbage_at_the_end, Rest}}.
-spec validate_topmost_via(via()) -> ok | {error, term()}.
validate_topmost_via(#via{sent_protocol = SentProtocol}) ->
case SentProtocol of
{sent_protocol, <<"SIP">>, <<"2.0">>, T} ->
case ersip_transport:is_known_transport(T) of
true -> ok;
false -> {error, {unknown_transport, T}}
end;
{sent_protocol, Proto, Version, _} ->
{error, {unknown_protocol, Proto, Version}}
end.
-spec parse_port_number(binary()) -> {ok, inet:port_number()} | {error, term()}.
parse_port_number(Bin) ->
case ersip_parser_aux:parse_non_neg_int(Bin) of
{ok, Int, <<>>} when Int > 0 andalso Int =< 65535 -> {ok, Int};
_ -> {error, {invalid_port, Bin}}
end.
|
a6b41c7690804be961966c67d583d4766ddff9a51d0d80bb2dccf735d427f93a | jellelicht/guix | pv.scm | ;;; GNU Guix --- Functional package management for GNU
Copyright © 2015 < >
;;;
;;; This file is part of GNU Guix.
;;;
GNU is free software ; you can redistribute it and/or modify it
under the terms of the GNU General Public License as published by
the Free Software Foundation ; either version 3 of the License , or ( at
;;; your option) any later version.
;;;
;;; GNU Guix is distributed in the hope that it will be useful, but
;;; WITHOUT ANY WARRANTY; without even the implied warranty of
;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
;;; GNU General Public License for more details.
;;;
You should have received a copy of the GNU General Public License
along with GNU . If not , see < / > .
(define-module (gnu packages pv)
#:use-module (guix licenses)
#:use-module (guix packages)
#:use-module (guix download)
#:use-module (guix build-system gnu))
(define-public pv
(package
(name "pv")
(version "1.6.0")
(source
(origin
(method url-fetch)
(uri (string-append "-"
version ".tar.bz2"))
(sha256
(base32
"13gg6r84pkvznpd1l11qw1jw9yna40gkgpni256khyx21m785khf"))))
(build-system gnu-build-system)
(home-page "")
(synopsis "Pipeline progress indicator")
(description
"pv (Pipe Viewer) is a terminal-based tool for monitoring the progress
of data through a pipeline. It can be inserted into any normal pipeline
between two processes to give a visual indication of how quickly data is
passing through, how long it has taken, how near to completion it is, and an
estimate of how long it will be until completion.")
(license artistic2.0)))
| null | https://raw.githubusercontent.com/jellelicht/guix/83cfc9414fca3ab57c949e18c1ceb375a179b59c/gnu/packages/pv.scm | scheme | GNU Guix --- Functional package management for GNU
This file is part of GNU Guix.
you can redistribute it and/or modify it
either version 3 of the License , or ( at
your option) any later version.
GNU Guix is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
| Copyright © 2015 < >
under the terms of the GNU General Public License as published by
You should have received a copy of the GNU General Public License
along with GNU . If not , see < / > .
(define-module (gnu packages pv)
#:use-module (guix licenses)
#:use-module (guix packages)
#:use-module (guix download)
#:use-module (guix build-system gnu))
(define-public pv
(package
(name "pv")
(version "1.6.0")
(source
(origin
(method url-fetch)
(uri (string-append "-"
version ".tar.bz2"))
(sha256
(base32
"13gg6r84pkvznpd1l11qw1jw9yna40gkgpni256khyx21m785khf"))))
(build-system gnu-build-system)
(home-page "")
(synopsis "Pipeline progress indicator")
(description
"pv (Pipe Viewer) is a terminal-based tool for monitoring the progress
of data through a pipeline. It can be inserted into any normal pipeline
between two processes to give a visual indication of how quickly data is
passing through, how long it has taken, how near to completion it is, and an
estimate of how long it will be until completion.")
(license artistic2.0)))
|
3216f1a775f870de0fb43c05868f6792776c44d35357293946f5cc3211d03ba1 | ocaml/oasis2debian | Main.ml | (******************************************************************************)
oasis2debian : Create and maintain Debian package for an OASIS package
(* *)
Copyright ( C ) 2013 ,
(* *)
(* This library is free software; you can redistribute it and/or modify it *)
(* under the terms of the GNU Lesser General Public License as published by *)
the Free Software Foundation ; either version 2.1 of the License , or ( at
(* your option) any later version, with the OCaml static compilation *)
(* exception. *)
(* *)
(* This library is distributed in the hope that it will be useful, but *)
(* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY *)
(* or FITNESS FOR A PARTICULAR PURPOSE. See the file COPYING for more *)
(* details. *)
(* *)
You should have received a copy of the GNU Lesser General Public License
along with this library ; if not , write to the Free Software Foundation ,
Inc. , 51 Franklin St , Fifth Floor , Boston , MA 02110 - 1301 USA
(******************************************************************************)
open OASISMessage
open Common
let backtrace =
let b = ref false in
Conf.create_full
~cli:"--backtrace"
(function
| "true" -> true
| "false" -> false
| str ->
failwith
(Printf.sprintf
"Unable to parse %S as a boolean (true or false)."
str))
"true|false Print backtrace if program exits with an error."
(Conf.Value !b)
let () =
let () =
(* Clean ENV *)
Unix.putenv "OCAMLPATH" "";
Unix.putenv "LC_ALL" "C"
in
let ctxt =
{(!OASISContext.default) with
OASISContext.ignore_plugins = true}
in
try
if Array.length Sys.argv >= 2 then
begin
let args =
Array.sub Sys.argv 1 ((Array.length Sys.argv) - 1)
in
let run =
match Sys.argv.(1) with
| "init" ->
ActInit.run
| "get" ->
ActGet.run
| "update" ->
ActUpdate.run
| "help" ->
ActHelp.run
| str ->
ActHelp.display ~ctxt stderr;
error ~ctxt "No action %s defined. Try \"help\"." str;
exit 2
in
run ~ctxt args
end
else
begin
ActHelp.display ~ctxt stderr;
error ~ctxt "Not enough arguments";
exit 2
end
with
| Failure str ->
error ~ctxt "%s" str;
if Conf.get ~ctxt backtrace then
Printexc.print_backtrace stderr;
exit 1
| ExitCode i ->
exit i
| null | https://raw.githubusercontent.com/ocaml/oasis2debian/41d268cada4afdac8c906ac99277d7c685bc15ae/src/Main.ml | ocaml | ****************************************************************************
This library is free software; you can redistribute it and/or modify it
under the terms of the GNU Lesser General Public License as published by
your option) any later version, with the OCaml static compilation
exception.
This library is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
or FITNESS FOR A PARTICULAR PURPOSE. See the file COPYING for more
details.
****************************************************************************
Clean ENV | oasis2debian : Create and maintain Debian package for an OASIS package
Copyright ( C ) 2013 ,
the Free Software Foundation ; either version 2.1 of the License , or ( at
You should have received a copy of the GNU Lesser General Public License
along with this library ; if not , write to the Free Software Foundation ,
Inc. , 51 Franklin St , Fifth Floor , Boston , MA 02110 - 1301 USA
open OASISMessage
open Common
let backtrace =
let b = ref false in
Conf.create_full
~cli:"--backtrace"
(function
| "true" -> true
| "false" -> false
| str ->
failwith
(Printf.sprintf
"Unable to parse %S as a boolean (true or false)."
str))
"true|false Print backtrace if program exits with an error."
(Conf.Value !b)
let () =
let () =
Unix.putenv "OCAMLPATH" "";
Unix.putenv "LC_ALL" "C"
in
let ctxt =
{(!OASISContext.default) with
OASISContext.ignore_plugins = true}
in
try
if Array.length Sys.argv >= 2 then
begin
let args =
Array.sub Sys.argv 1 ((Array.length Sys.argv) - 1)
in
let run =
match Sys.argv.(1) with
| "init" ->
ActInit.run
| "get" ->
ActGet.run
| "update" ->
ActUpdate.run
| "help" ->
ActHelp.run
| str ->
ActHelp.display ~ctxt stderr;
error ~ctxt "No action %s defined. Try \"help\"." str;
exit 2
in
run ~ctxt args
end
else
begin
ActHelp.display ~ctxt stderr;
error ~ctxt "Not enough arguments";
exit 2
end
with
| Failure str ->
error ~ctxt "%s" str;
if Conf.get ~ctxt backtrace then
Printexc.print_backtrace stderr;
exit 1
| ExitCode i ->
exit i
|
0477137edcbe169aa42ad8c8f13e0231c237644eb349d9dd84efff7e962d47b6 | exercism/babashka | space_age.clj | (ns space-age)
(def year-seconds (* 365.25 24 60 60))
(defmacro defperiod
[planet ratio]
`(defn ~(symbol (str "on-" planet))
[seconds#]
(/ seconds# (* ~ratio year-seconds))))
(defperiod "earth" 1.0)
(defperiod "mercury" 0.2408467)
(defperiod "venus" 0.61519726)
(defperiod "mars" 1.8808158)
(defperiod "jupiter" 11.862615)
(defperiod "saturn" 29.447498)
(defperiod "uranus" 84.016846)
(defperiod "neptune" 164.79132) | null | https://raw.githubusercontent.com/exercism/babashka/707356c52e08490e66cb1b2e63e4f4439d91cf08/exercises/practice/space-age/src/space_age.clj | clojure | (ns space-age)
(def year-seconds (* 365.25 24 60 60))
(defmacro defperiod
[planet ratio]
`(defn ~(symbol (str "on-" planet))
[seconds#]
(/ seconds# (* ~ratio year-seconds))))
(defperiod "earth" 1.0)
(defperiod "mercury" 0.2408467)
(defperiod "venus" 0.61519726)
(defperiod "mars" 1.8808158)
(defperiod "jupiter" 11.862615)
(defperiod "saturn" 29.447498)
(defperiod "uranus" 84.016846)
(defperiod "neptune" 164.79132) |
|
b58c5e8931bc2591305f2442339b1cedfbbdbd55f3e755f8c6d99a7d149fa7c5 | sol/tinc | Run.hs | # LANGUAGE RecordWildCards #
# LANGUAGE TemplateHaskell #
module Run where
import Control.Exception
import Control.Monad
import System.Environment
import System.FileLock
import System.FilePath
import System.Process
import Data.Version (showVersion)
import Paths_tinc (version)
import Tinc.Install
import Tinc.Facts
import Tinc.Types
import Tinc.Nix
import Tinc.RecentCheck
unsetEnvVars :: IO ()
unsetEnvVars = do
unsetEnv "CABAL_SANDBOX_CONFIG"
unsetEnv "CABAL_SANDBOX_PACKAGE_PATH"
unsetEnv "GHC_PACKAGE_PATH"
tinc :: [String] -> IO ()
tinc args = do
unsetEnvVars
facts@Facts{..} <- getExecutablePath >>= discoverFacts
case args of
[] -> do
withCacheLock factsCache $ do
installDependencies False facts
["--fast"] -> do
recent <- tincEnvCreationTime facts >>= isRecent
unless recent $ do
withCacheLock factsCache $ do
installDependencies False facts
["--dry-run"] -> withCacheLock factsCache $
installDependencies True facts
["--version"] -> putStrLn $ showVersion version
"exec" : name : rest -> callExec facts name rest
name : rest | Just plugin <- lookup name factsPlugins -> callPlugin plugin rest
_ -> throwIO (ErrorCall $ "unrecognized arguments: " ++ show args)
callExec :: Facts -> String -> [String] -> IO ()
callExec Facts{..} name args = do
let
cmd
| factsUseNix = nixShell name args
| otherwise = ("cabal", "v1-exec" : "--" : name : args)
uncurry rawSystemExit cmd
callPlugin :: String -> [String] -> IO ()
callPlugin = rawSystemExit
rawSystemExit :: FilePath -> [String] -> IO ()
rawSystemExit path args = rawSystem path args >>= throwIO
withCacheLock :: Path CacheDir -> IO a -> IO a
withCacheLock cache action = do
putStrLn $ "Acquiring " ++ lock
withFileLock lock Exclusive $ \ _ -> action
where
lock = path cache </> "tinc.lock"
| null | https://raw.githubusercontent.com/sol/tinc/427df659df20d548bbe4c7bd0ea76cc13de40238/src/Run.hs | haskell | # LANGUAGE RecordWildCards #
# LANGUAGE TemplateHaskell #
module Run where
import Control.Exception
import Control.Monad
import System.Environment
import System.FileLock
import System.FilePath
import System.Process
import Data.Version (showVersion)
import Paths_tinc (version)
import Tinc.Install
import Tinc.Facts
import Tinc.Types
import Tinc.Nix
import Tinc.RecentCheck
unsetEnvVars :: IO ()
unsetEnvVars = do
unsetEnv "CABAL_SANDBOX_CONFIG"
unsetEnv "CABAL_SANDBOX_PACKAGE_PATH"
unsetEnv "GHC_PACKAGE_PATH"
tinc :: [String] -> IO ()
tinc args = do
unsetEnvVars
facts@Facts{..} <- getExecutablePath >>= discoverFacts
case args of
[] -> do
withCacheLock factsCache $ do
installDependencies False facts
["--fast"] -> do
recent <- tincEnvCreationTime facts >>= isRecent
unless recent $ do
withCacheLock factsCache $ do
installDependencies False facts
["--dry-run"] -> withCacheLock factsCache $
installDependencies True facts
["--version"] -> putStrLn $ showVersion version
"exec" : name : rest -> callExec facts name rest
name : rest | Just plugin <- lookup name factsPlugins -> callPlugin plugin rest
_ -> throwIO (ErrorCall $ "unrecognized arguments: " ++ show args)
callExec :: Facts -> String -> [String] -> IO ()
callExec Facts{..} name args = do
let
cmd
| factsUseNix = nixShell name args
| otherwise = ("cabal", "v1-exec" : "--" : name : args)
uncurry rawSystemExit cmd
callPlugin :: String -> [String] -> IO ()
callPlugin = rawSystemExit
rawSystemExit :: FilePath -> [String] -> IO ()
rawSystemExit path args = rawSystem path args >>= throwIO
withCacheLock :: Path CacheDir -> IO a -> IO a
withCacheLock cache action = do
putStrLn $ "Acquiring " ++ lock
withFileLock lock Exclusive $ \ _ -> action
where
lock = path cache </> "tinc.lock"
|
|
b69d3d3c6ae2e03858bbb9e096b55bc927c8b1f0d440cb9edc4a4177ef7d7746 | zehnpaard/secd-ocaml | secd.ml | type t =
| Int of int
| Cons of int * int
let cells = Array.make 100000 (Int 0)
let s = ref 0;
let e = ref 0;
let c = ref 0;
let d = ref 0;
let f = ref 1;
let makeInt i =
let n = !f in
(cells.(n) <- Int i; f := n + 1; n)
let makeCons i j =
let n = !f in
(cells.(n) <- Cons (i, j); f := n + 1; n)
let getn i = match cells.(i) with
| Int n -> n
| _ -> failwith "Getting number from cons cell"
let car i = match cells.(i) with
| Cons (i, _) -> i
| _ -> failwith "Taking car of non-cons cell"
let cdr i = match cells.(i) with
| Cons (_, j) -> j
| _ -> failwith "Taking cdr of non-cons cell"
let popR r = match cells.(!r) with
| Cons (i, j) -> (r := j; i)
| _ -> failwith "Register points to a non-cons cell"
let pushR r i =
r := makeCons i !r
let rec locate i j =
let rec locatej j env =
if j = 0 then car env
else locatej (j - 1) (cdr env)
in
let rec locatei i j env =
if i = 0 then locatej j (car env)
else locatei (i - 1) j (cdr env)
in
locatei i j !e
let binOp r op =
let a = popR r in
let b = popR r in
pushR r (op a b)
let rplaca x y =
(cells.(x) := Cons (y, cdr x); x)
let load_simple_command i n =
makeCons (makeInt n) i
let rec load_commands' i = function
| [] -> i
| x :: xs ->
load_commands' (load_command i x) xs
and load_command i = function
| Compile.Stop -> load_simple_command i 0
| Compile.Nil -> load_simple_command i 1
| Compile.Ldc n ->
let j = makeCons (makeInt n) i in
load_simple_command 2 j
| Compile.Ld (n, m) ->
let j = makeCons (makeInt n) (makeInt m) in
load_simple_command 3 j
| Compile.Car -> load_simple_command i 4
| Compile.Cdr -> load_simple_command i 5
| Compile.Atom -> load_simple_command i 6
| Compile.Cons -> load_simple_command i 7
| Compile.Eq -> load_simple_command i 8
| Compile.Leq -> load_simple_command i 9
| Compile.Add -> load_simple_command i 10
| Compile.Sub -> load_simple_command i 11
| Compile.Mul -> load_simple_command i 12
| Compile.Div -> load_simple_command i 13
| Compile.Rem -> load_simple_command i 14
| Compile.Sel (ts, fs) ->
let j = load_commands' i (List.rev fs) in
let k = load_commands' j (List.rev ts) in
load_simple_command 15 k
| Compile.Join -> load_simple_command i 16
| Compile.Ldf cs ->
let j = load_commands' i (List.rev cs) in
load_simple_command 17 j
| Compile.Ap -> load_simple_command i 18
| Compile.Rtn -> load_simple_command i 19
| Compile.Dum -> load_simple_command i 20
| Compile.Rap -> load_simple_command i 21
let load_commands commands =
c := load_commands' (List.rev commands)
let runOneStep () = match cells.(popR c) with
| Int 0 (* STOP *) -> c := 0
NIL
| Int 2 (* LDC *) -> pushR s (popR c)
| Int 3 (* LD *) ->
let ij = popR c in
let i = getn (car ij) in
let j = getn (cdr ij) in
pushR s (locate i j)
| Int 4 (* CAR *) -> pushR s (car (popR s))
| Int 5 (* CDR *) -> pushR s (cdr (popR s))
| Int 6 (* ATOM *) ->
(match cells.(popR s) with
| Int _ -> pushR s (makeInt 1)
| _ -> pushR s (makeInt 0))
| Int 7 (* CONS *) -> binOp s (fun car_, cdr_ -> makeCons car_ cdr_)
EQ
LEQ
| Int 10 (* ADD *) -> binOp s (fun a, b -> makeInt (getn a + getn b))
| Int 11 (* SUB *) -> binOp s (fun a, b -> makeInt (getn a - getn b))
| Int 12 (* MUL *) -> binOp s (fun a, b -> makeInt (getn a * getn b))
DIV
| Int 14 (* REM *) -> binOp s (fun a, b -> makeInt (getn a mod getn b))
SEL
let cond = match cells.(popR s) with
| Int 0 -> false
| _ -> true
in
let true_branch = popR c in
let false_branch = popR c in
(pushR d !c; c := if cond then true_branch else false_branch)
| Int 16 (* JOIN *) -> c := popR d
LDF
let func = popR c in
pushR s (makeCons func !e)
AP
( f.e ' a).s e AP.c d - > nil a.e ' f ( s e c).d
let fe = popR s in
let func = car fe in
let env = cdr fe in
let arg = popR s in
begin
pushR d !c;
c := func;
pushR d !e;
e := makeCons arg env;
pushR d !s;
s := 0;
end; ()
| Int 19 (* RTN *) ->
let retv = popR s in
begin
s := makeCons retv (popR d);
e := (popR d);
c := (popR d);
end; ()
DUM
RAP
(* ((f.(nil.e)) v.s) (nil.e) (RAP.c) d ->
nil rplaca((nil.e),v) f (s e c.d) *)
( rplaca((nil.e),v).e ) according to AoSC ? ?
let fe = popR s in
let func = car fe in
let nenv = cdr fe in
let arg = popR s in
begin
pushR d !c;
c := func;
pushR d (cdr !e);
e := rplaca nenv arg;
pushR d !s;
s := 0;
end; ()
| Int _ -> failwith "Unknown command"
| _ -> failwith "Cons cell found in place of command"
let rec run () =
if !c = 0 then ()
else (runOneStep (); run ())
| null | https://raw.githubusercontent.com/zehnpaard/secd-ocaml/6a8086ed3a34a07b29fce18839e0ab30bde89eda/secd.ml | ocaml | STOP
LDC
LD
CAR
CDR
ATOM
CONS
ADD
SUB
MUL
REM
JOIN
RTN
((f.(nil.e)) v.s) (nil.e) (RAP.c) d ->
nil rplaca((nil.e),v) f (s e c.d) | type t =
| Int of int
| Cons of int * int
let cells = Array.make 100000 (Int 0)
let s = ref 0;
let e = ref 0;
let c = ref 0;
let d = ref 0;
let f = ref 1;
let makeInt i =
let n = !f in
(cells.(n) <- Int i; f := n + 1; n)
let makeCons i j =
let n = !f in
(cells.(n) <- Cons (i, j); f := n + 1; n)
let getn i = match cells.(i) with
| Int n -> n
| _ -> failwith "Getting number from cons cell"
let car i = match cells.(i) with
| Cons (i, _) -> i
| _ -> failwith "Taking car of non-cons cell"
let cdr i = match cells.(i) with
| Cons (_, j) -> j
| _ -> failwith "Taking cdr of non-cons cell"
let popR r = match cells.(!r) with
| Cons (i, j) -> (r := j; i)
| _ -> failwith "Register points to a non-cons cell"
let pushR r i =
r := makeCons i !r
let rec locate i j =
let rec locatej j env =
if j = 0 then car env
else locatej (j - 1) (cdr env)
in
let rec locatei i j env =
if i = 0 then locatej j (car env)
else locatei (i - 1) j (cdr env)
in
locatei i j !e
let binOp r op =
let a = popR r in
let b = popR r in
pushR r (op a b)
let rplaca x y =
(cells.(x) := Cons (y, cdr x); x)
let load_simple_command i n =
makeCons (makeInt n) i
let rec load_commands' i = function
| [] -> i
| x :: xs ->
load_commands' (load_command i x) xs
and load_command i = function
| Compile.Stop -> load_simple_command i 0
| Compile.Nil -> load_simple_command i 1
| Compile.Ldc n ->
let j = makeCons (makeInt n) i in
load_simple_command 2 j
| Compile.Ld (n, m) ->
let j = makeCons (makeInt n) (makeInt m) in
load_simple_command 3 j
| Compile.Car -> load_simple_command i 4
| Compile.Cdr -> load_simple_command i 5
| Compile.Atom -> load_simple_command i 6
| Compile.Cons -> load_simple_command i 7
| Compile.Eq -> load_simple_command i 8
| Compile.Leq -> load_simple_command i 9
| Compile.Add -> load_simple_command i 10
| Compile.Sub -> load_simple_command i 11
| Compile.Mul -> load_simple_command i 12
| Compile.Div -> load_simple_command i 13
| Compile.Rem -> load_simple_command i 14
| Compile.Sel (ts, fs) ->
let j = load_commands' i (List.rev fs) in
let k = load_commands' j (List.rev ts) in
load_simple_command 15 k
| Compile.Join -> load_simple_command i 16
| Compile.Ldf cs ->
let j = load_commands' i (List.rev cs) in
load_simple_command 17 j
| Compile.Ap -> load_simple_command i 18
| Compile.Rtn -> load_simple_command i 19
| Compile.Dum -> load_simple_command i 20
| Compile.Rap -> load_simple_command i 21
let load_commands commands =
c := load_commands' (List.rev commands)
let runOneStep () = match cells.(popR c) with
NIL
let ij = popR c in
let i = getn (car ij) in
let j = getn (cdr ij) in
pushR s (locate i j)
(match cells.(popR s) with
| Int _ -> pushR s (makeInt 1)
| _ -> pushR s (makeInt 0))
EQ
LEQ
DIV
SEL
let cond = match cells.(popR s) with
| Int 0 -> false
| _ -> true
in
let true_branch = popR c in
let false_branch = popR c in
(pushR d !c; c := if cond then true_branch else false_branch)
LDF
let func = popR c in
pushR s (makeCons func !e)
AP
( f.e ' a).s e AP.c d - > nil a.e ' f ( s e c).d
let fe = popR s in
let func = car fe in
let env = cdr fe in
let arg = popR s in
begin
pushR d !c;
c := func;
pushR d !e;
e := makeCons arg env;
pushR d !s;
s := 0;
end; ()
let retv = popR s in
begin
s := makeCons retv (popR d);
e := (popR d);
c := (popR d);
end; ()
DUM
RAP
( rplaca((nil.e),v).e ) according to AoSC ? ?
let fe = popR s in
let func = car fe in
let nenv = cdr fe in
let arg = popR s in
begin
pushR d !c;
c := func;
pushR d (cdr !e);
e := rplaca nenv arg;
pushR d !s;
s := 0;
end; ()
| Int _ -> failwith "Unknown command"
| _ -> failwith "Cons cell found in place of command"
let rec run () =
if !c = 0 then ()
else (runOneStep (); run ())
|
e6da56621573c3cfbdd0b2132efb365cad9867fd62148f45f2308fe666469926 | input-output-hk/ouroboros-network | Codec.hs | {-# LANGUAGE DataKinds #-}
# LANGUAGE GADTs #
# LANGUAGE NamedFieldPuns #
# LANGUAGE PolyKinds #
{-# LANGUAGE RankNTypes #-}
# LANGUAGE ScopedTypeVariables #
{-# LANGUAGE TypeOperators #-}
module Ouroboros.Network.Protocol.LocalStateQuery.Codec
( codecLocalStateQuery
, codecLocalStateQueryId
, Some (..)
) where
import Control.Monad.Class.MonadST
import qualified Codec.CBOR.Decoding as CBOR
import qualified Codec.CBOR.Encoding as CBOR
import qualified Codec.CBOR.Read as CBOR
import Data.ByteString.Lazy (ByteString)
import Data.Kind (Type)
import Data.Type.Equality ((:~:) (..))
import Text.Printf
import Network.TypedProtocol.Codec.CBOR
import Ouroboros.Network.Protocol.LocalStateQuery.Type
data Some (f :: k -> Type) where
Some :: f a -> Some f
codecLocalStateQuery
:: forall block point query m.
( MonadST m
, ShowQuery query
)
=> (point -> CBOR.Encoding)
-> (forall s . CBOR.Decoder s point)
-> (forall result . query result -> CBOR.Encoding)
-> (forall s . CBOR.Decoder s (Some query))
-> (forall result . query result -> result -> CBOR.Encoding)
-> (forall result . query result -> forall s . CBOR.Decoder s result)
-> Codec (LocalStateQuery block point query) CBOR.DeserialiseFailure m ByteString
codecLocalStateQuery encodePoint decodePoint
encodeQuery decodeQuery
encodeResult decodeResult =
mkCodecCborLazyBS encode decode
where
encodeFailure :: AcquireFailure -> CBOR.Encoding
encodeFailure AcquireFailurePointTooOld = CBOR.encodeWord8 0
encodeFailure AcquireFailurePointNotOnChain = CBOR.encodeWord8 1
decodeFailure :: forall s. CBOR.Decoder s AcquireFailure
decodeFailure = do
tag <- CBOR.decodeWord8
case tag of
0 -> return AcquireFailurePointTooOld
1 -> return AcquireFailurePointNotOnChain
_ -> fail $ "decodeFailure: invalid tag " <> show tag
encode :: forall (pr :: PeerRole)
(st :: LocalStateQuery block point query)
(st' :: LocalStateQuery block point query).
PeerHasAgency pr st
-> Message (LocalStateQuery block point query) st st'
-> CBOR.Encoding
encode (ClientAgency TokIdle) (MsgAcquire (Just pt)) =
CBOR.encodeListLen 2
<> CBOR.encodeWord 0
<> encodePoint pt
encode (ClientAgency TokIdle) (MsgAcquire Nothing) =
CBOR.encodeListLen 1
<> CBOR.encodeWord 8
encode (ServerAgency TokAcquiring) MsgAcquired =
CBOR.encodeListLen 1
<> CBOR.encodeWord 1
encode (ServerAgency TokAcquiring) (MsgFailure failure) =
CBOR.encodeListLen 2
<> CBOR.encodeWord 2
<> encodeFailure failure
encode (ClientAgency TokAcquired) (MsgQuery query) =
CBOR.encodeListLen 2
<> CBOR.encodeWord 3
<> encodeQuery query
encode (ServerAgency (TokQuerying _query)) (MsgResult query result) =
CBOR.encodeListLen 2
<> CBOR.encodeWord 4
<> encodeResult query result
encode (ClientAgency TokAcquired) MsgRelease =
CBOR.encodeListLen 1
<> CBOR.encodeWord 5
encode (ClientAgency TokAcquired) (MsgReAcquire (Just pt)) =
CBOR.encodeListLen 2
<> CBOR.encodeWord 6
<> encodePoint pt
encode (ClientAgency TokAcquired) (MsgReAcquire Nothing) =
CBOR.encodeListLen 1
<> CBOR.encodeWord 9
encode (ClientAgency TokIdle) MsgDone =
CBOR.encodeListLen 1
<> CBOR.encodeWord 7
decode :: forall (pr :: PeerRole) s (st :: LocalStateQuery block point query).
PeerHasAgency pr st
-> CBOR.Decoder s (SomeMessage st)
decode stok = do
len <- CBOR.decodeListLen
key <- CBOR.decodeWord
case (stok, len, key) of
(ClientAgency TokIdle, 2, 0) -> do
pt <- decodePoint
return (SomeMessage (MsgAcquire (Just pt)))
(ClientAgency TokIdle, 1, 8) -> do
return (SomeMessage (MsgAcquire Nothing))
(ServerAgency TokAcquiring, 1, 1) ->
return (SomeMessage MsgAcquired)
(ServerAgency TokAcquiring, 2, 2) -> do
failure <- decodeFailure
return (SomeMessage (MsgFailure failure))
(ClientAgency TokAcquired, 2, 3) -> do
Some query <- decodeQuery
return (SomeMessage (MsgQuery query))
(ServerAgency (TokQuerying query), 2, 4) -> do
result <- decodeResult query
return (SomeMessage (MsgResult query result))
(ClientAgency TokAcquired, 1, 5) ->
return (SomeMessage MsgRelease)
(ClientAgency TokAcquired, 2, 6) -> do
pt <- decodePoint
return (SomeMessage (MsgReAcquire (Just pt)))
(ClientAgency TokAcquired, 1, 9) -> do
return (SomeMessage (MsgReAcquire Nothing))
(ClientAgency TokIdle, 1, 7) ->
return (SomeMessage MsgDone)
--
-- failures per protocol state
--
(ClientAgency TokIdle, _, _) ->
fail (printf "codecLocalStateQuery (%s) unexpected key (%d, %d)" (show stok) key len)
(ClientAgency TokAcquired, _, _) ->
fail (printf "codecLocalStateQuery (%s) unexpected key (%d, %d)" (show stok) key len)
(ServerAgency TokAcquiring, _, _) ->
fail (printf "codecLocalStateQuery (%s) unexpected key (%d, %d)" (show stok) key len)
(ServerAgency (TokQuerying _), _, _) ->
fail (printf "codecLocalStateQuery (%s) unexpected key (%d, %d)" (show stok) key len)
-- | An identity 'Codec' for the 'LocalStateQuery' protocol. It does not do
any serialisation . It keeps the typed messages , wrapped in ' AnyMessage ' .
--
codecLocalStateQueryId
:: forall block point (query :: Type -> Type) m.
Monad m
=> (forall result1 result2.
query result1
-> query result2
-> Maybe (result1 :~: result2)
)
-> Codec (LocalStateQuery block point query)
CodecFailure m
(AnyMessage (LocalStateQuery block point query))
codecLocalStateQueryId eqQuery =
Codec encode decode
where
encode :: forall (pr :: PeerRole) st st'.
PeerHasAgency pr st
-> Message (LocalStateQuery block point query) st st'
-> AnyMessage (LocalStateQuery block point query)
encode _ = AnyMessage
decode :: forall (pr :: PeerRole) (st :: LocalStateQuery block point query).
PeerHasAgency pr st
-> m (DecodeStep (AnyMessage (LocalStateQuery block point query))
CodecFailure m (SomeMessage st))
decode stok = return $ DecodePartial $ \bytes -> case (stok, bytes) of
(ClientAgency TokIdle, Just (AnyMessage msg@(MsgAcquire{}))) -> res msg
(ClientAgency TokIdle, Just (AnyMessage msg@(MsgDone{}))) -> res msg
(ClientAgency TokAcquired, Just (AnyMessage msg@(MsgQuery{}))) -> res msg
(ClientAgency TokAcquired, Just (AnyMessage msg@(MsgReAcquire{}))) -> res msg
(ClientAgency TokAcquired, Just (AnyMessage msg@(MsgRelease{}))) -> res msg
(ServerAgency TokAcquiring, Just (AnyMessage msg@(MsgAcquired{}))) -> res msg
(ServerAgency TokAcquiring, Just (AnyMessage msg@(MsgFailure{}))) -> res msg
(ServerAgency (TokQuerying q), Just (AnyMessage msg@(MsgResult query _)))
| Just Refl <- eqQuery q query
-> res msg
(_, Nothing) -> return (DecodeFail CodecFailureOutOfInput)
(_, _) -> return (DecodeFail (CodecFailure failmsg))
res :: Message (LocalStateQuery block point query) st st'
-> m (DecodeStep bytes failure m (SomeMessage st))
res msg = return (DecodeDone (SomeMessage msg) Nothing)
failmsg = "codecLocalStateQueryId: no matching message"
| null | https://raw.githubusercontent.com/input-output-hk/ouroboros-network/2793b6993c8f6ed158f432055fa4ef581acdb661/ouroboros-network-protocols/src/Ouroboros/Network/Protocol/LocalStateQuery/Codec.hs | haskell | # LANGUAGE DataKinds #
# LANGUAGE RankNTypes #
# LANGUAGE TypeOperators #
failures per protocol state
| An identity 'Codec' for the 'LocalStateQuery' protocol. It does not do
| # LANGUAGE GADTs #
# LANGUAGE NamedFieldPuns #
# LANGUAGE PolyKinds #
# LANGUAGE ScopedTypeVariables #
module Ouroboros.Network.Protocol.LocalStateQuery.Codec
( codecLocalStateQuery
, codecLocalStateQueryId
, Some (..)
) where
import Control.Monad.Class.MonadST
import qualified Codec.CBOR.Decoding as CBOR
import qualified Codec.CBOR.Encoding as CBOR
import qualified Codec.CBOR.Read as CBOR
import Data.ByteString.Lazy (ByteString)
import Data.Kind (Type)
import Data.Type.Equality ((:~:) (..))
import Text.Printf
import Network.TypedProtocol.Codec.CBOR
import Ouroboros.Network.Protocol.LocalStateQuery.Type
data Some (f :: k -> Type) where
Some :: f a -> Some f
codecLocalStateQuery
:: forall block point query m.
( MonadST m
, ShowQuery query
)
=> (point -> CBOR.Encoding)
-> (forall s . CBOR.Decoder s point)
-> (forall result . query result -> CBOR.Encoding)
-> (forall s . CBOR.Decoder s (Some query))
-> (forall result . query result -> result -> CBOR.Encoding)
-> (forall result . query result -> forall s . CBOR.Decoder s result)
-> Codec (LocalStateQuery block point query) CBOR.DeserialiseFailure m ByteString
codecLocalStateQuery encodePoint decodePoint
encodeQuery decodeQuery
encodeResult decodeResult =
mkCodecCborLazyBS encode decode
where
encodeFailure :: AcquireFailure -> CBOR.Encoding
encodeFailure AcquireFailurePointTooOld = CBOR.encodeWord8 0
encodeFailure AcquireFailurePointNotOnChain = CBOR.encodeWord8 1
decodeFailure :: forall s. CBOR.Decoder s AcquireFailure
decodeFailure = do
tag <- CBOR.decodeWord8
case tag of
0 -> return AcquireFailurePointTooOld
1 -> return AcquireFailurePointNotOnChain
_ -> fail $ "decodeFailure: invalid tag " <> show tag
encode :: forall (pr :: PeerRole)
(st :: LocalStateQuery block point query)
(st' :: LocalStateQuery block point query).
PeerHasAgency pr st
-> Message (LocalStateQuery block point query) st st'
-> CBOR.Encoding
encode (ClientAgency TokIdle) (MsgAcquire (Just pt)) =
CBOR.encodeListLen 2
<> CBOR.encodeWord 0
<> encodePoint pt
encode (ClientAgency TokIdle) (MsgAcquire Nothing) =
CBOR.encodeListLen 1
<> CBOR.encodeWord 8
encode (ServerAgency TokAcquiring) MsgAcquired =
CBOR.encodeListLen 1
<> CBOR.encodeWord 1
encode (ServerAgency TokAcquiring) (MsgFailure failure) =
CBOR.encodeListLen 2
<> CBOR.encodeWord 2
<> encodeFailure failure
encode (ClientAgency TokAcquired) (MsgQuery query) =
CBOR.encodeListLen 2
<> CBOR.encodeWord 3
<> encodeQuery query
encode (ServerAgency (TokQuerying _query)) (MsgResult query result) =
CBOR.encodeListLen 2
<> CBOR.encodeWord 4
<> encodeResult query result
encode (ClientAgency TokAcquired) MsgRelease =
CBOR.encodeListLen 1
<> CBOR.encodeWord 5
encode (ClientAgency TokAcquired) (MsgReAcquire (Just pt)) =
CBOR.encodeListLen 2
<> CBOR.encodeWord 6
<> encodePoint pt
encode (ClientAgency TokAcquired) (MsgReAcquire Nothing) =
CBOR.encodeListLen 1
<> CBOR.encodeWord 9
encode (ClientAgency TokIdle) MsgDone =
CBOR.encodeListLen 1
<> CBOR.encodeWord 7
decode :: forall (pr :: PeerRole) s (st :: LocalStateQuery block point query).
PeerHasAgency pr st
-> CBOR.Decoder s (SomeMessage st)
decode stok = do
len <- CBOR.decodeListLen
key <- CBOR.decodeWord
case (stok, len, key) of
(ClientAgency TokIdle, 2, 0) -> do
pt <- decodePoint
return (SomeMessage (MsgAcquire (Just pt)))
(ClientAgency TokIdle, 1, 8) -> do
return (SomeMessage (MsgAcquire Nothing))
(ServerAgency TokAcquiring, 1, 1) ->
return (SomeMessage MsgAcquired)
(ServerAgency TokAcquiring, 2, 2) -> do
failure <- decodeFailure
return (SomeMessage (MsgFailure failure))
(ClientAgency TokAcquired, 2, 3) -> do
Some query <- decodeQuery
return (SomeMessage (MsgQuery query))
(ServerAgency (TokQuerying query), 2, 4) -> do
result <- decodeResult query
return (SomeMessage (MsgResult query result))
(ClientAgency TokAcquired, 1, 5) ->
return (SomeMessage MsgRelease)
(ClientAgency TokAcquired, 2, 6) -> do
pt <- decodePoint
return (SomeMessage (MsgReAcquire (Just pt)))
(ClientAgency TokAcquired, 1, 9) -> do
return (SomeMessage (MsgReAcquire Nothing))
(ClientAgency TokIdle, 1, 7) ->
return (SomeMessage MsgDone)
(ClientAgency TokIdle, _, _) ->
fail (printf "codecLocalStateQuery (%s) unexpected key (%d, %d)" (show stok) key len)
(ClientAgency TokAcquired, _, _) ->
fail (printf "codecLocalStateQuery (%s) unexpected key (%d, %d)" (show stok) key len)
(ServerAgency TokAcquiring, _, _) ->
fail (printf "codecLocalStateQuery (%s) unexpected key (%d, %d)" (show stok) key len)
(ServerAgency (TokQuerying _), _, _) ->
fail (printf "codecLocalStateQuery (%s) unexpected key (%d, %d)" (show stok) key len)
any serialisation . It keeps the typed messages , wrapped in ' AnyMessage ' .
codecLocalStateQueryId
:: forall block point (query :: Type -> Type) m.
Monad m
=> (forall result1 result2.
query result1
-> query result2
-> Maybe (result1 :~: result2)
)
-> Codec (LocalStateQuery block point query)
CodecFailure m
(AnyMessage (LocalStateQuery block point query))
codecLocalStateQueryId eqQuery =
Codec encode decode
where
encode :: forall (pr :: PeerRole) st st'.
PeerHasAgency pr st
-> Message (LocalStateQuery block point query) st st'
-> AnyMessage (LocalStateQuery block point query)
encode _ = AnyMessage
decode :: forall (pr :: PeerRole) (st :: LocalStateQuery block point query).
PeerHasAgency pr st
-> m (DecodeStep (AnyMessage (LocalStateQuery block point query))
CodecFailure m (SomeMessage st))
decode stok = return $ DecodePartial $ \bytes -> case (stok, bytes) of
(ClientAgency TokIdle, Just (AnyMessage msg@(MsgAcquire{}))) -> res msg
(ClientAgency TokIdle, Just (AnyMessage msg@(MsgDone{}))) -> res msg
(ClientAgency TokAcquired, Just (AnyMessage msg@(MsgQuery{}))) -> res msg
(ClientAgency TokAcquired, Just (AnyMessage msg@(MsgReAcquire{}))) -> res msg
(ClientAgency TokAcquired, Just (AnyMessage msg@(MsgRelease{}))) -> res msg
(ServerAgency TokAcquiring, Just (AnyMessage msg@(MsgAcquired{}))) -> res msg
(ServerAgency TokAcquiring, Just (AnyMessage msg@(MsgFailure{}))) -> res msg
(ServerAgency (TokQuerying q), Just (AnyMessage msg@(MsgResult query _)))
| Just Refl <- eqQuery q query
-> res msg
(_, Nothing) -> return (DecodeFail CodecFailureOutOfInput)
(_, _) -> return (DecodeFail (CodecFailure failmsg))
res :: Message (LocalStateQuery block point query) st st'
-> m (DecodeStep bytes failure m (SomeMessage st))
res msg = return (DecodeDone (SomeMessage msg) Nothing)
failmsg = "codecLocalStateQueryId: no matching message"
|
2d6b8920de8eaf8abd39660b2061dba6b3ffd051d89484bac96973ef80ddaf06 | dyoo/whalesong | printing.rkt | #lang whalesong
(current-print-mode "constructor")
'(1 2 3)
(list "hello" "world")
(list 'hello 'world)
(cons 1 2)
(cons 1 (cons 2 (cons 3 empty)))
(cons 1 (cons 2 (cons 3 4)))
'()
'hello
(box 'hello)
(vector 'hello 'world)
(define-struct person (name age))
(person 'danny 32)
(person "jerry" 32)
This is slightly broken : we should follow shared printing
;; notation.
(shared ([a (cons 1 a)])
a)
| null | https://raw.githubusercontent.com/dyoo/whalesong/636e0b4e399e4523136ab45ef4cd1f5a84e88cdc/whalesong/tests/more-tests/printing.rkt | racket | notation. | #lang whalesong
(current-print-mode "constructor")
'(1 2 3)
(list "hello" "world")
(list 'hello 'world)
(cons 1 2)
(cons 1 (cons 2 (cons 3 empty)))
(cons 1 (cons 2 (cons 3 4)))
'()
'hello
(box 'hello)
(vector 'hello 'world)
(define-struct person (name age))
(person 'danny 32)
(person "jerry" 32)
This is slightly broken : we should follow shared printing
(shared ([a (cons 1 a)])
a)
|
149b0950e8c7c9ac22a0a99c8b6499a718265497749aa2c84c39742840a73941 | bschwind/earthquakes | db.cljs | (ns earthquakes.db
(:require [clojure.spec :as s]))
;; spec of app-db
(s/def ::magnitude number?)
(s/def ::longitude number?)
(s/def ::latitude number?)
(s/def ::depth number?)
(s/def ::quake-description string?)
(s/def ::earthquake (s/keys
:req-un [::magnitude ::longitude ::latitude ::depth ::quake-description]))
(s/def ::greeting string?)
(s/def ::loading boolean?)
(s/def ::earthquakes (s/* ::earthquake))
(s/def ::app-db
(s/keys :req-un [::greeting ::loading ::earthquakes]))
;; initial state of app-db
(def app-db {:greeting "Hello Clojure in iOS and Android!"
:loading false
:earthquakes [{:magnitude 3.4
:latitude 35.713765
:longitude 139.704039
:depth 0
:quake-description "Oh no"}
{:magnitude 3.4
:latitude 37.713765
:longitude 139.704039
:depth 0
:quake-description "Hey"}]})
| null | https://raw.githubusercontent.com/bschwind/earthquakes/265d2e27504ee50f1a815a89a85601e9715af1d7/src/earthquakes/db.cljs | clojure | spec of app-db
initial state of app-db | (ns earthquakes.db
(:require [clojure.spec :as s]))
(s/def ::magnitude number?)
(s/def ::longitude number?)
(s/def ::latitude number?)
(s/def ::depth number?)
(s/def ::quake-description string?)
(s/def ::earthquake (s/keys
:req-un [::magnitude ::longitude ::latitude ::depth ::quake-description]))
(s/def ::greeting string?)
(s/def ::loading boolean?)
(s/def ::earthquakes (s/* ::earthquake))
(s/def ::app-db
(s/keys :req-un [::greeting ::loading ::earthquakes]))
(def app-db {:greeting "Hello Clojure in iOS and Android!"
:loading false
:earthquakes [{:magnitude 3.4
:latitude 35.713765
:longitude 139.704039
:depth 0
:quake-description "Oh no"}
{:magnitude 3.4
:latitude 37.713765
:longitude 139.704039
:depth 0
:quake-description "Hey"}]})
|
0ad510983433412d6d98131c67a9c03ced04525cf4ece80c3f1849c1200ee921 | tsloughter/kuberl | kuberl_v1_volume_attachment_list.erl | -module(kuberl_v1_volume_attachment_list).
-export([encode/1]).
-export_type([kuberl_v1_volume_attachment_list/0]).
-type kuberl_v1_volume_attachment_list() ::
#{ 'apiVersion' => binary(),
'items' := list(),
'kind' => binary(),
'metadata' => kuberl_v1_list_meta:kuberl_v1_list_meta()
}.
encode(#{ 'apiVersion' := ApiVersion,
'items' := Items,
'kind' := Kind,
'metadata' := Metadata
}) ->
#{ 'apiVersion' => ApiVersion,
'items' => Items,
'kind' => Kind,
'metadata' => Metadata
}.
| null | https://raw.githubusercontent.com/tsloughter/kuberl/f02ae6680d6ea5db6e8b6c7acbee8c4f9df482e2/gen/kuberl_v1_volume_attachment_list.erl | erlang | -module(kuberl_v1_volume_attachment_list).
-export([encode/1]).
-export_type([kuberl_v1_volume_attachment_list/0]).
-type kuberl_v1_volume_attachment_list() ::
#{ 'apiVersion' => binary(),
'items' := list(),
'kind' => binary(),
'metadata' => kuberl_v1_list_meta:kuberl_v1_list_meta()
}.
encode(#{ 'apiVersion' := ApiVersion,
'items' := Items,
'kind' := Kind,
'metadata' := Metadata
}) ->
#{ 'apiVersion' => ApiVersion,
'items' => Items,
'kind' => Kind,
'metadata' => Metadata
}.
|
|
4a77113d10576d7759080cd580af1820069db37af67c1525a221f905c4c53f65 | ocaml-multicore/tezos | script_set.mli | (*****************************************************************************)
(* *)
(* Open Source License *)
Copyright ( c ) 2018 Dynamic Ledger Solutions , Inc. < >
Copyright ( c ) 2020 Metastate AG < >
(* *)
(* Permission is hereby granted, free of charge, to any person obtaining a *)
(* copy of this software and associated documentation files (the "Software"),*)
to deal in the Software without restriction , including without limitation
(* the rights to use, copy, modify, merge, publish, distribute, sublicense, *)
and/or sell copies of the Software , and to permit persons to whom the
(* Software is furnished to do so, subject to the following conditions: *)
(* *)
(* The above copyright notice and this permission notice shall be included *)
(* in all copies or substantial portions of the Software. *)
(* *)
THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND , EXPRESS OR
(* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *)
(* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL *)
(* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER*)
LIABILITY , WHETHER IN AN ACTION OF CONTRACT , TORT OR OTHERWISE , ARISING
(* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER *)
(* DEALINGS IN THE SOFTWARE. *)
(* *)
(*****************************************************************************)
(** Convert a list to a Script IR set. If the list contains duplicates,
the last occurence is used. *)
val of_list :
'a Protocol.Script_typed_ir.comparable_ty ->
'a list ->
'a Protocol.Script_typed_ir.set
| null | https://raw.githubusercontent.com/ocaml-multicore/tezos/e4fd21a1cb02d194b3162ab42d512b7c985ee8a9/src/proto_012_Psithaca/lib_protocol/test/helpers/script_set.mli | ocaml | ***************************************************************************
Open Source License
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Software"),
the rights to use, copy, modify, merge, publish, distribute, sublicense,
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
***************************************************************************
* Convert a list to a Script IR set. If the list contains duplicates,
the last occurence is used. | Copyright ( c ) 2018 Dynamic Ledger Solutions , Inc. < >
Copyright ( c ) 2020 Metastate AG < >
to deal in the Software without restriction , including without limitation
and/or sell copies of the Software , and to permit persons to whom the
THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND , EXPRESS OR
LIABILITY , WHETHER IN AN ACTION OF CONTRACT , TORT OR OTHERWISE , ARISING
val of_list :
'a Protocol.Script_typed_ir.comparable_ty ->
'a list ->
'a Protocol.Script_typed_ir.set
|
bc9bcfd80439272f63148258bb5190bc448487bc06ac3db3349c53c874107f6f | EligiusSantori/L2Apf | ask_be_friends.scm | (module system racket/base
(require racket/string "../../packet.scm")
(provide game-server-packet/ask-be-friends)
(define (game-server-packet/ask-be-friends buffer)
(let ((s (open-input-bytes buffer)))
(list
(cons 'id (read-byte s))
(cons 'name (string-trim (read-utf16 s)))
)
)
)
)
| null | https://raw.githubusercontent.com/EligiusSantori/L2Apf/30ffe0828e8a401f58d39984efd862c8aeab8c30/packet/game/server/ask_be_friends.scm | scheme | (module system racket/base
(require racket/string "../../packet.scm")
(provide game-server-packet/ask-be-friends)
(define (game-server-packet/ask-be-friends buffer)
(let ((s (open-input-bytes buffer)))
(list
(cons 'id (read-byte s))
(cons 'name (string-trim (read-utf16 s)))
)
)
)
)
|
|
bf0b35282e9dc626b84c9db606d9b7d21182f3a3b899fa8d8bd12c045e39ef42 | liquidz/cuma | layout.clj | (ns cuma.extension.layout
(:require
[clojure.java.io :as io]
[filemodc.core :as fm])
(:import
[java.io FileNotFoundException]))
(def ^:private tmpl-cache (fm/init))
(defn- slurp-template
[^java.io.File f & [default-value]]
(try
(slurp f)
(catch FileNotFoundException e
default-value)))
(defn- slurp-template*
[^java.io.File f]
(if (fm/modified? tmpl-cache f)
(when-let [tmpl (slurp-template f)]
(fm/register! tmpl-cache f :optional {:content tmpl})
tmpl)
(-> (fm/lookup tmpl-cache f) :optional :content)))
(defn- block
[local-var data body block-name]
(let [render (:render data)
content (render body data)]
(swap! local-var assoc block-name content)
""))
(defn layout-file
[data body filename]
(let [render (:render data)
layout-body (slurp-template* (io/file filename))
local-var (atom {})
data* (merge {:block (partial block local-var)} data)
content (render body data*)]
(if layout-body
(render layout-body (merge data @local-var {:. content}))
content)))
| null | https://raw.githubusercontent.com/liquidz/cuma/120ff58a8601e0911591696622ad385e0616f1ff/src/cuma/extension/layout.clj | clojure | (ns cuma.extension.layout
(:require
[clojure.java.io :as io]
[filemodc.core :as fm])
(:import
[java.io FileNotFoundException]))
(def ^:private tmpl-cache (fm/init))
(defn- slurp-template
[^java.io.File f & [default-value]]
(try
(slurp f)
(catch FileNotFoundException e
default-value)))
(defn- slurp-template*
[^java.io.File f]
(if (fm/modified? tmpl-cache f)
(when-let [tmpl (slurp-template f)]
(fm/register! tmpl-cache f :optional {:content tmpl})
tmpl)
(-> (fm/lookup tmpl-cache f) :optional :content)))
(defn- block
[local-var data body block-name]
(let [render (:render data)
content (render body data)]
(swap! local-var assoc block-name content)
""))
(defn layout-file
[data body filename]
(let [render (:render data)
layout-body (slurp-template* (io/file filename))
local-var (atom {})
data* (merge {:block (partial block local-var)} data)
content (render body data*)]
(if layout-body
(render layout-body (merge data @local-var {:. content}))
content)))
|
|
f15d105e745a9a1f08aa7aa404a651108a5c3e650de7cf210c83e44d0fedc000 | ghc/packages-dph | Test.hs |
module Test
( module Data.Array.Parallel.Unlifted.Distributed
, module Data.Array.Parallel.Unlifted.Parallel
, module Data.Array.Parallel.Pretty
, module Data.Array.Parallel.Unlifted.Distributed.Types
, usegd
, upssegd
, pdatas
, results)
where
import Data.Array.Parallel.Pretty hiding (empty)
import Data.Array.Parallel.Unlifted.Parallel
import Data.Array.Parallel.Unlifted.Distributed
import Data.Array.Parallel.Unlifted.Distributed.Types
import Data.Array.Parallel.Unlifted.Sequential.USegd
import qualified Data.Array.Parallel.Unlifted.Parallel.UPSegd as UPSegd
import qualified Data.Array.Parallel.Unlifted.Parallel.UPSSegd as UPSSegd
import qualified Data.Array.Parallel.Unlifted.Sequential.Combinators as Seq
import qualified Data.Vector.Unboxed as U
import qualified Data.Vector as V
usegd = lengthsToUSegd
(U.fromList [80, 10, 20, 40, 50, 10])
upssegd = UPSSegd.mkUPSSegd
(U.fromList [100, 190, 200, 300, 450, 490])
(U.fromList [0, 0, 1, 2, 2, 3])
usegd
pdatas :: V.Vector (U.Vector Int)
pdatas = V.fromList
[ U.enumFromTo 0 499
, U.enumFromTo 1000 1499
, U.enumFromTo 2000 2499
, U.enumFromTo 3000 3499 ]
results = UPSSegd.foldSegsWith (+)
(Seq.foldSSU (+) 0)
upssegd pdatas | null | https://raw.githubusercontent.com/ghc/packages-dph/64eca669f13f4d216af9024474a3fc73ce101793/dph-prim-par/examples/Test.hs | haskell |
module Test
( module Data.Array.Parallel.Unlifted.Distributed
, module Data.Array.Parallel.Unlifted.Parallel
, module Data.Array.Parallel.Pretty
, module Data.Array.Parallel.Unlifted.Distributed.Types
, usegd
, upssegd
, pdatas
, results)
where
import Data.Array.Parallel.Pretty hiding (empty)
import Data.Array.Parallel.Unlifted.Parallel
import Data.Array.Parallel.Unlifted.Distributed
import Data.Array.Parallel.Unlifted.Distributed.Types
import Data.Array.Parallel.Unlifted.Sequential.USegd
import qualified Data.Array.Parallel.Unlifted.Parallel.UPSegd as UPSegd
import qualified Data.Array.Parallel.Unlifted.Parallel.UPSSegd as UPSSegd
import qualified Data.Array.Parallel.Unlifted.Sequential.Combinators as Seq
import qualified Data.Vector.Unboxed as U
import qualified Data.Vector as V
usegd = lengthsToUSegd
(U.fromList [80, 10, 20, 40, 50, 10])
upssegd = UPSSegd.mkUPSSegd
(U.fromList [100, 190, 200, 300, 450, 490])
(U.fromList [0, 0, 1, 2, 2, 3])
usegd
pdatas :: V.Vector (U.Vector Int)
pdatas = V.fromList
[ U.enumFromTo 0 499
, U.enumFromTo 1000 1499
, U.enumFromTo 2000 2499
, U.enumFromTo 3000 3499 ]
results = UPSSegd.foldSegsWith (+)
(Seq.foldSSU (+) 0)
upssegd pdatas |
|
5b1e36ca7b0b126e5041b521797b87446e7ddcd802c42c3c88a39e30efd5b1a6 | herd/herdtools7 | log_test.ml | (****************************************************************************)
(* the diy toolsuite *)
(* *)
, University College London , UK .
, INRIA Paris - Rocquencourt , France .
(* *)
Copyright 2010 - present Institut National de Recherche en Informatique et
(* en Automatique and the authors. All rights reserved. *)
(* *)
This software is governed by the CeCILL - B license under French law and
(* abiding by the rules of distribution of free software. You can use, *)
modify and/ or redistribute the software under the terms of the CeCILL - B
license as circulated by CEA , CNRS and INRIA at the following URL
" " . We also give a copy in LICENSE.txt .
(****************************************************************************)
(** Tests for the Log module. *)
module Fun = Base.Fun
module LogList = struct
let compare = Base.List.compare Log.compare
let to_ocaml_string = Base.List.to_ocaml_string Log.to_ocaml_string
end
let tests = [
"Log.of_string_list", (fun () ->
let tests = [
[
"Test A4 Allowed" ;
"States 1" ;
"0:X0=0;" ;
"Ok" ;
"Witnesses" ;
"Positive: 1 Negative: 0" ;
"Condition exists (0:X0=0)" ;
"Observation A4 Always 1 0" ;
"Time A4 0.00" ;
"Hash=b0a348f458429140b16552cc100cdc7c" ;
], [
{
Log.name = "A4" ;
Log.kind = Some ConstrGen.Allow ;
} ;
] ;
[
"Test A4 Allowed" ;
"States 1" ;
"0:X0=0;" ;
"Ok" ;
"Witnesses" ;
"Positive: 1 Negative: 0" ;
"Condition exists (0:X0=0)" ;
"Observation A4 Always 1 0" ;
"Time A4 0.00" ;
"Hash=b0a348f458429140b16552cc100cdc7c" ;
"" ;
"Test A8 Forbid" ;
"States 1" ;
"0:X0=0; 0:X1=x+44;" ;
"Ok" ;
"Witnesses" ;
"Positive: 1 Negative: 0" ;
"Condition exists (0:X0=0 /\ not (0:X1=x))" ;
"Observation A8 Always 1 0" ;
"Time A8 0.00" ;
"Hash=d1591baf0ba882a97685e1fa37c64e74" ;
], [
{
Log.name = "A4" ;
Log.kind = Some ConstrGen.Allow ;
} ;
{
Log.name = "A8" ;
Log.kind = Some ConstrGen.Allow ;
} ;
] ;
] in
List.iteri (fun i (log, expected) ->
let actual = Log.of_string_list log in
if LogList.compare actual expected <> 0 then
Test.fail (Printf.sprintf "[%i] expected %s, got %s" i (LogList.to_ocaml_string expected) (LogList.to_ocaml_string actual))
) tests
);
]
let () = Test.run tests
| null | https://raw.githubusercontent.com/herd/herdtools7/27263ad58cf5248d60010ce9b1202bbdacf05a4d/internal/lib/tests/log_test.ml | ocaml | **************************************************************************
the diy toolsuite
en Automatique and the authors. All rights reserved.
abiding by the rules of distribution of free software. You can use,
**************************************************************************
* Tests for the Log module. | , University College London , UK .
, INRIA Paris - Rocquencourt , France .
Copyright 2010 - present Institut National de Recherche en Informatique et
This software is governed by the CeCILL - B license under French law and
modify and/ or redistribute the software under the terms of the CeCILL - B
license as circulated by CEA , CNRS and INRIA at the following URL
" " . We also give a copy in LICENSE.txt .
module Fun = Base.Fun
module LogList = struct
let compare = Base.List.compare Log.compare
let to_ocaml_string = Base.List.to_ocaml_string Log.to_ocaml_string
end
let tests = [
"Log.of_string_list", (fun () ->
let tests = [
[
"Test A4 Allowed" ;
"States 1" ;
"0:X0=0;" ;
"Ok" ;
"Witnesses" ;
"Positive: 1 Negative: 0" ;
"Condition exists (0:X0=0)" ;
"Observation A4 Always 1 0" ;
"Time A4 0.00" ;
"Hash=b0a348f458429140b16552cc100cdc7c" ;
], [
{
Log.name = "A4" ;
Log.kind = Some ConstrGen.Allow ;
} ;
] ;
[
"Test A4 Allowed" ;
"States 1" ;
"0:X0=0;" ;
"Ok" ;
"Witnesses" ;
"Positive: 1 Negative: 0" ;
"Condition exists (0:X0=0)" ;
"Observation A4 Always 1 0" ;
"Time A4 0.00" ;
"Hash=b0a348f458429140b16552cc100cdc7c" ;
"" ;
"Test A8 Forbid" ;
"States 1" ;
"0:X0=0; 0:X1=x+44;" ;
"Ok" ;
"Witnesses" ;
"Positive: 1 Negative: 0" ;
"Condition exists (0:X0=0 /\ not (0:X1=x))" ;
"Observation A8 Always 1 0" ;
"Time A8 0.00" ;
"Hash=d1591baf0ba882a97685e1fa37c64e74" ;
], [
{
Log.name = "A4" ;
Log.kind = Some ConstrGen.Allow ;
} ;
{
Log.name = "A8" ;
Log.kind = Some ConstrGen.Allow ;
} ;
] ;
] in
List.iteri (fun i (log, expected) ->
let actual = Log.of_string_list log in
if LogList.compare actual expected <> 0 then
Test.fail (Printf.sprintf "[%i] expected %s, got %s" i (LogList.to_ocaml_string expected) (LogList.to_ocaml_string actual))
) tests
);
]
let () = Test.run tests
|
53034ee8907e1c41e5202574753d5a37e5998e9065745e9209ecc79a72dc5e0e | rabbitmq/erlando | error_t.erl | The contents of this file are subject to the Mozilla Public License
%% Version 1.1 (the "License"); you may not use this file except in
%% compliance with the License. You may obtain a copy of the License
%% at /
%%
Software distributed under the License is distributed on an " AS IS "
%% basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See
%% the License for the specific language governing rights and
%% limitations under the License.
%%
The Original Code is Erlando .
%%
The Initial Developer of the Original Code is VMware , Inc.
Copyright ( c ) 2011 - 2013 VMware , Inc. All rights reserved .
%%
-module(error_t).
-compile({parse_transform, do}).
-export_type([error_t/2]).
-behaviour(monad_trans).
-export([new/1, '>>='/3, return/2, fail/2, run/2, lift/2]).
-opaque error_t(M, A) :: monad:monadic(M, ok | {ok, A} | {error, any()}).
-spec new(M) -> TM when TM :: monad:monad(), M :: monad:monad().
new(M) ->
{?MODULE, M}.
-spec '>>='(error_t(M, A), fun( (A) -> error_t(M, B) ), M) -> error_t(M, B).
'>>='(X, Fun, {?MODULE, M}) ->
do([M || R <- X,
case R of
{error, _Err} = Error -> return(Error);
{ok, Result} -> Fun(Result);
ok -> Fun(ok)
end
]).
-spec return(A, M) -> error_t(M, A).
return(ok, {?MODULE, M}) -> M:return(ok);
return(X , {?MODULE, M}) -> M:return({ok, X}).
%% This is the equivalent of
%% fail msg = ErrorT $ return (Left (strMsg msg))
from the instance ( , Error e ) = > Monad ( ErrorT e m )
%%
%% -Monad-Error.html#ErrorT
%%
%% I.e. note that calling fail on the outer monad is not a failure of
%% the inner monad: it is success of the inner monad, but the failure
%% is encapsulated.
-spec fail(any(), M) -> error_t(M, _A).
fail(E, {?MODULE, M}) ->
M:return({error, E}).
-spec run(error_t(M, A), M) -> monad:monadic(M, ok | {ok, A} | {error, any()}).
run(EM, _M) -> EM.
-spec lift(monad:monadic(M, A), M) -> error_t(M, A).
lift(X, {?MODULE, M}) ->
do([M || A <- X,
return({ok, A})]).
| null | https://raw.githubusercontent.com/rabbitmq/erlando/1c1ef25a9bc228671b32b4a6ee30c7525314b1fd/src/error_t.erl | erlang | Version 1.1 (the "License"); you may not use this file except in
compliance with the License. You may obtain a copy of the License
at /
basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See
the License for the specific language governing rights and
limitations under the License.
This is the equivalent of
fail msg = ErrorT $ return (Left (strMsg msg))
-Monad-Error.html#ErrorT
I.e. note that calling fail on the outer monad is not a failure of
the inner monad: it is success of the inner monad, but the failure
is encapsulated. | The contents of this file are subject to the Mozilla Public License
Software distributed under the License is distributed on an " AS IS "
The Original Code is Erlando .
The Initial Developer of the Original Code is VMware , Inc.
Copyright ( c ) 2011 - 2013 VMware , Inc. All rights reserved .
-module(error_t).
-compile({parse_transform, do}).
-export_type([error_t/2]).
-behaviour(monad_trans).
-export([new/1, '>>='/3, return/2, fail/2, run/2, lift/2]).
-opaque error_t(M, A) :: monad:monadic(M, ok | {ok, A} | {error, any()}).
-spec new(M) -> TM when TM :: monad:monad(), M :: monad:monad().
new(M) ->
{?MODULE, M}.
-spec '>>='(error_t(M, A), fun( (A) -> error_t(M, B) ), M) -> error_t(M, B).
'>>='(X, Fun, {?MODULE, M}) ->
do([M || R <- X,
case R of
{error, _Err} = Error -> return(Error);
{ok, Result} -> Fun(Result);
ok -> Fun(ok)
end
]).
-spec return(A, M) -> error_t(M, A).
return(ok, {?MODULE, M}) -> M:return(ok);
return(X , {?MODULE, M}) -> M:return({ok, X}).
from the instance ( , Error e ) = > Monad ( ErrorT e m )
-spec fail(any(), M) -> error_t(M, _A).
fail(E, {?MODULE, M}) ->
M:return({error, E}).
-spec run(error_t(M, A), M) -> monad:monadic(M, ok | {ok, A} | {error, any()}).
run(EM, _M) -> EM.
-spec lift(monad:monadic(M, A), M) -> error_t(M, A).
lift(X, {?MODULE, M}) ->
do([M || A <- X,
return({ok, A})]).
|
a3ad8d8524333600d3c461adae139c2de73f69ac77717b3f0d8207fc73d762ad | fishcakez/sbroker | sregulator_statem2_valve.erl | %%-------------------------------------------------------------------
%%
Copyright ( c ) 2016 , < >
%%
This file is provided to you under the Apache License ,
%% Version 2.0 (the "License"); you may not use this file
%% except in compliance with the License. You may obtain
%% a copy of the License at
%%
%% -2.0
%%
%% Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
" AS IS " BASIS , WITHOUT WARRANTIES OR CONDITIONS OF ANY
%% KIND, either express or implied. See the License for the
%% specific language governing permissions and limitations
%% under the License.
%%
%%-------------------------------------------------------------------
-module(sregulator_statem2_valve).
-behaviour(sregulator_valve).
%% sregulator_valve_api
-export([init/3]).
-export([handle_ask/4]).
-export([handle_done/3]).
-export([handle_continue/3]).
-export([handle_update/3]).
-export([handle_info/3]).
-export([handle_timeout/2]).
-export([code_change/4]).
-export([config_change/3]).
-export([size/1]).
-export([open_time/1]).
-export([terminate/2]).
%% sregulator_valve api
init(Map, Time, Opens) ->
sregulator_statem_valve:init(Map, Time, Opens).
handle_ask(Pid, Ref, Time, State) ->
sregulator_statem_valve:handle_ask(Pid, Ref, Time, State).
handle_done(Ref, Time, State) ->
sregulator_statem_valve:handle_done(Ref, Time, State).
handle_continue(Ref, Time, State) ->
sregulator_statem_valve:handle_continue(Ref, Time, State).
handle_update(Value, Time, State) ->
sregulator_statem_valve:handle_update(Value, Time, State).
handle_info(Msg, Time, State) ->
sregulator_statem_valve:handle_info(Msg, Time, State).
handle_timeout(Time, State) ->
sregulator_statem_valve:handle_timeout(Time, State).
code_change(OldVsn, Time, State, Extra) ->
sregulator_statem_valve:code_change(OldVsn, Time, State, Extra).
config_change(Opens, Time, State) ->
sregulator_statem_valve:config_change(Opens, Time, State).
size(State) ->
sregulator_statem_valve:size(State).
open_time(State) ->
sregulator_statem_valve:open_time(State).
terminate(Reason, State) ->
sregulator_statem_valve:terminate(Reason, State).
| null | https://raw.githubusercontent.com/fishcakez/sbroker/10f7e3970d0a296fbf08b1d1a94c88979a7deb5e/test/sregulator_statem2_valve.erl | erlang | -------------------------------------------------------------------
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,
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
-------------------------------------------------------------------
sregulator_valve_api
sregulator_valve api | Copyright ( c ) 2016 , < >
This file is provided to you under the Apache License ,
software distributed under the License is distributed on an
" AS IS " BASIS , WITHOUT WARRANTIES OR CONDITIONS OF ANY
-module(sregulator_statem2_valve).
-behaviour(sregulator_valve).
-export([init/3]).
-export([handle_ask/4]).
-export([handle_done/3]).
-export([handle_continue/3]).
-export([handle_update/3]).
-export([handle_info/3]).
-export([handle_timeout/2]).
-export([code_change/4]).
-export([config_change/3]).
-export([size/1]).
-export([open_time/1]).
-export([terminate/2]).
init(Map, Time, Opens) ->
sregulator_statem_valve:init(Map, Time, Opens).
handle_ask(Pid, Ref, Time, State) ->
sregulator_statem_valve:handle_ask(Pid, Ref, Time, State).
handle_done(Ref, Time, State) ->
sregulator_statem_valve:handle_done(Ref, Time, State).
handle_continue(Ref, Time, State) ->
sregulator_statem_valve:handle_continue(Ref, Time, State).
handle_update(Value, Time, State) ->
sregulator_statem_valve:handle_update(Value, Time, State).
handle_info(Msg, Time, State) ->
sregulator_statem_valve:handle_info(Msg, Time, State).
handle_timeout(Time, State) ->
sregulator_statem_valve:handle_timeout(Time, State).
code_change(OldVsn, Time, State, Extra) ->
sregulator_statem_valve:code_change(OldVsn, Time, State, Extra).
config_change(Opens, Time, State) ->
sregulator_statem_valve:config_change(Opens, Time, State).
size(State) ->
sregulator_statem_valve:size(State).
open_time(State) ->
sregulator_statem_valve:open_time(State).
terminate(Reason, State) ->
sregulator_statem_valve:terminate(Reason, State).
|
c05c39158bb21473d19ba9b66b03d850c3d7210f6f5f0e696c1bcfd1fee7d54b | VisionsGlobalEmpowerment/webchange | index.cljs | (ns webchange.student.pages.index
(:require
[webchange.student.pages.sign-in.views :as sign-in]))
(def pages
{:sign-in sign-in/page})
| null | https://raw.githubusercontent.com/VisionsGlobalEmpowerment/webchange/6107ca500496df6cf7179f621d48d06fd8c4de2b/src/cljs/webchange/student/pages/index.cljs | clojure | (ns webchange.student.pages.index
(:require
[webchange.student.pages.sign-in.views :as sign-in]))
(def pages
{:sign-in sign-in/page})
|
|
07ef3eea46b2027b875d241b55269ea95ba9bc1e83514ef152b44a238871c36e | proglang/ldgv | Generate.hs | {-# LANGUAGE BangPatterns #-}
# LANGUAGE BlockArguments #
# LANGUAGE DataKinds #
# LANGUAGE DerivingStrategies #
# LANGUAGE DerivingVia #
# LANGUAGE FlexibleContexts #
{-# LANGUAGE GADTs #-}
# LANGUAGE GeneralizedNewtypeDeriving #
# LANGUAGE LambdaCase #
{-# LANGUAGE MultiWayIf #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RankNTypes #-}
# LANGUAGE ScopedTypeVariables #
# LANGUAGE TemplateHaskell #
# LANGUAGE TupleSections #
# LANGUAGE TypeApplications #
# LANGUAGE TypeFamilies #
# LANGUAGE ViewPatterns #
# OPTIONS_GHC -Wall #
module C.Generate (generate) where
import Control.Applicative
import Control.Lens
import Control.Monad.Except
import Control.Monad.RWS.Strict
import Control.Monad.State.Strict
import Control.Monad.Trans.Maybe
import Control.Monad.Writer.Strict
import Data.Bifunctor
import Data.ByteString.Builder (Builder)
import Data.Coerce
import Data.Foldable
import Data.List.NonEmpty (NonEmpty)
import Data.Map (Map)
import Data.Maybe
import Data.Proxy
import Data.Semigroup as S
import Data.Set (Set)
import Data.String
import Data.Version
import Kinds (Multiplicity(..))
import C.MonadStack
import Numeric
import C.CPS
import Validation
import qualified Data.ByteString.Builder as B
import qualified Data.Char as C
import qualified Data.List as List
import qualified Data.Map.Strict as Map
import qualified Data.Set as Set
import qualified Paths_ldgv
import qualified Syntax as S
-- | Type level tag for values.
--
-- @
-- union LDST_val {
-- int val_int;
-- LDST_t *val_pair;
-- LDST_chan_t *val_chan;
val_lam ;
-- const char *val_label;
-- };
-- @
data V
-- | Type level tag for lambdas.
--
-- @
-- struct LDST_lam {
LDST_fp fp ;
-- LDST_t *closure;
-- };
-- @
data L
-- | Type level tag for channels.
data C
-- | Type level tag for continuations.
--
-- @
-- struct LDST_cont {
LDST_fp fp ;
-- LDST_t *closure;
-- LDST_cont_t *cont;
-- };
-- @
data K
-- | Type level tag for @LDST_ctxt_t@.
data T
-- | Type level tag for @LDST_res_t@.
--
-- @
-- enum LDST_res {
LDST_OK ,
LDST_NO_MEM ,
-- LDST_DEADLOCK,
LDST_UNMATCHED_LABEL ,
-- };
-- @
data R
| Type level tag for a pointer to
data Pointer a
| Represents an expression of type
newtype CExp t = CExp { unCExp :: Builder }
TODO : By using an ADT to differentiate what the expression might represent
-- we could generate more idiomatic code. This isn't terribly necessary though,
-- the common C compilers are able to understand and optimize our intentions
-- quite well.
| Represents a variable reference of type
newtype CVar t = CVar { unCVar :: Builder }
newtype CStmt = CStmt Builder
deriving newtype (Semigroup, Monoid)
data Tag a where
TagInt :: Tag Int
TagDouble :: Tag Double
TagString :: Tag String
TagLabel :: Tag String
TagPair :: Tag (CExp V, CExp V)
TagLam :: Tag (CExp L)
TagChan :: Tag (CExp (Pointer C))
data FunctionArgs = FunctionArgs
{ funClosure :: [Maybe Ident]
-- ^ Variables accessible through the closure argument at the corresponding
-- index. The identifiers must be in ascending order. @Nothing@ slots
-- shouldn't be accessed.
, funArgIdent :: Ident
, funRecIdent :: Maybe Ident
-- ^ @Just ident@ if this function can call itself recursively with
-- identifier @ident@.
}
data FunctionHeader = FunctionHeader
{ funName :: !Builder
, funArgs :: !(Maybe FunctionArgs)
-- ^ A pair of the identifiers carried by the closure parameter and the
-- functions argument.
, funInternal :: !Bool
^ @True@ if this function is only used internally and should get
-- @static@ linkage.
--
Internal functions originate from lambda expressions while the nullary
-- top level functions correspond to non-internal functions.
}
data Function = Function
{ funHeader :: !FunctionHeader
, funHint :: !NameHint
-- ^ See '_infoNameHint'.
, funNestPrefix :: !NameHint
-- ^ See '_infoNestPrefix'.
, funBody :: !Exp
}
data Closure = Closure
{ _closureVars :: ![Maybe Ident]
-- ^ List of captured identifiers. The order corresponds to the order in
-- the C code in 'closureExpr', the identifiers must be in ascending order.
--
-- @Nothing@ values should not be accessed, these are slots indicating a
-- closure is reused but only with a subset of captured values.
, _closureExpr :: !(CExp (Pointer V))
-- ^ An expression of type @union LDST_t*@.
}
| A mapping from locally bound variables to their corresponding ' CVar ' .
type Env = Map Ident (CVar V)
-- | A newtype wrapping a builder to highlight the expected usage of the
-- wrapped value.
newtype NameHint = NameHint Builder
deriving newtype (IsString)
data Info = Info
{ _infoBindings :: !Env
-- ^ Mapping from bound variables to the corresponding identifiers in the
-- generated C code.
, _infoContinuation :: !(CVar (Pointer K))
-- ^ The current continuation.
, _infoNameHint :: !NameHint
^ Prepended to all fresh variables , helps with understandability of the
-- generated C code and tracking to which expression the variables belong.
, _infoNestPrefix :: !NameHint
^ Prepended to all functions originating from splitting lambdas and
-- continuations out of their enclosing function. This is necessary to be
-- unique per function, otherwise the generated function names might clash.
, _infoIndent :: !Int
-- ^ Current indent level.
}
data GenSt = GenSt
{ _stUnique :: !Word
, _stClosures :: ![Closure]
}
makeLenses ''Info
makeLenses ''GenSt
makeLenses ''Closure
class ExpLike e where
toCExp :: e t -> CExp t
instance ExpLike CExp where
toCExp = id
instance ExpLike CVar where
toCExp = coerce
class CType t where
typeName :: proxy t -> Builder
instance CType V where
typeName _ = "LDST_t"
instance CType L where
typeName _ = "LDST_lam_t"
instance CType C where
typeName _ = "LDST_chan_t"
instance CType K where
typeName _ = "LDST_cont_t"
instance CType T where
typeName _ = "LDST_ctxt_t"
instance CType R where
typeName _ = "LDST_res_t"
instance CType () where
typeName _ = "void"
instance CType a => CType (Pointer a) where
typeName _ = typeName @a Proxy <> B.char7 '*'
newtype GenM a = GenM { unGenM :: RWST Info CStmt GenSt (StackT Function Identity) a }
deriving (Semigroup, Monoid) via Ap GenM a
deriving newtype (Functor, Applicative, Monad)
deriving newtype (MonadReader Info, MonadWriter CStmt, MonadState GenSt, MonadStack Function)
data GenMonoid = GenMonoid
{ genSigs :: !(Map Ident (Maybe (S.Last Type)))
, genDecls :: !Builder
, genDefs :: !Builder
}
instance Semigroup GenMonoid where
GenMonoid a1 b1 c1 <> GenMonoid a2 b2 c2 =
GenMonoid (Map.unionWith (<>) a1 a2) (b1 <> b2) (c1 <> c2)
instance Monoid GenMonoid where
mempty = GenMonoid mempty mempty mempty
generate :: Maybe Ident -> [S.Decl] -> Either String Builder
generate entryPoint = joinParts . first concatErrors . validationToEither . foldMap \case
S.DFun name args body _ -> do
-- Curry the function.
let lambdaBody = foldr (\(m, idn, ty) -> S.Lam m idn ty) body args
let header = topLevelHeader name
root = Function
{ funHeader = header
, funHint = localIdentForC 'l' name
, funBody = toCPS lambdaBody
-- Appending a single 'q' to all top-level names makes it
-- impossible to write a top-level function in the source language
-- which gets the same name as an internal function.
, funNestPrefix = NameHint $ funName header <> B.char7 'q'
}
let addContext err =
"in function ‘" ++ name ++ "’:\n" ++ err
let identMap = Map.singleton name Nothing
eitherToValidation
$ bimap (pure . addContext) (uncurry $ GenMonoid identMap)
$ generateFunction root
S.DSig name _ typ -> do
-- When we encounter a signature we also have to emit this functions
-- top-level reference declaration, otherwise it will be missing when the
-- function is used but no definition is given.
let sig = functionSignature (topLevelHeader name) []
let gen = mempty
{ genSigs = Map.singleton name $ Just $ S.Last typ
, genDecls = sig <> ";\n"
}
pure gen
_ ->
-- Nothing to generate for this kind of top level thingy.
mempty
where
joinParts errOrGM = errOrGM >>= \gm ->
let gm' = case entryPoint of
Nothing -> pure gm
Just ep -> genMainFunction ep gm
in glueCode <$> fmap genDecls gm' <*> fmap genDefs gm'
concatErrors :: NonEmpty String -> String
concatErrors = intercalate "\n\n" . toList
topLevelHeader :: Ident -> FunctionHeader
topLevelHeader funIdent = FunctionHeader
{ funName = functionForC funIdent
, funArgs = Nothing
, funInternal = False
}
genMainFunction :: Ident -> GenMonoid -> Either String GenMonoid
genMainFunction mainId gm = case Map.lookup mainId (genSigs gm) of
Nothing -> Left $
"entry point: unknown identifier ‘" <> mainId <> "’"
Just Nothing -> Left $
"entry point: no type signature for identifier ‘" <> mainId <> "’"
Just (Just (S.Last ty)) ->
let mainBody = do
resultVar <- declareFresh $ callExp "LDST_main" [functionForC mainId]
silenceUnused resultVar
tellStmt $ explainExpression ty resultVar
info = baseInfo "result" "main"
(_, (_, mainFunction)) = evalRWST (unGenM mainBody) info (GenSt 0 [])
& evalStack []
& second (functionDeclDef "int main(void)")
in Right $ gm <> mempty{ genDefs = mainFunction }
-- | Generates a call to @printf@ which tries to output the value of the given
-- variable according to the given type. In case the type has non-printable
-- values (e.g. a function type) only the type is printed.
explainExpression :: Type -> CVar V -> CStmt
explainExpression ty0 v0 =
let format :: Type -> CVar V -> (Endo String, Endo [Builder])
format ty v = case ty of
TUnit -> literal "()"
TInt -> formatted "Int %d" $ access TagInt v
TNat -> formatted "Nat %d" $ access TagInt v
TDouble -> formatted "Double %.6f" $ access TagDouble v
TString -> formatted "String %s" $ access TagString v
TLab _ -> formatted "Label %s" $ access TagLabel v
TPair _ t1 t2 ->
let (v1, v2) = accessPair v in
mconcat
[ literal "<"
, format t1 v1
, literal ", "
, format t2 v2
, literal ">"
]
_ -> (Endo $ showsPrec 11 ty, mempty)
literal s =
(Endo (showString s), mempty)
formatted s val =
(Endo (showString s), Endo (val :))
(Endo fmt, Endo args) = format ty0 v0
fmt' = (showString "result: " . fmt) "\n"
in terminate $ callExp "printf" (escapedCString fmt' : args [])
-- | Builds a function signature, an 'Env' binding the arguments to the
-- function (including variables bound through the closure), and the variable
-- containing the continuation.
--
-- The function signature convention is
--
-- @
-- LDST_res_t /function-name/(
-- LDST_cont_t *continuation,
-- LDST_ctxt_t *context,
-- void *closure,
-- LDST_t argument)
-- @
--
where @closure@ and @argument@ are only present for non - top - level bindings ,
-- including the curried forms of toplevel bindings.
functionSignatureM :: FunctionHeader -> GenM (Builder, Env)
functionSignatureM fun = first (functionSignature fun) <$> argsEnv
where
-- List of parameters and environment corresponding to @funArgs fun@. If
-- 'fun' is a top-level function 'funArgs' will be 'Nothing' and we use an
-- empty parameter list and environment here.
argsEnv = foldMap (signatureParameters (funName fun)) (funArgs fun)
functionSignature :: FunctionHeader -> [Builder] -> Builder
functionSignature fun localArgs = functionHeader retType (funName fun) args
where
-- Adds the parameters which every function gets to the ones for
-- non-top-level functions passed to this function.
args =
varDeclaration cContVar
: varDeclaration cCtxtVar
: localArgs
-- The return type for all generated functions is the same. Internal
-- functions get static linkage.
retType = mconcat
[ if funInternal fun then "static " else mempty
, typeName @R Proxy
]
-- | The parameter name for the continuation argument.
cContVar :: CVar (Pointer K)
cContVar = CVar "_ldst_k"
-- | The parameter name for the closure argument.
cClosureVar :: CVar (Pointer ())
cClosureVar = CVar "_ldst_closure"
| The variable which will be bound to the passed @LDST_ctxt_t*@. Since this
-- value is a essentially a black box for the generated code and only passed to
other functions we use one global variable name .
cCtxtVar :: CVar (Pointer T)
cCtxtVar = CVar "_ldst_ctxt"
-- | Builds a list of function parameters for the function signatures together
with an ' Env ' mapping identifiers from the source language to ' CVar 's ,
-- including values captured via the closure.
signatureParameters :: Builder -> FunctionArgs -> GenM ([Builder], Env)
signatureParameters name args = do
let hint = localIdentForC 'a' $ funArgIdent args
argVar <- CVar @V <$> nameHint hint (fresh Nothing)
let params = [varDeclaration cClosureVar, varDeclaration argVar]
let closure = cast @(Pointer V) cClosureVar
vars <- ifor (funClosure args) \i -> traverse \ident ->
nameHint (localIdentForC 'c' ident) do
var <- storeVar (accessI i closure)
-- If the closure is reused it might happen that the captured
-- variables won't be referenced directly.
silenceUnused var
pure (ident, var)
insertRecArg <- case funRecIdent args of
Nothing -> pure id
Just recId -> do
-- It is possible that the recursion name recId shadows the functions
-- argument name, but this follows the typechecker rules!
--
-- Use the following code to doublecheck:
--
check = rec x ( x : Int ) : Int = x
--
-- If it typechecks 'recId' should *not* shadow an existing variable,
-- if it fails to typecheck, it *should* shadow the variable.
--
There exists a test case for this in " / name shadowing / in the source language " .
recVal <- mkValue TagLam . toCExp =<< mkLambda' name (unCVar cClosureVar)
pure $ Map.insert recId recVal
let bindings =
catMaybes vars
& Map.fromList
& Map.insert (funArgIdent args) argVar
& insertRecArg
pure (params, bindings)
| @functionDeclDef signature body@ returns a pair of @(declaration , definition)@.
--
-- The @signature@ should be built by 'functionSignature'.
functionDeclDef :: Builder -> CStmt -> (Builder, Builder)
functionDeclDef signature (CStmt body) =
let function = mconcat
[ signature
, "\n{\n"
, body
, "}\n\n"
]
in (signature <> ";\n", function)
generateFunction :: Function -> Either String (Builder, Builder)
generateFunction topLevelFun = evalStackT [topLevelFun] $ execWriterT go
where
go = popStack >>= \case
Nothing -> pure ()
Just fun -> lift (generateFunction' fun) >>= tell >> go
generateFunction'
:: Applicative m
=> Function -> StackT Function m (Builder, Builder)
generateFunction' fun = do
let genBody = do
(sig, bindings) <- functionSignatureM (funHeader fun)
local (infoBindings <>~ bindings) do
generateExp (funBody fun)
pure sig
let captured = funHeader fun
& funArgs
& fmap \args -> Closure (funClosure args) (toCExp $ cast cClosureVar)
genst = GenSt
{ _stUnique = 0
, _stClosures = maybeToList captured
}
let info = baseInfo
(funHint fun)
(funNestPrefix fun)
evalRWST (unGenM genBody) info genst
& fmap (uncurry functionDeclDef)
& generalizeStack
baseInfo :: NameHint -> NameHint -> Info
baseInfo nameH nestH = Info
{ _infoBindings = mempty
, _infoContinuation = cContVar
, _infoNameHint = nameH
, _infoNestPrefix = nestH
, _infoIndent = 1
}
generateVal :: Val -> GenM (CVar V)
generateVal = \case
Lit l -> generateLiteral l
Var name ->
-- The unsafe operator (^?!) is "safe" here because if the variable is not
locally bound the CPS transformation should have generated a ' TLCall '
-- node.
asks \env -> env ^?! infoBindings . ix name
e@(Lam _ argId _ body) -> do
lam <- pushFunction 'l' (fv e) Nothing argId body
mkValue TagLam lam
e@(Rec recId argId _ _ body) -> do
lam <- nameHint (localIdentForC 'r' recId) do
pushFunction 'r' (fv e) (Just recId) argId body
mkValue TagLam lam
Math m -> generateMath m
Succ e -> do
e' <- generateVal e
liftValue TagInt $ access TagInt e' <> " + 1"
Pair a b -> do
a' <- generateVal a
b' <- generateVal b
mkValue TagPair (toCExp a', toCExp b')
Fork e -> do
let free = fv e
lam <- pushFunction 'f' free Nothing (S.freshvar "unit" free) e
forkLambda lam
New _ -> do
chan <- mkValue TagChan . toCExp =<< newChannel
mkValue TagPair (toCExp chan, toCExp chan)
Send e -> do
chan <- accessValChannel <$> generateVal e
mkValue TagLam . toCExp =<< chanSendLambda chan
generateExp :: Exp -> GenM ()
generateExp = \case
Return val -> generateVal val >>= invokeContinuation
Let v a b -> do
a' <- nameHint (localIdentForC 'l' v) $ generateVal a
local (infoBindings . at v ?~ a') $ generateExp b
LetPair idnFst idnSnd pairExp body -> do
pairVar <- nameHint "letpair" $ generateVal pairExp
let (valFst, valSnd) = accessPair pairVar
let insert idn val = infoBindings . at idn ?~ val
-- In case idnFst and idnSnd are the same (should probably be diagnosed at
-- some earlier point) we follow the interpreter: idnSnd should shadow
-- idnFst.
--
This is verified in " / name shadowing / in the source language " .
local (insert idnSnd valSnd . insert idnFst valFst) do
generateExp body
LetCont k e -> do
k' <- generateContinuationM $ Just k
local (infoContinuation .~ k') $ generateExp e
Call funExp argExp mk -> do
lam <- generateVal funExp
arg <- generateVal argExp
k <- generateContinuationM mk
invoke (accessValLambda lam) k arg
TLCall funId mk -> do
k <- generateContinuationM mk
invoke' (functionForC funId) k []
Case e cs -> do
-- TODO: It is possible to arrange the comparisons to find the correct
branch in O(log n ) steps .
--
-- TODO: Should we assume that the matching branch always exists? Or check
-- all branches and panic, in case none matches?
label <- access TagLabel <$> generateVal e
let buildBranch :: (String, Exp) -> StateT Builder GenM ()
buildBranch (branchLabel, branchExp) = do
ifB <- get <* put "else if "
let cmpExp = callExp funStrcmp [label, labelForC branchLabel] <+> " == 0"
lift $ tellStmt $ CStmt $ callExp ifB [cmpExp] <> " {"
lift $ local (infoIndent +~ 1) $ generateExp branchExp
lift $ tellStmt $ CStmt "}"
evalStateT (traverse_ buildBranch cs) ("if " :: Builder)
tellStmt $ cReturn "LDST_UNMATCHED_LABEL"
NatRec e z n _ x t s -> do
e' <- generateVal e
z' <- generateVal z
let vars = Set.delete n $ Set.delete x $ fv s
s' <- pushFunction 'n' vars Nothing n $ Return $ Lam MMany x t s
f <- mkValue TagLam s'
Create the closure for LDST_nat_fold
1 . f (= s ' )
2 . n (= e ' )
3 . i
i <- mkValue TagInt 0
closure <- cloneAll [f, e', i]
-- Call into `LDST_nat_fold`.
k <- view infoContinuation
natFold <- mkLambda' "LDST_nat_fold" $ unCVar closure
invoke natFold k z'
Recv e mk -> do
c <- accessValChannel <$> generateVal e
k <- generateContinuationM mk
chanReceive k c
pushFunction :: Char -> Set Ident -> Maybe Ident -> Ident -> Exp -> GenM (CExp L)
pushFunction c freevars mRecId argId body = do
name <- fresh (Just c)
closure <- mkClosure freevars
hint <- view infoNameHint
pushStack $ Function
{ funHeader = FunctionHeader
{ funName = name
, funArgs = Just FunctionArgs
{ funClosure = closure^.closureVars
, funArgIdent = argId
, funRecIdent = mRecId
}
, funInternal = True
}
, funHint = hint
, funNestPrefix = NameHint name
, funBody = body
}
mkLambda name closure
generateMath :: MathOp Val -> GenM (CVar V)
generateMath = liftValue TagInt <=< \case
Add a b -> math '+' a b
Sub a b -> math '-' a b
Mul a b -> math '*' a b
Div a b -> math '/' a b
Neg a -> do
a' <- generateVal a
pure $ B.char7 '-' <> access TagInt a'
where
math c a b = do
a' <- generateVal a
b' <- generateVal b
pure $ bunwords [ access TagInt a', B.char7 c, access TagInt b' ]
generateLiteral :: Literal -> GenM (CVar V)
generateLiteral = \case
LInt i -> mkValue TagInt i
LNat n -> mkValue TagInt n
LDouble d -> mkValue TagDouble d
LString s -> mkValue TagString s
LLab l -> mkValue TagLabel l
LUnit -> newUnitVar
generateContinuationM :: Maybe Continuation -> GenM (CVar (Pointer K))
generateContinuationM Nothing = view infoContinuation
generateContinuationM (Just (resId, kbody)) =
nameHint "k" $ clone =<< join do
mkContinuation
<$> pushFunction 'k' (fv kbody) Nothing resId kbody
<*> view infoContinuation
invokeContinuation :: ExpLike e => e V -> GenM ()
invokeContinuation e = do
k <- view infoContinuation
invoke' "LDST_invoke" k [unCExp (toCExp e)]
invoke :: (ExpLike e1, ExpLike e2) => CVar L -> e1 (Pointer K) -> e2 V -> GenM ()
invoke lam k val = do
let (fun, closure) = accessLambda lam
invoke' fun k [closure, unCExp (toCExp val)]
invoke' :: ExpLike e => Builder -> e (Pointer K) -> [Builder] -> GenM ()
invoke' fun k args =
let allArgs = [unCExp (toCExp k), unCExp (toCExp cCtxtVar)] ++ args
in tellStmt $ cReturn $ callExp fun allArgs
-- | Adjusts 'infoNameHint'.
nameHint :: NameHint -> GenM a -> GenM a
nameHint h = local (infoNameHint .~ h)
functionHeader :: Builder -> Builder -> [Builder] -> Builder
functionHeader ret name args =
ret <> B.char7 ' ' <> callExp name args
-- | Generates a guaranteed fresh name for the current function. The returned
-- identifier is suitable for use in C code provided that 'infoNameHint' and
-- 'infoFuncHint' are never an invalid prefix.
--
If the first argument is @Just /funKind/@ the name is guaranteed to be fresh
-- for the whole module and @fresh@ uses 'infoFuncHint' instead of
-- 'infoNameHint' with @/funKind/@ appended before the unique id.
fresh :: Maybe Char -> GenM Builder
fresh funKind = do
n <- stUnique <<+= 1
hint <- case funKind of
Nothing -> (\(NameHint h) -> h <> B.char7 '_') <$> view infoNameHint
Just c -> (\(NameHint h) -> h <> B.char7 '_' <> B.char7 c) <$> view infoNestPrefix
pure $ hint <> B.wordHex n
declareFresh :: forall t. CType t => Builder -> GenM (CVar t)
declareFresh initExp = do
name <- fresh Nothing
let var = CVar name
tellStmt $ terminate $ varDeclaration var <+> B.char7 '=' <+> initExp
pure var
varDeclaration :: forall t. CType t => CVar t -> Builder
varDeclaration (CVar v) = typeName @t Proxy <+> v
newUnitVar :: GenM (CVar V)
newUnitVar = storeVar (CExp "{ 0 }")
silenceUnused :: CVar t -> GenM ()
silenceUnused (CVar v) = tellStmt $ terminate $ "(void)" <> v
-- | Writes the result of the given expression into a fresh variable.
storeVar :: (CType t, ExpLike e) => e t -> GenM (CVar t)
storeVar = declareFresh . unCExp . toCExp
mkClosure :: Set Ident -> GenM Closure
mkClosure vars = do
knownVars <- view infoBindings
let captured = Map.restrictKeys knownVars vars
mclosure <- runMaybeT (nullClosure captured <|> reuseClosure captured)
maybe (allocateNewClosure captured) pure mclosure
nullClosure :: Env -> MaybeT GenM Closure
nullClosure vars =
if Map.null vars
then pure Closure{ _closureVars = [], _closureExpr = nullPointer }
else empty
reuseClosure :: Env -> MaybeT GenM Closure
reuseClosure (Map.keys -> vars) = MaybeT do
allocated <- use stClosures
pure $ allocated
& mapMaybe (closureVars %%~ tryClosureReuse vars)
& preview _head
tryClosureReuse :: [Ident] -> [Maybe Ident] -> Maybe [Maybe Ident]
tryClosureReuse = go id
where
go f (x:xs) (Just y:ys) | x == y = go (f . (Just y:)) xs ys
go f xs@(_:_) (_:ys) = go (f . (Nothing:)) xs ys
go f [] ys = Just $ f (Nothing <$ ys)
go _ _ [] = Nothing
allocateNewClosure :: Env -> GenM Closure
allocateNewClosure (Map.toAscList -> unzip -> (ids, exprs)) = do
expr <- toCExp <$> cloneAll exprs
let closure = Closure (Just <$> ids) expr
stClosures %= cons closure
pure closure
mkLambda :: Builder -> Closure -> GenM (CExp L)
mkLambda fun = fmap toCExp . mkLambda' fun . unCExp . view closureExpr
mkLambda' :: Builder -> Builder -> GenM (CVar L)
mkLambda' fun closure = declareFresh $ braceList [fun, closure]
accessLambda :: CVar L -> (Builder, Builder)
accessLambda v = (accessRaw v "lam_fp", accessRaw v "lam_closure")
mkContinuation :: (ExpLike e1, ExpLike e2) => e1 L -> e2 (Pointer K) -> GenM (CVar K)
mkContinuation lambda next = declareFresh $ braceList [unCExp $ toCExp lambda, unCExp $ toCExp next]
accessI :: Int -> CVar (Pointer t) -> CVar t
accessI i (CVar v) = CVar $ v <> brackets (B.intDec i)
cast :: forall t' t. CType t' => CVar t -> CVar t'
cast (CVar v) = CVar $ parens $ parens (typeName @t' Proxy) <> v
takeAddress :: (ExpLike e, CType t) => e t -> GenM (CVar (Pointer t))
takeAddress = declareFresh . (B.char7 '&' <>) . unCExp . toCExp
mkValue :: Tag a -> a -> GenM (CVar V)
mkValue tag a = liftValue tag =<< case tag of
TagInt -> pure $ B.intDec a
TagDouble -> pure $ B.doubleDec a
TagString -> pure $ B.stringUtf8 a
TagLabel -> pure $ labelForC a
TagPair -> do
let (x, y) = a
unCExp . toCExp <$> cloneAll [x, y]
TagLam -> pure $ unCExp a
TagChan -> pure $ unCExp a
liftValue :: Tag a -> Builder -> GenM (CVar V)
liftValue tag a = storeVar
$ CExp
$ braceList
$ pure
$ bunwords
[ B.char7 '.' <> tagAccessor tag
, B.char7 '='
, a
]
-- | Clones the result of the given expression into a fresh variable which
-- lives on the heap instead of the stack.
clone :: forall t e. (CType t, ExpLike e) => e t -> GenM (CVar (Pointer t))
clone = cloneAll . pure
-- | Clones a list of values, if the list is empty the null pointer is used.
cloneAll :: forall t e. (CType t, ExpLike e) => [e t] -> GenM (CVar (Pointer t))
cloneAll [] = storeVar nullPointer
cloneAll exprs = do
let n = length exprs
var <- declareFresh $ callExp "malloc" [B.intDec n <+> B.char7 '*' <+> cSizeof @t Proxy]
tellStmt $ terminate $
callExp "if " [B.char7 '!' <> unCVar var] <> " return LDST_NO_MEM"
itraverse_ (tellAssignI var) exprs
pure var
nullPointer :: CExp (Pointer t)
nullPointer = CExp $ B.char7 '0'
-- | Glues the parts together to yield something looking like a function call.
-- It is also used to generate function headers and control structures.
callExp :: Builder -> [Builder] -> Builder
callExp f args = f <> parens (intercalate ", " args)
tellAssign :: ExpLike e => CVar t -> e t -> GenM ()
tellAssign (CVar v) val = tellStmt $ terminate $ bunwords [v, B.char7 '=', unCExp (toCExp val)]
tellAssignI :: ExpLike e => CVar (Pointer t) -> Int -> e t -> GenM ()
tellAssignI v idx = tellAssign (accessI idx v)
funStrcmp :: Builder
funStrcmp = "strcmp"
cSizeof :: CType t => proxy t -> Builder
cSizeof = callExp "sizeof" . pure . typeName
-- | Adds some generated code to the output.
--
-- /Note:/ It is the callers job to include the trailing semicolon.
tellStmt :: CStmt -> GenM ()
tellStmt (CStmt s) = do
lvl <- view infoIndent
let !indent = stimes (lvl * 2) (B.char7 ' ')
tell $ CStmt $ indent <> s <> B.char7 '\n'
cCodeHeader :: Builder
cCodeHeader = bunlines
[ "//"
, "// Generated by ldgv v" <> fromString (showVersion Paths_ldgv.version)
, "//"
, ""
, "#include <stdio.h>"
, "#include <stdlib.h> // malloc"
, "#include <string.h> // strcmp"
, "#include \"LDST.h\""
]
| Concatenates a builder containing the function signatures and a builder
-- containing the function definitions with the 'header' containing the type
-- definitions.
glueCode :: Builder -> Builder -> Builder
glueCode decls defs = bunlines
[ cCodeHeader
, ""
, "// Generated code - forward declarations"
, decls
, "// Generated code - function definitions"
, defs
]
newChannel :: GenM (CVar (Pointer C))
newChannel = do
chan <- storeVar nullPointer
chanAddress <- takeAddress chan
callChecked "LDST_chan_new" [unCVar cCtxtVar, unCVar chanAddress]
pure chan
chanSendLambda :: ExpLike e => e (Pointer C) -> GenM (CVar L)
chanSendLambda = mkLambda' "LDST_chan_send" . unCExp . toCExp
chanReceive :: (ExpLike e1, ExpLike e2) => e1 (Pointer K) -> e2 (Pointer C) -> GenM ()
chanReceive (toCExp -> CExp k) (toCExp -> CExp chan) =
tellStmt $ cReturn $ callExp "LDST_chan_recv" [k, unCExp (toCExp cCtxtVar), chan]
forkLambda :: ExpLike e => e L -> GenM (CVar V)
forkLambda (toCExp -> CExp l) = do
unit <- newUnitVar
callChecked "LDST_fork" [unCExp (toCExp cCtxtVar), l, unCVar unit]
pure unit
callChecked :: Builder -> [Builder] -> GenM ()
callChecked fun args = do
resVar <- nameHint "res" do
declareFresh @R $ callExp fun args
returnNotOk resVar
returnNotOk :: CVar R -> GenM ()
returnNotOk (CVar res) = do
tellStmt $ CStmt $ callExp "if " $ pure $ res <> " != LDST_OK"
local (infoIndent +~ 1) $ tellStmt $ cReturn res
braceList :: [Builder] -> Builder
braceList bs = braces (intercalate ", " bs)
accessRaw :: CVar t -> Builder -> Builder
accessRaw (CVar v) x = v <> B.char7 '.' <> x
access :: Tag a -> CVar V -> Builder
access tag v = accessRaw v (tagAccessor tag)
accessPair :: CVar V -> (CVar V, CVar V)
accessPair v =
let b = CVar $ access TagPair v :: CVar (Pointer V)
in (accessI 0 b, accessI 1 b)
accessValLambda :: CVar V -> CVar L
accessValLambda = CVar . access TagLam
accessValChannel :: CVar V -> CVar (Pointer C)
accessValChannel = CVar . access TagChan
tagAccessor :: Tag a -> Builder
tagAccessor = \case
TagInt -> "val_int"
TagDouble -> "val_double"
TagString -> "val_string"
TagLabel -> "val_label"
TagPair -> "val_pair"
TagLam -> "val_lam"
TagChan -> "val_chan"
(<+>) :: Builder -> Builder -> Builder
a <+> b = a <> B.char7 ' ' <> b
infixr 6 <+>
-- | Concatenate a list of builders using a single space character.
bunwords :: [Builder] -> Builder
bunwords = intercalate (B.char7 ' ')
-- | Concatenate a list of builders using a single newline character.
--
-- This differs from 'unlines' which also appends a trailing newline.
bunlines :: [Builder] -> Builder
bunlines = intercalate (B.char7 '\n')
-- | @"Data.List".'List.intercalate'@ generalized to arbitrary monoids.
--
-- >>> intercalate "a" ["x", "y", "z"]
-- "xayaz"
-- >>> getDual $ intercalate (Dual "a") (Dual <$> ["x", "y", "z"])
-- "zayax"
intercalate :: Monoid a => a -> [a] -> a
intercalate a = mconcat . List.intersperse a
| @surround l r a@ adds @l@ to the left of @a@ and @r@ to the right .
--
> > > surround " ( " " ) " " abc "
" ( abc ) "
surround :: Semigroup a => a -> a -> a -> a
surround l r a = l <> a <> r
-- | Wraps the given builder in parentheses.
--
-- @
-- parens b === surround "(" ")" b
-- @
parens :: Builder -> Builder
parens = surround (B.char7 '(') (B.char7 ')')
-- | Wraps the given builder in parentheses.
--
-- @
-- braces b === surround "{" "}" b
-- @
braces :: Builder -> Builder
braces = surround (B.char7 '{') (B.char7 '}')
-- | Wraps the given builder in brackets.
--
-- @
-- brackets b === surround "[" "]" b
-- @
brackets :: Builder -> Builder
brackets = surround (B.char7 '[') (B.char7 ']')
-- | Appends a semicolon to the given builder
--
-- @
-- terminate b === b <> ";"
-- @
terminate :: Builder -> CStmt
terminate b = CStmt $ b <> B.char7 ';'
cReturn :: Builder -> CStmt
cReturn b = terminate $ "return " <> b
| @localIdentForC kindChar identifier@ turns @identifier@ into a valid C
-- identifier which won't shadow any stdlib identifiers or generated functions.
--
-- @kindChar@ can be used to highlight the origin of the identifier. See the
uses of this function to observe @'a'@ for arguments , @'l'@ for local
-- identifiers etc.
--
-- @kindChar@ must be an ASCII letter otherwise the result of this function is
-- guaranteed to be a valid identifier.
localIdentForC :: Char -> Ident -> NameHint
localIdentForC c idn =
NameHint $ B.char7 c <> B.char7 '_' <> escapeIdentifier idn
-- | Turns an identifier into a function name suitable in the generated C code.
It uses the encoding from ' escapeIdentifier ' and prepends @"ldst_"@.
functionForC :: Ident -> Builder
functionForC idn = "ldst_" <> escapeIdentifier idn
| Escapes an LDST / LDGV identifier which may contain primes into a valid C
identifier using @q@ as an escape character :
--
* is replaced by @qq@
-- * primes/single quotes are replaced by @qQ@
--
-- This function should only be used through 'localIdentForC'/'functionForC'
escapeIdentifier :: Ident -> Builder
escapeIdentifier = foldMap \case
'\'' -> "qQ"
'q' -> "qq"
c -> B.charUtf8 c
labelForC :: String -> Builder
labelForC = escapedCString -- Labels are represented as C strings.
-- | Escapes a string value as a string literal in C, including the surrounding
-- quotes.
--
-- If the string contains non-ASCII characters the resulting C code requires
compilation with C11 as the @\\Unnnnnnnn@ escape sequence is used .
escapedCString :: String -> Builder
escapedCString = surround (B.char7 '"') (B.char7 '"') . B.string7 . concatMap \c ->
let hex = showHex (C.ord c) ""
hexPadded n = replicate (n - length hex) '0' ++ hex
in
if | c == '"' -> ['\\', '"']
| c == '\\' -> ['\\', '\\']
| c == '\n' -> ['\\', 'n'] -- Not strictly necessary.
| C.isAscii c && C.isPrint c -> [c]
| C.isAscii c -> '\\':'x':hexPadded 2
| otherwise -> '\\':'U':hexPadded 8
| null | https://raw.githubusercontent.com/proglang/ldgv/cabb502b81e831eece1c80ee70d520ac85e908c7/src/C/Generate.hs | haskell | # LANGUAGE BangPatterns #
# LANGUAGE GADTs #
# LANGUAGE MultiWayIf #
# LANGUAGE OverloadedStrings #
# LANGUAGE RankNTypes #
| Type level tag for values.
@
union LDST_val {
int val_int;
LDST_t *val_pair;
LDST_chan_t *val_chan;
const char *val_label;
};
@
| Type level tag for lambdas.
@
struct LDST_lam {
LDST_t *closure;
};
@
| Type level tag for channels.
| Type level tag for continuations.
@
struct LDST_cont {
LDST_t *closure;
LDST_cont_t *cont;
};
@
| Type level tag for @LDST_ctxt_t@.
| Type level tag for @LDST_res_t@.
@
enum LDST_res {
LDST_DEADLOCK,
};
@
we could generate more idiomatic code. This isn't terribly necessary though,
the common C compilers are able to understand and optimize our intentions
quite well.
^ Variables accessible through the closure argument at the corresponding
index. The identifiers must be in ascending order. @Nothing@ slots
shouldn't be accessed.
^ @Just ident@ if this function can call itself recursively with
identifier @ident@.
^ A pair of the identifiers carried by the closure parameter and the
functions argument.
@static@ linkage.
top level functions correspond to non-internal functions.
^ See '_infoNameHint'.
^ See '_infoNestPrefix'.
^ List of captured identifiers. The order corresponds to the order in
the C code in 'closureExpr', the identifiers must be in ascending order.
@Nothing@ values should not be accessed, these are slots indicating a
closure is reused but only with a subset of captured values.
^ An expression of type @union LDST_t*@.
| A newtype wrapping a builder to highlight the expected usage of the
wrapped value.
^ Mapping from bound variables to the corresponding identifiers in the
generated C code.
^ The current continuation.
generated C code and tracking to which expression the variables belong.
continuations out of their enclosing function. This is necessary to be
unique per function, otherwise the generated function names might clash.
^ Current indent level.
Curry the function.
Appending a single 'q' to all top-level names makes it
impossible to write a top-level function in the source language
which gets the same name as an internal function.
When we encounter a signature we also have to emit this functions
top-level reference declaration, otherwise it will be missing when the
function is used but no definition is given.
Nothing to generate for this kind of top level thingy.
| Generates a call to @printf@ which tries to output the value of the given
variable according to the given type. In case the type has non-printable
values (e.g. a function type) only the type is printed.
| Builds a function signature, an 'Env' binding the arguments to the
function (including variables bound through the closure), and the variable
containing the continuation.
The function signature convention is
@
LDST_res_t /function-name/(
LDST_cont_t *continuation,
LDST_ctxt_t *context,
void *closure,
LDST_t argument)
@
including the curried forms of toplevel bindings.
List of parameters and environment corresponding to @funArgs fun@. If
'fun' is a top-level function 'funArgs' will be 'Nothing' and we use an
empty parameter list and environment here.
Adds the parameters which every function gets to the ones for
non-top-level functions passed to this function.
The return type for all generated functions is the same. Internal
functions get static linkage.
| The parameter name for the continuation argument.
| The parameter name for the closure argument.
value is a essentially a black box for the generated code and only passed to
| Builds a list of function parameters for the function signatures together
including values captured via the closure.
If the closure is reused it might happen that the captured
variables won't be referenced directly.
It is possible that the recursion name recId shadows the functions
argument name, but this follows the typechecker rules!
Use the following code to doublecheck:
If it typechecks 'recId' should *not* shadow an existing variable,
if it fails to typecheck, it *should* shadow the variable.
The @signature@ should be built by 'functionSignature'.
The unsafe operator (^?!) is "safe" here because if the variable is not
node.
In case idnFst and idnSnd are the same (should probably be diagnosed at
some earlier point) we follow the interpreter: idnSnd should shadow
idnFst.
TODO: It is possible to arrange the comparisons to find the correct
TODO: Should we assume that the matching branch always exists? Or check
all branches and panic, in case none matches?
Call into `LDST_nat_fold`.
| Adjusts 'infoNameHint'.
| Generates a guaranteed fresh name for the current function. The returned
identifier is suitable for use in C code provided that 'infoNameHint' and
'infoFuncHint' are never an invalid prefix.
for the whole module and @fresh@ uses 'infoFuncHint' instead of
'infoNameHint' with @/funKind/@ appended before the unique id.
| Writes the result of the given expression into a fresh variable.
| Clones the result of the given expression into a fresh variable which
lives on the heap instead of the stack.
| Clones a list of values, if the list is empty the null pointer is used.
| Glues the parts together to yield something looking like a function call.
It is also used to generate function headers and control structures.
| Adds some generated code to the output.
/Note:/ It is the callers job to include the trailing semicolon.
containing the function definitions with the 'header' containing the type
definitions.
| Concatenate a list of builders using a single space character.
| Concatenate a list of builders using a single newline character.
This differs from 'unlines' which also appends a trailing newline.
| @"Data.List".'List.intercalate'@ generalized to arbitrary monoids.
>>> intercalate "a" ["x", "y", "z"]
"xayaz"
>>> getDual $ intercalate (Dual "a") (Dual <$> ["x", "y", "z"])
"zayax"
| Wraps the given builder in parentheses.
@
parens b === surround "(" ")" b
@
| Wraps the given builder in parentheses.
@
braces b === surround "{" "}" b
@
| Wraps the given builder in brackets.
@
brackets b === surround "[" "]" b
@
| Appends a semicolon to the given builder
@
terminate b === b <> ";"
@
identifier which won't shadow any stdlib identifiers or generated functions.
@kindChar@ can be used to highlight the origin of the identifier. See the
identifiers etc.
@kindChar@ must be an ASCII letter otherwise the result of this function is
guaranteed to be a valid identifier.
| Turns an identifier into a function name suitable in the generated C code.
* primes/single quotes are replaced by @qQ@
This function should only be used through 'localIdentForC'/'functionForC'
Labels are represented as C strings.
| Escapes a string value as a string literal in C, including the surrounding
quotes.
If the string contains non-ASCII characters the resulting C code requires
Not strictly necessary. | # LANGUAGE BlockArguments #
# LANGUAGE DataKinds #
# LANGUAGE DerivingStrategies #
# LANGUAGE DerivingVia #
# LANGUAGE FlexibleContexts #
# LANGUAGE GeneralizedNewtypeDeriving #
# LANGUAGE LambdaCase #
# LANGUAGE ScopedTypeVariables #
# LANGUAGE TemplateHaskell #
# LANGUAGE TupleSections #
# LANGUAGE TypeApplications #
# LANGUAGE TypeFamilies #
# LANGUAGE ViewPatterns #
# OPTIONS_GHC -Wall #
module C.Generate (generate) where
import Control.Applicative
import Control.Lens
import Control.Monad.Except
import Control.Monad.RWS.Strict
import Control.Monad.State.Strict
import Control.Monad.Trans.Maybe
import Control.Monad.Writer.Strict
import Data.Bifunctor
import Data.ByteString.Builder (Builder)
import Data.Coerce
import Data.Foldable
import Data.List.NonEmpty (NonEmpty)
import Data.Map (Map)
import Data.Maybe
import Data.Proxy
import Data.Semigroup as S
import Data.Set (Set)
import Data.String
import Data.Version
import Kinds (Multiplicity(..))
import C.MonadStack
import Numeric
import C.CPS
import Validation
import qualified Data.ByteString.Builder as B
import qualified Data.Char as C
import qualified Data.List as List
import qualified Data.Map.Strict as Map
import qualified Data.Set as Set
import qualified Paths_ldgv
import qualified Syntax as S
val_lam ;
data V
LDST_fp fp ;
data L
data C
LDST_fp fp ;
data K
data T
LDST_OK ,
LDST_NO_MEM ,
LDST_UNMATCHED_LABEL ,
data R
| Type level tag for a pointer to
data Pointer a
| Represents an expression of type
newtype CExp t = CExp { unCExp :: Builder }
TODO : By using an ADT to differentiate what the expression might represent
| Represents a variable reference of type
newtype CVar t = CVar { unCVar :: Builder }
newtype CStmt = CStmt Builder
deriving newtype (Semigroup, Monoid)
data Tag a where
TagInt :: Tag Int
TagDouble :: Tag Double
TagString :: Tag String
TagLabel :: Tag String
TagPair :: Tag (CExp V, CExp V)
TagLam :: Tag (CExp L)
TagChan :: Tag (CExp (Pointer C))
data FunctionArgs = FunctionArgs
{ funClosure :: [Maybe Ident]
, funArgIdent :: Ident
, funRecIdent :: Maybe Ident
}
data FunctionHeader = FunctionHeader
{ funName :: !Builder
, funArgs :: !(Maybe FunctionArgs)
, funInternal :: !Bool
^ @True@ if this function is only used internally and should get
Internal functions originate from lambda expressions while the nullary
}
data Function = Function
{ funHeader :: !FunctionHeader
, funHint :: !NameHint
, funNestPrefix :: !NameHint
, funBody :: !Exp
}
data Closure = Closure
{ _closureVars :: ![Maybe Ident]
, _closureExpr :: !(CExp (Pointer V))
}
| A mapping from locally bound variables to their corresponding ' CVar ' .
type Env = Map Ident (CVar V)
newtype NameHint = NameHint Builder
deriving newtype (IsString)
data Info = Info
{ _infoBindings :: !Env
, _infoContinuation :: !(CVar (Pointer K))
, _infoNameHint :: !NameHint
^ Prepended to all fresh variables , helps with understandability of the
, _infoNestPrefix :: !NameHint
^ Prepended to all functions originating from splitting lambdas and
, _infoIndent :: !Int
}
data GenSt = GenSt
{ _stUnique :: !Word
, _stClosures :: ![Closure]
}
makeLenses ''Info
makeLenses ''GenSt
makeLenses ''Closure
class ExpLike e where
toCExp :: e t -> CExp t
instance ExpLike CExp where
toCExp = id
instance ExpLike CVar where
toCExp = coerce
class CType t where
typeName :: proxy t -> Builder
instance CType V where
typeName _ = "LDST_t"
instance CType L where
typeName _ = "LDST_lam_t"
instance CType C where
typeName _ = "LDST_chan_t"
instance CType K where
typeName _ = "LDST_cont_t"
instance CType T where
typeName _ = "LDST_ctxt_t"
instance CType R where
typeName _ = "LDST_res_t"
instance CType () where
typeName _ = "void"
instance CType a => CType (Pointer a) where
typeName _ = typeName @a Proxy <> B.char7 '*'
newtype GenM a = GenM { unGenM :: RWST Info CStmt GenSt (StackT Function Identity) a }
deriving (Semigroup, Monoid) via Ap GenM a
deriving newtype (Functor, Applicative, Monad)
deriving newtype (MonadReader Info, MonadWriter CStmt, MonadState GenSt, MonadStack Function)
data GenMonoid = GenMonoid
{ genSigs :: !(Map Ident (Maybe (S.Last Type)))
, genDecls :: !Builder
, genDefs :: !Builder
}
instance Semigroup GenMonoid where
GenMonoid a1 b1 c1 <> GenMonoid a2 b2 c2 =
GenMonoid (Map.unionWith (<>) a1 a2) (b1 <> b2) (c1 <> c2)
instance Monoid GenMonoid where
mempty = GenMonoid mempty mempty mempty
generate :: Maybe Ident -> [S.Decl] -> Either String Builder
generate entryPoint = joinParts . first concatErrors . validationToEither . foldMap \case
S.DFun name args body _ -> do
let lambdaBody = foldr (\(m, idn, ty) -> S.Lam m idn ty) body args
let header = topLevelHeader name
root = Function
{ funHeader = header
, funHint = localIdentForC 'l' name
, funBody = toCPS lambdaBody
, funNestPrefix = NameHint $ funName header <> B.char7 'q'
}
let addContext err =
"in function ‘" ++ name ++ "’:\n" ++ err
let identMap = Map.singleton name Nothing
eitherToValidation
$ bimap (pure . addContext) (uncurry $ GenMonoid identMap)
$ generateFunction root
S.DSig name _ typ -> do
let sig = functionSignature (topLevelHeader name) []
let gen = mempty
{ genSigs = Map.singleton name $ Just $ S.Last typ
, genDecls = sig <> ";\n"
}
pure gen
_ ->
mempty
where
joinParts errOrGM = errOrGM >>= \gm ->
let gm' = case entryPoint of
Nothing -> pure gm
Just ep -> genMainFunction ep gm
in glueCode <$> fmap genDecls gm' <*> fmap genDefs gm'
concatErrors :: NonEmpty String -> String
concatErrors = intercalate "\n\n" . toList
topLevelHeader :: Ident -> FunctionHeader
topLevelHeader funIdent = FunctionHeader
{ funName = functionForC funIdent
, funArgs = Nothing
, funInternal = False
}
genMainFunction :: Ident -> GenMonoid -> Either String GenMonoid
genMainFunction mainId gm = case Map.lookup mainId (genSigs gm) of
Nothing -> Left $
"entry point: unknown identifier ‘" <> mainId <> "’"
Just Nothing -> Left $
"entry point: no type signature for identifier ‘" <> mainId <> "’"
Just (Just (S.Last ty)) ->
let mainBody = do
resultVar <- declareFresh $ callExp "LDST_main" [functionForC mainId]
silenceUnused resultVar
tellStmt $ explainExpression ty resultVar
info = baseInfo "result" "main"
(_, (_, mainFunction)) = evalRWST (unGenM mainBody) info (GenSt 0 [])
& evalStack []
& second (functionDeclDef "int main(void)")
in Right $ gm <> mempty{ genDefs = mainFunction }
explainExpression :: Type -> CVar V -> CStmt
explainExpression ty0 v0 =
let format :: Type -> CVar V -> (Endo String, Endo [Builder])
format ty v = case ty of
TUnit -> literal "()"
TInt -> formatted "Int %d" $ access TagInt v
TNat -> formatted "Nat %d" $ access TagInt v
TDouble -> formatted "Double %.6f" $ access TagDouble v
TString -> formatted "String %s" $ access TagString v
TLab _ -> formatted "Label %s" $ access TagLabel v
TPair _ t1 t2 ->
let (v1, v2) = accessPair v in
mconcat
[ literal "<"
, format t1 v1
, literal ", "
, format t2 v2
, literal ">"
]
_ -> (Endo $ showsPrec 11 ty, mempty)
literal s =
(Endo (showString s), mempty)
formatted s val =
(Endo (showString s), Endo (val :))
(Endo fmt, Endo args) = format ty0 v0
fmt' = (showString "result: " . fmt) "\n"
in terminate $ callExp "printf" (escapedCString fmt' : args [])
where @closure@ and @argument@ are only present for non - top - level bindings ,
functionSignatureM :: FunctionHeader -> GenM (Builder, Env)
functionSignatureM fun = first (functionSignature fun) <$> argsEnv
where
argsEnv = foldMap (signatureParameters (funName fun)) (funArgs fun)
functionSignature :: FunctionHeader -> [Builder] -> Builder
functionSignature fun localArgs = functionHeader retType (funName fun) args
where
args =
varDeclaration cContVar
: varDeclaration cCtxtVar
: localArgs
retType = mconcat
[ if funInternal fun then "static " else mempty
, typeName @R Proxy
]
cContVar :: CVar (Pointer K)
cContVar = CVar "_ldst_k"
cClosureVar :: CVar (Pointer ())
cClosureVar = CVar "_ldst_closure"
| The variable which will be bound to the passed @LDST_ctxt_t*@. Since this
other functions we use one global variable name .
cCtxtVar :: CVar (Pointer T)
cCtxtVar = CVar "_ldst_ctxt"
with an ' Env ' mapping identifiers from the source language to ' CVar 's ,
signatureParameters :: Builder -> FunctionArgs -> GenM ([Builder], Env)
signatureParameters name args = do
let hint = localIdentForC 'a' $ funArgIdent args
argVar <- CVar @V <$> nameHint hint (fresh Nothing)
let params = [varDeclaration cClosureVar, varDeclaration argVar]
let closure = cast @(Pointer V) cClosureVar
vars <- ifor (funClosure args) \i -> traverse \ident ->
nameHint (localIdentForC 'c' ident) do
var <- storeVar (accessI i closure)
silenceUnused var
pure (ident, var)
insertRecArg <- case funRecIdent args of
Nothing -> pure id
Just recId -> do
check = rec x ( x : Int ) : Int = x
There exists a test case for this in " / name shadowing / in the source language " .
recVal <- mkValue TagLam . toCExp =<< mkLambda' name (unCVar cClosureVar)
pure $ Map.insert recId recVal
let bindings =
catMaybes vars
& Map.fromList
& Map.insert (funArgIdent args) argVar
& insertRecArg
pure (params, bindings)
| @functionDeclDef signature body@ returns a pair of @(declaration , definition)@.
functionDeclDef :: Builder -> CStmt -> (Builder, Builder)
functionDeclDef signature (CStmt body) =
let function = mconcat
[ signature
, "\n{\n"
, body
, "}\n\n"
]
in (signature <> ";\n", function)
generateFunction :: Function -> Either String (Builder, Builder)
generateFunction topLevelFun = evalStackT [topLevelFun] $ execWriterT go
where
go = popStack >>= \case
Nothing -> pure ()
Just fun -> lift (generateFunction' fun) >>= tell >> go
generateFunction'
:: Applicative m
=> Function -> StackT Function m (Builder, Builder)
generateFunction' fun = do
let genBody = do
(sig, bindings) <- functionSignatureM (funHeader fun)
local (infoBindings <>~ bindings) do
generateExp (funBody fun)
pure sig
let captured = funHeader fun
& funArgs
& fmap \args -> Closure (funClosure args) (toCExp $ cast cClosureVar)
genst = GenSt
{ _stUnique = 0
, _stClosures = maybeToList captured
}
let info = baseInfo
(funHint fun)
(funNestPrefix fun)
evalRWST (unGenM genBody) info genst
& fmap (uncurry functionDeclDef)
& generalizeStack
baseInfo :: NameHint -> NameHint -> Info
baseInfo nameH nestH = Info
{ _infoBindings = mempty
, _infoContinuation = cContVar
, _infoNameHint = nameH
, _infoNestPrefix = nestH
, _infoIndent = 1
}
generateVal :: Val -> GenM (CVar V)
generateVal = \case
Lit l -> generateLiteral l
Var name ->
locally bound the CPS transformation should have generated a ' TLCall '
asks \env -> env ^?! infoBindings . ix name
e@(Lam _ argId _ body) -> do
lam <- pushFunction 'l' (fv e) Nothing argId body
mkValue TagLam lam
e@(Rec recId argId _ _ body) -> do
lam <- nameHint (localIdentForC 'r' recId) do
pushFunction 'r' (fv e) (Just recId) argId body
mkValue TagLam lam
Math m -> generateMath m
Succ e -> do
e' <- generateVal e
liftValue TagInt $ access TagInt e' <> " + 1"
Pair a b -> do
a' <- generateVal a
b' <- generateVal b
mkValue TagPair (toCExp a', toCExp b')
Fork e -> do
let free = fv e
lam <- pushFunction 'f' free Nothing (S.freshvar "unit" free) e
forkLambda lam
New _ -> do
chan <- mkValue TagChan . toCExp =<< newChannel
mkValue TagPair (toCExp chan, toCExp chan)
Send e -> do
chan <- accessValChannel <$> generateVal e
mkValue TagLam . toCExp =<< chanSendLambda chan
generateExp :: Exp -> GenM ()
generateExp = \case
Return val -> generateVal val >>= invokeContinuation
Let v a b -> do
a' <- nameHint (localIdentForC 'l' v) $ generateVal a
local (infoBindings . at v ?~ a') $ generateExp b
LetPair idnFst idnSnd pairExp body -> do
pairVar <- nameHint "letpair" $ generateVal pairExp
let (valFst, valSnd) = accessPair pairVar
let insert idn val = infoBindings . at idn ?~ val
This is verified in " / name shadowing / in the source language " .
local (insert idnSnd valSnd . insert idnFst valFst) do
generateExp body
LetCont k e -> do
k' <- generateContinuationM $ Just k
local (infoContinuation .~ k') $ generateExp e
Call funExp argExp mk -> do
lam <- generateVal funExp
arg <- generateVal argExp
k <- generateContinuationM mk
invoke (accessValLambda lam) k arg
TLCall funId mk -> do
k <- generateContinuationM mk
invoke' (functionForC funId) k []
Case e cs -> do
branch in O(log n ) steps .
label <- access TagLabel <$> generateVal e
let buildBranch :: (String, Exp) -> StateT Builder GenM ()
buildBranch (branchLabel, branchExp) = do
ifB <- get <* put "else if "
let cmpExp = callExp funStrcmp [label, labelForC branchLabel] <+> " == 0"
lift $ tellStmt $ CStmt $ callExp ifB [cmpExp] <> " {"
lift $ local (infoIndent +~ 1) $ generateExp branchExp
lift $ tellStmt $ CStmt "}"
evalStateT (traverse_ buildBranch cs) ("if " :: Builder)
tellStmt $ cReturn "LDST_UNMATCHED_LABEL"
NatRec e z n _ x t s -> do
e' <- generateVal e
z' <- generateVal z
let vars = Set.delete n $ Set.delete x $ fv s
s' <- pushFunction 'n' vars Nothing n $ Return $ Lam MMany x t s
f <- mkValue TagLam s'
Create the closure for LDST_nat_fold
1 . f (= s ' )
2 . n (= e ' )
3 . i
i <- mkValue TagInt 0
closure <- cloneAll [f, e', i]
k <- view infoContinuation
natFold <- mkLambda' "LDST_nat_fold" $ unCVar closure
invoke natFold k z'
Recv e mk -> do
c <- accessValChannel <$> generateVal e
k <- generateContinuationM mk
chanReceive k c
pushFunction :: Char -> Set Ident -> Maybe Ident -> Ident -> Exp -> GenM (CExp L)
pushFunction c freevars mRecId argId body = do
name <- fresh (Just c)
closure <- mkClosure freevars
hint <- view infoNameHint
pushStack $ Function
{ funHeader = FunctionHeader
{ funName = name
, funArgs = Just FunctionArgs
{ funClosure = closure^.closureVars
, funArgIdent = argId
, funRecIdent = mRecId
}
, funInternal = True
}
, funHint = hint
, funNestPrefix = NameHint name
, funBody = body
}
mkLambda name closure
generateMath :: MathOp Val -> GenM (CVar V)
generateMath = liftValue TagInt <=< \case
Add a b -> math '+' a b
Sub a b -> math '-' a b
Mul a b -> math '*' a b
Div a b -> math '/' a b
Neg a -> do
a' <- generateVal a
pure $ B.char7 '-' <> access TagInt a'
where
math c a b = do
a' <- generateVal a
b' <- generateVal b
pure $ bunwords [ access TagInt a', B.char7 c, access TagInt b' ]
generateLiteral :: Literal -> GenM (CVar V)
generateLiteral = \case
LInt i -> mkValue TagInt i
LNat n -> mkValue TagInt n
LDouble d -> mkValue TagDouble d
LString s -> mkValue TagString s
LLab l -> mkValue TagLabel l
LUnit -> newUnitVar
generateContinuationM :: Maybe Continuation -> GenM (CVar (Pointer K))
generateContinuationM Nothing = view infoContinuation
generateContinuationM (Just (resId, kbody)) =
nameHint "k" $ clone =<< join do
mkContinuation
<$> pushFunction 'k' (fv kbody) Nothing resId kbody
<*> view infoContinuation
invokeContinuation :: ExpLike e => e V -> GenM ()
invokeContinuation e = do
k <- view infoContinuation
invoke' "LDST_invoke" k [unCExp (toCExp e)]
invoke :: (ExpLike e1, ExpLike e2) => CVar L -> e1 (Pointer K) -> e2 V -> GenM ()
invoke lam k val = do
let (fun, closure) = accessLambda lam
invoke' fun k [closure, unCExp (toCExp val)]
invoke' :: ExpLike e => Builder -> e (Pointer K) -> [Builder] -> GenM ()
invoke' fun k args =
let allArgs = [unCExp (toCExp k), unCExp (toCExp cCtxtVar)] ++ args
in tellStmt $ cReturn $ callExp fun allArgs
nameHint :: NameHint -> GenM a -> GenM a
nameHint h = local (infoNameHint .~ h)
functionHeader :: Builder -> Builder -> [Builder] -> Builder
functionHeader ret name args =
ret <> B.char7 ' ' <> callExp name args
If the first argument is @Just /funKind/@ the name is guaranteed to be fresh
fresh :: Maybe Char -> GenM Builder
fresh funKind = do
n <- stUnique <<+= 1
hint <- case funKind of
Nothing -> (\(NameHint h) -> h <> B.char7 '_') <$> view infoNameHint
Just c -> (\(NameHint h) -> h <> B.char7 '_' <> B.char7 c) <$> view infoNestPrefix
pure $ hint <> B.wordHex n
declareFresh :: forall t. CType t => Builder -> GenM (CVar t)
declareFresh initExp = do
name <- fresh Nothing
let var = CVar name
tellStmt $ terminate $ varDeclaration var <+> B.char7 '=' <+> initExp
pure var
varDeclaration :: forall t. CType t => CVar t -> Builder
varDeclaration (CVar v) = typeName @t Proxy <+> v
newUnitVar :: GenM (CVar V)
newUnitVar = storeVar (CExp "{ 0 }")
silenceUnused :: CVar t -> GenM ()
silenceUnused (CVar v) = tellStmt $ terminate $ "(void)" <> v
storeVar :: (CType t, ExpLike e) => e t -> GenM (CVar t)
storeVar = declareFresh . unCExp . toCExp
mkClosure :: Set Ident -> GenM Closure
mkClosure vars = do
knownVars <- view infoBindings
let captured = Map.restrictKeys knownVars vars
mclosure <- runMaybeT (nullClosure captured <|> reuseClosure captured)
maybe (allocateNewClosure captured) pure mclosure
nullClosure :: Env -> MaybeT GenM Closure
nullClosure vars =
if Map.null vars
then pure Closure{ _closureVars = [], _closureExpr = nullPointer }
else empty
reuseClosure :: Env -> MaybeT GenM Closure
reuseClosure (Map.keys -> vars) = MaybeT do
allocated <- use stClosures
pure $ allocated
& mapMaybe (closureVars %%~ tryClosureReuse vars)
& preview _head
tryClosureReuse :: [Ident] -> [Maybe Ident] -> Maybe [Maybe Ident]
tryClosureReuse = go id
where
go f (x:xs) (Just y:ys) | x == y = go (f . (Just y:)) xs ys
go f xs@(_:_) (_:ys) = go (f . (Nothing:)) xs ys
go f [] ys = Just $ f (Nothing <$ ys)
go _ _ [] = Nothing
allocateNewClosure :: Env -> GenM Closure
allocateNewClosure (Map.toAscList -> unzip -> (ids, exprs)) = do
expr <- toCExp <$> cloneAll exprs
let closure = Closure (Just <$> ids) expr
stClosures %= cons closure
pure closure
mkLambda :: Builder -> Closure -> GenM (CExp L)
mkLambda fun = fmap toCExp . mkLambda' fun . unCExp . view closureExpr
mkLambda' :: Builder -> Builder -> GenM (CVar L)
mkLambda' fun closure = declareFresh $ braceList [fun, closure]
accessLambda :: CVar L -> (Builder, Builder)
accessLambda v = (accessRaw v "lam_fp", accessRaw v "lam_closure")
mkContinuation :: (ExpLike e1, ExpLike e2) => e1 L -> e2 (Pointer K) -> GenM (CVar K)
mkContinuation lambda next = declareFresh $ braceList [unCExp $ toCExp lambda, unCExp $ toCExp next]
accessI :: Int -> CVar (Pointer t) -> CVar t
accessI i (CVar v) = CVar $ v <> brackets (B.intDec i)
cast :: forall t' t. CType t' => CVar t -> CVar t'
cast (CVar v) = CVar $ parens $ parens (typeName @t' Proxy) <> v
takeAddress :: (ExpLike e, CType t) => e t -> GenM (CVar (Pointer t))
takeAddress = declareFresh . (B.char7 '&' <>) . unCExp . toCExp
mkValue :: Tag a -> a -> GenM (CVar V)
mkValue tag a = liftValue tag =<< case tag of
TagInt -> pure $ B.intDec a
TagDouble -> pure $ B.doubleDec a
TagString -> pure $ B.stringUtf8 a
TagLabel -> pure $ labelForC a
TagPair -> do
let (x, y) = a
unCExp . toCExp <$> cloneAll [x, y]
TagLam -> pure $ unCExp a
TagChan -> pure $ unCExp a
liftValue :: Tag a -> Builder -> GenM (CVar V)
liftValue tag a = storeVar
$ CExp
$ braceList
$ pure
$ bunwords
[ B.char7 '.' <> tagAccessor tag
, B.char7 '='
, a
]
clone :: forall t e. (CType t, ExpLike e) => e t -> GenM (CVar (Pointer t))
clone = cloneAll . pure
cloneAll :: forall t e. (CType t, ExpLike e) => [e t] -> GenM (CVar (Pointer t))
cloneAll [] = storeVar nullPointer
cloneAll exprs = do
let n = length exprs
var <- declareFresh $ callExp "malloc" [B.intDec n <+> B.char7 '*' <+> cSizeof @t Proxy]
tellStmt $ terminate $
callExp "if " [B.char7 '!' <> unCVar var] <> " return LDST_NO_MEM"
itraverse_ (tellAssignI var) exprs
pure var
nullPointer :: CExp (Pointer t)
nullPointer = CExp $ B.char7 '0'
callExp :: Builder -> [Builder] -> Builder
callExp f args = f <> parens (intercalate ", " args)
tellAssign :: ExpLike e => CVar t -> e t -> GenM ()
tellAssign (CVar v) val = tellStmt $ terminate $ bunwords [v, B.char7 '=', unCExp (toCExp val)]
tellAssignI :: ExpLike e => CVar (Pointer t) -> Int -> e t -> GenM ()
tellAssignI v idx = tellAssign (accessI idx v)
funStrcmp :: Builder
funStrcmp = "strcmp"
cSizeof :: CType t => proxy t -> Builder
cSizeof = callExp "sizeof" . pure . typeName
tellStmt :: CStmt -> GenM ()
tellStmt (CStmt s) = do
lvl <- view infoIndent
let !indent = stimes (lvl * 2) (B.char7 ' ')
tell $ CStmt $ indent <> s <> B.char7 '\n'
cCodeHeader :: Builder
cCodeHeader = bunlines
[ "//"
, "// Generated by ldgv v" <> fromString (showVersion Paths_ldgv.version)
, "//"
, ""
, "#include <stdio.h>"
, "#include <stdlib.h> // malloc"
, "#include <string.h> // strcmp"
, "#include \"LDST.h\""
]
| Concatenates a builder containing the function signatures and a builder
glueCode :: Builder -> Builder -> Builder
glueCode decls defs = bunlines
[ cCodeHeader
, ""
, "// Generated code - forward declarations"
, decls
, "// Generated code - function definitions"
, defs
]
newChannel :: GenM (CVar (Pointer C))
newChannel = do
chan <- storeVar nullPointer
chanAddress <- takeAddress chan
callChecked "LDST_chan_new" [unCVar cCtxtVar, unCVar chanAddress]
pure chan
chanSendLambda :: ExpLike e => e (Pointer C) -> GenM (CVar L)
chanSendLambda = mkLambda' "LDST_chan_send" . unCExp . toCExp
chanReceive :: (ExpLike e1, ExpLike e2) => e1 (Pointer K) -> e2 (Pointer C) -> GenM ()
chanReceive (toCExp -> CExp k) (toCExp -> CExp chan) =
tellStmt $ cReturn $ callExp "LDST_chan_recv" [k, unCExp (toCExp cCtxtVar), chan]
forkLambda :: ExpLike e => e L -> GenM (CVar V)
forkLambda (toCExp -> CExp l) = do
unit <- newUnitVar
callChecked "LDST_fork" [unCExp (toCExp cCtxtVar), l, unCVar unit]
pure unit
callChecked :: Builder -> [Builder] -> GenM ()
callChecked fun args = do
resVar <- nameHint "res" do
declareFresh @R $ callExp fun args
returnNotOk resVar
returnNotOk :: CVar R -> GenM ()
returnNotOk (CVar res) = do
tellStmt $ CStmt $ callExp "if " $ pure $ res <> " != LDST_OK"
local (infoIndent +~ 1) $ tellStmt $ cReturn res
braceList :: [Builder] -> Builder
braceList bs = braces (intercalate ", " bs)
accessRaw :: CVar t -> Builder -> Builder
accessRaw (CVar v) x = v <> B.char7 '.' <> x
access :: Tag a -> CVar V -> Builder
access tag v = accessRaw v (tagAccessor tag)
accessPair :: CVar V -> (CVar V, CVar V)
accessPair v =
let b = CVar $ access TagPair v :: CVar (Pointer V)
in (accessI 0 b, accessI 1 b)
accessValLambda :: CVar V -> CVar L
accessValLambda = CVar . access TagLam
accessValChannel :: CVar V -> CVar (Pointer C)
accessValChannel = CVar . access TagChan
tagAccessor :: Tag a -> Builder
tagAccessor = \case
TagInt -> "val_int"
TagDouble -> "val_double"
TagString -> "val_string"
TagLabel -> "val_label"
TagPair -> "val_pair"
TagLam -> "val_lam"
TagChan -> "val_chan"
(<+>) :: Builder -> Builder -> Builder
a <+> b = a <> B.char7 ' ' <> b
infixr 6 <+>
bunwords :: [Builder] -> Builder
bunwords = intercalate (B.char7 ' ')
bunlines :: [Builder] -> Builder
bunlines = intercalate (B.char7 '\n')
intercalate :: Monoid a => a -> [a] -> a
intercalate a = mconcat . List.intersperse a
| @surround l r a@ adds @l@ to the left of @a@ and @r@ to the right .
> > > surround " ( " " ) " " abc "
" ( abc ) "
surround :: Semigroup a => a -> a -> a -> a
surround l r a = l <> a <> r
parens :: Builder -> Builder
parens = surround (B.char7 '(') (B.char7 ')')
braces :: Builder -> Builder
braces = surround (B.char7 '{') (B.char7 '}')
brackets :: Builder -> Builder
brackets = surround (B.char7 '[') (B.char7 ']')
terminate :: Builder -> CStmt
terminate b = CStmt $ b <> B.char7 ';'
cReturn :: Builder -> CStmt
cReturn b = terminate $ "return " <> b
| @localIdentForC kindChar identifier@ turns @identifier@ into a valid C
uses of this function to observe @'a'@ for arguments , @'l'@ for local
localIdentForC :: Char -> Ident -> NameHint
localIdentForC c idn =
NameHint $ B.char7 c <> B.char7 '_' <> escapeIdentifier idn
It uses the encoding from ' escapeIdentifier ' and prepends @"ldst_"@.
functionForC :: Ident -> Builder
functionForC idn = "ldst_" <> escapeIdentifier idn
| Escapes an LDST / LDGV identifier which may contain primes into a valid C
identifier using @q@ as an escape character :
* is replaced by @qq@
escapeIdentifier :: Ident -> Builder
escapeIdentifier = foldMap \case
'\'' -> "qQ"
'q' -> "qq"
c -> B.charUtf8 c
labelForC :: String -> Builder
compilation with C11 as the @\\Unnnnnnnn@ escape sequence is used .
escapedCString :: String -> Builder
escapedCString = surround (B.char7 '"') (B.char7 '"') . B.string7 . concatMap \c ->
let hex = showHex (C.ord c) ""
hexPadded n = replicate (n - length hex) '0' ++ hex
in
if | c == '"' -> ['\\', '"']
| c == '\\' -> ['\\', '\\']
| C.isAscii c && C.isPrint c -> [c]
| C.isAscii c -> '\\':'x':hexPadded 2
| otherwise -> '\\':'U':hexPadded 8
|